Skip to content

test(vision): key bf16 oracles on the kernel each backend selects - #2631

Merged
inureyes merged 4 commits into
mainfrom
fix/issue-2626-metal-addmm-oracles
Oct 26, 2026
Merged

inureyes merged 4 commits into
mainfrom
fix/issue-2626-metal-addmm-oracles

Conversation

@inureyes

@inureyes inureyes commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

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 update: advance MLX pin and preserve backend overlays #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

The bf16 addmm rounding oracles were captured on ROCm and x86_64 Linux CPU and failed on Metal. MLX's Metal AddMM routes a single-row product to gemv_axbpy, whose epilogue casts the F32 accumulator to bf16 before adding the bias, so at one row addmm rounds like a separate add. Upstream mlx 0.32.4 on an M1 Ultra shows the same split: GPU addmm gives the separate value at one row and the fused value at two or more rows, and the CPU stream is fused at every row count.

- Run the addmm routing oracles (DINOv2 Objects linear, attention and MLP, SAM 3, SAM 3D Body and Sapiens2 linears) on two identical rows, where every backend rounds once, and pin the single-row value per backend through a shared test helper.
- Key the Sapiens2 compiled RoPE oracle on ROCm. Metal and CPU produce the eager value for both graphs, as upstream does.
- Keep the SAM 3D Body MHR CPU geometry oracle bit-exact on Linux. On other hosts, bound the four transcendental fields to 2 ULP, since macOS MLX CPU evaluates atan2, sin and cos through Apple's math library.
- Hold the default-device lock in tests whose expectation or comparison depends on the default device, so a concurrent CPU guard cannot switch it mid-test.
@inureyes inureyes added type:test Test related changes priority:medium Medium priority platform:macos macOS (Apple Silicon) specific status:review Under review labels Oct 26, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review of the test-only change: no CRITICAL, HIGH, or MEDIUM findings, no fixes pushed.

  • Lock ordering: every added span takes lock_default_device() once, and the three batched-decode wrapper tests take mlx_test_guard() (serial mutex, then device lock), matching its documented order. No helper called inside a new span takes either lock again (production code never takes the device lock, assert_batched_decode_matches_sequential does not, and the same-named helper in vlm_family_batched_decode_tests is a separate function). Both locks recover from poisoning, so a failing oracle does not cascade.
  • Runtime: the serialized spans are sub-millisecond tensor ops; vision::dense runs in about 0.6 s in parallel (5 of 5 runs, 192 passed) and vision:: in 1.7 s (882 passed).
  • ULP comparison in mhr_tests.rs: the ordered-integer mapping cannot overflow (i32::MIN - bits for negative bits stays in range, widened to i64 before subtraction), signed zeros compare equal, NaN fails the bound, and dtype and shape are asserted before zipping, so chunks_exact cannot silently truncate. The fixture is a checked-in file, so it is not an untrusted input.

LOW, no change requested:

  • cfg!(target_os = "linux") keeps the four transcendental fields bit-exact on every Linux arch, while only x86_64 glibc is the measured capture host. An aarch64 Linux run may need the same ULP bound; the PR body already lists this as unverified.
  • single_row_addmm_rounds_twice encodes only the M == 1 side of Metal's min(M, N) == 1 routing. Correct for the current oracles (N is 3 or 4), but a future oracle with a one-column output would also round twice; a doc line on the helper would prevent that surprise.

…le notes

Review follow-up: state that the CUDA addmm key comes from reading its source, warn that one-column outputs also take Metal's gemv route, and say in the Sapiens2 fixture README that the compiled RoPE capture is ROCm-only.
@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 26, 2026
@inureyes
inureyes marked this pull request as ready for review October 26, 2026 13:48
@inureyes
inureyes merged commit d38d021 into main Oct 26, 2026
13 checks passed
@inureyes
inureyes deleted the fix/issue-2626-metal-addmm-oracles branch October 26, 2026 13:48
@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

platform:macos macOS (Apple Silicon) specific priority:medium Medium priority status:done Completed type:test Test related changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test(vision): bf16 addmm rounding oracles fail on M1 Ultra

1 participant