Meta SAM 3 Playground

Fix · sam3.pt · sam3.1_multiplex.pt

SAM Checkpoint Not Loading A checkpoint fails to load for one of five reasons: the path, permissions, a broken download, a code version that doesn’t match, or key names that don’t line up. Find your error, then fix it in that order.

file → model
Animation of the five checks between a checkpoint file and a loaded modelA checkpoint file travels through five gates: path, permission, file integrity, version and key names. In turn, it stops at the file gate because the download is incomplete, then at the version gate because the code is too old, and finally passes all five and the model loads. sam3.pt → model pathexists?permissionreadable?filecomplete?versioncode matches?keysnames match? ✗ failed finding central directory→ re-download, check SHA-256 ✗ Missing key(s) in state_dict→ update the sam3 code ✓ all five pass → model loaded check in this order; the first failure is the real problem
Illustration: five checks between the file and the model.

Error lookup

Find Your Error Message

Match the first error in the traceback, not the last line.

Error containsCauseGo to
FileNotFoundError / No such file or directoryWrong or relative pathPaths
IsADirectoryErrorPointed at the folder, not the filePaths
PermissionError / Permission deniedCan’t read the file or write the cachePermissions
failed finding central directoryIncomplete downloadDownloads
invalid load key, 'v'Git LFS pointer, not the modelDownloads
invalid load key, '<'An HTML page saved as the fileDownloads
401 / 403 / GatedRepoErrorNo access to the gated repoModel access
Weights only load failedPyTorch 2.6+ safe-loading defaultVersions
Missing key(s) / Unexpected key(s)Code and checkpoint don’t matchVersions · Keys
size mismatch for …Wrong model variant or configVersions
bpe_simple_vocab_16e6.txt.gz not foundTokenizer asset missing from installVersions
No space left on deviceDisk or cache fullDownloads

Paths

Path Problems

Relative paths resolve from the folder you start Python in, which is often not where your script or notebook lives.

relative vs absolute
Animation of a relative path resolving to the wrong folderA relative path “checkpoints/sam3.pt” is resolved from the folder where Python was started. Run from the project folder it finds the file; run from a notebook folder it points to a folder with no checkpoint and fails. An absolute path finds the file from anywhere. /home/ana/project/ checkpoints/sam3.pt 3.45 GB notebooks/demo.ipynb "checkpoints/sam3.pt" run from: project/✓ found run from: notebooks/✗ notebooks/checkpoints/sam3.ptFileNotFoundError absolute path/home/ana/project/checkpoints/sam3.pt✓ found from anywhere relative paths depend on where you run, not where the script lives
Illustration of path resolution.
  • Use absolute paths, or build them from the script’s own folder.
  • Point at the file: …/sam3.pt, not the folder.
  • ~ isn’t always expanded: use Path("~/…").expanduser().
  • Windows: raw strings or forward slashes; watch for spaces and OneDrive folders.
  • Hugging Face cache: files live under ~/.cache/huggingface/hub (or HF_HOME) with hashed folder names; use --local-dir for a plain path.

Code

Build Paths That Work Anywhere

safe paths

from pathlib import Path

ROOT = Path(__file__).resolve().parent          # folder of THIS script, not the current directory
CKPT = ROOT / "checkpoints" / "sam3.pt"         # works on Windows and Linux
assert CKPT.is_file(), f"checkpoint not found: {CKPT}"

# Windows strings: use r"C:\models\sam3.pt" or forward slashes "C:/models/sam3.pt"

Permissions

Permission Problems

The process must read the checkpoint and write to the cache.

SituationFix
File downloaded as another user (e.g. with sudo)sudo chown $USER checkpoints/sam3.pt or chmod a+r
Cache folder not writable (shared server, read-only home)Set HF_HOME to a writable folder before starting Python
Docker containerMount the folder (-v /models:/models) and check the container user can read it
Windows: file locked or blockedClose other programs using it; check antivirus quarantine; avoid synced cloud folders
Windows: cache symlink errorsEnable Developer Mode, or download with --local-dir
Network driveCopy the checkpoint to a local disk; network reads can time out

Downloads

Broken or Incomplete Downloads

A checkpoint is a single 3–4 GB file. Check its size and SHA-256 before anything else.

download states
Animation of good and broken checkpoint downloadsThree files named sam3.pt are compared. A Git LFS pointer is only 134 bytes of text. An interrupted download stops partway. The complete file is 3.45 GB and its SHA-256 matches the official value. LFS pointer: “version https://git-lfs…”134 bytesinterrupted download1.9 of 3.45 GBcomplete · SHA-256 matches3.45 GB · 9999e234… size first, then checksum; both are on the download page
Illustration of a pointer, a partial file and a complete file.
  • Git LFS pointer: a ~130-byte text file starting with version https://git-lfs. Use hf download or git lfs pull.
  • HTML instead of the model: a login or error page saved under the model’s name. Download with your token, not a browser link.
  • Incomplete: smaller than expected; re-run hf download, which resumes.
  • Disk full: check free space where the cache lives.
  • Official sizes and checksums: download page.

Code

Download a Clean Copy and Verify It

terminal

# get a clean copy in a folder you choose (no cache symlinks)
hf download facebook/sam3 sam3.pt --local-dir checkpoints/sam3
hf download facebook/sam3.1 sam3.1_multiplex.pt --local-dir checkpoints/sam3.1

df -h .                                   # enough free space? (~4 GB per checkpoint)
ls -l checkpoints/sam3/sam3.pt            # size
sha256sum checkpoints/sam3/sam3.pt        # compare with the download page

Version compatibility

Checkpoint and Code Versions

Each checkpoint needs code that knows its layout. Most “missing keys” errors are version mismatches.

compatibility
Animated checkpoint and code compatibility gridA grid fills row by row. sam3.pt loads with old and new sam3 code and with Ultralytics. sam3.1_multiplex.pt needs the latest sam3 code and loads in Ultralytics 8.4.148 or newer for images only. SAM 2 checkpoints don’t load in SAM 3 code. new sam3old sam3Ultralytics sam3.pt✓✓✓ 8.3.237+sam3.1_multiplex.ptlatest✗8.4.148+ imgSAM 2 .pt✗✗SAM 2 classes match the checkpoint to the code before debugging anything else
Illustration of which code loads which checkpoint.
CheckpointLoad with
sam3.ptsam3 repo; Ultralytics (SAM 3 support from 8.3.237); Transformers loads facebook/sam3 by name
sam3.1_multiplex.ptLatest sam3 code and the SAM 3.1 builders; Ultralytics 8.4.148+ for images. Not Transformers.
sam3.1_multiplex_fp16.safetensorsComfyUI native nodes
SAM 2 / 2.1 checkpointsSAM 2 code only, not SAM 3 builders
Your fine-tuned fileSame code version you trained with; see keys

Version notes

Known Version Issues

IssueWhat to do
SAM 3.1 with older sam3 code: about a thousand missing keysgit pull and pip install -e .; use the SAM 3.1 builder. Users have reported missing-key warnings with some public versions; check open facebookresearch/sam3 issues for your commit. For images, sam3.pt remains a reliable fallback.
Ultralytics before 8.4.148 with SAM 3.1Parts of the model could load with random weights without an error. Upgrade: pip install -U "ultralytics>=8.4.148".
PyTorch 2.6+: Weights only load failedPyTorch now loads with weights_only=True. Official tensors-only files load fine. For your own trusted files that contain extra objects, re-save as a plain state dict, or set weights_only=False only for files you fully trust.
size mismatch for …Builder config doesn’t match the file (wrong model, wrong image size); use the builder meant for that checkpoint.
Missing bpe_simple_vocab_16e6.txt.gzReinstall from a fresh clone; otherwise pass the BPE path to the builder or place the file in the package’s assets folder.
mat1 and mat2 must have the same dtype after loadingRun inference under torch.autocast("cuda", dtype=torch.bfloat16).

Upgrading SAM 3 → 3.1 step by step: upgrade guide · Where 3.1 runs: SAM 3.1 compatibility

Key mismatches

Fine-Tuned Checkpoints and Key Names

Training wrappers change key names. Rename them to what the model expects, then load and check the report.

key prefixes
Animation of checkpoint keys matching model keysLeft: key names stored in a fine-tuned checkpoint, starting with “module.”. Right: the names the model expects, starting with “detector.”. At first nothing matches and loading reports missing and unexpected keys. After rewriting the prefix, every key lines up. checkpoint keysmodel expects detector.backbone.trunk.posdetector.transformer.dec.0detector.seg_head.maskdetector.presence.head module.backbone.trunk.posmodule.transformer.dec.0module.seg_head.maskmodule.presence.head✗ 4 missing · 4 unexpected backbone.trunk.postransformer.dec.0seg_head.maskpresence.headstrip “module.” … detector.backbone.trunk.posdetector.transformer.dec.0detector.seg_head.maskdetector.presence.head✓ add “detector.”: all keys match example names; check your own with the inspect script
Illustration of renaming key prefixes.
  • module. comes from multi-GPU (DDP) training; _orig_mod. from torch.compile.
  • Official SAM 3 files nest detector weights under detector.; some fine-tunes save them flat.
  • Load with strict=False only to see the report, then fix until missing/unexpected are empty or expected.
  • Prefer the training repo’s own loader if it provides one.

Code

Rename Keys and Check the Load Report

remap_keys.py

# fine-tuned checkpoint with different key names → rename, then load and report
import torch

def remap(sd, strip=("module.", "_orig_mod."), add=""):
    out = {}
    for k, v in sd.items():
        for s in strip:                      # DDP / torch.compile prefixes
            if k.startswith(s):
                k = k[len(s):]
        if add and not k.startswith(add):
            k = add + k                      # e.g. "detector." to match the official layout
        out[k] = v
    return out

ckpt = torch.load("my_finetuned.pt", map_location="cpu", weights_only=True)
sd = ckpt.get("model", ckpt)
result = model.load_state_dict(remap(sd, add="detector."), strict=False)   # model built without a checkpoint
print("missing:", len(result.missing_keys), result.missing_keys[:5])
print("unexpected:", len(result.unexpected_keys), result.unexpected_keys[:5])

Fine-tuning setup: fine-tune SAM.

Inspect

Inspect a Checkpoint File

Answers “what is this file?” before you debug code: path, permission, size, format, pointer or HTML, checksum and key prefixes.

inspect_checkpoint.py · python inspect_checkpoint.py checkpoints/sam3.pt

# inspect_checkpoint.py: what is this file, really?  python inspect_checkpoint.py PATH
import hashlib, os, sys, zipfile
from pathlib import Path

OFFICIAL = {
    "sam3.pt": (3_450_000_000, "9999e2341ceef5e136daa386eecb55cb414446a00ac2b55eb2dfd2f7c3cf8c9e"),
    "sam3.1_multiplex.pt": (3_502_755_717, "0567debeec80ba4ac6369540c6c248025283cb3ff2b92827509e57e2b3541cb6"),
}

def inspect(arg):
    p = Path(arg).expanduser()
    print("path      ", p.resolve())
    if not p.exists():
        return print("✗ not found; check the folder you run from (cwd:", os.getcwd() + ")")
    if p.is_dir():
        return print("✗ this is a folder; point to the file inside it")
    if not os.access(p, os.R_OK):
        return print("✗ no read permission for this user")
    size = p.stat().st_size
    print(f"size       {size:,} bytes")
    head = p.open("rb").read(64)
    if head.startswith(b"version https://git-lfs"):
        return print("✗ Git LFS pointer, not the model: use hf download or git lfs pull")
    if head.lstrip().startswith(b"<"):
        return print("✗ HTML page saved instead of the file (login or error page)")
    if p.suffix == ".safetensors":
        print("format     safetensors")
    elif zipfile.is_zipfile(p):
        print("format     PyTorch zip checkpoint")
    else:
        print("⚠ not a zip archive: truncated download or an old/other format")
    if p.name in OFFICIAL:
        want_size, want_sha = OFFICIAL[p.name]
        if p.name == "sam3.1_multiplex.pt" and size != want_size:
            return print(f"✗ size differs from official {want_size:,} bytes: re-download")
        h = hashlib.sha256()
        with p.open("rb") as f:
            for chunk in iter(lambda: f.read(1 << 20), b""):
                h.update(chunk)
        ok = h.hexdigest() == want_sha
        print("sha256    ", "✓ matches official" if ok else "✗ MISMATCH: re-download")
    try:
        import torch
        sd = torch.load(p, map_location="cpu", weights_only=True) if p.suffix != ".safetensors" else None
        if isinstance(sd, dict):
            sd = sd.get("model", sd.get("state_dict", sd))
            prefixes = {}
            for k in sd:
                prefixes[k.split(".")[0]] = prefixes.get(k.split(".")[0], 0) + 1
            print(f"keys       {len(sd):,}; top-level prefixes: {dict(sorted(prefixes.items(), key=lambda x: -x[1])[:6])}")
    except Exception as e:
        print(f"⚠ torch.load: {type(e).__name__}: {str(e)[:160]}")

for a in sys.argv[1:]:
    inspect(a)
    print()

The key listing needs PyTorch; everything else runs without it. Loading uses weights_only=True, so no code inside the file is executed.

Per tool

Where Each Tool Expects the Checkpoint

ToolExpects
sam3 repoDownloads from Hugging Face by default; or pass a local checkpoint_path with Hugging Face loading turned off
UltralyticsThe path you pass, e.g. SAM("checkpoints/sam3.pt"); SAM 3 weights aren’t auto-downloaded
TransformersA repo name (facebook/sam3) or a local folder in Transformers format, not a single .pt
ComfyUI (native)ComfyUI/models/checkpoints/sam3.1_multiplex_fp16.safetensors
ComfyUI-SAM3 packComfyUI/models/sam3/sam3.pt by default

Setup guides: install SAM 3 · ComfyUI · Other problems: troubleshooting

Questions

Checkpoint Loading FAQ

Why does my SAM checkpoint say “failed finding central directory”?

The file is incomplete, usually an interrupted download. Delete it, download again, and compare its size and SHA-256 with the official values.

What does “invalid load key, 'v'” mean?

You have a Git LFS pointer, a tiny text file, instead of the real checkpoint. Download with hf download, or run git lfs pull.

Why do I get missing or unexpected keys?

The code and checkpoint don’t match: an old sam3 version with a SAM 3.1 file, the wrong builder, or a fine-tuned checkpoint saved with different key names.

Is it safe to set weights_only=False?

Only for files from a source you trust completely, because it can run code inside the file. Official Meta checkpoints from Hugging Face are the trusted case; random downloads are not.

Where does Hugging Face store downloaded checkpoints?

In its cache, ~/.cache/huggingface/hub by default, or under HF_HOME if set. Use --local-dir to save a plain copy somewhere you choose.

Can I load sam3.1_multiplex.pt with Transformers?

Not officially. Transformers loads facebook/sam3 with from_pretrained; SAM 3.1 needs Meta’s sam3 code, Ultralytics 8.4.148+ (images) or ComfyUI.

Keep reading