Skip to content

Split View: Segment Anything Model 완전 정복: SAM 1 → SAM 2 → SAM 3 논문 분석과 실전 가이드

|

Segment Anything Model 완전 정복: SAM 1 → SAM 2 → SAM 3 논문 분석과 실전 가이드


1. 개요: Segment Anything Model의 진화

**Segment Anything Model(SAM)**은 Meta AI Research가 발표한 이미지·비디오 세그멘테이션 분야의 Foundation Model 시리즈다. NLP 분야에서 GPT가 "프롬프트" 패러다임을 확립한 것처럼, SAM은 Computer Vision 세그멘테이션에 Promptable Segmentation이라는 새로운 패러다임을 도입했다.

버전발표핵심 능력논문
SAM 12023.04 (ICCV 2023)이미지 프롬프터블 세그멘테이션Segment Anything
SAM 22024.08이미지 + 비디오 실시간 세그멘테이션SAM 2: Segment Anything in Images and Videos
SAM 32025.11 (ICLR 2026)개념 인식(Concept-Aware) 세그멘테이션SAM 3: Segment Anything with Concepts

세 모델의 핵심 진화 방향을 한 문장으로 요약하면 다음과 같다.

SAM 1: "어디(Where)를 세그멘테이션할까?" → SAM 2: "비디오에서도 어디를?" → SAM 3: "무엇(What)을 세그멘테이션할까?"


2. SAM 1: Segment Anything (2023)

2.1 논문 정보

2.2 핵심 기여 3가지

SAM 1은 세 가지를 동시에 제안했다.

  1. 새로운 태스크 — Promptable Segmentation: 포인트, 박스, 마스크, 텍스트 등 임의의 프롬프트가 주어지면 유효한 세그멘테이션 마스크를 반환한다
  2. 새로운 모델 — SAM: 프롬프트 기반 세그멘테이션을 수행하는 Foundation Model
  3. 새로운 데이터셋 — SA-1B: 1,100만 장 이미지에서 11억 개 마스크를 포함하는 역대 최대 세그멘테이션 데이터셋

2.3 아키텍처 상세

SAM의 아키텍처는 세 가지 컴포넌트로 분리된다. 핵심 설계 원칙은 무거운 이미지 인코더는 한 번만 실행하고, 가벼운 프롬프트 인코더와 마스크 디코더를 실시간으로 반복 호출하는 것이다.

┌─────────────────────────────────────────────────────────┐
SAM Architecture│                                                          │
│  ┌──────────────┐   ┌────────────────┐                   │
│  │ Image Encoder │   │ Prompt Encoder │                   │
  (ViT-H/L/B) (Point/Box/    │                   │
│  │  MAE 사전학습  │   │  Mask/Text)    │                   │
│  └──────┬───────┘   └───────┬────────┘                   │
│         │                   │                            │
│         └─────────┬─────────┘                            │
│                   ▼                                      │
│          ┌────────────────┐                              │
│          │  Mask Decoder   │                              │
 (Transformer    │                              │
│          │  2-layer)       │──→ 3개 마스크 + IoU 점수      │
│          └────────────────┘                              │
└─────────────────────────────────────────────────────────┘

Image Encoder (이미지 인코더)

변형파라미터체크포인트 크기
ViT-B91M~375 MB
ViT-L308M~1.25 GB
ViT-H (기본)636M~2.56 GB
  • MAE(Masked Autoencoder)로 사전학습된 Vision Transformer
  • 입력 해상도: 1024×1024
  • 출력: 64×64 이미지 임베딩 (256차원)
  • 이미지당 한 번만 실행 → 이후 프롬프트별로 재사용

Prompt Encoder (프롬프트 인코더)

Sparse 프롬프트 (포인트, 박스, 텍스트):

  • 포인트/박스 → Positional Encoding + 학습된 타입 임베딩 (전경 포인트 vs 배경 포인트)
  • 텍스트 → CLIP 텍스트 인코더로 처리

Dense 프롬프트 (마스크):

  • Convolution 레이어로 임베딩 후 이미지 임베딩과 Element-wise 합산

Mask Decoder (마스크 디코더)

  • 수정된 Transformer Decoder (2 레이어)
  • 임베딩 차원: 256, MLP 내부 차원: 2048
  • Ambiguity-Aware 출력: 하나의 프롬프트에 대해 3개의 후보 마스크를 동시에 예측
    • Whole(전체), Part(부분), Sub-part(하위 부분) 수준
    • 각 마스크에 IoU 신뢰도 점수 부여
  • GPU에서 프롬프트당 ~50ms 추론 → 실시간 상호작용 가능

2.4 SA-1B 데이터셋

항목수치
이미지 수1,100만 장
마스크 수11억 개 (이미지당 평균 ~100개)
자동 생성 비율99.1%
원본 해상도~3300×4950
데이터셋 크기~5TB (이미지) + ~20GB (어노테이션)

Data Engine — 3단계 구축 과정

Phase 1: Assisted-Manual        Phase 2: Semi-Automatic       Phase 3: Fully Automatic
─────────────────────          ──────────────────────         ──────────────────────
SAM + 사람 어노테이터           • SAM이 자동 마스크 제안        • 32×32 그리드 포인트 자동 생성
• 브라우저 기반 도구              • 사람이 누락된 객체 추가       • NMS + 신뢰도 필터링
12만 이미지 / 430만 마스크     • 18만 이미지 / 590만 마스크    • 11억 마스크의 대부분

품질 검증: 500장 이미지(~50,000 마스크) 인간 감사 결과 **94%**가 IoU > 0.90 달성

2.5 핵심 혁신

Zero-Shot Transfer: Fine-tuning 없이 새로운 도메인에 즉시 적용

  • 엣지 검출 (BSDS500 ODS: 0.768)
  • Object Proposal 생성 (LVIS AR@1000: 59.3)
  • 의료영상, 위성사진, 수중사진, 현미경 이미지 등

벤치마크 성능:

  • 23개 데이터셋 Zero-Shot 평가에서 16개에서 기존 SOTA(RITM) 초과
  • Oracle 선택 시 23개 전부 RITM 초과
  • 인종/성별 등 인구통계 그룹 간 성능 편차 없음 (공정성 검증)

2.6 설치 및 실행

# 설치
pip install git+https://github.com/facebookresearch/segment-anything.git

# 선택 의존성
pip install opencv-python pycocotools matplotlib onnxruntime onnx

체크포인트 다운로드:

모델파일
ViT-H (기본)sam_vit_h_4b8939.pth
ViT-Lsam_vit_l_0b3195.pth
ViT-Bsam_vit_b_01ec64.pth

프롬프트 기반 세그멘테이션:

from segment_anything import SamPredictor, sam_model_registry
import numpy as np

# 모델 로드
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to(device="cuda")

# 예측기 생성
predictor = SamPredictor(sam)

# 이미지 설정 (이미지 임베딩 1회 계산)
predictor.set_image(image)  # numpy array (H, W, 3) RGB

# 포인트 프롬프트로 예측
masks, scores, logits = predictor.predict(
    point_coords=np.array([[500, 375]]),  # (N, 2) 좌표
    point_labels=np.array([1]),            # 1=전경, 0=배경
    multimask_output=True,                 # 3개 후보 마스크 반환
)

자동 마스크 생성 (Segment Everything):

from segment_anything import SamAutomaticMaskGenerator, sam_model_registry

sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to(device="cuda")

mask_generator = SamAutomaticMaskGenerator(sam)
masks = mask_generator.generate(image)
# 각 마스크: segmentation, area, bbox, predicted_iou, stability_score

3. SAM 2: Segment Anything in Images and Videos (2024)

3.1 논문 정보

3.2 SAM 1에서 무엇이 바뀌었나

SAM 2의 핵심 질문: "이미지에서만 되는 세그멘테이션을 비디오로 확장할 수 있을까?"

비교 항목SAM 1SAM 2
입력단일 이미지이미지 + 비디오
이미지 인코더ViT (MAE 사전학습)Hiera (계층적, MAE 사전학습)
시간 모델링없음Memory Attention 메커니즘
추론 속도프롬프트당 ~50ms이미지에서 6배 빠름
Occlusion 처리불가Occlusion Head
상호작용이미지에서 프롬프트비디오의 임의 프레임에서 프롬프트

3.3 아키텍처 상세

┌────────────────────────────────────────────────────────────────────┐
SAM 2 Streaming Architecture│                                                                    │
│  프레임 t-2    프레임 t-1    프레임 t (현재)│     │            │            │                                    │
│     ▼            ▼            ▼                                    │
│  ┌──────┐    ┌──────┐    ┌──────────────┐                          │
│  │Hiera │    │Hiera │    │ Hiera Image  │                          │
│  │Enc.      │Enc.  Encoder    │                          │
│  └──┬───┘    └──┬───┘    └──────┬───────┘                          │
│     │           │               │                                  │
│     ▼           ▼               ▼                                  │
│  ┌──────────────────────────────────────────┐                      │
│  │            Memory Bank                    │                      │
│  │  ┌──────────────┐  ┌───────────────────┐ │                      │
│  │  │ FIFO Queue   │  │ Prompted Frames   │ │                      │
│  │   (N 최근 프레임) (M 프롬프트 프레임)│ │                      │
│  │  └──────────────┘  └───────────────────┘ │                      │
│  │  ┌──────────────────────────────────────┐│                      │
│  │  │     Object Pointers (256-dim)        ││                      │
│  │  └──────────────────────────────────────┘│                      │
│  └──────────────────┬───────────────────────┘                      │
│                     ▼                                              │
│  ┌──────────────────────────────┐   ┌───────────────┐              │
│  │    Memory Attention Module    │←──│Prompt Encoder │              │
 (L Transformer Blocks:(Point/Box/    │              │
│  │  Self-Attn + Cross-Attn)     │   │ Mask)         │              │
│  └──────────────┬───────────────┘   └───────────────┘              │
│                 ▼                                                   │
│  ┌──────────────────────────┐                                      │
│  │      Mask Decoder        │──→ 마스크 + IoU + Occlusion Score (+ Skip Connections)     │                                      │
│  └──────────────────────────┘                                      │
└────────────────────────────────────────────────────────────────────┘

Hiera 이미지 인코더

SAM 1의 ViT를 **Hiera(계층적 ViT)**로 교체했다.

  • Stage 3+4 (stride 16, 32) → FPN으로 융합 → 이미지 임베딩 (Memory Attention 입력)
  • Stage 1+2 (stride 4, 8) → 마스크 디코더의 업샘플링 레이어에 Skip Connection
  • Windowed Absolute Positional Embedding 사용

Memory 메커니즘 (핵심 혁신)

Memory Encoder: 각 프레임 처리 후, 프레임 특징과 예측 마스크를 Memory Bank에 저장 (64차원으로 투영)

Memory Bank 구조:

  • FIFO Queue: 최근 N개 비프롬프트 프레임 → 시간적 맥락 유지
  • Prompted Frames: 최대 M개 프롬프트 프레임 → 사용자 가이던스 보존
  • Object Pointers: 256차원 벡터 → 추적 객체의 고수준 의미 정보

Memory Attention Module: L개의 Transformer 블록

  • Self-Attention: 현재 프레임 특징 내부
  • Cross-Attention: Memory Bank의 과거 프레임 + Object Pointer와 상호작용

Occlusion Prediction Head

비디오에서 객체가 가려지거나 화면 밖으로 나가는 상황 처리:

  • 프레임별 가시성 점수 출력
  • 가려진 객체 → 노이즈 예측 억제
  • 재등장 시 → Memory Bank 통해 즉시 재식별

3.4 SA-V 데이터셋

항목수치
비디오 수50,900개
총 시간~196시간
총 프레임~420만
Spatio-temporal Masklet642,600개
총 마스크 수3,550만 개
해상도240p ~ 4K (평균 1,401×1,037)
평균 길이~14초
장면 분포실내 54%, 실외 46%
지리적 다양성47개국
기존 대비 규모비디오 4.5배, 어노테이션 53배

Data Engine 3단계:

단계방법속도생산량
Phase 1SAM per Frame37.8초/프레임16K masklet
Phase 2SAM + SAM 2 Mask7.4초/프레임 (5.1배↑)63.5K masklet
Phase 3Full SAM 2가장 빠름나머지 전부

3.5 모델 변형 및 성능

SAM 2.1 (2024년 9월 출시, 최신 권장 버전):

모델파라미터FPS (A100)SA-V Test (J&F)MOSE Val (J&F)
sam2.1_hiera_tiny38.9M91.276.571.8
sam2.1_hiera_small46.0M84.876.673.5
sam2.1_hiera_base_plus80.8M64.178.273.7
sam2.1_hiera_large224.4M39.579.574.6

주요 벤치마크:

벤치마크SAM 2 (J&F)기존 SOTA 대비
MOSE val77.9%+6.2%
DAVIS 2017 val90.7%+2.6%
  • 이미지 세그멘테이션: SAM 1 대비 6배 빠르면서 정확도도 상승
  • 상호작용 효율: 동일 품질 달성에 3배 적은 사용자 개입

3.6 설치 및 실행

# 설치
git clone https://github.com/facebookresearch/sam2.git && cd sam2
pip install -e .

# 체크포인트 다운로드
cd checkpoints && ./download_ckpts.sh && cd ..

이미지 세그멘테이션:

import torch
from sam2.build_sam import build_sam2
from sam2.sam2_image_predictor import SAM2ImagePredictor

checkpoint = "./checkpoints/sam2.1_hiera_large.pt"
model_cfg = "configs/sam2.1/sam2.1_hiera_l.yaml"
predictor = SAM2ImagePredictor(build_sam2(model_cfg, checkpoint))

with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
    predictor.set_image(image)
    masks, _, _ = predictor.predict(
        point_coords=np.array([[500, 375]]),
        point_labels=np.array([1]),
    )

비디오 세그멘테이션:

import torch
from sam2.build_sam import build_sam2_video_predictor

checkpoint = "./checkpoints/sam2.1_hiera_large.pt"
model_cfg = "configs/sam2.1/sam2.1_hiera_l.yaml"
predictor = build_sam2_video_predictor(model_cfg, checkpoint)

with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
    state = predictor.init_state(video_path)

    # 특정 프레임에 프롬프트 추가
    frame_idx, object_ids, masks = predictor.add_new_points_or_box(
        state, frame_idx=0, obj_id=1,
        points=np.array([[500, 375]]),
        labels=np.array([1]),
    )

    # 비디오 전체 전파
    for frame_idx, object_ids, masks in predictor.propagate_in_video(state):
        # 각 프레임의 마스크 처리
        process_masks(frame_idx, masks)

Hugging Face 통합:

from sam2.sam2_image_predictor import SAM2ImagePredictor
predictor = SAM2ImagePredictor.from_pretrained("facebook/sam2-hiera-large")

from sam2.sam2_video_predictor import SAM2VideoPredictor
predictor = SAM2VideoPredictor.from_pretrained("facebook/sam2-hiera-large")

4. SAM 3: Segment Anything with Concepts (2025)

4.1 논문 정보

4.2 패러다임 전환: Where → What

SAM 1과 SAM 2는 "어디를" 세그멘테이션할지 알려주는 기하학적 프롬프트(포인트, 박스)에 의존했다. SAM 3는 근본적으로 다른 질문을 한다: "무엇을" 세그멘테이션할까?

SAM 1: 포인트/박스 → "이 위치의 객체를 분리해줘"
SAM 2: 포인트/박스 + 비디오 추적 → "이 객체를 비디오에서 따라가줘"
SAM 3: 텍스트/이미지 예시 → "이 개념에 해당하는 모든 것을 찾아줘"

Promptable Concept Segmentation (PCS) — SAM 3가 제안한 새로운 태스크:

  • 텍스트 프롬프트: 자연어 명사구 (예: "yellow school bus")
  • 이미지 예시(Exemplar): 시각적 예시 이미지
  • 결합 프롬프트: 텍스트 + Exemplar 동시 사용
  • 기존 프롬프트: 포인트, 박스, 마스크 (SAM 2 하위 호환)

4.3 아키텍처 상세

총 파라미터: 848M (~3.4 GB)

┌───────────────────────────────────────────────────────────────────────┐
SAM 3 Architecture│                                                                       │
│  ┌────────────┐  ┌────────────┐  ┌──────────────────┐                 │
│  │ Text       │  │ Exemplar   │  │ Visual Prompts   │                 │
│  │ Encoder    │  │ Encoder (Point/Box/Mask) │                 │
│  │ "school    │  │ [이미지]    │  │                  │                 │
│  │  bus"      │  │            │  │                  │                 │
│  └─────┬──────┘  └─────┬──────┘  └────────┬─────────┘                 │
│        └────────────┬───┘                  │                          │
│                     ▼                      │                          │
│  ┌──────────────────────────────┐          │                          │
│  │   Meta Perception Encoder    │          │                          │
   (Vision-Language 공동 공간) │          │                          │
│  └──────────────┬───────────────┘          │                          │
│                 │                          │                          │
│        ┌────────┴────────┐                 │                          │
│        ▼                 ▼                 │                          │
│  ┌───────────┐    ┌─────────────────┐      │                          │
│  │ Presence  │    │  Fusion Encoder │      │                          │
│  │   Head  (조건부 특징)   │      │                          │
│  │ "있다/없다"│    └────────┬────────┘      │                          │
│  └───────────┘             │               │                          │
│                            ▼               │                          │
│               ┌──────────────────┐         │                          │
│               │  DETR Detector   │←────────┘                          │
  (Transformer    │                                    │
│               │   기반 검출)      │                                    │
│               └────────┬─────────┘                                    │
│                        │                                              │
│                        ▼                                              │
│  ┌──────────────────────────────────────┐                             │
│  │    SAM 2-inspired Tracker            │                             │
    (Memory Bank + 시간적 일관성)      │                             │
│  └──────────────────┬───────────────────┘                             │
│                     ▼                                                 │
│              마스크 + 박스 + 점수                                      │
└───────────────────────────────────────────────────────────────────────┘

핵심 혁신: Presence Head

Presence Head는 SAM 3의 가장 중요한 아키텍처 혁신이다. **인식(Recognition)**과 **위치파악(Localization)**을 분리한다.

기존 방식: 검출기가 "찾기""있는지 판단" 동시 수행 → 최적화 충돌
SAM 3:    Presence Head가 "있는지" 먼저 판단 → 검출기는 "찾기"에만 집중

효과:

구성CGF1
Presence Head 없음57.6
Presence Head 있음63.3 (+5.7, +9.9%)

Decoupled Detector-Tracker 설계

SAM 2의 모놀리식 구조와 달리, SAM 3는 Detection과 Tracking을 독립 모듈로 분리:

  • 공유: 백본 (Perception Encoder)
  • 분리: 디코더 헤드 (검출 vs 추적)
  • 장점: 태스크 간 간섭 감소, 독립적 스케일링 가능

학습 파이프라인 (4단계)

단계내용
1Perception Encoder 사전학습
2Detector 사전학습
3SA-Co 데이터로 Detector Fine-tuning
4백본 고정(frozen) 후 Tracker 학습

4.4 SA-Co 데이터셋

SAM 3는 **SA-Co (Segment Anything with Concepts)**라는 역대 최대·최다양 세그멘테이션 데이터셋으로 학습했다.

학습 데이터

서브셋내용
SA-Co/HQ520만 고품질 이미지, 400만 고유 명사구, 5,200만 마스크
SA-Co/SYN3,800만 합성 문구, 14억 마스크 (대규모 사전학습)
SA-Co/VIDEO52,500 비디오, 24,800 고유 개념, 467,000+ masklet

총 온톨로지: 2,200만 엔티티 (17개 상위 카테고리, 72개 하위 카테고리)

평가 벤치마크

벤치마크설명
SA-Co/Gold7개 다중 검토 이미지 서브셋 (최고 품질)
SA-Co/Silver10개 도메인 특화 이미지 서브셋
SA-Co/VEval3개 비디오 평가 서브셋
  • 214,000 고유 문구, 126,000 이미지/비디오 → 기존 COCO/LVIS 대비 50배 이상 다양한 개념

추가 공개 데이터셋

  • SA-FARI: 10,000+ 야생동물 카메라 트랩 비디오 (100+ 종 어노테이션)
  • FathomNet: 해양 이미지 수중 세그멘테이션 벤치마크

4.5 성능 벤치마크

이미지 세그멘테이션 (Zero-Shot)

벤치마크메트릭SAM 3기존 최고향상
LVISMask AP47.038.5 (T-Rex2)+22.1%
COCOBox AP53.552.2+2.5%
SA-Co/GoldCGF165.034.3+89.5% (~2배)
ODinWvs T-Rex2--+20.1 AP

비디오 세그멘테이션

벤치마크SAM 3 (J&F)SAM 2.1 Large향상
MOSEv260.147.9+25.5%
DAVIS 201792.090.7+1.4%
LVOSv288.279.6+10.8%

Exemplar 활용 효과

프롬프트 구성CGF1텍스트 대비 향상
텍스트만46.4-
텍스트 + 1 Exemplar57.6+11.2
텍스트 + 3 Exemplar65.0+18.6

속도 및 효율

  • 추론 속도: H200 GPU에서 이미지당 ~30ms (100+ 객체 검출 포함)
  • 모델 크기: 848M 파라미터 (~3.4 GB)
  • 16GB GPU에서 실행 가능
  • 인간 성능 대비: SA-Co/Gold에서 인간 하한의 88% 달성

4.6 설치 및 실행

공식 저장소

# 환경 생성
conda create -n sam3 python=3.12
conda activate sam3

# PyTorch 설치
pip install torch==2.7.0 torchvision torchaudio \
    --index-url https://download.pytorch.org/whl/cu126

# SAM 3 설치
git clone https://github.com/facebookresearch/sam3.git
cd sam3
pip install -e .

# 선택: 노트북 또는 개발용
pip install -e ".[notebooks]"
pip install -e ".[train,dev]"

이미지 세그멘테이션 (텍스트 프롬프트):

from PIL import Image
from sam3.model_builder import build_sam3_image_model
from sam3.model.sam3_image_processor import Sam3Processor

model = build_sam3_image_model()
processor = Sam3Processor(model)
image = Image.open("path/to/image.jpg")

# 텍스트 프롬프트로 개념 세그멘테이션
inference_state = processor.set_image(image)
output = processor.set_text_prompt(
    state=inference_state,
    prompt="yellow school bus"
)
masks, boxes, scores = output["masks"], output["boxes"], output["scores"]

비디오 추적:

from sam3.model_builder import build_sam3_video_predictor

video_predictor = build_sam3_video_predictor()
response = video_predictor.handle_request(
    request=dict(
        type="start_session",
        resource_path="path/to/video.mp4"
    )
)

Ultralytics 통합

pip install -U ultralytics
from ultralytics.models.sam import SAM3SemanticPredictor

overrides = dict(
    conf=0.25, task="segment", mode="predict",
    model="sam3.pt", half=True
)
predictor = SAM3SemanticPredictor(overrides=overrides)
predictor.set_image("path/to/image.jpg")

# 여러 개념 동시 세그멘테이션
results = predictor(text=["person", "bus", "glasses"])

5. 세 모델 비교 종합

5.1 아키텍처 비교

항목SAM 1SAM 2SAM 3
이미지 인코더ViT (MAE)Hiera (MAE)Meta Perception Encoder
파라미터636M (ViT-H)224.4M (Hiera-L)848M
프롬프트포인트, 박스, 마스크, 텍스트포인트, 박스, 마스크텍스트, Exemplar, 포인트, 박스, 마스크
시간 모델링없음Memory AttentionMemory + Tracker
검출기없음없음DETR 기반
Occlusion미지원Occlusion HeadOcclusion + Presence Head
출력마스크 + IoU마스크 + IoU + Occlusion마스크 + 박스 + 점수 + 개념

5.2 데이터셋 비교

항목SA-1B (SAM 1)SA-V (SAM 2)SA-Co (SAM 3)
이미지1,100만-520만 (HQ)
비디오-50,90052,500
마스크11억3,550만14억+ (SYN 포함)
개념/라벨없음 (Class-Agnostic)없음2,200만 엔티티
고유 문구--400만

5.3 성능 진화

벤치마크SAM 1SAM 2/2.1SAM 3
DAVIS 2017 (J&F)N/A90.792.0
MOSE val (J&F)N/A74.660.1 (MOSEv2, 다른 벤치마크)
이미지 속도 대비기준6배 빠름~30ms/이미지
Zero-Shot 능력기하학적기하학적 + 시간개념 수준

6. 실전 활용 시나리오

6.1 SAM 1이 적합한 경우

  • 단일 이미지에서 빠른 세그멘테이션이 필요할 때
  • 인터랙티브 어노테이션 도구 구축
  • 기존 파이프라인에 간단히 통합할 때 (가장 성숙한 생태계)

6.2 SAM 2가 적합한 경우

  • 비디오 객체 추적이 필요할 때
  • 실시간 비디오 스트리밍 분석
  • 가려짐(Occlusion) 처리가 중요한 시나리오
  • 이미지에서도 SAM 1보다 빠른 속도 필요 시

6.3 SAM 3가 적합한 경우

  • 자연어로 검색하며 세그멘테이션할 때 ("모든 자동차를 찾아줘")
  • Open-Vocabulary 객체 검출 + 세그멘테이션
  • 시각적 예시 기반 Few-Shot 세그멘테이션
  • 대규모 이미지/비디오 자동 라벨링

6.4 실제 배포 사례 (SAM 3)

  • Instagram Edits 앱: 비디오 속 특정 인물/객체에 동적 이펙트 적용
  • Facebook Marketplace "View in Room": AR 가구 배치 (SAM 3 + SAM 3D)
  • 야생동물 보전: SA-FARI 데이터셋 기반 카메라 트랩 모니터링

7. 공부 로드맵

SAM 시리즈를 깊이 이해하고 활용하기 위한 단계별 학습 가이드.

7.1 사전 지식

7.2 핵심 논문 읽기 순서

1. SAM 1 논문 (2023) → 기초 개념 확립
2. SAM 2 논문 (2024) → 비디오 확장 이해
3. SAM 3 논문 (2025) → 개념 인식 이해
4.GitHub 레포의 노트북 실습

7.3 실습 추천

단계실습난이도
1SAM 1 자동 마스크 생성 (Colab 노트북)쉬움
2SAM 2 비디오 추적 실습중간
3SAM 3 텍스트 프롬프트 세그멘테이션중간
4SAM + Grounding DINO 파이프라인 구축어려움
5커스텀 데이터셋 Fine-tuning어려움
6ONNX/TensorRT 변환 및 Edge 배포고급

7.4 관련 후속 연구

모델특징논문
EfficientSAM경량화 SAM (SAMI 증류)arxiv.org/abs/2312.00863
FastSAMCNN 기반 실시간 SAMarxiv.org/abs/2306.12156
MobileSAM모바일 최적화 SAMarxiv.org/abs/2306.14289
Grounded SAMGrounding DINO + SAMgithub.com/IDEA-Research/Grounded-Segment-Anything
SAM-HQ고품질 마스크 SAMarxiv.org/abs/2306.01567
SAM 3D3D 객체/인체 복원 (Meta)ai.meta.com/sam3

8. References

핵심 논문

  1. Kirillov, A., Mintun, E., Ravi, N., et al. (2023). "Segment Anything". ICCV 2023. arxiv.org/abs/2304.02643
  2. Ravi, N., Gabeur, V., Hu, Y.-T., et al. (2024). "SAM 2: Segment Anything in Images and Videos". arxiv.org/abs/2408.00714
  3. Carion, N., Gustafson, L., Hu, Y.-T., et al. (2025). "SAM 3: Segment Anything with Concepts". ICLR 2026. arxiv.org/abs/2511.16719

사전 지식 논문

  1. Dosovitskiy, A., et al. (2021). "An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale". ICLR 2021. arxiv.org/abs/2010.11929
  2. He, K., et al. (2022). "Masked Autoencoders Are Scalable Vision Learners". CVPR 2022. arxiv.org/abs/2111.06377
  3. Carion, N., et al. (2020). "End-to-End Object Detection with Transformers (DETR)". ECCV 2020. arxiv.org/abs/2005.12872
  4. Radford, A., et al. (2021). "Learning Transferable Visual Models From Natural Language Supervision (CLIP)". ICML 2021. arxiv.org/abs/2103.00020
  5. Ryali, C., et al. (2023). "Hiera: A Hierarchical Vision Transformer without the Bells-and-Whistles". ICML 2023. arxiv.org/abs/2306.00989

GitHub 저장소

  1. github.com/facebookresearch/segment-anything — SAM 1
  2. github.com/facebookresearch/sam2 — SAM 2
  3. github.com/facebookresearch/sam3 — SAM 3

해설 및 튜토리얼

  1. Ultralytics SAM Documentation — docs.ultralytics.com/models/sam
  2. Ultralytics SAM 2 Documentation — docs.ultralytics.com/models/sam-2
  3. Ultralytics SAM 3 Documentation — docs.ultralytics.com/models/sam-3
  4. Encord Blog: Segment Anything Model Explained — encord.com/blog/segment-anything-model-explained
  5. Roboflow: What is SAM 3 — blog.roboflow.com/what-is-sam3
  6. Meta AI Blog: Introducing SAM 3 — ai.meta.com/blog/segment-anything-model-3

프로젝트 페이지 및 데이터셋

  1. Meta AI SAM 2 Project — ai.meta.com/sam2
  2. Meta AI SAM 3 Project — ai.meta.com/sam3
  3. SA-1B Dataset — ai.meta.com/datasets/segment-anything
  4. SA-V Dataset — ai.meta.com/datasets/segment-anything-video

Mastering the Segment Anything Model: Paper Analysis and Practical Guide from SAM 1 to SAM 2 to SAM 3


1. Overview: The Evolution of the Segment Anything Model

Segment Anything Model (SAM) is a series of foundation models for image and video segmentation published by Meta AI Research. Just as GPT established the "prompt" paradigm in NLP, SAM introduced a new paradigm called Promptable Segmentation to computer vision segmentation.

VersionReleasedCore CapabilityPaper
SAM 12023.04 (ICCV 2023)Image promptable segmentationSegment Anything
SAM 22024.08Image + real-time video segmentationSAM 2: Segment Anything in Images and Videos
SAM 32025.11 (ICLR 2026)Concept-aware segmentationSAM 3: Segment Anything with Concepts

The core evolutionary direction of the three models can be summarized in one line:

SAM 1: "Where to segment?" → SAM 2: "Where — even in video?" → SAM 3: "What to segment?"


2. SAM 1: Segment Anything (2023)

2.1 Paper Information

2.2 Three Key Contributions

SAM 1 simultaneously introduced three things:

  1. A new task — Promptable Segmentation: Given any prompt (point, box, mask, or text), the model returns a valid segmentation mask
  2. A new model — SAM: A foundation model for prompt-based segmentation
  3. A new dataset — SA-1B: The largest segmentation dataset ever, containing 1.1 billion masks from 11 million images

2.3 Architecture Details

SAM's architecture is decomposed into three components. The core design principle is to run the heavy image encoder only once and repeatedly call the lightweight prompt encoder and mask decoder in real time.

┌─────────────────────────────────────────────────────────┐
SAM Architecture│                                                          │
│  ┌──────────────┐   ┌────────────────┐                   │
│  │ Image Encoder │   │ Prompt Encoder │                   │
  (ViT-H/L/B) (Point/Box/    │                   │
│  │  MAE Pretrain │   │  Mask/Text)    │                   │
│  └──────┬───────┘   └───────┬────────┘                   │
│         │                   │                            │
│         └─────────┬─────────┘                            │
│                   ▼                                      │
│          ┌────────────────┐                              │
│          │  Mask Decoder   │                              │
 (Transformer    │                              │
│          │  2-layer)       │──→ 3 masks + IoU scores      │
│          └────────────────┘                              │
└─────────────────────────────────────────────────────────┘

Image Encoder

VariantParametersCheckpoint Size
ViT-B91M~375 MB
ViT-L308M~1.25 GB
ViT-H (default)636M~2.56 GB
  • Vision Transformer pretrained with MAE (Masked Autoencoder)
  • Input resolution: 1024×1024
  • Output: 64×64 image embedding (256-dim)
  • Runs only once per image — reused for each prompt afterwards

Prompt Encoder

Sparse prompts (points, boxes, text):

  • Points/boxes → Positional Encoding + learned type embeddings (foreground point vs. background point)
  • Text → processed via CLIP text encoder

Dense prompts (masks):

  • Embedded via convolution layers and element-wise summed with the image embedding

Mask Decoder

  • Modified Transformer Decoder (2 layers)
  • Embedding dimension: 256, MLP inner dimension: 2048
  • Ambiguity-aware output: predicts 3 candidate masks simultaneously for a single prompt
    • Whole, Part, and Sub-part levels
    • Each mask is assigned an IoU confidence score
  • ~50ms inference per prompt on GPU — enabling real-time interaction

2.4 SA-1B Dataset

ItemValue
Images11 million
Masks1.1 billion (~100 per image on average)
Auto-generated99.1%
Original resolution~3300×4950
Dataset size~5 TB (images) + ~20 GB (annotations)

Data Engine — 3-Phase Construction Process

Phase 1: Assisted-Manual        Phase 2: Semi-Automatic       Phase 3: Fully Automatic
─────────────────────          ──────────────────────         ──────────────────────
SAM + human annotators        • SAM auto-suggests masks     • 32×32 grid points auto-generated
Browser-based tool            • Humans add missed objects   • NMS + confidence filtering
• 120K images / 4.3M masks     • 180K images / 5.9M masks    • Majority of 1.1B masks

Quality verification: Human audit of 500 images (~50,000 masks) showed 94% achieving IoU > 0.90

2.5 Key Innovations

Zero-Shot Transfer: Instantly applicable to new domains without fine-tuning

  • Edge detection (BSDS500 ODS: 0.768)
  • Object proposal generation (LVIS AR@1000: 59.3)
  • Medical imaging, satellite imagery, underwater photography, microscopy images, etc.

Benchmark performance:

  • Zero-shot evaluation across 23 datasets: outperformed existing SOTA (RITM) on 16
  • With oracle selection: outperformed RITM on all 23
  • No performance disparity across demographic groups such as race/gender (fairness validation)

2.6 Installation and Usage

# Installation
pip install git+https://github.com/facebookresearch/segment-anything.git

# Optional dependencies
pip install opencv-python pycocotools matplotlib onnxruntime onnx

Checkpoint download:

ModelFile
ViT-H (default)sam_vit_h_4b8939.pth
ViT-Lsam_vit_l_0b3195.pth
ViT-Bsam_vit_b_01ec64.pth

Prompt-based segmentation:

from segment_anything import SamPredictor, sam_model_registry
import numpy as np

# Load model
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to(device="cuda")

# Create predictor
predictor = SamPredictor(sam)

# Set image (image embedding computed once)
predictor.set_image(image)  # numpy array (H, W, 3) RGB

# Predict with point prompt
masks, scores, logits = predictor.predict(
    point_coords=np.array([[500, 375]]),  # (N, 2) coordinates
    point_labels=np.array([1]),            # 1=foreground, 0=background
    multimask_output=True,                 # Return 3 candidate masks
)

Automatic mask generation (Segment Everything):

from segment_anything import SamAutomaticMaskGenerator, sam_model_registry

sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to(device="cuda")

mask_generator = SamAutomaticMaskGenerator(sam)
masks = mask_generator.generate(image)
# Each mask: segmentation, area, bbox, predicted_iou, stability_score

3. SAM 2: Segment Anything in Images and Videos (2024)

3.1 Paper Information

3.2 What Changed from SAM 1

The core question behind SAM 2: "Can we extend image-only segmentation to video?"

ComparisonSAM 1SAM 2
InputSingle imageImage + video
Image encoderViT (MAE pretrained)Hiera (hierarchical, MAE pretrained)
Temporal modelingNoneMemory Attention mechanism
Inference speed~50ms per prompt6x faster on images
Occlusion handlingNot supportedOcclusion Head
InteractionPrompts on imagesPrompts on any frame in video

3.3 Architecture Details

┌────────────────────────────────────────────────────────────────────┐
SAM 2 Streaming Architecture│                                                                    │
Frame t-2      Frame t-1      Frame t (current)│     │            │            │                                    │
│     ▼            ▼            ▼                                    │
│  ┌──────┐    ┌──────┐    ┌──────────────┐                          │
│  │Hiera │    │Hiera │    │ Hiera Image  │                          │
│  │Enc.      │Enc.  Encoder    │                          │
│  └──┬───┘    └──┬───┘    └──────┬───────┘                          │
│     │           │               │                                  │
│     ▼           ▼               ▼                                  │
│  ┌──────────────────────────────────────────┐                      │
│  │            Memory Bank                    │                      │
│  │  ┌──────────────┐  ┌───────────────────┐ │                      │
│  │  │ FIFO Queue   │  │ Prompted Frames   │ │                      │
│  │   (N recent    │   (M prompted       │ │                      │
│  │  │  frames)     │  │  frames)          │ │                      │
│  │  └──────────────┘  └───────────────────┘ │                      │
│  │  ┌──────────────────────────────────────┐│                      │
│  │  │     Object Pointers (256-dim)        ││                      │
│  │  └──────────────────────────────────────┘│                      │
│  └──────────────────┬───────────────────────┘                      │
│                     ▼                                              │
│  ┌──────────────────────────────┐   ┌───────────────┐              │
│  │    Memory Attention Module    │←──│Prompt Encoder │              │
 (L Transformer Blocks:(Point/Box/    │              │
│  │  Self-Attn + Cross-Attn)     │   │ Mask)         │              │
│  └──────────────┬───────────────┘   └───────────────┘              │
│                 ▼                                                   │
│  ┌──────────────────────────┐                                      │
│  │      Mask Decoder        │──→ Mask + IoU + Occlusion Score (+ Skip Connections)     │                                      │
│  └──────────────────────────┘                                      │
└────────────────────────────────────────────────────────────────────┘

Hiera Image Encoder

SAM 1's ViT was replaced with Hiera (hierarchical ViT).

  • Stages 3+4 (stride 16, 32) → fused via FPN → image embedding (input to Memory Attention)
  • Stages 1+2 (stride 4, 8) → skip connections to the mask decoder's upsampling layers
  • Uses windowed absolute positional embedding

Memory Mechanism (Key Innovation)

Memory Encoder: After processing each frame, frame features and predicted masks are stored in the Memory Bank (projected to 64-dim)

Memory Bank structure:

  • FIFO Queue: The most recent N non-prompted frames — maintains temporal context
  • Prompted Frames: Up to M prompted frames — preserves user guidance
  • Object Pointers: 256-dim vectors — high-level semantic information about tracked objects

Memory Attention Module: L Transformer blocks

  • Self-Attention: within the current frame features
  • Cross-Attention: interaction with past frames + object pointers from the Memory Bank

Occlusion Prediction Head

Handles situations in video where objects become occluded or leave the frame:

  • Outputs a visibility score per frame
  • Suppresses noisy predictions for occluded objects
  • On reappearance → immediate re-identification via the Memory Bank

3.4 SA-V Dataset

ItemValue
Videos50,900
Total duration~196 hours
Total frames~4.2 million
Spatio-temporal masklets642,600
Total masks35.5 million
Resolution240p to 4K (average 1,401×1,037)
Average length~14 seconds
Scene distributionIndoor 54%, Outdoor 46%
Geographic diversity47 countries
Scale vs. existing4.5x more video, 53x more annotations

3-Phase Data Engine:

PhaseMethodSpeedOutput
Phase 1SAM per Frame37.8 sec/frame16K masklets
Phase 2SAM + SAM 2 Mask7.4 sec/frame (5.1x faster)63.5K masklets
Phase 3Full SAM 2FastestAll remaining

3.5 Model Variants and Performance

SAM 2.1 (released September 2024, latest recommended version):

ModelParametersFPS (A100)SA-V Test (J&F)MOSE Val (J&F)
sam2.1_hiera_tiny38.9M91.276.571.8
sam2.1_hiera_small46.0M84.876.673.5
sam2.1_hiera_base_plus80.8M64.178.273.7
sam2.1_hiera_large224.4M39.579.574.6

Key benchmarks:

BenchmarkSAM 2 (J&F)vs. Previous SOTA
MOSE val77.9%+6.2%
DAVIS 2017 val90.7%+2.6%
  • Image segmentation: 6x faster than SAM 1 while also improving accuracy
  • Interaction efficiency: 3x fewer user interactions to achieve the same quality

3.6 Installation and Usage

# Installation
git clone https://github.com/facebookresearch/sam2.git && cd sam2
pip install -e .

# Download checkpoints
cd checkpoints && ./download_ckpts.sh && cd ..

Image segmentation:

import torch
from sam2.build_sam import build_sam2
from sam2.sam2_image_predictor import SAM2ImagePredictor

checkpoint = "./checkpoints/sam2.1_hiera_large.pt"
model_cfg = "configs/sam2.1/sam2.1_hiera_l.yaml"
predictor = SAM2ImagePredictor(build_sam2(model_cfg, checkpoint))

with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
    predictor.set_image(image)
    masks, _, _ = predictor.predict(
        point_coords=np.array([[500, 375]]),
        point_labels=np.array([1]),
    )

Video segmentation:

import torch
from sam2.build_sam import build_sam2_video_predictor

checkpoint = "./checkpoints/sam2.1_hiera_large.pt"
model_cfg = "configs/sam2.1/sam2.1_hiera_l.yaml"
predictor = build_sam2_video_predictor(model_cfg, checkpoint)

with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
    state = predictor.init_state(video_path)

    # Add prompt to a specific frame
    frame_idx, object_ids, masks = predictor.add_new_points_or_box(
        state, frame_idx=0, obj_id=1,
        points=np.array([[500, 375]]),
        labels=np.array([1]),
    )

    # Propagate through entire video
    for frame_idx, object_ids, masks in predictor.propagate_in_video(state):
        # Process masks for each frame
        process_masks(frame_idx, masks)

Hugging Face integration:

from sam2.sam2_image_predictor import SAM2ImagePredictor
predictor = SAM2ImagePredictor.from_pretrained("facebook/sam2-hiera-large")

from sam2.sam2_video_predictor import SAM2VideoPredictor
predictor = SAM2VideoPredictor.from_pretrained("facebook/sam2-hiera-large")

4. SAM 3: Segment Anything with Concepts (2025)

4.1 Paper Information

4.2 Paradigm Shift: From Where to What

SAM 1 and SAM 2 relied on geometric prompts (points, boxes) that specify "where" to segment. SAM 3 asks a fundamentally different question: "What" to segment?

SAM 1: Point/Box"Isolate the object at this location"
SAM 2: Point/Box + Video Tracking"Track this object through the video"
SAM 3: Text/Image Exemplar"Find everything matching this concept"

Promptable Concept Segmentation (PCS) — the new task proposed by SAM 3:

  • Text prompts: Natural language noun phrases (e.g., "yellow school bus")
  • Image exemplars: Visual example images
  • Combined prompts: Text + exemplar used simultaneously
  • Legacy prompts: Points, boxes, masks (backward compatible with SAM 2)

4.3 Architecture Details

Total parameters: 848M (~3.4 GB)

┌───────────────────────────────────────────────────────────────────────┐
SAM 3 Architecture│                                                                       │
│  ┌────────────┐  ┌────────────┐  ┌──────────────────┐                 │
│  │ Text       │  │ Exemplar   │  │ Visual Prompts   │                 │
│  │ Encoder    │  │ Encoder (Point/Box/Mask) │                 │
│  │ "school    │  │ [image]    │  │                  │                 │
│  │  bus"      │  │            │  │                  │                 │
│  └─────┬──────┘  └─────┬──────┘  └────────┬─────────┘                 │
│        └────────────┬───┘                  │                          │
│                     ▼                      │                          │
│  ┌──────────────────────────────┐          │                          │
│  │   Meta Perception Encoder    │          │                          │
   (Vision-Language joint     │          │                          │
│  │    embedding space)          │          │                          │
│  └──────────────┬───────────────┘          │                          │
│                 │                          │                          │
│        ┌────────┴────────┐                 │                          │
│        ▼                 ▼                 │                          │
│  ┌───────────┐    ┌─────────────────┐      │                          │
│  │ Presence  │    │  Fusion Encoder │      │                          │
│  │   Head  (Conditional   │      │                          │
│  │ "yes/no"  │    │   features)     │      │                          │
│  └───────────┘    └────────┬────────┘      │                          │
│                            │               │                          │
│                            ▼               │                          │
│               ┌──────────────────┐         │                          │
│               │  DETR Detector   │←────────┘                          │
  (Transformer-   │                                    │
│               │   based detect.) │                                    │
│               └────────┬─────────┘                                    │
│                        │                                              │
│                        ▼                                              │
│  ┌──────────────────────────────────────┐                             │
│  │    SAM 2-inspired Tracker            │                             │
    (Memory Bank + temporal           │                             │
│  │     consistency)                     │                             │
│  └──────────────────┬───────────────────┘                             │
│                     ▼                                                 │
Masks + Boxes + Scores└───────────────────────────────────────────────────────────────────────┘

Key Innovation: Presence Head

The Presence Head is SAM 3's most important architectural innovation. It decouples recognition from localization.

Previous approach: Detector simultaneously "finds" and "judges existence" → optimization conflict
SAM 3:            Presence Head first judges "does it exist?"Detector focuses solely on "finding"

Impact:

ConfigurationCGF1
Without Presence Head57.6
With Presence Head63.3 (+5.7, +9.9%)

Decoupled Detector-Tracker Design

Unlike SAM 2's monolithic architecture, SAM 3 separates detection and tracking into independent modules:

  • Shared: backbone (Perception Encoder)
  • Separate: decoder heads (detection vs. tracking)
  • Advantage: reduced inter-task interference, independent scaling

Training Pipeline (4 Stages)

StageDescription
1Perception Encoder pretraining
2Detector pretraining
3Detector fine-tuning with SA-Co data
4Backbone frozen, then Tracker training

4.4 SA-Co Dataset

SAM 3 was trained on SA-Co (Segment Anything with Concepts), the largest and most diverse segmentation dataset ever.

Training Data

SubsetContents
SA-Co/HQ5.2M high-quality images, 4M unique noun phrases, 52M masks
SA-Co/SYN38M synthetic phrases, 1.4 billion masks (large-scale pretraining)
SA-Co/VIDEO52,500 videos, 24,800 unique concepts, 467,000+ masklets

Total ontology: 22 million entities (17 top-level categories, 72 subcategories)

Evaluation Benchmarks

BenchmarkDescription
SA-Co/Gold7 multi-review image subsets (highest quality)
SA-Co/Silver10 domain-specific image subsets
SA-Co/VEval3 video evaluation subsets
  • 214,000 unique phrases, 126,000 images/videosover 50x more diverse concepts than existing COCO/LVIS

Additional Public Datasets

  • SA-FARI: 10,000+ wildlife camera trap videos (100+ species annotated)
  • FathomNet: Underwater segmentation benchmark for marine imagery

4.5 Performance Benchmarks

Image Segmentation (Zero-Shot)

BenchmarkMetricSAM 3Previous BestImprovement
LVISMask AP47.038.5 (T-Rex2)+22.1%
COCOBox AP53.552.2+2.5%
SA-Co/GoldCGF165.034.3+89.5% (~2x)
ODinWvs T-Rex2--+20.1 AP

Video Segmentation

BenchmarkSAM 3 (J&F)SAM 2.1 LargeImprovement
MOSEv260.147.9+25.5%
DAVIS 201792.090.7+1.4%
LVOSv288.279.6+10.8%

Exemplar Utilization Effect

Prompt ConfigurationCGF1Improvement over Text Only
Text only46.4-
Text + 1 exemplar57.6+11.2
Text + 3 exemplars65.0+18.6

Speed and Efficiency

  • Inference speed: ~30ms per image on H200 GPU (including 100+ object detection)
  • Model size: 848M parameters (~3.4 GB)
  • Runnable on 16 GB GPUs
  • vs. human performance: achieves 88% of the human lower bound on SA-Co/Gold

4.6 Installation and Usage

Official Repository

# Create environment
conda create -n sam3 python=3.12
conda activate sam3

# Install PyTorch
pip install torch==2.7.0 torchvision torchaudio \
    --index-url https://download.pytorch.org/whl/cu126

# Install SAM 3
git clone https://github.com/facebookresearch/sam3.git
cd sam3
pip install -e .

# Optional: for notebooks or development
pip install -e ".[notebooks]"
pip install -e ".[train,dev]"

Image segmentation (text prompt):

from PIL import Image
from sam3.model_builder import build_sam3_image_model
from sam3.model.sam3_image_processor import Sam3Processor

model = build_sam3_image_model()
processor = Sam3Processor(model)
image = Image.open("path/to/image.jpg")

# Concept segmentation with text prompt
inference_state = processor.set_image(image)
output = processor.set_text_prompt(
    state=inference_state,
    prompt="yellow school bus"
)
masks, boxes, scores = output["masks"], output["boxes"], output["scores"]

Video tracking:

from sam3.model_builder import build_sam3_video_predictor

video_predictor = build_sam3_video_predictor()
response = video_predictor.handle_request(
    request=dict(
        type="start_session",
        resource_path="path/to/video.mp4"
    )
)

Ultralytics Integration

pip install -U ultralytics
from ultralytics.models.sam import SAM3SemanticPredictor

overrides = dict(
    conf=0.25, task="segment", mode="predict",
    model="sam3.pt", half=True
)
predictor = SAM3SemanticPredictor(overrides=overrides)
predictor.set_image("path/to/image.jpg")

# Segment multiple concepts simultaneously
results = predictor(text=["person", "bus", "glasses"])

5. Comprehensive Comparison of All Three Models

5.1 Architecture Comparison

ItemSAM 1SAM 2SAM 3
Image encoderViT (MAE)Hiera (MAE)Meta Perception Encoder
Parameters636M (ViT-H)224.4M (Hiera-L)848M
PromptsPoint, box, mask, textPoint, box, maskText, exemplar, point, box, mask
Temporal modelNoneMemory AttentionMemory + Tracker
DetectorNoneNoneDETR-based
OcclusionNot supportedOcclusion HeadOcclusion + Presence Head
OutputMask + IoUMask + IoU + OcclusionMask + box + score + concept

5.2 Dataset Comparison

ItemSA-1B (SAM 1)SA-V (SAM 2)SA-Co (SAM 3)
Images11M-5.2M (HQ)
Videos-50,90052,500
Masks1.1B35.5M1.4B+ (incl. SYN)
Concepts/LabelsNone (class-agnostic)None22M entities
Unique phrases--4M

5.3 Performance Evolution

BenchmarkSAM 1SAM 2/2.1SAM 3
DAVIS 2017 (J&F)N/A90.792.0
MOSE val (J&F)N/A74.660.1 (MOSEv2, different benchmark)
Image speedBaseline6x faster~30ms/image
Zero-shot abilityGeometricGeometric + temporalConcept-level

6. Practical Use Cases

6.1 When SAM 1 Is the Right Choice

  • When fast segmentation on single images is needed
  • Building interactive annotation tools
  • When simple integration into existing pipelines is needed (most mature ecosystem)

6.2 When SAM 2 Is the Right Choice

  • When video object tracking is needed
  • Real-time video stream analysis
  • Scenarios where occlusion handling is critical
  • When faster speeds than SAM 1 are needed for images as well

6.3 When SAM 3 Is the Right Choice

  • When segmenting via natural language search ("find all the cars")
  • Open-vocabulary object detection + segmentation
  • Visual exemplar-based few-shot segmentation
  • Large-scale automatic labeling of images/videos

6.4 Real-World Deployment Examples (SAM 3)

  • Instagram Edits app: Applying dynamic effects to specific people/objects in videos
  • Facebook Marketplace "View in Room": AR furniture placement (SAM 3 + SAM 3D)
  • Wildlife conservation: Camera trap monitoring based on the SA-FARI dataset

7. Study Roadmap

A step-by-step learning guide for deeply understanding and utilizing the SAM series.

7.1 Prerequisites

1. SAM 1 paper (2023)Establish foundational concepts
2. SAM 2 paper (2024)Understand video extension
3. SAM 3 paper (2025)Understand concept awareness
4. Hands-on notebooks from each GitHub repository
StepExerciseDifficulty
1SAM 1 automatic mask generation (Colab notebook)Easy
2SAM 2 video tracking walkthroughIntermediate
3SAM 3 text-prompt segmentationIntermediate
4SAM + Grounding DINO pipeline constructionHard
5Custom dataset fine-tuningHard
6ONNX/TensorRT conversion and edge deploymentAdvanced
ModelCharacteristicsPaper
EfficientSAMLightweight SAM (SAMI distill.)arxiv.org/abs/2312.00863
FastSAMCNN-based real-time SAMarxiv.org/abs/2306.12156
MobileSAMMobile-optimized SAMarxiv.org/abs/2306.14289
Grounded SAMGrounding DINO + SAMgithub.com/IDEA-Research/Grounded-Segment-Anything
SAM-HQHigh-quality mask SAMarxiv.org/abs/2306.01567
SAM 3D3D object/body reconstruction (Meta)ai.meta.com/sam3

8. References

Core Papers

  1. Kirillov, A., Mintun, E., Ravi, N., et al. (2023). "Segment Anything". ICCV 2023. arxiv.org/abs/2304.02643
  2. Ravi, N., Gabeur, V., Hu, Y.-T., et al. (2024). "SAM 2: Segment Anything in Images and Videos". arxiv.org/abs/2408.00714
  3. Carion, N., Gustafson, L., Hu, Y.-T., et al. (2025). "SAM 3: Segment Anything with Concepts". ICLR 2026. arxiv.org/abs/2511.16719

Prerequisite Papers

  1. Dosovitskiy, A., et al. (2021). "An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale". ICLR 2021. arxiv.org/abs/2010.11929
  2. He, K., et al. (2022). "Masked Autoencoders Are Scalable Vision Learners". CVPR 2022. arxiv.org/abs/2111.06377
  3. Carion, N., et al. (2020). "End-to-End Object Detection with Transformers (DETR)". ECCV 2020. arxiv.org/abs/2005.12872
  4. Radford, A., et al. (2021). "Learning Transferable Visual Models From Natural Language Supervision (CLIP)". ICML 2021. arxiv.org/abs/2103.00020
  5. Ryali, C., et al. (2023). "Hiera: A Hierarchical Vision Transformer without the Bells-and-Whistles". ICML 2023. arxiv.org/abs/2306.00989

GitHub Repositories

  1. github.com/facebookresearch/segment-anything — SAM 1
  2. github.com/facebookresearch/sam2 — SAM 2
  3. github.com/facebookresearch/sam3 — SAM 3

Tutorials and Guides

  1. Ultralytics SAM Documentation — docs.ultralytics.com/models/sam
  2. Ultralytics SAM 2 Documentation — docs.ultralytics.com/models/sam-2
  3. Ultralytics SAM 3 Documentation — docs.ultralytics.com/models/sam-3
  4. Encord Blog: Segment Anything Model Explained — encord.com/blog/segment-anything-model-explained
  5. Roboflow: What is SAM 3 — blog.roboflow.com/what-is-sam3
  6. Meta AI Blog: Introducing SAM 3 — ai.meta.com/blog/segment-anything-model-3

Project Pages and Datasets

  1. Meta AI SAM 2 Project — ai.meta.com/sam2
  2. Meta AI SAM 3 Project — ai.meta.com/sam3
  3. SA-1B Dataset — ai.meta.com/datasets/segment-anything
  4. SA-V Dataset — ai.meta.com/datasets/segment-anything-video

Quiz

Q1: What is the main topic covered in "Mastering the Segment Anything Model: Paper Analysis and Practical Guide from SAM 1 to SAM 2 to SAM 3"?

A comprehensive deep dive into Meta AI's Segment Anything Model (SAM) series. Covering SAM 1 (image promptable segmentation), SAM 2 (real-time video segmentation), and SAM 3 (concept-aware segmentation) — including architecture details, datasets, key innovations, performance benc...

Q2: What is SAM 1: Segment Anything (2023)? 2.1 Paper Information Title: Segment Anything Authors: Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao et al.

Q3: Explain the core concept of SAM 2: Segment Anything in Images and Videos (2024).

3.1 Paper Information Title: SAM 2: Segment Anything in Images and Videos Authors: Nikhila Ravi, Valentin Gabeur, Yuan-Ting Hu et al.

Q4: What are the key aspects of SAM 3: Segment Anything with Concepts (2025)? 4.1 Paper Information Title: SAM 3: Segment Anything with Concepts Authors: Nicolas Carion, Laura Gustafson, Yuan-Ting Hu et al.

Q5: How does Comprehensive Comparison of All Three Models work? 5.1 Architecture Comparison 5.2 Dataset Comparison 5.3 Performance Evolution