Skip to content

feat: add SAM 3 promptable segmentation and tracking - #2551

Merged
inureyes merged 4 commits into
mainfrom
feature/issue-2429-sam3-segmentation
Oct 23, 2026
Merged

inureyes merged 4 commits into
mainfrom
feature/issue-2429-sam3-segmentation

Conversation

@inureyes

@inureyes inureyes commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

SAM 3 checkpoints previously failed classification, and mlxcel had no promptable instance-mask output. This PR adds the shared prompt and instance surface and ports the native image detector, segmenter, and memory-based video tracker.

  • Add repeatable text and pixel-box prompts, structured instances, U8 mask tensors and PNGs, source-pixel boxes and scores, and stable video object IDs to mlxcel predict.
  • Port the ViT-L backbone, CLIP text encoder, DETR encoder and decoder, geometry prompts, segmentation heads, SAM prompt and mask decoder, and memory tracker with dense and affine-quantized UnifiedLinear support.
  • Preserve upstream BF16 arithmetic with scoped fused biased linear projections and exact GELU operation order.
  • Pin authentic exact-native text, two-cat, box-prompt, and short-video fixtures with source revisions, hashes, and bilingual technical reports.

Validation

  • Exact-native BF16 text parity: maximum and mean error 0 through all 24 CLIP layers and the detector projection.
  • Image and box-prompt parity: scores within 0.01, boxes within 2 px, and per-instance mask IoU at least 0.9989319.
  • Video parity: stable object ID across three frames, frame 0 mask IoU 0.9982227, and explicit zero-foreground assertions for the two later masks that are also empty upstream. Raw negative tracker scores are preserved.
  • Real mlx-community/sam3-4bit prompted segmentation inference completes with finite detections and non-empty source-resolution masks.
  • Integrated mlxcel predict image and video commands write the complete JSON, safetensor, metadata, and PNG contracts. mlxcel arch --json advertises both SAM 3 model types with the predict runtime and masks output. mlxcel generate redirects both model types to mlxcel predict.
  • Focused SAM 3 tests, cargo clippy -p mlxcel --profile test-fast --features rocm --lib --tests -- -D warnings, formatting, repository asset/provenance checks, and independent implementation review pass.

Final integration at df47faf937b9a942089baff9c0688af21c97cbb6 includes the merged DINOv2 and Sapiens 2 implementations. The focused SAM regressions and all 13 DINOv2 tests pass against the same newly compiled library. Actual CLI artifact checks were run at c1ed3f8a; subsequent integration preserves SAM inference and serialization. The branch was subsequently rebased to f4b6318fa1ff8222ccb7e6cc1daf2f899960e7ab on main 853050b3; all runtime source, fixtures, and Cargo files are byte-identical to the tested head. The rebase only imports the WebUI Activity CI changes, and all eight fast contracts, formatting, and whitespace checks pass. Fresh rebased-head CI is checked separately before merging.

The pinned upstream tracker produces empty masks on later frames in both the moving-clip and repeated-frame/box experiments; this validates parity, not useful propagation quality. Checkpoint execution was validated on Linux ROCm, not Metal.

Closes #2429

@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:low Low priority area:models Model architectures, weights, loading, metadata modelsize:small 4-bit checkpoint <= 10GB; fast iteration, safe for smoke tests modeltype:vlm Vision-language model labels Oct 22, 2026
@inureyes
inureyes force-pushed the feature/issue-2429-sam3-segmentation branch 2 times, most recently from e5cf1df to df47faf Compare October 22, 2026 21:05
@inureyes
inureyes marked this pull request as ready for review October 22, 2026 21:21
@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 22, 2026
Add the shared prompt and instance-mask contract to mlxcel predict, including structured instances, U8 mask artifacts, source-pixel boxes, stable video object IDs, and prompt-capable registry metadata.

Port the SAM 3 ViT, CLIP, DETR, geometry, mask decoder, and memory tracker with native BF16 and quantized UnifiedLinear checkpoint loading. Pin authentic mlx-vlm text, image, box-prompt, and video inputs for parity coverage.

Validation: rustfmt and diff checks pass, and a default-feature library check passed during integration. ROCm, real-checkpoint, and parity validation remain pending serialized build access.

Refs #2429
Route DINOv2 bicubic preprocessing through the shared Pillow RGB8 implementation while preserving its existing regression test and SAM's bilinear and floating-mask paths. Restrict SAM tracking fixture allowances to the six committed mask files.

Validated formatting, diff checks, and all eight fast contract targets after rebasing SAM onto the merged DINOv2 base.
@inureyes
inureyes force-pushed the feature/issue-2429-sam3-segmentation branch from df47faf to f4b6318 Compare October 23, 2026 02:02
@inureyes
inureyes merged commit 6ca04d1 into main Oct 23, 2026
29 checks passed
@inureyes
inureyes deleted the feature/issue-2429-sam3-segmentation branch October 23, 2026 02:16
inureyes added a commit that referenced this pull request Oct 26, 2026
)

## Summary

The bf16 addmm rounding oracles in `dinov2_layers::policy` and `vision::dense` fail on Metal because they were captured on ROCm gfx1151 and x86_64 Linux CPU (#2551 and #2578 were validated on ROCm, not Metal). The failures come from which MLX kernel runs on each backend. This PR keys each oracle on a property the test can detect, without a production change. It also fixes a default-device race that made one failure vary between runs.

## Root cause

- **addmm at one row on Metal rounds twice.** MLX's Metal `AddMM::eval_gpu` sends `min(M, N) == 1` to `gemv_axbpy`. The `GEMVKernel` epilogue in `mlx/backend/metal/kernels/gemv.h` casts the F32 accumulator to bf16 before adding the bias, so the result equals a separate add. Two or more rows go to steel GEMM or `gemv_wide` (`gemv_wide_config` rejects `M <= 1` on every architecture generation), and those apply the bias before the single rounding. CPU and ROCm copy C into the output and run one GEMM with beta, so they round once at every row count.
- **Upstream MLX gives the same values.** Upstream `mlx` 0.32.4 from PyPI on this M1 Ultra (`applegpu_g13d`): GPU `mx.addmm` at 1 row gives `1.9375` (separate), at 2, 5, 16 and 64 rows it gives `1.9296875` (fused); the CPU stream gives `1.9296875` at every row count. The fc2 halfway case gives `1.0` at `[1,1,4]` and `1.0078125` at `[2,1,4]`, `[1,2,4]` and `[2,4]`.
- **The MLX bump in #2614 did not cause it.** `gemv.h` and `AddMM::eval_gpu` are byte-identical between the previous pin `bff10220` and the current pin `7ca40033`. Upstream `main` still has the cast before the bias add, and the 0.32.4 wheel, which predates both pins, reproduces the failure. I found no existing ml-explore/mlx issue for it.
- **Sapiens2 compiled RoPE.** The fixture's compiled value `-4.5597553e-6` is a ROCm capture. Upstream `mlx` 0.32.4 on this host gives `-4.589557647705078e-6` for both the compiled and the eager graph, on GPU and on CPU, and the repository generator `tests/fixtures/sapiens2/generate_rope_oracle.py` stops with "compiled and eager RoPE unexpectedly agree".
- **SAM 3D Body MHR CPU geometry.** The fixture was captured with MLX CPU on x86_64 Linux (glibc). On macOS, MLX CPU computes atan2, sin and cos through Apple's math library (`mlx/backend/cpu/simd/accelerate_simd.h`). Of the 388 elements in `body_params`, `hand_params`, `fk_state` and `fk_global_rot`, 27 differ by 1 or 2 ULP, and every other field matches bit for bit. Seven of the 27 are single atan2 calls. For those seven, upstream `mx.arctan2` on this host's CPU returns exactly mlxcel's values, and it differs from the fixture at exactly those seven.
- **The varying fifth failure is a device race.** The MHR test holds `DefaultDeviceGuard::cpu()`. Tests that read the default device without `lock_default_device()` could run on the CPU in the middle of their span. That is why `compiled_objects_gelu_tanh_matches_authentic_power_oracle` failed only in parallel, and `sapiens2_bf16_linear_uses_fused_bias_epilogue` passed in parallel only when it happened to run on the CPU. Once the MHR test passes, it holds its guard longer, which also exposed `moge3_refiner_forced_cache_pressure_preserves_full_unet_output` (12 of 24 parallel runs) and the batched-decode wrapper tests. Skipping the MHR test alone took that to 0 of 24.

## Changes

- New `src/vision/addmm_oracle_test_support.rs` (test-only) documents the routing and provides `ROUTING_ROWS`, `routing_rows` and `single_row_addmm_rounds_twice` (Metal GPU default device).
- The DINOv2 Objects linear, attention (qkv and proj), MLP (fc1 and fc2), SAM 3, SAM 3D Body and Sapiens2 linear oracles now run on two identical rows. There, the fused value is asserted on every backend and the separate value still differs, so the tests still prove the layer routes through addmm. The single-row value is also pinned per backend: separate on Metal GPU, and fused (the original authenticated oracle) elsewhere. No assertion was loosened to a tolerance.
- The Sapiens2 RoPE oracle expects the ROCm capture on ROCm GPU and upstream's eager-equal value elsewhere.
- The MHR geometry oracle stays bit-exact on Linux and for every non-transcendental field. Only on non-Linux hosts are the four transcendental fields bounded to 2 ULP.
- These tests now hold `lock_default_device()` (or `mlx_test_guard()`): every test touched above, the tanh GELU oracle and feed-forward tests, the MoGe3 focal solver oracle, the MoGe3 refiner cache-pressure test, and the three dense VLM batched-decode wrapper tests. The lock was not added inside `batched_decode_harness`, because `vlm_family_batched_decode_tests` already calls it under `mlx_test_guard()` and the lock is not reentrant.

- `tests/fixtures/sapiens2/README.md` now says the compiled RoPE capture is ROCm-only and gives the Metal and CPU value.

## Changes during review

- Implementation and security reviews found nothing at CRITICAL or HIGH. A follow-up commit updates comments only: the helper module now says the CUDA addmm key comes from reading its source and was not measured, and it warns that Metal also rounds twice for a one-column output. It also adds the README note above.

## Validation

Done on an Apple M1 Ultra, release build with `--features metal,accelerate`:

- `cargo test --release --features metal,accelerate --lib vision::dense`: 192 passed, 3 of 3 runs in default mode and 3 of 3 with `--test-threads=1`. A stress loop of the same binary passed 40 of 40 default-mode runs (main failed 5 per run).
- `cargo test --release --features metal,accelerate --lib dinov2_layers::policy`: 5 passed, 3 of 3 runs in each mode (main failed 5 of 5).
- `vision::` filter, one default-mode run: 882 passed. `vision::encoders::dinov2`: 20 of 20 runs passed.
- `cargo fmt --check`, `cargo clippy --features metal,accelerate --lib --tests -- -D warnings`, `scripts/ci/check_cross_repo_refs.py`.

No real-checkpoint run was needed: no production code changed. The diff touches only `#[cfg(test)]` code and test files, and the production layers keep calling `mlxcel_core::addmm` exactly as upstream `nn.Linear` does on each backend.

Not verified:

- ROCm gfx1151. The two-row fused expectation on ROCm comes from reading the overlay's `AddMM::eval_gpu` (one rocBLAS or naive GEMM with beta for every M), not from a run.
- Metal M3 or newer, where two rows select `gemv_wide`. That this path rounds once comes from its source (`alpha * result + beta * bias` computed in F32, then one cast), not from a run.
- Linux on architectures other than x86_64 for the MHR oracle, and CUDA for the RoPE oracle, which has no capture.

Closes #2626
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata modelsize:small 4-bit checkpoint <= 10GB; fast iteration, safe for smoke tests modeltype:vlm Vision-language model priority:low Low priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Port SAM 3 (sam3) promptable segmentation and video tracking

1 participant