Skip to content

Run inference on Apple Silicon (MPS) and CPU; fix SAM 3.1 start_session - #627

Open
vadims-git wants to merge 3 commits into
facebookresearch:mainfrom
vadims-git:mac-mps
Open

vadims-git wants to merge 3 commits into
facebookresearch:mainfrom
vadims-git:mac-mps

Conversation

@vadims-git

Copy link
Copy Markdown

Summary

These are three separate commits, so each can be taken on its own.

What changed (commit 3)

  • New sam3/device_utils.py: DEVICE and bf16_autocast() replace the ~90 hardcoded .cuda(), device="cuda" and torch.autocast(device_type="cuda") call sites. bf16 autocast stays on for every device, because the SAM 3.1 multiplex path casts features to bf16 explicitly.
  • Guard the import-time torch.cuda.get_device_properties(0) call in sam3_multiplex_base.py.
  • Import the triton EDT kernel lazily (fixes No module named 'triton' on Mac #179).
  • Replace pkg_resources (dropped from setuptools>=81) with importlib.resources.
  • addmm_act: off CUDA, compute the linear + activation unfused, since _addmm_activation has no MPS kernel. The fallback matches the reference kernel exactly.
  • Disable FlashAttention 3 off CUDA; catch the AssertionError that torch.cuda.mem_get_info() raises on builds without CUDA; use torch.mps.empty_cache() on MPS.
  • Skip decord on macOS in the notebooks extra (no wheels, and no notebook uses it). Document Apple Silicon/CPU setup in the README.

CUDA behavior should be unchanged: DEVICE is cuda there, and every rewritten call site resolves to the same device and autocast as before.

Testing

Apple M5 (16 GB), macOS 26, Python 3.12, torch 2.14:

  • SAM 3.1 (build_sam3_multiplex_video_predictor, real facebook/sam3.1 weights): text and point prompts, propagation, close_session, on MP4, JPEG-folder and single-image inputs. All ops run natively on MPS (PYTORCH_ENABLE_MPS_FALLBACK=0). As a sanity check, "person" detections on two reference frames match hand counts (1 and 11) on both MPS and CPU. All 64 missing checkpoint keys are freqs_cis_* buffers computed at init, and there are no unexpected keys.
  • SAM 3 image API (build_sam3_image_model + Sam3Processor): text prompt, box prompt and batched images, on MPS and CPU. This used random weights, because I don't have access to the facebook/sam3 checkpoint.
  • Unit tests: 16 pass (11 existing, 5 new). The new ones cover start_session kwarg filtering (fails on main with the Bug: start_session() raises TypeError with multiplex predictor (SAM 3.1) #544 TypeError), the SAM3_DEVICE override, bf16 autocast, and the addmm_act fallback against the _addmm_activation reference for GELU and ReLU.
  • Formatting: ufmt check sam3 scripts with the versions pinned in format.yml reports no new failures. main already has 58 files that fail it.
  • Not tested on CUDA (no NVIDIA GPU available). A CUDA run would be appreciated.

On the M5, SAM 3.1 tracks 720p video at roughly 1.3 fps with a peak of ~7 GB; CPU is about 50x slower.

Not covered

  • build_sam3_video_predictor (the SAM 3 multi-GPU video predictor) still requires CUDA.
  • The torchcodec video loader is still CUDA-only; the default OpenCV loader works.
  • Training code is unchanged.

Related

Fixes #179, fixes #544.

🤖 Generated with Claude Code

@meta-cla

meta-cla Bot commented Sep 25, 2026

Copy link
Copy Markdown

Hi @vadims-git!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at cla@meta.com. Thanks!

vadims-git and others added 3 commits September 25, 2026 19:27
Sam3BasePredictor.start_session() always passes offload_state_to_cpu to
init_state(), but Sam3MultiplexTrackingWithInteractivity.init_state() does
not accept it, so every SAM 3.1 session failed with a TypeError (facebookresearch#544).
Filter the kwargs by the model's signature, as add_prompt() and
propagate_in_video() already do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
sam3/model/sam3_video_predictor.py imports psutil at module level and
model_builder imports that module, so `import sam3` fails on a fresh
`pip install -e .` unless psutil arrives transitively (e.g. via the
jupyter packages in the notebooks extra). See facebookresearch#227 and facebookresearch#252.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Inference hardcoded CUDA in about 90 places (.cuda(), device="cuda",
torch.autocast(device_type="cuda")) and hit CUDA-only code at import
time, so `import sam3` failed on macOS and the models could not run
without an NVIDIA GPU.

- Add sam3/device_utils.py: DEVICE resolves to cuda, then mps, then cpu
  (overridable with SAM3_DEVICE), and bf16_autocast() replaces the
  hardcoded CUDA autocast. bf16 autocast stays on for every device
  because the SAM 3.1 multiplex path casts features to bf16 explicitly.
- Route the hardcoded CUDA call sites through DEVICE / bf16_autocast().
- Guard the import-time get_device_properties(0) call in
  sam3_multiplex_base.py.
- Import the triton EDT kernel lazily (fixes facebookresearch#179).
- Replace pkg_resources, which setuptools>=81 no longer ships, with
  importlib.resources.
- Off CUDA, compute addmm_act unfused: _addmm_activation has no MPS
  kernel. The fallback matches the reference kernel exactly.
- Disable FlashAttention 3 off CUDA, catch the AssertionError that
  torch.cuda.mem_get_info() raises on builds without CUDA, and use
  torch.mps.empty_cache() on MPS.
- Skip decord on macOS in the notebooks extra (no wheels; no notebook
  uses it) and document Apple Silicon/CPU setup in the README.

CUDA behavior is unchanged: DEVICE is cuda there, and every rewritten
call site resolves to the same device and autocast as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 25, 2026
@meta-cla

meta-cla Bot commented Sep 25, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

tianxiao18 added a commit to tianxiao18/sam3 that referenced this pull request Oct 12, 2026
…ers fix)

Applies facebookresearch/sam3 PR facebookresearch#627 in full:
- New sam3/device_utils.py: auto-selects CUDA > MPS > CPU (SAM3_DEVICE env override)
- Replaces all hardcoded .cuda(), device="cuda", torch.autocast(device_type="cuda")
  across 18 files with DEVICE / bf16_autocast() from device_utils
- Lazy import of edt_triton (triton is CUDA-only, unavailable on Mac/Windows)
- CPU/MPS fallback for addmm_act in perflib/fused.py
- decord excluded on macOS in pyproject.toml

Additional fix not in PR facebookresearch#627:
- sam3/model/geometry_encoders.py: guard pin_memory().to(non_blocking=True)
  behind IS_CUDA — calling pin_memory() without CUDA segfaults on Mac/Windows
  during image inference whenever a geometric prompt is provided.

Also adds .gitignore to exclude model weights and HuggingFace-downloaded files.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@vadims-git

Copy link
Copy Markdown
Author

Could a maintainer help get CI running on this PR? The SAM3/ufmt workflow is marked as failed, but no jobs ran. The CLA is signed. Could you check whether the workflow needs approval or a rerun?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: start_session() raises TypeError with multiplex predictor (SAM 3.1) No module named 'triton' on Mac

1 participant