SAM 3 ONNX
ONNX builds of SAM 3, made by Moonbox for on-device use with ONNX Runtime (CPU, CUDA, DirectML). Each
precision is one folder holding the graphs and a small Python pipeline.py that does the rest (image preprocessing,
prompt coordinates, mask upsampling); what the graphs take and return is under How to run.
Files
The last column is the benchmark against the original PyTorch model (details under How to run): IoU of every predicted mask with the original's on the same pictures and prompts.
| Precision | File | Size | sha256 | Benchmark |
|---|---|---|---|---|
| fp16 | fp16/box_decoder.onnx |
0.3 MB | bf9f20ff610b |
ViT fp16 weights / fp32 math, text encoder fp16, heads fp32: worst mask IoU 0.986 / 0.989 (detection / SAM decoder; mean 0.9995 / 0.999), scores within 0.026 of the reference (float32 graphs: 0.990 / 0.991, 0.016); 0.76 s per photo (CUDA) |
| fp16 | fp16/box_decoder.onnx.data |
16.8 MB | 79ff6c6b5708 |
(the same build: numbers in its first row) |
| fp16 | fp16/detector.onnx |
0.9 MB | 4d76db0133b4 |
(the same build: numbers in its first row) |
| fp16 | fp16/detector.onnx.data |
95.8 MB | 1548fc0dbae3 |
(the same build: numbers in its first row) |
| fp16 | fp16/geometry_cls.onnx |
52.9 kB | e29e62d3e388 |
(the same build: numbers in its first row) |
| fp16 | fp16/geometry_cls.onnx.data |
19.2 MB | aa79b4d8c891 |
(the same build: numbers in its first row) |
| fp16 | fp16/geometry_encoder.onnx |
0.2 MB | 0147419c1105 |
(the same build: numbers in its first row) |
| fp16 | fp16/geometry_encoder.onnx.data |
32.3 MB | 5cbbc6a6e9c4 |
(the same build: numbers in its first row) |
| fp16 | fp16/pipeline.py |
9.6 kB | 96ae13c5476a |
(the same build: numbers in its first row) |
| fp16 | fp16/point_decoder.onnx |
0.3 MB | e17b71d628d0 |
(the same build: numbers in its first row) |
| fp16 | fp16/point_decoder.onnx.data |
16.8 MB | 261cd4d48a5e |
(the same build: numbers in its first row) |
| fp16 | fp16/processor_config.json |
1.7 kB | 6420cf2671fa |
(the same build: numbers in its first row) |
| fp16 | fp16/special_tokens_map.json |
0.6 kB | 2cdb3b8331a6 |
(the same build: numbers in its first row) |
| fp16 | fp16/text_encoder.onnx |
707.0 MB | 4f66b8f3b965 |
(the same build: numbers in its first row) |
| fp16 | fp16/tokenizer.json |
3.6 MB | 6d9109cc8389 |
(the same build: numbers in its first row) |
| fp16 | fp16/tokenizer_config.json |
0.8 kB | 39670ad98457 |
(the same build: numbers in its first row) |
| fp16 | fp16/vision_encoder.onnx |
941.2 MB | 8d10551f4d66 |
(the same build: numbers in its first row) |
How to run
SAM 3 (Meta's promptable concept segmentation model, image use) as seven ONNX graphs plus pipeline.py, a numpy
runtime around them that follows transformers' Sam3Processor / Sam3TrackerProcessor + Sam3Model /
Sam3TrackerModel (with Meta's own behaviour in the two places where transformers 5.23 differs, below). Three ways to
prompt an image:
- text ("yellow school bus"): every instance of the concept, each with a score, a box and a mask;
- exemplar boxes (with or without text): more objects like the boxed one(s); positive or negative boxes;
- points or a box for one object (SAM 1 / 2 style): the tracker's SAM decoder, 3 candidate masks for a point, 1 for a box.
Not included: video. Neither SAM 3's video model (per-frame detection, association, memory) nor point tracking through a video is converted; only the single-image paths.
The graphs (fixed 1008 x 1008 input):
vision_encoder.onnx:pixel_values[1, 3, 1008, 1008] -> the detector's feature mapsfpn_0[1, 256, 288, 288],fpn_1[1, 256, 144, 144],fpn_2[1, 256, 72, 72] and the SAM decoder'sfeat_s0[1, 32, 288, 288],feat_s1[1, 64, 144, 144],image_embed[1, 256, 72, 72]. The ViT (32 layers, 1024 wide) runs once for both; run it once per image.text_encoder.onnx:input_ids,attention_mask[B, 32] ->text_features[B, 32, 256].geometry_encoder.onnx:fpn_2,boxes[1, N, 4] (cx, cy, w, h in 0..1),box_labels[1, N] (1 positive, 0 negative) ->geometry_features[1, N + 1, 256] (the boxes and the encoder's CLS token).geometry_cls.onnx:fpn_2->cls_features[1, 1, 256], the geometry encoder with no boxes.detector.onnx:fpn_0..2,prompt_features[1, T, 256] (the text features, then the geometry features),prompt_mask[1, T] (bool, True = valid) ->pred_masks[1, 200, 288, 288] (logits),pred_boxes[1, 200, 4] (x0, y0, x1, y1 in 0..1),pred_logits[1, 200],presence_logits[1, 1],semantic_seg[1, 1, 288, 288].point_decoder.onnx:feat_s0,feat_s1,image_embed,points[1, 1, N, 2] (1008-pixel coordinates),labels[1, 1, N] (1 foreground, 0 background) ->masks[1, 1, 3, 288, 288] (logits),iou[1, 1, 3],object_score[1, 1, 1].box_decoder.onnx: the three maps,boxes[1, 1, 4] (1008-pixel x0, y0, x1, y1) ->masks[1, 1, 1, 288, 288],iou,object_score(one mask, the model's dynamic multimask choice by stability).
pipeline.py resizes the image to 1008 x 1008 (bilinear) and normalises it to [-1, 1], tokenizes the text with the
CLIP BPE tokenizer in tokenizer.json (32 tokens, through the tokenizers package) and puts the graphs together. It
needs numpy, onnxruntime (or onnxruntime-gpu), Pillow and tokenizers:
import sys, numpy as np
from PIL import Image
sys.path.insert(0, "fp16")
import pipeline
sam = pipeline.SAM3("fp16", "cuda")
maps, size = sam.embed(np.array(Image.open("photo.jpg").convert("RGB"))) # once per image
scores, boxes, masks = sam.detect(maps, size, text="person") # every person: [K], [K, 4], [K, H, W]
scores, boxes, masks = sam.detect(maps, size, boxes=[[120, 80, 300, 560]]) # objects like the boxed one
masks3, iou = sam.point(maps, size, [[410, 300]]) # one object: 3 masks [3, H, W]
mask, iou = sam.box(maps, size, [120, 80, 700, 560]) # one object: 1 mask [H, W]
Memory: on CUDA the pipeline settles at about 6 GB (the vision encoder's fp32 weights and its 5184-token attention; measured as the process's commit on Windows). It frees each graph's GPU scratch memory after the run (ONNX Runtime's arena shrinkage), without which the seven sessions' arenas added up to over 12 GB.
Detection keeps the queries scoring above 0.5 (threshold=): score = sigmoid(logit) x sigmoid(presence logit), the
presence head saying whether the concept is in the image at all. Masks: sigmoid, bilinear to the image size, > 0.5.
The pipeline resizes with Pillow; the transformers processors resize uint8 tensors with torchvision, which can differ
by a level here and there. Feed their pixel_values to vision_encoder.onnx where exact agreement with transformers
matters.
Where these follow Meta's code rather than transformers. (1) Meta's Sam3Image always runs the geometry
encoder, so a text-only prompt is the text tokens followed by the encoder's CLS token (geometry_cls.onnx);
transformers' Sam3Model leaves the token out when there are no boxes. (2) Meta adds the tracker's no_mem_embed to
the 72 x 72 image embedding before the SAM decoder; transformers' Sam3TrackerModel adds it to a fourth (36 x 36)
feature level that it then drops. On SAM 3.1, whose checkpoint Meta's own code can run here, the CLS token moved the
transformers result from Meta's by up to 1.4 in the presence logit; with it the two agree (see the SAM 3.1 repository).
Precision. fp16/: the vision encoder stores its weights in fp16 and computes in fp32 (ONNX Runtime turns them
back into fp32 when it loads, so it uses fp32's memory, 1.8 GB on the GPU); the text encoder is fp16 throughout; the
geometry encoders, the detector and the SAM decoders (200 MB) are fp32. Measured alternatives that failed the
benchmark: every graph in fp16 (detection scores off by up to 0.47), fp16 arithmetic in the ViT (one mask at IoU
0.90, 0.86 with LayerNorm and Softmax kept in fp32), weight-only int8 in the ViT and text encoder (scores off by 0.32;
int8 in the text encoder alone: 0.07), 4-bit MatMulNBits (scores off by 0.49, worst mask IoU 0.29).
Benchmark. The first sixteen photos of the lab's DIS5K-250 set, each with: a text prompt written from looking at
the photo ("person", "headphones", "metal pipe", "bicycle", "chair", "staircase", ...), the ground-truth box as an
exemplar (text "visual"), a positive point (the ground-truth foreground pixel nearest its centroid; 3 masks) and the
ground-truth box for the SAM decoder (1 mask). The reference is transformers' Sam3Model / Sam3TrackerModel in
float32 on the CPU with Meta's two behaviours above; reference and builds get the processors' pixel_values, tokens
and coordinates (the conversion measured alone). Detection: every query the reference keeps (score > 0.5) gives a
mask compared with the build's mask of the same query, and all 200 query scores of each prompt are compared. SAM
decoder: the 3 point masks and the box mask (logits bilinear to 1008 and then to the photo, > 0). Pass: mask IoU at
least 0.95 on every mask and every score within 0.05 of the reference's. Time: vision encoder + text encoder +
detector for one photo and one text prompt on an RTX 3080 Laptop GPU (CUDA).
| worst mask IoU (detection / SAM decoder) | mean mask IoU | largest score difference | seconds per photo | |
|---|---|---|---|---|
| ONNX graphs in float32 (not published) | 0.990 / 0.991 | 0.9996 / 0.9989 | 0.016 | 0.78 |
fp16/ (CUDA) |
0.986 / 0.989 | 0.9995 / 0.9990 | 0.026 | 0.76 |
49 detection masks (32 prompts) and 64 SAM-decoder masks; no query crosses the 0.5 score threshold in either build.
With the geometry encoder's CLS token (Meta's behaviour) the reference keeps fewer detections than transformers'
Sam3Model on four of the sixteen text prompts (e.g. "staircase" 1 instead of 3).
License. SAM License (Meta, November 19, 2025), copied in this repository (LICENSE): use, copying,
modification and redistribution are allowed, commercial use included, but only under the same agreement, passing a
copy of it on with the files; publications that use SAM must acknowledge it; use must comply with the law and with
trade controls (not by sanctioned parties), and is not allowed for military or warfare purposes, nuclear
applications, espionage, or guns and illegal weapons (ITAR end uses), nor in ways that encourage reverse engineering
of SAM. No warranty; the license ends for anyone who sues Meta claiming SAM infringes their intellectual property.
How these were made
From SAM 3 at revision 3c879f3982. The graphs were exported from the original PyTorch modules with
torch.onnx (opset 17 / 18) and checked against them. Weight-only quantization: int8 is a per-output-channel int8
weight behind DequantizeLinear, int4 is ONNX Runtime's MatMulNBits (block 32). Each card above says which precision
every graph uses. Every precision was benchmarked against the original before upload (pass: IoU at least 0.95 on every
mask, otherwise marked below threshold), and the sha256 column above is what the files must hash to.
License
SAM License (custom, gated). These files are a derivative of the original model and carry its license: it is copied in this repository, and it governs your use of these files. The original model card follows unchanged.
Original model card
SAM 3 is a unified foundation model for promptable segmentation in images and videos. It can detect, segment, and track objects using text or visual prompts such as points, boxes, and masks. Compared to its predecessor SAM 2, SAM 3 introduces the ability to exhaustively segment all instances of an open-vocabulary concept specified by a short text phrase or exemplars. Unlike prior work, SAM 3 can handle a vastly larger set of open-vocabulary prompts. It achieves 75-80% of human performance on our new SA-CO benchmark which contains 270K unique concepts, over 50 times more than existing benchmarks.
Basic Usage
import torch
#################################### For Image ####################################
from PIL import Image
from sam3.model_builder import build_sam3_image_model
from sam3.model.sam3_image_processor import Sam3Processor
# Load the model
model = build_sam3_image_model()
processor = Sam3Processor(model)
# Load an image
image = Image.open("<YOUR_IMAGE_PATH.jpg>")
inference_state = processor.set_image(image)
# Prompt the model with text
output = processor.set_text_prompt(state=inference_state, prompt="<YOUR_TEXT_PROMPT>")
# Get the masks, bounding boxes, and scores
masks, boxes, scores = output["masks"], output["boxes"], output["scores"]
#################################### For Video ####################################
from sam3.model_builder import build_sam3_video_predictor
video_predictor = build_sam3_video_predictor()
video_path = "<YOUR_VIDEO_PATH>" # a JPEG folder or an MP4 video file
# Start a session
response = video_predictor.handle_request(
request=dict(
type="start_session",
resource_path=video_path,
)
)
response = video_predictor.handle_request(
request=dict(
type="add_prompt",
session_id=response["session_id"],
frame_index=0, # Arbitrary frame index
text="<YOUR_TEXT_PROMPT>",
)
)
output = response["outputs"]
The official code is publicly released in the sam3 repo.
Usage with ๐ค Transformers
SAM3 - Promptable Concept Segmentation (PCS) for Images
SAM3 performs Promptable Concept Segmentation (PCS) on images, taking text and/or image exemplars as prompts and returning segmentation masks for all matching object instances in the image.
Text-Only Prompts
>>> from transformers import Sam3Processor, Sam3Model
>>> import torch
>>> from PIL import Image
>>> import requests
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> model = Sam3Model.from_pretrained("facebook/sam3").to(device)
>>> processor = Sam3Processor.from_pretrained("facebook/sam3")
>>> # Load image
>>> image_url = "http://images.cocodataset.org/val2017/000000077595.jpg"
>>> image = Image.open(requests.get(image_url, stream=True).raw).convert("RGB")
>>> # Segment using text prompt
>>> inputs = processor(images=image, text="ear", return_tensors="pt").to(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # Post-process results
>>> results = processor.post_process_instance_segmentation(
... outputs,
... threshold=0.5,
... mask_threshold=0.5,
... target_sizes=inputs.get("original_sizes").tolist()
... )[0]
>>> print(f"Found {len(results['masks'])} objects")
>>> # Results contain:
>>> # - masks: Binary masks resized to original image size
>>> # - boxes: Bounding boxes in absolute pixel coordinates (xyxy format)
>>> # - scores: Confidence scores
You can display masks using a simple helper like the following:
import numpy as np
import matplotlib
def overlay_masks(image, masks):
image = image.convert("RGBA")
masks = 255 * masks.cpu().numpy().astype(np.uint8)
n_masks = masks.shape[0]
cmap = matplotlib.colormaps.get_cmap("rainbow").resampled(n_masks)
colors = [
tuple(int(c * 255) for c in cmap(i)[:3])
for i in range(n_masks)
]
for mask, color in zip(masks, colors):
mask = Image.fromarray(mask)
overlay = Image.new("RGBA", image.size, color + (0,))
alpha = mask.point(lambda v: int(v * 0.5))
overlay.putalpha(alpha)
image = Image.alpha_composite(image, overlay)
return image
Then you can save the resulting composite image or display it in a notebook:
>>> overlay_masks(image, results["masks"])
Single Bounding Box Prompt
Segment objects using a bounding box:
>>> # Box in xyxy format: [x1, y1, x2, y2] in pixel coordinates
>>> # Example: laptop region
>>> box_xyxy = [100, 150, 500, 450]
>>> input_boxes = [[box_xyxy]] # [batch, num_boxes, 4]
>>> input_boxes_labels = [[1]] # 1 = positive box
>>> inputs = processor(
... images=image,
... input_boxes=input_boxes,
... input_boxes_labels=input_boxes_labels,
... return_tensors="pt"
... ).to(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # Post-process results
>>> results = processor.post_process_instance_segmentation(
... outputs,
... threshold=0.5,
... mask_threshold=0.5,
... target_sizes=inputs.get("original_sizes").tolist()
... )[0]
Multiple Box Prompts (Positive and Negative)
Use multiple boxes with positive and negative labels to refine the concept:
>>> # Load kitchen image
>>> kitchen_url = "http://images.cocodataset.org/val2017/000000136466.jpg"
>>> kitchen_image = Image.open(requests.get(kitchen_url, stream=True).raw).convert("RGB")
>>> # Define two positive boxes (e.g., dial and button on oven)
>>> # Boxes are in xyxy format [x1, y1, x2, y2] in pixel coordinates
>>> box1_xyxy = [59, 144, 76, 163] # Dial box
>>> box2_xyxy = [87, 148, 104, 159] # Button box
>>> input_boxes = [[box1_xyxy, box2_xyxy]]
>>> input_boxes_labels = [[1, 1]] # Both positive
>>> inputs = processor(
... images=kitchen_image,
... input_boxes=input_boxes,
... input_boxes_labels=input_boxes_labels,
... return_tensors="pt"
... ).to(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # Post-process results
>>> results = processor.post_process_instance_segmentation(
... outputs,
... threshold=0.5,
... mask_threshold=0.5,
... target_sizes=inputs.get("original_sizes").tolist()
... )[0]
>>> overlay_masks(kitchen_image, results["masks"])
Combined Prompts (Text + Negative Box)
Use text prompts with negative visual prompts to refine the concept:
>>> # Segment "handle" but exclude the oven handle using a negative box
>>> text = "handle"
>>> # Negative box covering oven handle area (xyxy): [40, 183, 318, 204]
>>> oven_handle_box = [40, 183, 318, 204]
>>> input_boxes = [[oven_handle_box]]
>>> inputs = processor(
... images=kitchen_image,
... text=text,
... input_boxes=input_boxes,
... input_boxes_labels=[[0]], # 0 = negative (exclude this region)
... return_tensors="pt"
... ).to(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # Post-process results
>>> results = processor.post_process_instance_segmentation(
... outputs,
... threshold=0.5,
... mask_threshold=0.5,
... target_sizes=inputs.get("original_sizes").tolist()
... )[0]
>>> # This will segment pot handles but exclude the oven handle
Batched Inference with Text Prompts
Process multiple images with different text prompts by batch:
>>> cat_url = "http://images.cocodataset.org/val2017/000000077595.jpg"
>>> kitchen_url = "http://images.cocodataset.org/val2017/000000136466.jpg"
>>> images = [
... Image.open(requests.get(cat_url, stream=True).raw).convert("RGB"),
... Image.open(requests.get(kitchen_url, stream=True).raw).convert("RGB")
... ]
>>> text_prompts = ["ear", "dial"]
>>> inputs = processor(images=images, text=text_prompts, return_tensors="pt").to(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # Post-process results for both images
>>> results = processor.post_process_instance_segmentation(
... outputs,
... threshold=0.5,
... mask_threshold=0.5,
... target_sizes=inputs.get("original_sizes").tolist()
... )
>>> print(f"Image 1: {len(results[0]['masks'])} objects found")
>>> print(f"Image 2: {len(results[1]['masks'])} objects found")
Batched Mixed Prompts
Use different prompt types for different images in the same batch:
>>> # Image 1: text prompt "laptop"
>>> # Image 2: visual prompt (dial box)
>>> box2_xyxy = [59, 144, 76, 163]
>>> inputs = processor(
... images=images,
... text=["laptop", None], # Only first image has text
... input_boxes=[None, [box2_xyxy]], # Only second image has box
... input_boxes_labels=[None, [1]], # Positive box for second image
... return_tensors="pt"
... ).to(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # Post-process results for both images
>>> results = processor.post_process_instance_segmentation(
... outputs,
... threshold=0.5,
... mask_threshold=0.5,
... target_sizes=inputs.get("original_sizes").tolist()
... )
>>> # Both images processed in single forward pass
Semantic Segmentation Output
SAM3 also provides semantic segmentation alongside instance masks:
>>> inputs = processor(images=image, text="ear", return_tensors="pt").to(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # Instance segmentation masks
>>> instance_masks = torch.sigmoid(outputs.pred_masks) # [batch, num_queries, H, W]
>>> # Semantic segmentation (single channel)
>>> semantic_seg = outputs.semantic_seg # [batch, 1, H, W]
>>> print(f"Instance masks: {instance_masks.shape}")
>>> print(f"Semantic segmentation: {semantic_seg.shape}")
SAM3 Video - Promptable Concept Segmentation (PCS) for Videos
SAM3 Video performs Promptable Concept Segmentation (PCS) on videos, taking text as prompts and detecting and tracking all matching object instances across video frames.
Pre-loaded Video Inference
Process a video with all frames already available using text prompts:
>>> from transformers import Sam3VideoModel, Sam3VideoProcessor
>>> from accelerate import Accelerator
>>> import torch
>>> device = Accelerator().device
>>> model = Sam3VideoModel.from_pretrained("facebook/sam3").to(device, dtype=torch.bfloat16)
>>> processor = Sam3VideoProcessor.from_pretrained("facebook/sam3")
>>> # Load video frames
>>> from transformers.video_utils import load_video
>>> video_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/bedroom.mp4"
>>> video_frames, _ = load_video(video_url)
>>> # Initialize video inference session
>>> inference_session = processor.init_video_session(
... video=video_frames,
... inference_device=device,
... processing_device="cpu",
... video_storage_device="cpu",
... dtype=torch.bfloat16,
... )
>>> # Add text prompt to detect and track objects
>>> text = "person"
>>> inference_session = processor.add_text_prompt(
... inference_session=inference_session,
... text=text,
... )
>>> # Process all frames in the video
>>> outputs_per_frame = {}
>>> for model_outputs in model.propagate_in_video_iterator(
... inference_session=inference_session, max_frame_num_to_track=50
... ):
... processed_outputs = processor.postprocess_outputs(inference_session, model_outputs)
... outputs_per_frame[model_outputs.frame_idx] = processed_outputs
>>> print(f"Processed {len(outputs_per_frame)} frames")
Processed 51 frames
>>> # Access results for a specific frame
>>> frame_0_outputs = outputs_per_frame[0]
>>> print(f"Detected {len(frame_0_outputs['object_ids'])} objects")
>>> print(f"Object IDs: {frame_0_outputs['object_ids'].tolist()}")
>>> print(f"Scores: {frame_0_outputs['scores'].tolist()}")
>>> print(f"Boxes shape (XYXY format, absolute coordinates): {frame_0_outputs['boxes'].shape}")
>>> print(f"Masks shape: {frame_0_outputs['masks'].shape}")
Streaming Video Inference
For real-time applications, the Transformers implementation of SAM3 Video supports processing video frames as they arrive:
>>> # Initialize session for streaming
>>> streaming_inference_session = processor.init_video_session(
... inference_device=device,
... processing_device="cpu",
... video_storage_device="cpu",
... dtype=torch.bfloat16,
... )
>>> # Add text prompt
>>> text = "person"
>>> streaming_inference_session = processor.add_text_prompt(
... inference_session=streaming_inference_session,
... text=text,
... )
>>> # Process frames one by one (streaming mode)
>>> streaming_outputs_per_frame = {}
>>> for frame_idx, frame in enumerate(video_frames[:50]): # Process first 50 frames
... # First, process the frame using the processor
... inputs = processor(images=frame, device=device, return_tensors="pt")
...
... # Process frame using streaming inference - pass the processed pixel_values
... model_outputs = model(
... inference_session=streaming_inference_session,
... frame=inputs.pixel_values[0], # Provide processed frame - this enables streaming mode
... reverse=False,
... )
...
... # Post-process outputs with original_sizes for proper resolution handling
... processed_outputs = processor.postprocess_outputs(
... streaming_inference_session,
... model_outputs,
... original_sizes=inputs.original_sizes, # Required for streaming inference
... )
... streaming_outputs_per_frame[frame_idx] = processed_outputs
...
... if (frame_idx + 1) % 10 == 0:
... print(f"Processed {frame_idx + 1} frames...")
>>> print(f"โ Streaming inference complete! Processed {len(streaming_outputs_per_frame)} frames")
โ Streaming inference complete! Processed 50 frames
>>> # Access results
>>> frame_0_outputs = streaming_outputs_per_frame[0]
>>> print(f"Detected {len(frame_0_outputs['object_ids'])} objects in first frame")
>>> print(f"Boxes are in XYXY format (absolute pixel coordinates): {frame_0_outputs['boxes'].shape}")
>>> print(f"Masks are at original video resolution: {frame_0_outputs['masks'].shape}")
SAM3 Tracker - Promptable Visual Segmentation (PVS) for Images
Sam3Tracker performs Promptable Visual Segmentation (PVS) on images, taking interactive visual prompts (points, boxes, masks) to segment a specific object instance per prompt. It is an updated version of SAM2 that maintains the same API while providing improved performance, making it a drop-in replacement for SAM2 workflows.
Automatic Mask Generation with Pipeline
>>> from transformers import pipeline
>>> generator = pipeline("mask-generation", model="facebook/sam3", device=0)
>>> image_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg"
>>> outputs = generator(image_url, points_per_batch=64)
>>> len(outputs["masks"]) # Number of masks generated
Basic Image Segmentation
Single Point Click
>>> from transformers import Sam3TrackerProcessor, Sam3TrackerModel
>>> from accelerate import Accelerator
>>> import torch
>>> from PIL import Image
>>> import requests
>>> device = Accelerator().device
>>> model = Sam3TrackerModel.from_pretrained("facebook/sam3").to(device)
>>> processor = Sam3TrackerProcessor.from_pretrained("facebook/sam3")
>>> image_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg"
>>> raw_image = Image.open(requests.get(image_url, stream=True).raw).convert("RGB")
>>> input_points = [[[[500, 375]]]] # Single point click, 4 dimensions (image_dim, object_dim, point_per_object_dim, coordinates)
>>> input_labels = [[[1]]] # 1 for positive click, 0 for negative click, 3 dimensions (image_dim, object_dim, point_label)
>>> inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
>>> # The model outputs multiple mask predictions ranked by quality score
>>> print(f"Generated {masks.shape[1]} masks with shape {masks.shape}")
Multiple Points for Refinement
>>> # Add both positive and negative points to refine the mask
>>> input_points = [[[[500, 375], [1125, 625]]]] # Multiple points for refinement
>>> input_labels = [[[1, 1]]] # Both positive clicks
>>> inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
Bounding Box Input
>>> # Define bounding box as [x_min, y_min, x_max, y_max]
>>> input_boxes = [[[75, 275, 1725, 850]]]
>>> inputs = processor(images=raw_image, input_boxes=input_boxes, return_tensors="pt").to(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
Multiple Objects Segmentation
>>> # Define points for two different objects
>>> input_points = [[[[500, 375]], [[650, 750]]]] # Points for two objects in same image
>>> input_labels = [[[1], [1]]] # Positive clicks for both objects
>>> inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)
>>> with torch.no_grad():
... outputs = model(**inputs, multimask_output=False)
>>> # Each object gets its own mask
>>> masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
>>> print(f"Generated masks for {masks.shape[0]} objects")
Generated masks for 2 objects
Batch Inference
>>> # Load multiple images
>>> image_urls = [
... "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg",
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/dog-sam.png"
... ]
>>> raw_images = [Image.open(requests.get(url, stream=True).raw).convert("RGB") for url in image_urls]
>>> # Single point per image
>>> input_points = [[[[500, 375]]], [[[770, 200]]]] # One point for each image
>>> input_labels = [[[1]], [[1]]] # Positive clicks for both images
>>> inputs = processor(images=raw_images, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)
>>> with torch.no_grad():
... outputs = model(**inputs, multimask_output=False)
>>> # Post-process masks for each image
>>> all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])
>>> print(f"Processed {len(all_masks)} images, each with {all_masks[0].shape[0]} objects")
SAM3 Tracker Video - Promptable Visual Segmentation (PVS) for Videos
Sam3TrackerVideo performs Promptable Visual Segmentation (PVS) on videos, taking interactive visual prompts (points, boxes, masks) to track a specific object instance per prompt across video frames. It is an updated version of SAM2 Video that maintains the same API while providing improved performance, making it a drop-in replacement for SAM2 Video workflows.
Basic Video Tracking
>>> from transformers import Sam3TrackerVideoModel, Sam3TrackerVideoProcessor
>>> from accelerate import Accelerator
>>> import torch
>>> device = Accelerator().device
>>> model = Sam3TrackerVideoModel.from_pretrained("facebook/sam3").to(device, dtype=torch.bfloat16)
>>> processor = Sam3TrackerVideoProcessor.from_pretrained("facebook/sam3")
>>> # Load video frames
>>> from transformers.video_utils import load_video
>>> video_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/bedroom.mp4"
>>> video_frames, _ = load_video(video_url)
>>> # Initialize video inference session
>>> inference_session = processor.init_video_session(
... video=video_frames,
... inference_device=device,
... dtype=torch.bfloat16,
... )
>>> # Add click on first frame to select object
>>> ann_frame_idx = 0
>>> ann_obj_id = 1
>>> points = [[[[210, 350]]]]
>>> labels = [[[1]]]
>>> processor.add_inputs_to_inference_session(
... inference_session=inference_session,
... frame_idx=ann_frame_idx,
... obj_ids=ann_obj_id,
... input_points=points,
... input_labels=labels,
... )
>>> # Segment the object on the first frame (optional, you can also propagate the masks through the video directly)
>>> outputs = model(
... inference_session=inference_session,
... frame_idx=ann_frame_idx,
... )
>>> video_res_masks = processor.post_process_masks(
... [outputs.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
... )[0]
>>> print(f"Segmentation shape: {video_res_masks.shape}")
Segmentation shape: torch.Size([1, 1, 480, 854])
>>> # Propagate through the entire video
>>> video_segments = {}
>>> for sam3_tracker_video_output in model.propagate_in_video_iterator(inference_session):
... video_res_masks = processor.post_process_masks(
... [sam3_tracker_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
... )[0]
... video_segments[sam3_tracker_video_output.frame_idx] = video_res_masks
>>> print(f"Tracked object through {len(video_segments)} frames")
Tracked object through 180 frames
Multi-Object Video Tracking
Track multiple objects simultaneously across video frames:
>>> # Reset for new tracking session
>>> inference_session.reset_inference_session()
>>> # Add multiple objects on the first frame
>>> ann_frame_idx = 0
>>> obj_ids = [2, 3]
>>> input_points = [[[[200, 300]], [[400, 150]]]] # Points for two objects (batched)
>>> input_labels = [[[1], [1]]]
>>> processor.add_inputs_to_inference_session(
... inference_session=inference_session,
... frame_idx=ann_frame_idx,
... obj_ids=obj_ids,
... input_points=input_points,
... input_labels=input_labels,
... )
>>> # Get masks for both objects on first frame (optional, you can also propagate the masks through the video directly)
>>> outputs = model(
... inference_session=inference_session,
... frame_idx=ann_frame_idx,
... )
>>> # Propagate both objects through video
>>> video_segments = {}
>>> for sam3_tracker_video_output in model.propagate_in_video_iterator(inference_session):
... video_res_masks = processor.post_process_masks(
... [sam3_tracker_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
... )[0]
... video_segments[sam3_tracker_video_output.frame_idx] = {
... obj_id: video_res_masks[i]
... for i, obj_id in enumerate(inference_session.obj_ids)
... }
>>> print(f"Tracked {len(inference_session.obj_ids)} objects through {len(video_segments)} frames")
Tracked 2 objects through 180 frames
Streaming Video Inference
For real-time applications, Sam3TrackerVideo supports processing video frames as they arrive:
>>> # Initialize session for streaming
>>> inference_session = processor.init_video_session(
... inference_device=device,
... dtype=torch.bfloat16,
... )
>>> # Process frames one by one
>>> for frame_idx, frame in enumerate(video_frames[:10]): # Process first 10 frames
... inputs = processor(images=frame, device=device, return_tensors="pt")
...
... if frame_idx == 0:
... # Add point input on first frame
... processor.add_inputs_to_inference_session(
... inference_session=inference_session,
... frame_idx=0,
... obj_ids=1,
... input_points=[[[[210, 350], [250, 220]]]],
... input_labels=[[[1, 1]]],
... original_size=inputs.original_sizes[0], # need to be provided when using streaming video inference
... )
...
... # Process current frame
... sam3_tracker_video_output = model(inference_session=inference_session, frame=inputs.pixel_values[0])
...
... video_res_masks = processor.post_process_masks(
... [sam3_tracker_video_output.pred_masks], original_sizes=inputs.original_sizes, binarize=False
... )[0]
... print(f"Frame {frame_idx}: mask shape {video_res_masks.shape}")
Model tree for moonbox-dev/sam3-ONNX
Base model
facebook/sam3