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.
Error lookup
Find Your Error Message
Match the first error in the traceback, not the last line.
| Error contains | Cause | Go to |
|---|---|---|
FileNotFoundError / No such file or directory | Wrong or relative path | Paths |
IsADirectoryError | Pointed at the folder, not the file | Paths |
PermissionError / Permission denied | Can’t read the file or write the cache | Permissions |
failed finding central directory | Incomplete download | Downloads |
invalid load key, 'v' | Git LFS pointer, not the model | Downloads |
invalid load key, '<' | An HTML page saved as the file | Downloads |
401 / 403 / GatedRepoError | No access to the gated repo | Model access |
Weights only load failed | PyTorch 2.6+ safe-loading default | Versions |
Missing key(s) / Unexpected key(s) | Code and checkpoint don’t match | Versions · Keys |
size mismatch for … | Wrong model variant or config | Versions |
bpe_simple_vocab_16e6.txt.gz not found | Tokenizer asset missing from install | Versions |
No space left on device | Disk or cache full | Downloads |
Paths
Path Problems
Relative paths resolve from the folder you start Python in, which is often not where your script or notebook lives.
- 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: usePath("~/…").expanduser().- Windows: raw strings or forward slashes; watch for spaces and OneDrive folders.
- Hugging Face cache: files live under
~/.cache/huggingface/hub(orHF_HOME) with hashed folder names; use--local-dirfor 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.
| Situation | Fix |
|---|---|
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 container | Mount the folder (-v /models:/models) and check the container user can read it |
| Windows: file locked or blocked | Close other programs using it; check antivirus quarantine; avoid synced cloud folders |
| Windows: cache symlink errors | Enable Developer Mode, or download with --local-dir |
| Network drive | Copy 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.
- Git LFS pointer: a ~130-byte text file starting with
version https://git-lfs. Usehf downloadorgit 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 pageVersion compatibility
Checkpoint and Code Versions
Each checkpoint needs code that knows its layout. Most “missing keys” errors are version mismatches.
| Checkpoint | Load with |
|---|---|
sam3.pt | sam3 repo; Ultralytics (SAM 3 support from 8.3.237); Transformers loads facebook/sam3 by name |
sam3.1_multiplex.pt | Latest sam3 code and the SAM 3.1 builders; Ultralytics 8.4.148+ for images. Not Transformers. |
sam3.1_multiplex_fp16.safetensors | ComfyUI native nodes |
| SAM 2 / 2.1 checkpoints | SAM 2 code only, not SAM 3 builders |
| Your fine-tuned file | Same code version you trained with; see keys |
Version notes
Known Version Issues
| Issue | What to do |
|---|---|
| SAM 3.1 with older sam3 code: about a thousand missing keys | git 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.1 | Parts 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 failed | PyTorch 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.gz | Reinstall 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 loading | Run 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.
module.comes from multi-GPU (DDP) training;_orig_mod.fromtorch.compile.- Official SAM 3 files nest detector weights under
detector.; some fine-tunes save them flat. - Load with
strict=Falseonly 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
| Tool | Expects |
|---|---|
| sam3 repo | Downloads from Hugging Face by default; or pass a local checkpoint_path with Hugging Face loading turned off |
| Ultralytics | The path you pass, e.g. SAM("checkpoints/sam3.pt"); SAM 3 weights aren’t auto-downloaded |
| Transformers | A 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 pack | ComfyUI/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.