Fix · SAM 3 / 3.1 · GPU memory
SAM CUDA Out of Memory: Causes and Fixes Why Meta SAM runs out of GPU memory, which part of the job is using it, and memory-reduction approaches with the evidence behind each, from measured results to documented settings.
Step 1
Read the Error Message
PyTorch tells you how much it wanted and where the memory already is.
example error (your numbers will differ)
| Part | What it tells you |
|---|---|
| Tried to allocate | The single step that failed. Huge (GBs)? Usually output masks or a batch of frames. |
| Total capacity | Your GPU. Other apps (browser, games, another notebook) share it. |
| Allocated by PyTorch | What SAM is holding: weights, frames, object memory, results. |
| Reserved but unallocated | Large? Fragmentation. Set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True before starting Python. |
Check what else is on the GPU with nvidia-smi. Restart notebook kernels that hold old models.
Step 2
Where SAM’s GPU Memory Goes
Five things compete for memory. Images mostly use the first two; video uses all five.
- Model weights: fixed; halved by bfloat16.
- Activations: working memory during a forward pass; grows with batch size and input resolution.
- Video frames: every decoded frame, if stored on the GPU.
- Object memory: the tracker’s memory and state for every object in a session.
- Output masks: full-resolution masks for every object; easy to overlook, and can be gigabytes.
Step 3
Memory-Reduction Approaches, Ranked
Start at the top. Each row says what it saves, what it costs, and what evidence backs it.
Measured results reported from real runs · Documented in official docs or code · Standard general PyTorch practice
| Approach | Saves | Costs | Evidence |
|---|---|---|---|
| Run in bfloat16 | Weights + activations, roughly half | Tiny precision loss | Documented Transformers SAM 3 video examples run in bfloat16 |
| Masks to CPU as bool, straight away | Up to GBs with many objects | Nothing noticeable | Standard see the calculator |
| One prompt / class at a time | Large for multi-class runs | No joint tracking across prompts | Measured under 10 GB vs 29+ GB for official batched multi-class (RTX 3080 10 GB) |
| Video frames and processing on CPU | All stored frames | Small speed loss | Documented video_storage_device="cpu", processing_device="cpu" |
| Offload tracker state to CPU | Object memory | A few FPS | Measured by Meta for SAM 2: 27 → 24 FPS, one object, 768 px |
| Lower internal resolution (e.g. 560) | Activations + features | Less detail on small objects | Documented Transformers config.image_size |
| Chunk long videos, close sessions | Stops growth with length | Re-prompt per chunk; IDs restart | Standard |
| Split across two GPUs | Per-GPU load | Needs two GPUs | Measured ~4 GB each to load; 6–7 GB each on 400–500-frame sequences |
| Upgrade to SAM 3.1 (video) | Multi-object tracking cost | Upgrade work | Documented Meta: reduces overall GPU requirements |
expandable_segments:True | Fragmentation waste | None | Documented PyTorch allocator setting |
Evidence
What Others Measured
Published numbers from real runs. Setups differ, so treat them as ballpark figures and confirm on your hardware.
| Setup | Reported memory | Source |
|---|---|---|
| SAM 3, single image | Just under 4 GB peak | Third-party hands-on test on an RTX 6000 (48 GB) |
| SAM 3 multi-class image and video, one class per loop | Under 10 GB | Tutorial on an RTX 3080 10 GB; official batched multi-class path needed 29+ GB |
| SAM 3 split over 2× RTX 4090, 419 and 506 frames | ~4 GB per GPU to load; 5.4–7.2 GB per GPU while running | Research paper (3D reconstruction pipeline) |
| SAM 2 video, state offloaded to CPU | Lower VRAM; FPS 27 → 24 (1 object), 24 → 21 (2 objects) | Comment in Meta’s SAM 2 video predictor code |
We haven’t run these on our own hardware. They come from the sources described, and your numbers will vary with GPU, drivers, resolution and clip length. Use the measuring script to get yours.
Images
Fixes for Image Out-of-Memory
Single images rarely need much. Problems come from many prompts at once, many objects, or keeping results on the GPU.
- bfloat16 +
inference_mode: load once, no gradients. - Masks off the GPU: convert to
boolon CPU the moment you have them. - One prompt at a time instead of many classes in one batch.
- Huge photos: the model resizes internally, but full-size output masks don’t; save them per object.
- Batch jobs: drop references between images; use
empty_cache()between jobs, not every step.
images · Transformers
import torch
from PIL import Image
from transformers import Sam3Processor, Sam3Model
# 1) load once, in bfloat16
model = Sam3Model.from_pretrained("facebook/sam3", dtype=torch.bfloat16).to("cuda").eval()
processor = Sam3Processor.from_pretrained("facebook/sam3")
def segment(path, prompt):
image = Image.open(path).convert("RGB")
inputs = processor(images=image, text=prompt, return_tensors="pt").to("cuda", torch.bfloat16)
with torch.inference_mode(): # 2) no autograd buffers
outputs = model(**inputs)
r = processor.post_process_instance_segmentation(
outputs, threshold=0.5, mask_threshold=0.5,
target_sizes=inputs.get("original_sizes").tolist())[0]
masks = r["masks"].to("cpu", torch.bool) # 3) masks off the GPU, 1 byte per pixel
scores = r["scores"].float().cpu()
del inputs, outputs, r # 4) drop GPU references before the next image
return masks, scores
for prompt in ["person", "car", "dog"]: # 5) one prompt at a time, not all at once
masks, scores = segment("street.jpg", prompt)
torch.cuda.empty_cache() # optional: return cached blocks between jobsVideo
Fixes for Video Out-of-Memory
Video memory grows with frames, resolution and objects. Keep frames on the CPU, shrink the input, and don’t let sessions grow forever.
video · Transformers, offloaded + lower resolution
import torch
from transformers import Sam3VideoConfig, Sam3VideoModel, Sam3VideoProcessor
config = Sam3VideoConfig.from_pretrained("facebook/sam3")
config.image_size = 560 # smaller internal resolution: less memory, some detail lost
model = Sam3VideoModel.from_pretrained("facebook/sam3", config=config).to("cuda", dtype=torch.bfloat16)
processor = Sam3VideoProcessor.from_pretrained("facebook/sam3") # match the config's image size if prompted
session = processor.init_video_session(
video=video_frames, # e.g. from transformers.video_utils.load_video
inference_device="cuda",
processing_device="cpu", # decode/resize frames on CPU
video_storage_device="cpu", # keep the frames in RAM, not VRAM
dtype=torch.bfloat16,
)
session = processor.add_text_prompt(inference_session=session, text="person")
for out in model.propagate_in_video_iterator(inference_session=session):
res = processor.postprocess_outputs(session, out)
# move each frame's masks to CPU right away
masks = {oid: m.to("cpu", torch.bool) for oid, m in zip(res["object_ids"].tolist(), res["masks"])}video · chunks with the official sam3 predictor
# long clips: process in chunks, re-prompt each chunk, close the session in between
import subprocess
from pathlib import Path
import torch
def split(video, seconds=20):
subprocess.run(["ffmpeg", "-y", "-i", video, "-c", "copy", "-map", "0",
"-f", "segment", "-segment_time", str(seconds), "-reset_timestamps", "1",
"chunk_%03d.mp4"], check=True)
# official sam3 video predictor (request names as in Meta's video notebook)
for chunk in sorted(Path(".").glob("chunk_*.mp4")):
sid = predictor.handle_request(dict(type="start_session", resource_path=str(chunk)))["session_id"]
predictor.handle_request(dict(type="add_prompt", session_id=sid, frame_index=0, text="person"))
for r in predictor.handle_stream_request(dict(type="propagate_in_video", session_id=sid)):
save_masks_to_disk(chunk, r) # write to disk, don't keep in memory
predictor.handle_request(dict(type="close_session", session_id=sid)) # free the session
torch.cuda.empty_cache()Request names follow Meta’s video notebook; confirm close_session and any offload options for your commit. Fewer objects per session also helps: track only what you need (select one object in video). Many objects? SAM 3.1 handles them more efficiently. Also slow? Slow video tracking.
Calculator
Output Mask Memory Calculator
How much memory your masks take if kept at full resolution. This part is exact arithmetic.
per frame · float32 would be 8.94 GiB
For video, multiply by the frames you keep in memory. Write masks to disk as you go: export masks.
Measure
Measure Peak Memory on Your GPU
Change one thing at a time and record the peak. This is the only reliable way to know what helps on your setup.
measure_vram.py
# measure_vram.py: compare approaches on YOUR GPU; one line per run
import time
import torch
def measure(name, fn, *args, **kwargs):
torch.cuda.synchronize()
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats()
t = time.perf_counter()
try:
fn(*args, **kwargs)
status = "ok"
except torch.cuda.OutOfMemoryError:
status = "OOM"
torch.cuda.synchronize()
peak = torch.cuda.max_memory_allocated() / 2**30
print(f"{name:<32} {status:<4} peak {peak:6.2f} GiB {time.perf_counter() - t:6.1f} s")
# example: same image and prompt, different settings
# measure("fp32", run_fp32, "street.jpg", "person")
# measure("bf16", run_bf16, "street.jpg", "person")
# measure("bf16 + masks to cpu", run_bf16_cpu_masks, "street.jpg", "person")Peak allocated memory is what PyTorch actually used; nvidia-smi shows more because of the cache and the CUDA context.
GPU size
Rough Starting Points by GPU Memory
Starting settings, not guarantees. Confirm with the script above.
| GPU memory | Start with |
|---|---|
| 8 GB | Images in bfloat16, one prompt at a time, masks to CPU. Video: short clips, lower resolution, frames on CPU. |
| 10–12 GB | Comfortable for images. Short video with one prompt, frames on CPU, chunks of a few hundred frames. |
| 16–24 GB | Longer clips and several objects with offloading; chunk long videos. |
| 40 GB+ | Long, crowded or high-resolution video; batched multi-class runs. |
| No suitable GPU | A hosted API or the playground. |
Hardware and software basics: system requirements · All problems: troubleshooting
Questions
CUDA Out of Memory FAQ
How much GPU memory does SAM 3 need?
For a single image, third-party tests report peaks around 4 GB. Video is different: memory grows with frames, resolution and objects, so long or crowded clips can need far more. Measure your own workload with the script on this page.
Why does SAM 3 run out of memory on video but not images?
A video session stores frames, per-frame features and a memory of every tracked object. That grows with clip length and object count; a single image has none of it.
Does half precision help?
Yes. Running in bfloat16 roughly halves the memory for weights and activations compared with float32, with little or no visible quality change in most cases.
Will moving frames to CPU slow SAM down?
A little. Meta’s SAM 2 code notes a small FPS drop when offloading state to CPU in its own test; the saving in GPU memory is usually worth it.
Does SAM 3.1 use less memory?
Meta says SAM 3.1 reduces overall GPU requirements, mainly for multi-object video. Single-image memory is about the same.
Can I run SAM 3 on CPU instead?
It runs, but very slowly; it’s fine for testing a few images, not for video.
Why is there free memory but still an out-of-memory error?
Fragmentation: memory is free in small pieces. Setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True before starting Python often helps.