Meta SAM 3 Playground

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.

GPU memory
Animation of SAM GPU memory going over the limit and coming back underA GPU memory bar fills with five parts: model weights, activations, stored video frames, object memory and output masks. Together they pass the GPU limit and cause an out-of-memory error. Then bfloat16 shrinks weights and activations, frames move to CPU, and masks move off the GPU, so the bar fits under the limit. GPU memory your GPU weightsactivationsvideo framesobject memoryoutput masks✗ CUDA out of memoryfp32 · frames on GPU · masks kept on GPU video framesobject memoryoutput masksbfloat16: weights + activations halvestill over the limit ✓ fits: + frames on CPU + masks to CPUbars are illustrative, not measured sizes weightsactivationsvideo framesobject memoryoutput masks fix the biggest block first; measure after each change
Illustration: shrinking the biggest blocks until it fits.

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)

torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 2.31 GiB. GPU 0 has a total capacity of 11.72 GiB of which 1.02 GiB is free. Of the allocated memory 8.94 GiB is allocated by PyTorch, and 1.21 GiB is reserved by PyTorch but unallocated.
PartWhat it tells you
Tried to allocateThe single step that failed. Huge (GBs)? Usually output masks or a batch of frames.
Total capacityYour GPU. Other apps (browser, games, another notebook) share it.
Allocated by PyTorchWhat SAM is holding: weights, frames, object memory, results.
Reserved but unallocatedLarge? 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.

memory by job
Animation comparing memory use for images and videoThree stacked bars appear. A single image uses mostly model weights and activations. Many objects in one image add a large block of output masks. A long video adds stored frames and object memory on top, making the tallest bar. weightsactivationsone image weightsactivationsoutput masks200 objects weightsactivationsvideo framesobject memorylong video weightsactivationsvideo framesobject memoryoutput masks illustrative proportions
Illustration of which parts grow for images and video.
  • 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

ApproachSavesCostsEvidence
Run in bfloat16Weights + activations, roughly halfTiny precision lossDocumented Transformers SAM 3 video examples run in bfloat16
Masks to CPU as bool, straight awayUp to GBs with many objectsNothing noticeableStandard see the calculator
One prompt / class at a timeLarge for multi-class runsNo joint tracking across promptsMeasured under 10 GB vs 29+ GB for official batched multi-class (RTX 3080 10 GB)
Video frames and processing on CPUAll stored framesSmall speed lossDocumented video_storage_device="cpu", processing_device="cpu"
Offload tracker state to CPUObject memoryA few FPSMeasured by Meta for SAM 2: 27 → 24 FPS, one object, 768 px
Lower internal resolution (e.g. 560)Activations + featuresLess detail on small objectsDocumented Transformers config.image_size
Chunk long videos, close sessionsStops growth with lengthRe-prompt per chunk; IDs restartStandard
Split across two GPUsPer-GPU loadNeeds two GPUsMeasured ~4 GB each to load; 6–7 GB each on 400–500-frame sequences
Upgrade to SAM 3.1 (video)Multi-object tracking costUpgrade workDocumented Meta: reduces overall GPU requirements
expandable_segments:TrueFragmentation wasteNoneDocumented 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.

SetupReported memorySource
SAM 3, single imageJust under 4 GB peakThird-party hands-on test on an RTX 6000 (48 GB)
SAM 3 multi-class image and video, one class per loopUnder 10 GBTutorial 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 runningResearch paper (3D reconstruction pipeline)
SAM 2 video, state offloaded to CPULower 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.

mask memory
Animation of output masks filling GPU memoryOne full-resolution float mask is a small block. As the number of detected objects grows to 50 and then 200, the stack of full-size float masks becomes many gigabytes. Converting them to boolean on the CPU shrinks the stack to a small fraction. masks at 4000 × 3000, float32 on GPU 1 object ≈ 48 MB 50 objects ≈ 2.4 GB200 objects ≈ 9.6 GB bool on CPU: 200 × 12 MBand 0 bytes left on the GPU objects × width × height × bytes per pixel
Illustration of mask memory growing with object count.
  • bfloat16 + inference_mode: load once, no gradients.
  • Masks off the GPU: convert to bool on 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 jobs

Video

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.

offload frames
Animation of offloading video frames to CPU memoryVideo frames first sit in GPU memory next to the model. With offloading, the frames move to CPU memory, and each frame is copied to the GPU only when the model needs it, freeing most of the GPU. GPU CPU RAM model frames wait in RAM; only the current frame visits the GPU
Illustration of frames offloaded to CPU.
chunking
Animation of video memory growing and chunkingA line chart shows GPU memory rising steadily as more video frames are processed in one session until it crosses the GPU limit. A second line, processing the same video in chunks and closing each session, rises and falls in a sawtooth that stays under the limit. memoryframes → GPU limit one long session → OOM chunks + close each session → stays under
Illustration of one long session vs chunks.

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.

2.24 GiB

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 memoryStart with
8 GBImages in bfloat16, one prompt at a time, masks to CPU. Video: short clips, lower resolution, frames on CPU.
10–12 GBComfortable for images. Short video with one prompt, frames on CPU, chunks of a few hundred frames.
16–24 GBLonger clips and several objects with offloading; chunk long videos.
40 GB+Long, crowded or high-resolution video; batched multi-class runs.
No suitable GPUA 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.

Keep reading