SAM 3.1 Release (#503)

Summary:
SAM 3.1 multiplex video tracking for the OSS sam3 repository.

Features:
- Multiplex architecture: batch N objects into fixed-capacity buckets for efficient multi-object tracking (16 objects per bucket)
- Unified API: build_sam3_predictor(version="sam3.1") with auto-download from HuggingFace (facebook/sam3.1)
- Flash Attention 3, torch.compile support (~31 FPS compiled on H100)
- Text prompts, point prompts, box prompts, object removal, refinement
- Clean inheritance: Sam3MultiplexBase extends Sam3VideoBase
- Shared base predictor (Sam3BasePredictor) for both SAM3 and SAM3.1

Performance (H100, 5 objects, compiled):
- SAM 3.1: ~31 FPS
- Memory: ~17.7 GB

Usage:
  from sam3 import build_sam3_predictor predictor = build_sam3_predictor()  # auto-downloads SAM 3.1 from HF

Pull Request resolved: https://github.com/facebookresearch/sam3/pull/503

Reviewed By: josephgreer

Differential Revision: D98500763

Pulled By: arpitkalla

fbshipit-source-id: e2b74568f24bb4ecfb3144a4e8ec559aae6db5e8
This commit is contained in:
Arpit Kalla
2026-03-27 10:18:58 -07:00
committed by meta-codesync[bot]
parent 86ed770940
commit 9f22cb976f
79 changed files with 20772 additions and 792 deletions
+3 -3
View File
@@ -243,9 +243,9 @@ def download_sav():
def main():
assert len(sys.argv) > 1, "You have to provide the name of the dataset"
dataset_name = sys.argv[1]
assert dataset_name in annotation_files, (
f"The dataset can be one of {list(annotation_files.keys())}"
)
assert (
dataset_name in annotation_files
), f"The dataset can be one of {list(annotation_files.keys())}"
if dataset_name == "yt1b":
download_youtube()
+3 -3
View File
@@ -68,9 +68,9 @@ def process_image(args):
def main():
assert len(sys.argv) > 1, "You have to provide the name of the dataset"
dataset_name = sys.argv[1]
assert dataset_name in annotation_files, (
f"The dataset can be one of {list(annotation_files.keys())}"
)
assert (
dataset_name in annotation_files
), f"The dataset can be one of {list(annotation_files.keys())}"
all_outputs = []
for file in annotation_files[dataset_name]:
with open(os.path.join(config["path_annotations"], file), "r") as f:
@@ -58,9 +58,9 @@ class YtVideoPrep:
df = self.yt1b_start_end_time_df[
self.yt1b_start_end_time_df.saco_yt1b_id == self.saco_yt1b_id
]
assert len(df) == 1, (
f"Expected exactly 1 row for saco_yt1b_id: {self.saco_yt1b_id}, found {len(df)}"
)
assert (
len(df) == 1
), f"Expected exactly 1 row for saco_yt1b_id: {self.saco_yt1b_id}, found {len(df)}"
id_and_frame_map_row = df.iloc[0]
yt_video_id = (
@@ -82,9 +82,9 @@ class YtVideoPrep:
def download_youtube_video(self):
video_url = f"https://youtube.com/watch?v={self.yt_video_id}"
assert os.path.exists(self.cookies_file), (
f"Cookies file '{self.cookies_file}' not found. Must have it to download videos."
)
assert os.path.exists(
self.cookies_file
), f"Cookies file '{self.cookies_file}' not found. Must have it to download videos."
outtmpl = self.raw_video_path
+304
View File
@@ -0,0 +1,304 @@
"""
SAM3 Speed Test — supports both SAM3 and SAM3.1 (multiplex).
Generates synthetic video with moving circles, runs text-prompt detection
+ propagation, and measures FPS. Checkpoints are auto-downloaded from
HuggingFace if not provided.
Usage:
# SAM 3.1 (default, auto-downloads from HuggingFace):
python scripts/measure_speed.py
# SAM 3 (non-multiplex):
python scripts/measure_speed.py --version sam3
# Custom settings:
python scripts/measure_speed.py --num_objects 32 --n_frames 100 --no-compile
python scripts/measure_speed.py --version sam3.1 --compile --num_objects 5
"""
import argparse
import getpass
import os
import shutil
import time
import numpy as np
import torch
from PIL import Image, ImageDraw
def max_memory_allocated():
max_memory_allocated_bytes = torch.cuda.max_memory_allocated()
_, total_memory = torch.cuda.mem_get_info()
max_memory_allocated_percentage = int(
100 * (max_memory_allocated_bytes / total_memory)
)
max_memory_allocated_bytes = max_memory_allocated_bytes >> 20
print(
f"max_memory_allocated_bytes: {max_memory_allocated_bytes}MiB or {max_memory_allocated_percentage}%"
)
def synthesize_video_data(
num_objects: int,
out_dir: str,
radius: int,
speed: int,
width: int,
height: int,
n_frames: int,
):
circle_colors = [
tuple(np.random.randint(0, 256, size=3).tolist()) for _ in range(num_objects)
]
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
os.makedirs(out_dir, exist_ok=True)
positions = []
velocities = []
for _ in range(num_objects):
px = float(np.random.randint(radius, width - radius))
py = float(np.random.randint(radius, height - radius))
vx = np.random.choice([-1, 1]) * speed
vy = np.random.choice([-1, 1]) * speed
positions.append([px, py])
velocities.append([vx, vy])
print(f"Generate {n_frames} frames with {num_objects} objects")
for i in range(n_frames):
img = Image.new("RGB", (width, height), (0, 0, 0))
draw = ImageDraw.Draw(img)
for obj_idx in range(num_objects):
x, y = positions[obj_idx]
rx, ry = round(x), round(y)
draw.ellipse(
[(rx - radius, ry - radius), (rx + radius, ry + radius)],
fill=circle_colors[obj_idx],
)
vx, vy = velocities[obj_idx]
x += vx
y += vy
positions[obj_idx] = [
np.clip(x, radius, width - radius),
np.clip(y, radius, height - radius),
]
if x - radius < 0 or x + radius > width:
vx *= -1
if y - radius < 0 or y + radius > height:
vy *= -1
velocities[obj_idx] = [vx, vy]
img.save(os.path.join(out_dir, f"{i:03d}.jpg"))
def profiler_runner(fn, profile_save_dir=None, profile_end_frame=-1, *args, **kwargs):
if profile_save_dir is None:
profile_save_dir = os.path.expanduser("~/traces")
os.environ["ENABLE_PROFILING"] = "1"
os.environ["PROFILE_SAVE_DIR"] = profile_save_dir
if profile_end_frame >= 0:
os.environ["PROFILE_END_FRAME"] = str(profile_end_frame)
print(f"Profiling enabled. Traces will be saved to: {profile_save_dir}")
if profile_end_frame >= 0:
print(f"Profiling will stop at frame: {profile_end_frame}")
try:
result = fn(*args, **kwargs)
finally:
os.environ.pop("ENABLE_PROFILING", None)
os.environ.pop("PROFILE_SAVE_DIR", None)
os.environ.pop("PROFILE_END_FRAME", None)
return result
def main_loop(model_wrapper, session_id, text_prompt):
model_wrapper.handle_request({"type": "reset_session", "session_id": session_id})
model_wrapper.handle_request(
{
"type": "add_prompt",
"session_id": session_id,
"frame_index": 0,
"text": text_prompt,
}
)
t0 = time.perf_counter()
frame_count = 0
for _response in model_wrapper.handle_stream_request(
{"type": "propagate_in_video", "session_id": session_id}
):
frame_count += 1
torch.cuda.synchronize()
t1 = time.perf_counter()
if frame_count > 0:
return frame_count / (t1 - t0)
return -1
def run_test(
version: str,
profile: bool,
video_dir: str,
num_objects: int,
radius: int,
speed: int,
width: int,
height: int,
n_frames: int,
synthesize_data: bool = True,
profile_save_dir: str = None,
profile_end_frame: int = -1,
do_compile: bool = True,
checkpoint_path: str = None,
) -> float:
torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__()
if synthesize_data:
synthesize_video_data(
num_objects=num_objects,
out_dir=video_dir,
radius=radius,
speed=speed,
width=width,
height=height,
n_frames=n_frames,
)
from sam3 import build_sam3_predictor
print(f"Building {version} model...")
build_kwargs = dict(
version=version,
compile=do_compile,
async_loading_frames=False,
)
if checkpoint_path:
build_kwargs["checkpoint_path"] = checkpoint_path
if version == "sam3.1":
build_kwargs["warm_up"] = do_compile
build_kwargs["max_num_objects"] = num_objects
model_wrapper = build_sam3_predictor(**build_kwargs)
# Initialize session
response = model_wrapper.handle_request(
{"type": "start_session", "resource_path": video_dir}
)
session_id = response["session_id"]
print("\nWarm-up round.")
NUM_WARMUP_TRIES = 3
fps = 0
for _ in range(NUM_WARMUP_TRIES):
fps = max(
main_loop(
model_wrapper=model_wrapper, session_id=session_id, text_prompt="circle"
),
fps,
)
print("\nProfile round.")
if profile:
profiler_runner(
main_loop,
profile_save_dir=profile_save_dir or os.path.expanduser("~/traces"),
profile_end_frame=profile_end_frame,
model_wrapper=model_wrapper,
session_id=session_id,
text_prompt="circle",
)
else:
fps = max(
main_loop(
model_wrapper=model_wrapper, session_id=session_id, text_prompt="circle"
),
fps,
)
NUM_TRIES = 10
for i in range(NUM_TRIES):
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats()
print(f"\nTiming round {i + 1} ")
fps = max(
main_loop(
model_wrapper=model_wrapper, session_id=session_id, text_prompt="circle"
),
fps,
)
print(f"Frames per second (FPS): {fps:.2f}")
max_memory_allocated()
if synthesize_data:
print("\nDeleting temporary video directory.")
shutil.rmtree(video_dir)
return fps
if __name__ == "__main__":
username = getpass.getuser()
os.environ["TORCHINDUCTOR_CACHE_DIR"] = f"/tmp/torchinductor_cache_{username}"
os.environ["USE_PERFLIB"] = "1"
parser = argparse.ArgumentParser(description="SAM3 Speed Test")
parser.add_argument(
"--version",
type=str,
default="sam3.1",
choices=["sam3", "sam3.1"],
help="Model version (default: sam3.1)",
)
parser.add_argument(
"--checkpoint",
type=str,
default=None,
help="Path to checkpoint (auto-downloads from HuggingFace if not provided)",
)
parser.add_argument(
"--video_dir", type=str, default="/tmp/segment-anything-3/synth_video"
)
parser.add_argument("--num_objects", type=int, default=5)
parser.add_argument("--n_frames", type=int, default=50)
parser.add_argument("--radius", type=int, default=50)
parser.add_argument("--speed", type=int, default=20)
parser.add_argument("--width", type=int, default=1024)
parser.add_argument("--height", type=int, default=1024)
parser.add_argument(
"--no-compile",
action="store_false",
dest="compile",
help="Disable torch.compile",
)
parser.add_argument("--no-torch-profiling", action="store_false", dest="profile")
parser.add_argument(
"--no-data-synthesis", action="store_false", dest="synthesize_data"
)
parser.add_argument("--profile-save-dir", type=str, default=None)
parser.add_argument("--profile-end-frame", type=int, default=-1)
args = parser.parse_args()
run_test(
version=args.version,
profile=args.profile,
num_objects=args.num_objects,
video_dir=args.video_dir,
radius=args.radius,
speed=args.speed,
width=args.width,
height=args.height,
n_frames=args.n_frames,
synthesize_data=args.synthesize_data,
profile_save_dir=args.profile_save_dir,
profile_end_frame=args.profile_end_frame,
do_compile=args.compile,
checkpoint_path=args.checkpoint,
)
+312
View File
@@ -0,0 +1,312 @@
"""
SAM3 Qualitative Test — supports both SAM3 and SAM3.1.
Tests text prompt detection + propagation on a synthetic video.
Checkpoints are auto-downloaded from HuggingFace.
Usage:
python scripts/qualitative_test.py # SAM 3.1 default
python scripts/qualitative_test.py --version sam3 # SAM 3
python scripts/qualitative_test.py --video /path/to/video.mp4
"""
import argparse
import getpass
import os
import shutil
import cv2
import matplotlib
import numpy as np
import torch
from PIL import Image as PIL_Image, ImageDraw
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from PIL import Image as PIL_Image, ImageDraw
OUTPUT_DIR = "/tmp/sam3_qualitative_test"
MASK_COLORS = [
(255, 0, 0),
(0, 255, 0),
(0, 0, 255),
(255, 255, 0),
(255, 0, 255),
(0, 255, 255),
(255, 128, 0),
(128, 0, 255),
(0, 128, 255),
(255, 64, 128),
(128, 255, 0),
(64, 128, 255),
(255, 200, 0),
(0, 200, 128),
(200, 0, 128),
(128, 128, 255),
(255, 128, 128),
(128, 255, 128),
(128, 128, 0),
(0, 128, 128),
]
def extract_frames(video_path, output_dir):
if os.path.exists(output_dir) and len(os.listdir(output_dir)) > 0:
n = len([f for f in os.listdir(output_dir) if f.endswith(".jpg")])
print(f"Using existing {n} frames in {output_dir}")
return n
if os.path.exists(output_dir):
shutil.rmtree(output_dir)
os.makedirs(output_dir)
cap = cv2.VideoCapture(video_path)
idx = 0
while True:
ret, frame = cap.read()
if not ret:
break
cv2.imwrite(os.path.join(output_dir, f"{idx:05d}.jpg"), frame)
idx += 1
cap.release()
print(f"Extracted {idx} frames to {output_dir}")
return idx
def synthesize_video(out_dir, num_objects=5, n_frames=30, width=1024, height=1024):
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
os.makedirs(out_dir)
colors = [
tuple(np.random.randint(0, 256, size=3).tolist()) for _ in range(num_objects)
]
positions = [
[
float(np.random.randint(80, width - 80)),
float(np.random.randint(80, height - 80)),
]
for _ in range(num_objects)
]
velocities = [
[np.random.choice([-1, 1]) * 15, np.random.choice([-1, 1]) * 15]
for _ in range(num_objects)
]
for i in range(n_frames):
img = PIL_Image.new("RGB", (width, height), (0, 0, 0))
draw = ImageDraw.Draw(img)
for j in range(num_objects):
x, y = positions[j]
draw.ellipse([(x - 50, y - 50), (x + 50, y + 50)], fill=colors[j])
vx, vy = velocities[j]
positions[j] = [
np.clip(x + vx, 50, width - 50),
np.clip(y + vy, 50, height - 50),
]
if x < 50 or x > width - 50:
velocities[j][0] *= -1
if y < 50 or y > height - 50:
velocities[j][1] *= -1
img.save(os.path.join(out_dir, f"{i:05d}.jpg"))
print(f"Generated {n_frames} synthetic frames with {num_objects} circles")
return n_frames
def load_frame(frame_dir, frame_idx):
return cv2.cvtColor(
cv2.imread(os.path.join(frame_dir, f"{frame_idx:05d}.jpg")),
cv2.COLOR_BGR2RGB,
)
def render_overlay(frame_rgb, masks_by_obj, alpha=0.4):
overlay = frame_rgb.copy().astype(np.float32)
for obj_id, mask in sorted(masks_by_obj.items()):
color = MASK_COLORS[obj_id % len(MASK_COLORS)]
mask_bool = mask.astype(bool)
for c in range(3):
overlay[:, :, c] = np.where(
mask_bool,
overlay[:, :, c] * (1 - alpha) + color[c] * alpha,
overlay[:, :, c],
)
return overlay.astype(np.uint8)
def save_overlay(frame_rgb, masks_by_obj, output_path, title=None):
overlay = render_overlay(frame_rgb, masks_by_obj)
fig, ax = plt.subplots(1, 1, figsize=(12, 7), dpi=100)
ax.imshow(overlay)
for obj_id, mask in sorted(masks_by_obj.items()):
mask_bool = mask.astype(bool)
if mask_bool.any():
ys, xs = np.where(mask_bool)
cx, cy = int(xs.mean()), int(ys.mean())
color_rgb = MASK_COLORS[obj_id % len(MASK_COLORS)]
facecolor = (color_rgb[0] / 255, color_rgb[1] / 255, color_rgb[2] / 255)
ax.text(
cx,
cy,
str(obj_id),
color="white",
fontsize=10,
ha="center",
va="center",
fontweight="bold",
bbox=dict(boxstyle="round,pad=0.2", facecolor=facecolor, alpha=0.8),
)
if title:
ax.set_title(title, fontsize=12, fontweight="bold", pad=8)
ax.axis("off")
fig.tight_layout(pad=0)
fig.savefig(output_path, bbox_inches="tight", pad_inches=0)
plt.close(fig)
def collect_propagation(model, session_id):
mask_dict = {}
for response in model.handle_stream_request(
{"type": "propagate_in_video", "session_id": session_id}
):
frame_idx = response.get("frame_index")
if frame_idx is None:
continue
outputs = response.get("outputs", {})
obj_ids = outputs.get("out_obj_ids", [])
binary_masks = outputs.get("out_binary_masks")
if binary_masks is None:
mask_dict[frame_idx] = {}
continue
if isinstance(obj_ids, torch.Tensor):
obj_ids = obj_ids.cpu().numpy()
if isinstance(binary_masks, torch.Tensor):
binary_masks = binary_masks.cpu().numpy()
masks = {}
for i, oid in enumerate(obj_ids):
m = binary_masks[i]
if m.ndim == 3:
m = m[0]
masks[int(oid)] = m
mask_dict[frame_idx] = masks
torch.cuda.synchronize()
return mask_dict
def main():
parser = argparse.ArgumentParser(description="SAM3 Qualitative Test")
parser.add_argument(
"--version", type=str, default="sam3.1", choices=["sam3", "sam3.1"]
)
parser.add_argument(
"--video",
type=str,
default=None,
help="Path to video file. If not provided, generates synthetic video.",
)
parser.add_argument(
"--checkpoint",
type=str,
default=None,
help="Path to checkpoint (auto-downloads from HuggingFace if not provided)",
)
parser.add_argument(
"--text_prompt", type=str, default="circle", help="Text prompt for detection"
)
parser.add_argument(
"--n_frames", type=int, default=30, help="Number of frames for synthetic video"
)
args = parser.parse_args()
username = getpass.getuser()
os.environ["TORCHINDUCTOR_CACHE_DIR"] = f"/tmp/torchinductor_cache_{username}"
os.environ["USE_PERFLIB"] = "1"
torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__()
# Prepare video frames
frame_dir = "/tmp/sam3_qualitative_frames"
if args.video:
n_frames = extract_frames(args.video, frame_dir)
else:
n_frames = synthesize_video(frame_dir, n_frames=args.n_frames)
img = load_frame(frame_dir, 0)
img_h, img_w = img.shape[:2]
print(f"Video: {img_w}x{img_h}, {n_frames} frames")
# Build model
from sam3 import build_sam3_predictor
print(f"\nBuilding {args.version} model...")
build_kwargs = dict(version=args.version, compile=False, async_loading_frames=False)
if args.checkpoint:
build_kwargs["checkpoint_path"] = args.checkpoint
model = build_sam3_predictor(**build_kwargs)
# Start session
response = model.handle_request(
{"type": "start_session", "resource_path": frame_dir}
)
session_id = response["session_id"]
print(f"Session: {session_id}")
# Test: text prompt -> propagate
out_dir = os.path.join(OUTPUT_DIR, f"{args.version}_text_{args.text_prompt}")
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
os.makedirs(out_dir)
print(f"\nTest: text prompt '{args.text_prompt}' -> propagate")
model.handle_request(
{
"type": "add_prompt",
"session_id": session_id,
"frame_index": 0,
"text": args.text_prompt,
}
)
mask_dict = collect_propagation(model, session_id)
print(f"Propagated through {len(mask_dict)} frames")
# Save overlays
saved = 0
for frame_idx in sorted(mask_dict.keys()):
if frame_idx % 5 != 0:
continue
masks = mask_dict[frame_idx]
if not masks:
continue
frame_rgb = load_frame(frame_dir, frame_idx)
save_overlay(
frame_rgb,
masks,
os.path.join(out_dir, f"frame_{frame_idx:05d}.png"),
title=f"{args.version} | frame {frame_idx} | {len(masks)} objects",
)
saved += 1
# Print results
frame0 = mask_dict.get(0, {})
print(f"\nDetected {len(frame0)} objects on frame 0:")
for obj_id, mask in sorted(frame0.items()):
mask_bool = mask.astype(bool)
n_pixels = int(mask_bool.sum())
if mask_bool.any():
ys, xs = np.where(mask_bool)
print(
f" obj {obj_id}: centroid ({int(xs.mean())}, {int(ys.mean())}), {n_pixels} pixels"
)
print(f"\nSaved {saved} overlay images to {out_dir}")
print(
"QUALITATIVE TEST PASSED"
if len(frame0) > 0
else "WARNING: No objects detected!"
)
# Cleanup
if not args.video:
shutil.rmtree(frame_dir)
if __name__ == "__main__":
main()