Split View: Segment Anything Model 완전 정복: SAM 1 → SAM 2 → SAM 3 논문 분석과 실전 가이드
Segment Anything Model 완전 정복: SAM 1 → SAM 2 → SAM 3 논문 분석과 실전 가이드
- 1. 개요: Segment Anything Model의 진화
- 2. SAM 1: Segment Anything (2023)
- 3. SAM 2: Segment Anything in Images and Videos (2024)
- 4. SAM 3: Segment Anything with Concepts (2025)
- 5. 세 모델 비교 종합
- 6. 실전 활용 시나리오
- 7. 공부 로드맵
- 8. References
1. 개요: Segment Anything Model의 진화
**Segment Anything Model(SAM)**은 Meta AI Research가 발표한 이미지·비디오 세그멘테이션 분야의 Foundation Model 시리즈다. NLP 분야에서 GPT가 "프롬프트" 패러다임을 확립한 것처럼, SAM은 Computer Vision 세그멘테이션에 Promptable Segmentation이라는 새로운 패러다임을 도입했다.
| 버전 | 발표 | 핵심 능력 | 논문 |
|---|---|---|---|
| SAM 1 | 2023.04 (ICCV 2023) | 이미지 프롬프터블 세그멘테이션 | Segment Anything |
| SAM 2 | 2024.08 | 이미지 + 비디오 실시간 세그멘테이션 | SAM 2: Segment Anything in Images and Videos |
| SAM 3 | 2025.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 논문 정보
- 제목: Segment Anything
- 저자: Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao 외 (Meta AI Research)
- 발표: 2023년 4월 (arXiv), ICCV 2023 채택
- 논문: arxiv.org/abs/2304.02643
- GitHub: github.com/facebookresearch/segment-anything
- 라이선스: Apache 2.0
2.2 핵심 기여 3가지
SAM 1은 세 가지를 동시에 제안했다.
- 새로운 태스크 — Promptable Segmentation: 포인트, 박스, 마스크, 텍스트 등 임의의 프롬프트가 주어지면 유효한 세그멘테이션 마스크를 반환한다
- 새로운 모델 — SAM: 프롬프트 기반 세그멘테이션을 수행하는 Foundation Model
- 새로운 데이터셋 — 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-B | 91M | ~375 MB |
| ViT-L | 308M | ~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-L | sam_vit_l_0b3195.pth |
| ViT-B | sam_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 논문 정보
- 제목: SAM 2: Segment Anything in Images and Videos
- 저자: Nikhila Ravi, Valentin Gabeur, Yuan-Ting Hu 외 15명 (Meta AI Research)
- 발표: 2024년 8월 (arXiv), 2024년 10월 개정
- 논문: arxiv.org/abs/2408.00714
- GitHub: github.com/facebookresearch/sam2
- 프로젝트 페이지: ai.meta.com/sam2
- 라이선스: Apache 2.0
3.2 SAM 1에서 무엇이 바뀌었나
SAM 2의 핵심 질문: "이미지에서만 되는 세그멘테이션을 비디오로 확장할 수 있을까?"
| 비교 항목 | SAM 1 | SAM 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 Masklet | 642,600개 |
| 총 마스크 수 | 3,550만 개 |
| 해상도 | 240p ~ 4K (평균 1,401×1,037) |
| 평균 길이 | ~14초 |
| 장면 분포 | 실내 54%, 실외 46% |
| 지리적 다양성 | 47개국 |
| 기존 대비 규모 | 비디오 4.5배, 어노테이션 53배 |
Data Engine 3단계:
| 단계 | 방법 | 속도 | 생산량 |
|---|---|---|---|
| Phase 1 | SAM per Frame | 37.8초/프레임 | 16K masklet |
| Phase 2 | SAM + SAM 2 Mask | 7.4초/프레임 (5.1배↑) | 63.5K masklet |
| Phase 3 | Full SAM 2 | 가장 빠름 | 나머지 전부 |
3.5 모델 변형 및 성능
SAM 2.1 (2024년 9월 출시, 최신 권장 버전):
| 모델 | 파라미터 | FPS (A100) | SA-V Test (J&F) | MOSE Val (J&F) |
|---|---|---|---|---|
| sam2.1_hiera_tiny | 38.9M | 91.2 | 76.5 | 71.8 |
| sam2.1_hiera_small | 46.0M | 84.8 | 76.6 | 73.5 |
| sam2.1_hiera_base_plus | 80.8M | 64.1 | 78.2 | 73.7 |
| sam2.1_hiera_large | 224.4M | 39.5 | 79.5 | 74.6 |
주요 벤치마크:
| 벤치마크 | SAM 2 (J&F) | 기존 SOTA 대비 |
|---|---|---|
| MOSE val | 77.9% | +6.2% |
| DAVIS 2017 val | 90.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 논문 정보
- 제목: SAM 3: Segment Anything with Concepts
- 저자: Nicolas Carion, Laura Gustafson, Yuan-Ting Hu 외 35명 (Meta AI Research)
- 발표: 2025년 11월 20일 (arXiv), ICLR 2026 채택
- 논문: arxiv.org/abs/2511.16719
- GitHub: github.com/facebookresearch/sam3
- 프로젝트 페이지: ai.meta.com/sam3
- 라이선스: Apache 2.0
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단계)
| 단계 | 내용 |
|---|---|
| 1 | Perception Encoder 사전학습 |
| 2 | Detector 사전학습 |
| 3 | SA-Co 데이터로 Detector Fine-tuning |
| 4 | 백본 고정(frozen) 후 Tracker 학습 |
4.4 SA-Co 데이터셋
SAM 3는 **SA-Co (Segment Anything with Concepts)**라는 역대 최대·최다양 세그멘테이션 데이터셋으로 학습했다.
학습 데이터
| 서브셋 | 내용 |
|---|---|
| SA-Co/HQ | 520만 고품질 이미지, 400만 고유 명사구, 5,200만 마스크 |
| SA-Co/SYN | 3,800만 합성 문구, 14억 마스크 (대규모 사전학습) |
| SA-Co/VIDEO | 52,500 비디오, 24,800 고유 개념, 467,000+ masklet |
총 온톨로지: 2,200만 엔티티 (17개 상위 카테고리, 72개 하위 카테고리)
평가 벤치마크
| 벤치마크 | 설명 |
|---|---|
| SA-Co/Gold | 7개 다중 검토 이미지 서브셋 (최고 품질) |
| SA-Co/Silver | 10개 도메인 특화 이미지 서브셋 |
| SA-Co/VEval | 3개 비디오 평가 서브셋 |
- 214,000 고유 문구, 126,000 이미지/비디오 → 기존 COCO/LVIS 대비 50배 이상 다양한 개념
추가 공개 데이터셋
- SA-FARI: 10,000+ 야생동물 카메라 트랩 비디오 (100+ 종 어노테이션)
- FathomNet: 해양 이미지 수중 세그멘테이션 벤치마크
4.5 성능 벤치마크
이미지 세그멘테이션 (Zero-Shot)
| 벤치마크 | 메트릭 | SAM 3 | 기존 최고 | 향상 |
|---|---|---|---|---|
| LVIS | Mask AP | 47.0 | 38.5 (T-Rex2) | +22.1% |
| COCO | Box AP | 53.5 | 52.2 | +2.5% |
| SA-Co/Gold | CGF1 | 65.0 | 34.3 | +89.5% (~2배) |
| ODinW | vs T-Rex2 | - | - | +20.1 AP |
비디오 세그멘테이션
| 벤치마크 | SAM 3 (J&F) | SAM 2.1 Large | 향상 |
|---|---|---|---|
| MOSEv2 | 60.1 | 47.9 | +25.5% |
| DAVIS 2017 | 92.0 | 90.7 | +1.4% |
| LVOSv2 | 88.2 | 79.6 | +10.8% |
Exemplar 활용 효과
| 프롬프트 구성 | CGF1 | 텍스트 대비 향상 |
|---|---|---|
| 텍스트만 | 46.4 | - |
| 텍스트 + 1 Exemplar | 57.6 | +11.2 |
| 텍스트 + 3 Exemplar | 65.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 1 | SAM 2 | SAM 3 |
|---|---|---|---|
| 이미지 인코더 | ViT (MAE) | Hiera (MAE) | Meta Perception Encoder |
| 파라미터 | 636M (ViT-H) | 224.4M (Hiera-L) | 848M |
| 프롬프트 | 포인트, 박스, 마스크, 텍스트 | 포인트, 박스, 마스크 | 텍스트, Exemplar, 포인트, 박스, 마스크 |
| 시간 모델링 | 없음 | Memory Attention | Memory + Tracker |
| 검출기 | 없음 | 없음 | DETR 기반 |
| Occlusion | 미지원 | Occlusion Head | Occlusion + Presence Head |
| 출력 | 마스크 + IoU | 마스크 + IoU + Occlusion | 마스크 + 박스 + 점수 + 개념 |
5.2 데이터셋 비교
| 항목 | SA-1B (SAM 1) | SA-V (SAM 2) | SA-Co (SAM 3) |
|---|---|---|---|
| 이미지 | 1,100만 | - | 520만 (HQ) |
| 비디오 | - | 50,900 | 52,500 |
| 마스크 | 11억 | 3,550만 | 14억+ (SYN 포함) |
| 개념/라벨 | 없음 (Class-Agnostic) | 없음 | 2,200만 엔티티 |
| 고유 문구 | - | - | 400만 |
5.3 성능 진화
| 벤치마크 | SAM 1 | SAM 2/2.1 | SAM 3 |
|---|---|---|---|
| DAVIS 2017 (J&F) | N/A | 90.7 | 92.0 |
| MOSE val (J&F) | N/A | 74.6 | 60.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 사전 지식
| 순서 | 주제 | 추천 자료 |
|---|---|---|
| 1 | Vision Transformer (ViT) | An Image is Worth 16x16 Words |
| 2 | MAE (Masked Autoencoder) | Masked Autoencoders Are Scalable Vision Learners |
| 3 | DETR | End-to-End Object Detection with Transformers |
| 4 | CLIP | Learning Transferable Visual Models |
| 5 | Hiera | Hiera: A Hierarchical Vision Transformer without the Bells-and-Whistles |
7.2 핵심 논문 읽기 순서
1. SAM 1 논문 (2023) → 기초 개념 확립
↓
2. SAM 2 논문 (2024) → 비디오 확장 이해
↓
3. SAM 3 논문 (2025) → 개념 인식 이해
↓
4. 각 GitHub 레포의 노트북 실습
7.3 실습 추천
| 단계 | 실습 | 난이도 |
|---|---|---|
| 1 | SAM 1 자동 마스크 생성 (Colab 노트북) | 쉬움 |
| 2 | SAM 2 비디오 추적 실습 | 중간 |
| 3 | SAM 3 텍스트 프롬프트 세그멘테이션 | 중간 |
| 4 | SAM + Grounding DINO 파이프라인 구축 | 어려움 |
| 5 | 커스텀 데이터셋 Fine-tuning | 어려움 |
| 6 | ONNX/TensorRT 변환 및 Edge 배포 | 고급 |
7.4 관련 후속 연구
| 모델 | 특징 | 논문 |
|---|---|---|
| EfficientSAM | 경량화 SAM (SAMI 증류) | arxiv.org/abs/2312.00863 |
| FastSAM | CNN 기반 실시간 SAM | arxiv.org/abs/2306.12156 |
| MobileSAM | 모바일 최적화 SAM | arxiv.org/abs/2306.14289 |
| Grounded SAM | Grounding DINO + SAM | github.com/IDEA-Research/Grounded-Segment-Anything |
| SAM-HQ | 고품질 마스크 SAM | arxiv.org/abs/2306.01567 |
| SAM 3D | 3D 객체/인체 복원 (Meta) | ai.meta.com/sam3 |
8. References
핵심 논문
- Kirillov, A., Mintun, E., Ravi, N., et al. (2023). "Segment Anything". ICCV 2023. arxiv.org/abs/2304.02643
- Ravi, N., Gabeur, V., Hu, Y.-T., et al. (2024). "SAM 2: Segment Anything in Images and Videos". arxiv.org/abs/2408.00714
- Carion, N., Gustafson, L., Hu, Y.-T., et al. (2025). "SAM 3: Segment Anything with Concepts". ICLR 2026. arxiv.org/abs/2511.16719
사전 지식 논문
- Dosovitskiy, A., et al. (2021). "An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale". ICLR 2021. arxiv.org/abs/2010.11929
- He, K., et al. (2022). "Masked Autoencoders Are Scalable Vision Learners". CVPR 2022. arxiv.org/abs/2111.06377
- Carion, N., et al. (2020). "End-to-End Object Detection with Transformers (DETR)". ECCV 2020. arxiv.org/abs/2005.12872
- Radford, A., et al. (2021). "Learning Transferable Visual Models From Natural Language Supervision (CLIP)". ICML 2021. arxiv.org/abs/2103.00020
- Ryali, C., et al. (2023). "Hiera: A Hierarchical Vision Transformer without the Bells-and-Whistles". ICML 2023. arxiv.org/abs/2306.00989
GitHub 저장소
- github.com/facebookresearch/segment-anything — SAM 1
- github.com/facebookresearch/sam2 — SAM 2
- github.com/facebookresearch/sam3 — SAM 3
해설 및 튜토리얼
- Ultralytics SAM Documentation — docs.ultralytics.com/models/sam
- Ultralytics SAM 2 Documentation — docs.ultralytics.com/models/sam-2
- Ultralytics SAM 3 Documentation — docs.ultralytics.com/models/sam-3
- Encord Blog: Segment Anything Model Explained — encord.com/blog/segment-anything-model-explained
- Roboflow: What is SAM 3 — blog.roboflow.com/what-is-sam3
- Meta AI Blog: Introducing SAM 3 — ai.meta.com/blog/segment-anything-model-3
프로젝트 페이지 및 데이터셋
- Meta AI SAM 2 Project — ai.meta.com/sam2
- Meta AI SAM 3 Project — ai.meta.com/sam3
- SA-1B Dataset — ai.meta.com/datasets/segment-anything
- 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
- 2. SAM 1: Segment Anything (2023)
- 3. SAM 2: Segment Anything in Images and Videos (2024)
- 4. SAM 3: Segment Anything with Concepts (2025)
- 5. Comprehensive Comparison of All Three Models
- 6. Practical Use Cases
- 7. Study Roadmap
- 8. References
- Quiz
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.
| Version | Released | Core Capability | Paper |
|---|---|---|---|
| SAM 1 | 2023.04 (ICCV 2023) | Image promptable segmentation | Segment Anything |
| SAM 2 | 2024.08 | Image + real-time video segmentation | SAM 2: Segment Anything in Images and Videos |
| SAM 3 | 2025.11 (ICLR 2026) | Concept-aware segmentation | SAM 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
- Title: Segment Anything
- Authors: Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao et al. (Meta AI Research)
- Published: April 2023 (arXiv), accepted at ICCV 2023
- Paper: arxiv.org/abs/2304.02643
- GitHub: github.com/facebookresearch/segment-anything
- License: Apache 2.0
2.2 Three Key Contributions
SAM 1 simultaneously introduced three things:
- A new task — Promptable Segmentation: Given any prompt (point, box, mask, or text), the model returns a valid segmentation mask
- A new model — SAM: A foundation model for prompt-based segmentation
- 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
| Variant | Parameters | Checkpoint Size |
|---|---|---|
| ViT-B | 91M | ~375 MB |
| ViT-L | 308M | ~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
| Item | Value |
|---|---|
| Images | 11 million |
| Masks | 1.1 billion (~100 per image on average) |
| Auto-generated | 99.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:
| Model | File |
|---|---|
| ViT-H (default) | sam_vit_h_4b8939.pth |
| ViT-L | sam_vit_l_0b3195.pth |
| ViT-B | sam_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
- Title: SAM 2: Segment Anything in Images and Videos
- Authors: Nikhila Ravi, Valentin Gabeur, Yuan-Ting Hu et al. (15 authors, Meta AI Research)
- Published: August 2024 (arXiv), revised October 2024
- Paper: arxiv.org/abs/2408.00714
- GitHub: github.com/facebookresearch/sam2
- Project page: ai.meta.com/sam2
- License: Apache 2.0
3.2 What Changed from SAM 1
The core question behind SAM 2: "Can we extend image-only segmentation to video?"
| Comparison | SAM 1 | SAM 2 |
|---|---|---|
| Input | Single image | Image + video |
| Image encoder | ViT (MAE pretrained) | Hiera (hierarchical, MAE pretrained) |
| Temporal modeling | None | Memory Attention mechanism |
| Inference speed | ~50ms per prompt | 6x faster on images |
| Occlusion handling | Not supported | Occlusion Head |
| Interaction | Prompts on images | Prompts 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
| Item | Value |
|---|---|
| Videos | 50,900 |
| Total duration | ~196 hours |
| Total frames | ~4.2 million |
| Spatio-temporal masklets | 642,600 |
| Total masks | 35.5 million |
| Resolution | 240p to 4K (average 1,401×1,037) |
| Average length | ~14 seconds |
| Scene distribution | Indoor 54%, Outdoor 46% |
| Geographic diversity | 47 countries |
| Scale vs. existing | 4.5x more video, 53x more annotations |
3-Phase Data Engine:
| Phase | Method | Speed | Output |
|---|---|---|---|
| Phase 1 | SAM per Frame | 37.8 sec/frame | 16K masklets |
| Phase 2 | SAM + SAM 2 Mask | 7.4 sec/frame (5.1x faster) | 63.5K masklets |
| Phase 3 | Full SAM 2 | Fastest | All remaining |
3.5 Model Variants and Performance
SAM 2.1 (released September 2024, latest recommended version):
| Model | Parameters | FPS (A100) | SA-V Test (J&F) | MOSE Val (J&F) |
|---|---|---|---|---|
| sam2.1_hiera_tiny | 38.9M | 91.2 | 76.5 | 71.8 |
| sam2.1_hiera_small | 46.0M | 84.8 | 76.6 | 73.5 |
| sam2.1_hiera_base_plus | 80.8M | 64.1 | 78.2 | 73.7 |
| sam2.1_hiera_large | 224.4M | 39.5 | 79.5 | 74.6 |
Key benchmarks:
| Benchmark | SAM 2 (J&F) | vs. Previous SOTA |
|---|---|---|
| MOSE val | 77.9% | +6.2% |
| DAVIS 2017 val | 90.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
- Title: SAM 3: Segment Anything with Concepts
- Authors: Nicolas Carion, Laura Gustafson, Yuan-Ting Hu et al. (35 authors, Meta AI Research)
- Published: November 20, 2025 (arXiv), accepted at ICLR 2026
- Paper: arxiv.org/abs/2511.16719
- GitHub: github.com/facebookresearch/sam3
- Project page: ai.meta.com/sam3
- License: Apache 2.0
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:
| Configuration | CGF1 |
|---|---|
| Without Presence Head | 57.6 |
| With Presence Head | 63.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)
| Stage | Description |
|---|---|
| 1 | Perception Encoder pretraining |
| 2 | Detector pretraining |
| 3 | Detector fine-tuning with SA-Co data |
| 4 | Backbone 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
| Subset | Contents |
|---|---|
| SA-Co/HQ | 5.2M high-quality images, 4M unique noun phrases, 52M masks |
| SA-Co/SYN | 38M synthetic phrases, 1.4 billion masks (large-scale pretraining) |
| SA-Co/VIDEO | 52,500 videos, 24,800 unique concepts, 467,000+ masklets |
Total ontology: 22 million entities (17 top-level categories, 72 subcategories)
Evaluation Benchmarks
| Benchmark | Description |
|---|---|
| SA-Co/Gold | 7 multi-review image subsets (highest quality) |
| SA-Co/Silver | 10 domain-specific image subsets |
| SA-Co/VEval | 3 video evaluation subsets |
- 214,000 unique phrases, 126,000 images/videos — over 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)
| Benchmark | Metric | SAM 3 | Previous Best | Improvement |
|---|---|---|---|---|
| LVIS | Mask AP | 47.0 | 38.5 (T-Rex2) | +22.1% |
| COCO | Box AP | 53.5 | 52.2 | +2.5% |
| SA-Co/Gold | CGF1 | 65.0 | 34.3 | +89.5% (~2x) |
| ODinW | vs T-Rex2 | - | - | +20.1 AP |
Video Segmentation
| Benchmark | SAM 3 (J&F) | SAM 2.1 Large | Improvement |
|---|---|---|---|
| MOSEv2 | 60.1 | 47.9 | +25.5% |
| DAVIS 2017 | 92.0 | 90.7 | +1.4% |
| LVOSv2 | 88.2 | 79.6 | +10.8% |
Exemplar Utilization Effect
| Prompt Configuration | CGF1 | Improvement over Text Only |
|---|---|---|
| Text only | 46.4 | - |
| Text + 1 exemplar | 57.6 | +11.2 |
| Text + 3 exemplars | 65.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
| Item | SAM 1 | SAM 2 | SAM 3 |
|---|---|---|---|
| Image encoder | ViT (MAE) | Hiera (MAE) | Meta Perception Encoder |
| Parameters | 636M (ViT-H) | 224.4M (Hiera-L) | 848M |
| Prompts | Point, box, mask, text | Point, box, mask | Text, exemplar, point, box, mask |
| Temporal model | None | Memory Attention | Memory + Tracker |
| Detector | None | None | DETR-based |
| Occlusion | Not supported | Occlusion Head | Occlusion + Presence Head |
| Output | Mask + IoU | Mask + IoU + Occlusion | Mask + box + score + concept |
5.2 Dataset Comparison
| Item | SA-1B (SAM 1) | SA-V (SAM 2) | SA-Co (SAM 3) |
|---|---|---|---|
| Images | 11M | - | 5.2M (HQ) |
| Videos | - | 50,900 | 52,500 |
| Masks | 1.1B | 35.5M | 1.4B+ (incl. SYN) |
| Concepts/Labels | None (class-agnostic) | None | 22M entities |
| Unique phrases | - | - | 4M |
5.3 Performance Evolution
| Benchmark | SAM 1 | SAM 2/2.1 | SAM 3 |
|---|---|---|---|
| DAVIS 2017 (J&F) | N/A | 90.7 | 92.0 |
| MOSE val (J&F) | N/A | 74.6 | 60.1 (MOSEv2, different benchmark) |
| Image speed | Baseline | 6x faster | ~30ms/image |
| Zero-shot ability | Geometric | Geometric + temporal | Concept-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
| Order | Topic | Recommended Reading |
|---|---|---|
| 1 | Vision Transformer (ViT) | An Image is Worth 16x16 Words |
| 2 | MAE (Masked Autoencoder) | Masked Autoencoders Are Scalable Vision Learners |
| 3 | DETR | End-to-End Object Detection with Transformers |
| 4 | CLIP | Learning Transferable Visual Models |
| 5 | Hiera | Hiera: A Hierarchical Vision Transformer without the Bells-and-Whistles |
7.2 Recommended Paper Reading Order
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
7.3 Recommended Hands-On Exercises
| Step | Exercise | Difficulty |
|---|---|---|
| 1 | SAM 1 automatic mask generation (Colab notebook) | Easy |
| 2 | SAM 2 video tracking walkthrough | Intermediate |
| 3 | SAM 3 text-prompt segmentation | Intermediate |
| 4 | SAM + Grounding DINO pipeline construction | Hard |
| 5 | Custom dataset fine-tuning | Hard |
| 6 | ONNX/TensorRT conversion and edge deployment | Advanced |
7.4 Related Follow-Up Research
| Model | Characteristics | Paper |
|---|---|---|
| EfficientSAM | Lightweight SAM (SAMI distill.) | arxiv.org/abs/2312.00863 |
| FastSAM | CNN-based real-time SAM | arxiv.org/abs/2306.12156 |
| MobileSAM | Mobile-optimized SAM | arxiv.org/abs/2306.14289 |
| Grounded SAM | Grounding DINO + SAM | github.com/IDEA-Research/Grounded-Segment-Anything |
| SAM-HQ | High-quality mask SAM | arxiv.org/abs/2306.01567 |
| SAM 3D | 3D object/body reconstruction (Meta) | ai.meta.com/sam3 |
8. References
Core Papers
- Kirillov, A., Mintun, E., Ravi, N., et al. (2023). "Segment Anything". ICCV 2023. arxiv.org/abs/2304.02643
- Ravi, N., Gabeur, V., Hu, Y.-T., et al. (2024). "SAM 2: Segment Anything in Images and Videos". arxiv.org/abs/2408.00714
- 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
- Dosovitskiy, A., et al. (2021). "An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale". ICLR 2021. arxiv.org/abs/2010.11929
- He, K., et al. (2022). "Masked Autoencoders Are Scalable Vision Learners". CVPR 2022. arxiv.org/abs/2111.06377
- Carion, N., et al. (2020). "End-to-End Object Detection with Transformers (DETR)". ECCV 2020. arxiv.org/abs/2005.12872
- Radford, A., et al. (2021). "Learning Transferable Visual Models From Natural Language Supervision (CLIP)". ICML 2021. arxiv.org/abs/2103.00020
- Ryali, C., et al. (2023). "Hiera: A Hierarchical Vision Transformer without the Bells-and-Whistles". ICML 2023. arxiv.org/abs/2306.00989
GitHub Repositories
- github.com/facebookresearch/segment-anything — SAM 1
- github.com/facebookresearch/sam2 — SAM 2
- github.com/facebookresearch/sam3 — SAM 3
Tutorials and Guides
- Ultralytics SAM Documentation — docs.ultralytics.com/models/sam
- Ultralytics SAM 2 Documentation — docs.ultralytics.com/models/sam-2
- Ultralytics SAM 3 Documentation — docs.ultralytics.com/models/sam-3
- Encord Blog: Segment Anything Model Explained — encord.com/blog/segment-anything-model-explained
- Roboflow: What is SAM 3 — blog.roboflow.com/what-is-sam3
- Meta AI Blog: Introducing SAM 3 — ai.meta.com/blog/segment-anything-model-3
Project Pages and Datasets
- Meta AI SAM 2 Project — ai.meta.com/sam2
- Meta AI SAM 3 Project — ai.meta.com/sam3
- SA-1B Dataset — ai.meta.com/datasets/segment-anything
- 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