Repository navigation
fix(cuda): drain cp.async before qmm_sm80 epilogue smem store (#910) - #923
Conversation
Temp-0 decode of every 4-bit CUDA model was bitwise non-deterministic run to run, with occasional garbage tokens at positions where clean runs are confident by 14+ logits (issue #910). Bisection localized the defect to the qmm_sm80 CTA kernel: repeated identical forwards flip 23/23 at prefill length 8 (the M * B >= 8 dispatch boundary into qmm_sm80) and 0/23 at length 4 (qmv path), and compute-sanitizer racecheck reports a shared-memory write-write hazard inside qmm_sm80_kernel. Root cause: SharedStorage in device/qmm_sm80.cuh is a union, so the epilogue's C staging tile aliases the A/B cp.async pipeline slots, but the mainloop only ever waits down to K_PIPE_MAX-2 outstanding cp.async groups and its final iteration issues a redundant fetch_gmem of the last K tile. The epilogue then writes the C tile into the same shared memory bytes with no cp_async_wait and no barrier, so a late-landing async copy of A/B data overwrites staged C values before the smem-to-gmem copy reads them. The winner depends on DMA timing, which is why CUDA_LAUNCH_BLOCKING=1 and other host-slowing knobs suppress (but do not eliminate) the flips. bf16 dense models are clean because they use cuBLASLt and never reach this kernel; MoE routing flips (the issue's Layer B) are downstream of the same defect via the gather_qmm dispatch of qmm_sm80. Fix, carried as an overlay on the pinned MLX b7c3dd6d: add cp_async_wait<0>() plus __syncthreads() at the top of the epilogue in device/qmm_sm80.cuh, retiring all outstanding copy groups and re-converging the CTA before any thread overwrites the union (this also closes the cross-thread write-after-read hazard on the final pipeline slot reads). The JIT module name in quantized/qmm/qmm_sm80.cu is bumped to qmm_sm80_r2 because the on-disk PTX cache is keyed by module name only and would otherwise keep serving the racy kernel after an upgrade. Validation on GB10 (sm_121): 20/20 temp-0 CLI runs of 128 tokens byte-identical on llama-3.2-1b-4bit, matching the CUDA_LAUNCH_BLOCKING=1 output; 6/6 on qwen3-4b-4bit; 3/3 on qwen3-30b-a3b-4bit (MoE); 6/6 with MLX_USE_CUDA_GRAPHS=0 (previously ~1/10 flips); racecheck 0 hazards (was 214 errors); decode throughput unchanged (256 vs 259 tok/s noise). New CUDA-gated regression test repeats an identical prefill+decode sequence and asserts byte-identical logits; it failed 23/23 iterations pre-fix. Upstream MLX report drafted in docs/upstream/mlx-cuda-quantized-matmul-nondeterminism.md. Refs #910
Implementation Review SummaryIntent
Verdict on the two highest-priority questionsSync-fix correctness: CORRECT. JIT-name-bump completeness: COMPLETE. Verification
Notes (informational, no action needed)
Remaining Items
|
…#910) (lablup#923) ## Summary Fixes the run-to-run bitwise non-determinism (and occasional garbage tokens) of temp-0 decode on all 4-bit CUDA models by closing a shared-memory write-write race in the vendored MLX qmm_sm80 kernel: the epilogue staged its output tile into shared memory that aliases the A/B cp.async pipeline slots (SharedStorage is a union) without first retiring in-flight cp.async groups, so a late-landing async copy could overwrite freshly staged C values before they were copied to global memory. ## Root cause (refines the issue's working hypothesis) The issue's Layer A hypothesis pointed at the async-allocator/command-encoder machinery; evidence-driven bisection landed one level deeper, inside the kernel itself. Repeated identical in-process forwards flip 23/23 at prefill length 8 and 0/23 at length 4, exactly the `M * B < 8 ? qmv : qmm_sm80` dispatch boundary in quantized.cpp, and `compute-sanitizer --tool racecheck` deterministically reports a write-write hazard in `qmm_sm80_kernel` (214 errors pre-fix, 0 post-fix). Even `CUDA_LAUNCH_BLOCKING=1` still flipped 1/23 in a tight in-process loop, proving the race is intra-kernel rather than a host-side missing stream dependency; launch-blocking (and graphs-off, and graph-cache-off) merely narrow the DMA timing window, which is why they looked like discriminators. In upstream MLX b7c3dd6d `mlx/backend/cuda/device/qmm_sm80.cuh`, the mainloop only ever waits down to `K_PIPE_MAX-2` outstanding cp.async groups (lines 235, 249) and its final iteration issues a redundant `fetch_gmem` of the last K tile (line 257), yet the epilogue (lines 265-272) writes the aliasing C tile with no `cp_async_wait<0>()` and no leading `__syncthreads()`. bf16 dense models were never affected because they use cuBLASLt and do not reach this kernel; the issue's Layer B (MoE router expert-set flips) is downstream of the same defect via the batched gather_qmm dispatch of qmm_sm80 and resolves with this fix (no separate Layer B change needed). ## What changed - `src/lib/mlx-cpp/patches/mlx/backend/cuda/device/qmm_sm80.cuh` (new overlay): adds `cp_async_wait<0>()` + `__syncthreads()` at the top of the qmm_sm80_mainloop epilogue, retiring all outstanding copy groups and re-converging the CTA before any thread overwrites the union (also closes the cross-thread write-after-read hazard on the final pipeline-slot reads); otherwise byte-identical to upstream b7c3dd6d. - `src/lib/mlx-cpp/patches/mlx/backend/cuda/quantized/qmm/qmm_sm80.cu` (existing overlay): JIT module name bumped to `qmm_sm80_r2` because the on-disk PTX cache is keyed by module name only, so without the bump a stale cached PTX would keep serving the racy kernel after an upgrade; top-of-file overlay header now documents both the lablup#637 tile change and this fix. - `tests/cuda_qmm_determinism.rs` (new): CUDA-gated regression test that repeats an identical prefill (64 tokens, forcing the qmm_sm80 path) + fixed-token decode sequence with fresh KV caches and asserts byte-identical logits at every step across 10 iterations; failed 23/23 iterations pre-fix, skips gracefully when the model checkpoint is absent, model dir overridable via `MLXCEL_TEST_QMM_MODEL_DIR`. - `docs/upstream/mlx-cuda-quantized-matmul-nondeterminism.md` (new): upstream MLX bug report draft with the evidence tables, exact file/line root cause, minimal fix diff, and standalone repro (value-level loop plus deterministic racecheck detection), ready for manual submission to ml-explore/mlx. ## Test plan - [x] `MLX_CUDA_ARCHITECTURES=121 cargo test --release --features cuda --test cuda_qmm_determinism` passes (GB10) - [x] 20/20 temp-0 CLI runs of 128 tokens byte-identical on llama-3.2-1b-4bit, matching the `CUDA_LAUNCH_BLOCKING=1` reference output (pre-fix: 3+ distinct outputs in 4 runs) - [x] 6/6 byte-identical on qwen3-4b-4bit, 3/3 on qwen3-30b-a3b-4bit (MoE, Layer B path) - [x] 6/6 byte-identical with `MLX_USE_CUDA_GRAPHS=0` (pre-fix ~1/10 flips) - [x] `compute-sanitizer --tool racecheck`: 0 hazards (pre-fix 214 errors in qmm_sm80_kernel) - [x] Decode throughput unchanged (256 vs 259 tok/s, run-to-run noise); orchestrator to run the full 6-model determinism matrix including the gemma4 26B 5-paragraph repro Closes lablup#910
## Summary The micro-oracle executor now runs the emitted IREE operation on `cuda` and `hip` as well as local CPU, and `mlxcel_xla::run_production_probe` takes an external reference with its backend identity, so `mlxcel-xla` never calls MLX. The new `xla_mlx_micro_oracle` example (`--features cuda,xla-micro-oracle`) supplies MLX CUDA references through `mlxcel-core` and produces `production-mlx` reports. Every family reference-check example pins `MLX_ENABLE_TF32=0` before MLX starts, refuses any other value, and records it. - Probe artifacts get their operator contract from the production builder (`production_operator_contract`, emitter revision `mlxcel-xla-stablehlo-emitter-v1`); the SSCP convolution reuses Gemma3n's own `subsample.convolution` declaration and the subsampler's operand-layout and BF16-result helpers, factored out of `sscp_conv` without changing its emission order. - Comparisons: the canonical suite's modes for the f32 operators (ExactBits for dense matmul, residual add, cumsum); Q4 uses the Qwen same-input `--atol/--rtol` 0.08; the convolution uses ExactBits, because its BF16-exact fixture keeps every window sum exact in F32 under any accumulation order (the Gemma3n stage gate's `max_abs` 5e-3 plus RMS 5e-4 has no single element-wise mode). No new tolerance. - The example refuses a binary whose Q4 kernel sources changed since build or lack the #923 `qmm_sm80_r2` revision, and writes Q4 reports in a separate `q4_post_923_reports` section. ## Evidence (GB10 spark-102, all GPU work under `gpu-lock`) MLX `fc344c98`, overlays sha256 `543a0239...`, Q4 kernel sha256 `abbae771...`, `MLX_ENABLE_TF32=0`, CUDA archs `121`, NVIDIA GB10 sm_121. IREE compiler 3.12.0rc20260721 @ `dc9601f8`, runtime `libiree-runtime-sha256-41529a0b...`, `--iree-hal-target-device=cuda`. | Operator | Mode | Result | max_abs | | --- | --- | --- | --- | | dense matmul | ExactBits | pass | 0 | | RMSNorm | 2e-6/2e-5 | pass | 0 | | LayerNorm | 2e-6/2e-5 | pass | 2.98e-8 | | softmax | 2e-6/2e-5 | pass | 2.98e-8 | | SiLU projection | 3e-6/3e-5 | pass | 4.77e-7 | | GELU projection | 3e-6/3e-5 | pass | 4.77e-7 | | residual add | ExactBits | pass | 0 | | cumsum [2,130] | ExactBits | pass | 0 | | SSCP conv2d [1,32,128,1] x [128,3,3,1], stride 2 | ExactBits | pass | 0 | | Q4 qmv, 1x256 -> 128 (MLX path `qmv`) | 0.08/0.08 | pass | 1.95e-3 | | Q4 qmm, 16x256 -> 128 (MLX path `qmm_sm80`) | 0.08/0.08 | pass (bit-identical) | 0 | Every report is `production-mlx` with `production_qualified=false`, because IREE exposes no dispatch kernel identity. Kernel paths come from `MLXCEL_TRACE_ARCH=1` runs with `--only q4-qmv` and `--only q4-qmm`. With `MLX_ENABLE_TF32=1` the example exits before MLX starts. Greedy token comparison, `tests/fixtures/test_image.png`, prompt "Describe this image.", `-n 64 --temp 0`, XLA with `MLXCEL_BACKEND=xla MLXCEL_XLA_DEVICE=cuda MLXCEL_XLA_CONTEXT_CAPACITY=16512`: - Qwen2.5-VL 3B 4bit: MLX emits `785 2168 374 264 6437 18575 1894 13` then stops at `<|im_end|>`. XLA emits the same 8 tokens, then 151645 and keeps going, because the checkpoint has no `generation_config.json` and `mlxcel_xla::read_eos` reads only that file (#3292). Token-exact up to EOS. - Qwen3-VL 2B 4bit: the first 8 tokens match (`1986 2168 374 264 7377 39034 315 264`); at generated index 8 MLX picks 48204 and XLA picks 6437. Two causes, neither an XLA operator defect. First, the eager image processor ignores the checkpoint's pixel bounds, so eager sees 49 image tokens where XLA and HF see 64 (#3290). Second, with identical 64-token input the step is a near-tie: XLA top-2 margin 0.020, eager 0.125 (one bf16 step), and eager language fed the XLA vision features is an exact bf16 tie. XLA runs the vision tower in f32 and eager in bf16; matching the rounding boundaries is #3291. Every same-input per-block vision control and the same-input language control pass at the unchanged 0.08/0.08. `xla_qwen3_vl_deepstack_check` gains `--token-ids` (teacher-forced replay of a real prompt), top-5 logits and top-2 margins for IREE, eager, and eager on IREE vision, report-only per-block same-input vision controls for blocks 2-23, and a same-input language control. `Qwen3VLModel::get_input_embeddings_from_features` shares the existing merge, DeepStack and MRoPE steps with the production path through one private helper. Two more pre-existing findings: the CLI sizes an XLA Qwen-VL image request from the worst-case floor at `DEFAULT_MAX_PIXELS` (16410 positions for a 224x224 image that expands to 64 tokens), and the request-sized 32768 shape runs out of CUDA memory in `prefill_embeddings`. An explicit 16512 capacity works. ## Test plan - [x] `cargo test -p mlxcel-xla --lib --profile test-fast --features iree,micro-oracle` filters `numeric_probe`, `production_probe_ops`, `gemma3n_audio`, `numeric_ops`, `operator_numeric_contract` (all pass) - [x] `cargo clippy -p mlxcel-xla --lib --tests --features iree,micro-oracle -- -D warnings`, and `--lib --features iree` - [x] `cargo clippy --features cuda,xla-diagnostics,xla-reference-diagnostics,xla-micro-oracle --examples -- -D warnings` - [x] `xla_numeric_probe local-task`: all 9 canonical reports pass unchanged - [x] `xla_mlx_micro_oracle` on cuda: 11 of 11 pass - [x] `python3 scripts/ci/check_env_var_docs.py`, `cargo fmt --check` - [x] `cargo check --features cuda,xla-iree --all-targets` and `--no-default-features --features xla-diagnostics --all-targets` - [x] `spike/openxla/test_youtu_vl_reference_oracle.py` (15 pass; the oracle now accepts `mlx_enable_tf32=0` on the mlxcel capture only) Closes #3212
Summary
Fixes the run-to-run bitwise non-determinism (and occasional garbage tokens) of temp-0 decode on all 4-bit CUDA models by closing a shared-memory write-write race in the vendored MLX qmm_sm80 kernel: the epilogue staged its output tile into shared memory that aliases the A/B cp.async pipeline slots (SharedStorage is a union) without first retiring in-flight cp.async groups, so a late-landing async copy could overwrite freshly staged C values before they were copied to global memory.
Root cause (refines the issue's working hypothesis)
The issue's Layer A hypothesis pointed at the async-allocator/command-encoder machinery; evidence-driven bisection landed one level deeper, inside the kernel itself. Repeated identical in-process forwards flip 23/23 at prefill length 8 and 0/23 at length 4, exactly the
M * B < 8 ? qmv : qmm_sm80dispatch boundary in quantized.cpp, andcompute-sanitizer --tool racecheckdeterministically reports a write-write hazard inqmm_sm80_kernel(214 errors pre-fix, 0 post-fix). EvenCUDA_LAUNCH_BLOCKING=1still flipped 1/23 in a tight in-process loop, proving the race is intra-kernel rather than a host-side missing stream dependency; launch-blocking (and graphs-off, and graph-cache-off) merely narrow the DMA timing window, which is why they looked like discriminators. In upstream MLX b7c3dd6dmlx/backend/cuda/device/qmm_sm80.cuh, the mainloop only ever waits down toK_PIPE_MAX-2outstanding cp.async groups (lines 235, 249) and its final iteration issues a redundantfetch_gmemof the last K tile (line 257), yet the epilogue (lines 265-272) writes the aliasing C tile with nocp_async_wait<0>()and no leading__syncthreads(). bf16 dense models were never affected because they use cuBLASLt and do not reach this kernel; the issue's Layer B (MoE router expert-set flips) is downstream of the same defect via the batched gather_qmm dispatch of qmm_sm80 and resolves with this fix (no separate Layer B change needed).What changed
src/lib/mlx-cpp/patches/mlx/backend/cuda/device/qmm_sm80.cuh(new overlay): addscp_async_wait<0>()+__syncthreads()at the top of the qmm_sm80_mainloop epilogue, retiring all outstanding copy groups and re-converging the CTA before any thread overwrites the union (also closes the cross-thread write-after-read hazard on the final pipeline-slot reads); otherwise byte-identical to upstream b7c3dd6d.src/lib/mlx-cpp/patches/mlx/backend/cuda/quantized/qmm/qmm_sm80.cu(existing overlay): JIT module name bumped toqmm_sm80_r2because the on-disk PTX cache is keyed by module name only, so without the bump a stale cached PTX would keep serving the racy kernel after an upgrade; top-of-file overlay header now documents both the perf(cuda/quant): sm_120/sm_121-tuned quantized GEMM for Blackwell prefill #637 tile change and this fix.tests/cuda_qmm_determinism.rs(new): CUDA-gated regression test that repeats an identical prefill (64 tokens, forcing the qmm_sm80 path) + fixed-token decode sequence with fresh KV caches and asserts byte-identical logits at every step across 10 iterations; failed 23/23 iterations pre-fix, skips gracefully when the model checkpoint is absent, model dir overridable viaMLXCEL_TEST_QMM_MODEL_DIR.docs/upstream/mlx-cuda-quantized-matmul-nondeterminism.md(new): upstream MLX bug report draft with the evidence tables, exact file/line root cause, minimal fix diff, and standalone repro (value-level loop plus deterministic racecheck detection), ready for manual submission to ml-explore/mlx.Test plan
MLX_CUDA_ARCHITECTURES=121 cargo test --release --features cuda --test cuda_qmm_determinismpasses (GB10)CUDA_LAUNCH_BLOCKING=1reference output (pre-fix: 3+ distinct outputs in 4 runs)MLX_USE_CUDA_GRAPHS=0(pre-fix ~1/10 flips)compute-sanitizer --tool racecheck: 0 hazards (pre-fix 214 errors in qmm_sm80_kernel)Closes #910