Meta SAM 3 Playground

Advanced guide · SAM 3 / 3.1

How to Fine-Tune SAM on a Custom Dataset Adapt SAM 3 to cracks, cells, crops or any niche concept: pick a supported setup, prepare a clean COCO dataset, train with Meta’s trainer, and prove the gain against the zero-shot baseline.

before vs after
Animation of SAM 3 before and after fine-tuningA concrete slab with two hairline cracks and a stain. Before fine-tuning, the prompt “crack” finds one crack partly and wrongly masks the stain. After fine-tuning, both cracks are fully masked and the stain is ignored. prompt › “crack” zero-shot✗ 1 crack, partial✗ stain = crack✗ 1 missed fine-tuned✓ both cracks✓ full length✓ stain ignored illustrative
Illustration: fine-tuning fixes misses and false positives in a niche domain.

First

Should You Fine-Tune at All?

SAM 3 is strong zero-shot. Climb this ladder and stop at the first step that works.

try cheaper fixes first
Animated ladder of options before full fine-tuningFour steps rise like stairs: first improve the text prompt, then add positive and negative example boxes, then try LoRA fine-tuning of about 1% of the weights, and finally full fine-tuning with Meta’s trainer. Cost and effort rise with each step. 1 · better prompt“hairline crack”2 · example boxes+ / − exemplars3 · LoRA~1% of weights4 · full fine-tuneofficial trainer effort and cost →
Illustration: effort rises with each step.
  • Better prompts: a more specific noun phrase often fixes misses. Prompts guide
  • Example boxes: positive and negative exemplars teach a look-alike instantly, no training.
  • Fine-tune when: the domain looks unlike everyday photos (medical, aerial, microscopy, industrial), the concept has no good name, or you need consistently higher accuracy at scale.
  • Measure first: record zero-shot accuracy on a test split so you can prove the gain later.

Supported setups

Supported Fine-Tuning Setups

Three practical routes for SAM 3, plus SAM 2.1 as a fallback. Meta’s trainer is the reference; the others trade control for convenience or cost.

SetupWhat it isHardwareGood for
Official trainer (facebookresearch/sam3)sam3/train/train.py with Hydra YAML configs; local single/multi-GPU or SLURM multi-node; examples for Roboflow 100-VL and ODinWCUDA GPUs; data-centre cards recommended for full fine-tuningReference results, full control, research
LoRA (community)Train small adapters (about 1% of weights) on a COCO dataset, e.g. the open-source sam3_lora projectProjects report 16 GB GPUsLimited VRAM, fast iteration, small checkpoints
Managed (Roboflow)Upload or label data, generate a version, click “Custom Train” and choose SAM 3; deploy via WorkflowsNone of your ownTeams without ML infra; paid plans, usage-based
SAM 2.1 (alternative)Meta’s SAM 2 training code, Apache 2.0, click and box prompts onlySmaller GPUsWhen you don’t need text prompts

Base requirements for the official route: Python 3.12+, PyTorch 2.7+, CUDA 12.6+ and approved access to the facebook/sam3 checkpoint. Install SAM 3 · Hugging Face access

Step 1

Install the Training Extras

Inside your existing sam3 checkout (see the Python tutorial for the base install):

terminal

cd sam3
pip install -e ".[train]"            # training dependencies
pip install pycocotools tensorboard  # for checks and evaluation
  1. 1Measure the baselineRun zero-shot SAM 3 on a held-out test split and record mask AP.
  2. 2Prepare the datasetCOCO JSON with masks, noun-phrase class names, train/valid/test splits.
  3. 3Install training extraspip install -e ".[train]" in the sam3 repo.
  4. 4Write a configCopy a Roboflow 100-VL config and point paths at your data.
  5. 5Trainpython sam3/train/train.py -c your_config.yaml --use-cluster 0 --num-gpus 1
  6. 6EvaluateSet trainer.mode to val, compare with the baseline, test unrelated prompts.

Dataset preparation

Prepare the Dataset

Clean, consistent labels matter more than volume. SAM 3’s trainer expects COCO-style data like Roboflow 100-VL.

folder + COCO JSON
Animation of the dataset layout and COCO annotationLeft, a folder tree: my_dataset with train, valid and test folders, each holding images and an _annotations.coco.json file. Right, the JSON fills in: images, annotations with polygon segmentation and bbox, and categories whose name, “hairline crack”, becomes the text prompt. my_dataset/├── train/│ ├── img_0001.jpg …│ └── _annotations.coco.json├── valid/│ └── _annotations.coco.json└── test/ └── _annotations.coco.json { "images": [{"id": 1, "file_name": …}], "annotations": [{"image_id": 1, "category_id": 2, "segmentation": [[x1,y1,…]], "bbox": [x,y,w,h], "iscrowd": 0}], "categories": [{"id": 2, "name": "hairline crack"}] } class name = text prompt
Illustration of the expected layout and annotation fields.
  • Format: COCO JSON with instance masks (polygons or RLE), one _annotations.coco.json per split.
  • Splits: train, valid, test. Keep test images out of training, ideally from different sites, days or devices.
  • Class names are prompts: use short noun phrases (“hairline crack”, not “class_3”).
  • Masks, not just boxes: trace every instance in every image; missing labels teach the model to ignore objects.
  • Negatives: include images with none of your objects so the model learns when to return nothing.
  • Size: Meta’s example config uses 100 training images per dataset; start there and grow if evaluation says so.
  • Label faster: pre-label with SAM 3 itself, then correct by hand. Labelme or CVAT exports can be converted to COCO.

Step 2

Check the Dataset Before Training

A 30-second sanity check catches most failed runs: missing files, unmasked boxes, class imbalance, no negatives.

check_dataset.py

import json, sys
from collections import Counter
from pathlib import Path

root = Path(sys.argv[1])                   # python check_dataset.py my_dataset
for split in ["train", "valid", "test"]:
    ann = root / split / "_annotations.coco.json"
    if not ann.exists():
        print(f"{split}: missing {ann.name}")
        continue
    coco = json.loads(ann.read_text())
    cats = {c["id"]: c["name"] for c in coco["categories"]}
    anns = coco["annotations"]
    with_objects = {a["image_id"] for a in anns}
    no_mask = sum(1 for a in anns if not a.get("segmentation"))
    missing = [i["file_name"] for i in coco["images"]
               if not (root / split / i["file_name"]).exists()]
    print(f"{split}: {len(coco['images'])} images, {len(anns)} masks, "
          f"{len(coco['images']) - len(with_objects)} negatives, "
          f"{no_mask} without masks, {len(missing)} missing files")
    print("   per class:", dict(Counter(cats.get(a["category_id"], "?") for a in anns)))

example output

train: 412 images, 1630 masks, 61 negatives, 0 without masks, 0 missing files
   per class: {'hairline crack': 1210, 'spalling': 420}
valid: 88 images, 341 masks, 12 negatives, 0 without masks, 0 missing files
   per class: {'hairline crack': 255, 'spalling': 86}

More on formats: mask formats · export masks

Step 3

Write a Training Config

Configs live in sam3/train/configs/ and use Hydra YAML. Copy the Roboflow 100-VL fine-tuning config rather than starting from scratch.

my_dataset_ft.yaml

# configs/my_dataset/my_dataset_ft.yaml
# Start from a copy of configs/roboflow_v100/roboflow_v100_full_ft_100_images.yaml,
# keep its model/trainer sections, and point the dataset entries at your folder.
paths:
  dataset_root: /data/my_dataset
  experiment_log_dir: /experiments/my_dataset_ft
  bpe_path: sam3/assets/bpe_simple_vocab_16e6.txt.gz

launcher:
  num_nodes: 1
  gpus_per_node: 1

submitit:
  use_cluster: False

trainer:
  mode: train            # switch to val to evaluate
  • Key sections: paths (data, logs, BPE vocab), launcher (nodes, GPUs), submitit (cluster settings), trainer (mode, epochs, optimisation).
  • Dataset entries: names differ between versions; mirror how the copied config points at one Roboflow dataset folder.
  • Reference configs: roboflow_v100_full_ft_100_images.yaml (train), roboflow_v100_eval.yaml (eval), odinw_text_only_train.yaml, odinw_text_only.yaml.

Step 4

Launch Training and Monitor It

One script covers a single GPU, a multi-GPU box and SLURM clusters.

training curves
Animated training curvesTwo curves draw over epochs. Training loss falls steeply then levels off. Validation mask AP rises and plateaus; a marker shows the best checkpoint at the peak, before a slight dip that signals overfitting. best checkpoint train lossval mask APoverfitting → epochs → · watch in TensorBoard (illustrative)
Illustrative loss and validation curves.
  • Local runs: --use-cluster 0 forces local even if the config targets a cluster.
  • Scale out: --num-gpus per node and --num-nodes for distributed training.
  • SLURM: set partition, account and timeout_hour in submitit or via flags.
  • Watch: TensorBoard for loss and validation; keep the best checkpoint, not the last.
  • Diverged? Meta’s guide suggests using the last checkpoint before divergence.

terminal

# one GPU, local
python sam3/train/train.py -c configs/my_dataset/my_dataset_ft.yaml --use-cluster 0 --num-gpus 1

# four GPUs on one machine
python sam3/train/train.py -c configs/my_dataset/my_dataset_ft.yaml --use-cluster 0 --num-gpus 4

# SLURM, two nodes × 8 GPUs
python sam3/train/train.py -c configs/my_dataset/my_dataset_ft.yaml --use-cluster 1 \
    --partition gpu_partition --account my_account --num-gpus 8 --num-nodes 2

# watch progress
tensorboard --logdir /experiments/my_dataset_ft/tensorboard

outputs

/experiments/my_dataset_ft/
├── config.yaml             # what you launched
├── config_resolved.yaml    # fully expanded config
├── checkpoints/
├── tensorboard/
└── logs/

Evaluation

Evaluate Against the Zero-Shot Baseline

A fine-tune only counts if it beats zero-shot SAM 3 on images it never saw, without breaking other prompts.

accuracy + discrimination
Animated evaluation: accuracy and prompt discriminationLeft, bars compare zero-shot SAM 3 and the fine-tuned model on the same held-out test split for mask AP and AP50; the fine-tuned bars are taller. Right, a check that unrelated prompts like “car” still return no masks on crack images, with a green tick. test split · same images mask APAP50 zero-shotfine-tuned discrimination check “crack” → 2 masks ✓“car” → 0 masks ✓“person” → 0 masks ✓ illustrative numbers
Illustrative evaluation results.
  • Built-in: set trainer.mode: val in your config and re-run train.py; results land in the log folder.
  • Metric: COCO mask AP and AP50 on the test split; Meta’s paper also reports cgF1 for concept segmentation.
  • Per class: a rare class can get worse while the average improves.
  • Prompt discrimination: run unrelated prompts (“car”, “person”) on your images; a healthy model returns nothing.
  • Real samples: view overlays on 20–50 test images; numbers miss systematic edge errors.

Evaluation code

Independent Evaluation with pycocotools

Generate predictions for both models on the same test split, then score them identically.

predict.py

import json
import numpy as np
from PIL import Image
from pycocotools import mask as mask_utils
from pycocotools.coco import COCO
from sam3.model_builder import build_sam3_image_model
from sam3.model.sam3_image_processor import Sam3Processor

GT, IMG_DIR, OUT = "my_dataset/test/_annotations.coco.json", "my_dataset/test", "preds_zero_shot.json"
gt = COCO(GT)
processor = Sam3Processor(build_sam3_image_model())   # for the fine-tuned run, load your checkpoint here

preds = []
for img_id in gt.getImgIds():
    info = gt.loadImgs(img_id)[0]
    state = processor.set_image(Image.open(f"{IMG_DIR}/{info['file_name']}").convert("RGB"))
    for cat in gt.loadCats(gt.getCatIds()):
        out = processor.set_text_prompt(state=state, prompt=cat["name"])
        for m, s in zip(out["masks"], out["scores"]):
            rle = mask_utils.encode(np.asfortranarray(m.squeeze().cpu().numpy().astype(np.uint8)))
            rle["counts"] = rle["counts"].decode()
            preds.append({"image_id": img_id, "category_id": cat["id"],
                          "segmentation": rle, "score": float(s)})
json.dump(preds, open(OUT, "w"))

evaluate.py

from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval

gt = COCO("my_dataset/test/_annotations.coco.json")
for run in ["zero_shot", "fine_tuned"]:
    ev = COCOeval(gt, gt.loadRes(f"preds_{run}.json"), iouType="segm")
    ev.evaluate(); ev.accumulate(); ev.summarize()
    print(run, "mask AP", round(ev.stats[0], 3), "AP50", round(ev.stats[1], 3))

Run predict.py twice: once with the base model (preds_zero_shot.json) and once with your fine-tuned checkpoint (preds_fine_tuned.json). How you pass a checkpoint path depends on your sam3 version’s model builder.

After training

Use and Ship the Fine-Tuned Model

Run itLoad your checkpoint in the same image or video code as the base model; prompts stay the same. Python tutorial
Serve itWrap it in your own endpoint or deploy through a managed platform. API guide
LicenceFine-tuned weights derive from SAM 3, so the SAM License still applies. Terms summary

Troubleshooting

Common Fine-Tuning Problems

ProblemLikely causeFix
Loss becomes NaN / divergesLearning rate too high, bad labelsLower LR; check data; resume from the last good checkpoint
Val AP falls after a few epochsOverfitting a small datasetFewer epochs, more data or augmentation, keep the best checkpoint
Fires on any promptTrained only on positive promptsAdd negative images and hard-negative prompts; re-check discrimination
CUDA out of memoryBatch or resolution too largeSmaller batch, more GPUs, or LoRA. OOM fixes
File not found / empty datasetWrong paths or file_nameRun check_dataset.py; fix paths in the config
Checkpoint won’t loadCode and weights out of syncPull the latest repo. Checkpoint loading

Questions

Fine-Tuning FAQ

Can SAM 3 be fine-tuned?

Yes. Meta’s sam3 repository includes training and fine-tuning code, with example configs for Roboflow 100-VL and ODinW datasets, single-GPU, multi-GPU and SLURM launch options.

What dataset format does SAM 3 fine-tuning use?

COCO-style JSON with instance masks, organised in train, valid and test folders, as in Roboflow 100-VL. Category names act as the text prompts, so name them as short noun phrases.

How many images do I need?

Start small: Meta’s example config fine-tunes on 100 images per dataset. Add more for hard or very different domains, and always keep a separate test split.

How much GPU memory does fine-tuning need?

Full fine-tuning of the ~848M-parameter model needs data-centre GPUs. Community LoRA projects report training on 16 GB cards by updating about 1% of parameters. Check your exact setup.

Should I use LoRA or full fine-tuning?

LoRA is cheaper, faster and gives small adapter files, and is a good first try. Full fine-tuning with Meta’s trainer is the reference path and may adapt further on very different data.

How do I evaluate a fine-tuned SAM 3 model?

Compare mask AP on a held-out test set against zero-shot SAM 3, check per-class results, and test unrelated prompts to make sure the model hasn’t started firing on everything.

Is a fine-tuned SAM 3 still under the SAM License?

Yes. Fine-tuned weights are derived from SAM 3, so the SAM License terms continue to apply. This is not legal advice.

Keep reading