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.
First
Should You Fine-Tune at All?
SAM 3 is strong zero-shot. Climb this ladder and stop at the first step that works.
- 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.
| Setup | What it is | Hardware | Good 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 ODinW | CUDA GPUs; data-centre cards recommended for full fine-tuning | Reference results, full control, research |
| LoRA (community) | Train small adapters (about 1% of weights) on a COCO dataset, e.g. the open-source sam3_lora project | Projects report 16 GB GPUs | Limited VRAM, fast iteration, small checkpoints |
| Managed (Roboflow) | Upload or label data, generate a version, click “Custom Train” and choose SAM 3; deploy via Workflows | None of your own | Teams without ML infra; paid plans, usage-based |
| SAM 2.1 (alternative) | Meta’s SAM 2 training code, Apache 2.0, click and box prompts only | Smaller GPUs | When 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- 1Measure the baselineRun zero-shot SAM 3 on a held-out test split and record mask AP.
- 2Prepare the datasetCOCO JSON with masks, noun-phrase class names, train/valid/test splits.
- 3Install training extraspip install -e ".[train]" in the sam3 repo.
- 4Write a configCopy a Roboflow 100-VL config and point paths at your data.
- 5Trainpython sam3/train/train.py -c your_config.yaml --use-cluster 0 --num-gpus 1
- 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.
- Format: COCO JSON with instance masks (polygons or RLE), one
_annotations.coco.jsonper 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.
- Local runs:
--use-cluster 0forces local even if the config targets a cluster. - Scale out:
--num-gpusper node and--num-nodesfor distributed training. - SLURM: set partition, account and
timeout_hourinsubmititor 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/tensorboardoutputs
/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.
- Built-in: set
trainer.mode: valin your config and re-runtrain.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
Troubleshooting
Common Fine-Tuning Problems
| Problem | Likely cause | Fix |
|---|---|---|
| Loss becomes NaN / diverges | Learning rate too high, bad labels | Lower LR; check data; resume from the last good checkpoint |
| Val AP falls after a few epochs | Overfitting a small dataset | Fewer epochs, more data or augmentation, keep the best checkpoint |
| Fires on any prompt | Trained only on positive prompts | Add negative images and hard-negative prompts; re-check discrimination |
| CUDA out of memory | Batch or resolution too large | Smaller batch, more GPUs, or LoRA. OOM fixes |
| File not found / empty dataset | Wrong paths or file_name | Run check_dataset.py; fix paths in the config |
| Checkpoint won’t load | Code and weights out of sync | Pull 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.