Repository navigation
fix(cuda): take the batch stride in sorted gather_mm, make captures barriers - #2477
Merged
Merged
Conversation
…arriers Two CUDA overlay defects produced silently wrong values on GB10, each hidden behind a model-level workaround (issue #2462). `gather_mm_rhs` (the `M == 1 && right_sorted` branch every sorted MoE expert gather takes) passed `a.strides(-2)` to the grouped GEMM as the stride between consecutive gathered rows. In that branch `a` is `[rows, 1, K]`, so that is the stride of a size-1 axis, which MLX ignores when it flags an array row-contiguous and leaves at whatever the producer wrote. The Privacy Filter's per-expert bias add (`out + expand_dims(take(bias, ids), -2)`) hands down a unit stride there whenever the add donates the bias operand, which depends on the buffer the cache gave the other operand, so every row after the first of an expert group read shifted activations: PR #2460's allocation-history-dependent drift. The branch now makes `a` row-contiguous and uses `lda = K`, and the Privacy Filter sorts its dense planes again. Separately, upstream orders a stream-captured child graph (every cuBLASLt matmul) only by the buffers it declares, which lets its kernels run alongside unrelated kernel nodes of the same CUDA graph. On GB10 that overlap corrupted f32 GEMMs in about 40% of fresh processes: the first run of GLiNER2.5's 12-layer DeBERTa-v2 encoder returned wrong hidden states from a random layer, every replay correct; chaining the graph in program order removed it, chaining only kernel-kernel edges did not, and the shared resource inside cuBLASLt is not identified. The new `device.cpp` overlay makes captured child graphs barriers (join the open branches before, gate the nodes after; `MLXCEL_CUDA_GRAPH_CAPTURE_BARRIER=0` for A/B), and the encoder no longer ends a graph after every layer. New tests: a unit-stride `[rows, 1, K]` and the Privacy Filter's biased op chain fed to the sorted gather (both fail on the unfixed overlay), three allocation-history tests, and `real_encoder_first_run_equals_replay`, run in 20 fresh processes (0 failures with the barrier, 5 of 10 without). Privacy Filter checkpoint gates pass on the sorted dense path, including the bf16, 8-bit, bf16 order PR #2460 saw drift in. `mlxcel_core::array_strides` is new. Closes #2462
Review pass follow-ups on the barrier overlay and the sorted gather tests (issue #2462). MLXCEL_CUDA_GRAPH_CAPTURE_BARRIER and MLXCEL_CUDA_GRAPHS_DOT_VERBOSE now parse with the convention docs/environment-variables.md documents (trimmed, case-insensitive, 0/false/off/no and 1/true/on/yes) instead of MLX's atoi env reader, which read `on` as 0 and would have disabled the barrier by default. A concurrent batch (ConcurrentContext) whose nodes include a captured child graph now makes its join node the barrier and inherits the capture flag from any node collected inside it, so cuBLASLt matmuls grouped under a concurrent section gate later nodes the same way single nodes do, and the batch join clears the open-branch state so nothing points at a node the batch already closed. The per-encoder barrier map is leaked on purpose: CommandEncoder's destructor runs commit and clear_graph_state during thread exit, after a thread_local with a destructor may already be gone, and the comment records that reasoning and the new_thread_unsafe_stream caveat that would move the map under a mutex. The sorted gather test RNG draws from the symmetric top-24-bit form (the same as openai_privacy_filter_tests::Lcg) and reads activations back through the bf16 promotion the CUDA dtype overlay applies, and the layout tests assert their stride setups with assert_eq instead of printing them, so a regression fails loudly. The CHANGELOG entry lists every family that sorts its routed rows into the branch and the three whose per-expert bias adds hand it a unit stride today; the two env docs rows describe the flag grammar and the overlay README covers the added device.cpp and the pin-bump checklist's drift check. Revalidated after these edits: the 6 sorted gather layout and history tests, the Privacy Filter checkpoint gates on the sorted dense path, and real_encoder_first_run_equals_replay in 20 fresh processes with the barrier (0 failures; 13 of 20 without it even with CUDA_MODULE_LOADING=EAGER, so lazy module loading is not the trigger and the barrier is).
…ather-mm-graph-first-run # Conflicts: # src/lib/mlxcelverse/overlays/cuda/README.md
8 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Two CUDA overlay fixes for silently wrong values on GB10, each with tests that fail on the unfixed overlay, and both model-level workarounds removed: the OpenAI Privacy Filter sorts its dense expert planes again and the DeBERTa-v2 encoder (GLiNER2.5) no longer ends a CUDA graph after every layer.
A1: sorted
gather_mmread the stride of a size-1 axis as its leading dimensiongather_mm_rhs(matmul.cpp, theM == 1 && right_sorted_branch every sorted MoE expert gather takes) passeda.strides(-2)to the grouped GEMM as the stride between consecutive gathered rows. Thereais[rows, 1, K], so that is the stride of a size-1 axis, which MLX ignores when it flags an array row-contiguous (check_contiguity) and leaves at whatever the producer wrote. The branch now makesarow-contiguous and useslda = K, the batch stride, asGatherQMM's grouped path already did.The producer in the Privacy Filter is the per-expert bias add in
ExpertLinear::forward,out + expand_dims(take(bias, ids), -2):expand_dimsinserts a stride of 1, and a binary op inherits its second operand's layout when it donates that operand, which happens only when the first operand's cached buffer is more than 16 KiB over size (the cache hands out buffers up to two pages larger). So gate and up carried strides[N, 1, 1]or not depending on what the allocator had handed out, the compiled SwiGLU and the bf16 cast inherited them, and the down projection's sorted gather readlda = 1: the first row of every expert group right, every later row shifted by one element. That is PR #2460's drift (2024-05-17sliding fromprivate_datetoprivate_phoneafter the 8-bit model had run). A deferred per-plane capture showed exactly that signature (gate and up off by one bf16 ulp,downrows 1.. of each group off by up to 7.7e2). Also recorded: the overlay promotesbf16 + f32to bf16 (overlays/cuda/mlx/dtype.cpp), so "f32 activations" never reach this kernel as f32; the stride bug is dtype-independent.Exposure: every
SwitchLinear::forward(.., sorted = true)caller with non-quantized planes reaches the branch (deepseek, exaone_moe, glm4_moe, glm4_moe_lite, gpt_oss, hunyuan_moe, ernie4_5_moe, llama4, qwen3_next, gemma4, phixtral, the SwitchGLU families, openai_privacy_filter). Theirsorted_xis atakeoutput with natural strides; the producers that reach the branch with a unit stride today are the biasedExpertLinearplanes of GPT-OSS and the Privacy Filter, so a dense (bf16) GPT-OSS checkpoint was exposed the same way (quantized ones takegather_qmm).A2: captured child graphs race with concurrent kernel nodes
The first
encodeof a fresh process returned wrong hidden states in about 40% of processes (7 of 20 on main with the split forced off), from a random layer each time, every replay correct. Allocation poisoning (0xFF on every allocation) changed nothing and produced no NaN. Bisection, 20 fresh processes each: graphs off 0, one op per graph 0, the whole encode in one graph 0, graph exec cache of 1 (fresh instantiation per graph) 10 of 10, program-order chaining of every node 0, chaining only edges that touch a stream-captured child graph (the cuBLASLt matmuls) 0, chaining only kernel-kernel edges 18, zeroing the whole cuBLASLt workspace inside the capture 0, workspace ceiling 0 (no split-K) 10. The child graphs holdcutlass_80_simt_sgemm_*withcublasLt::splitKreduce_kerneland a 240-byte workspace memset; their declared buffers and the dumped edges are correct. The resource that makes a cuBLASLt child graph wrong when an unrelated kernel node of the same graph runs alongside it is not identified.Fix (
device.cppoverlay, new): a captured child graph is a barrier inside a graph. It joins every open branch added before it and every node added after it depends on it, on top of upstream's buffer-derived edges; kernel nodes between two child graphs stay concurrent. 0 of 30 fresh processes with the barrier, 5 of 10 withMLXCEL_CUDA_GRAPH_CAPTURE_BARRIER=0on the same binary.MLXCEL_CUDA_GRAPHS_DOT_VERBOSE=1adds node parameters toMLX_SAVE_CUDA_GRAPHS_DOT_FILEdumps. Both are indocs/environment-variables.md.Review pass (
5e29de95): the two switches parse with the docs grammar (trimmed, case-insensitive,0/false/off/noand1/true/on/yes) via a newmlxcel_env_flaghelper, since MLX'satoienv reader readsonas 0 and would have disabled the barrier by default; aConcurrentContextbatch whose nodes include a captured child graph makes its join node the barrier and clears the open-branch state afterwards, so cuBLASLt matmuls grouped under a concurrent section gate later nodes the same way single nodes do; and the per-encoder barrier map is leaked on purpose (~CommandEncoderrunscommitandclear_graph_stateduring thread exit, after athread_localwith a destructor may be gone).Perf A/B (same binary, barrier on vs off, 3 rounds interleaved,
mlxcel generate --profileon a 1767-token prompt): prefill qwen2.5-0.5b-bf16 on 3274 / 3415 / 3413 tok/s vs off 3421 / 3277 / 3260; llama-3.2-1b-4bit on 3896 / 4094 / 3847 vs off 3879 / 3929 / 3947, both within the run-to-run spread. Decode of 64 tokens after the same prompt, qwen2.5-0.5b-bf16 on 151.6 / 156.9 tok/s vs off 155.1 / 154.2 / 157.1 (the first "on" run, 97.5, was the cold process); llama-3.2-1b-4bit on 165.1 / 167.0 vs off 164.9 / 163.4 / 166.8. Decode runs gemv kernels, so no child graph is captured and the barrier is inert. The f32 encoder (mlxcel extract, gliner2.5-small-v1, 1400-character text, wall including load): on 1.25 / 1.26 / 1.25 s vs off 1.19 / 1.19 / 1.25 s, about +4%, the prefill GEMMs no longer overlap their neighbours.mlxcel tagon openai-privacy-filter-bf16: on 2.27 / 2.34 s vs off 2.31 / 2.19 / 2.35 s. MoE decode A/B (bench-decode, same binary, barrier on vs off, 4 interleaved rounds per arm): qwen3-moe-4bit on 76.46 vs off 75.96 tok/s, phi-3.5-moe-4bit on 43.21 vs off 42.61, paired deltas alternate sign and sit inside the ~1.5% host noise floor, so the barrier costs nothing measurable on MoE decode either.Tests and code
src/models/switch_layers_sorted_gather_layout_tests.rsand_history_tests.rs(new, helpers in_test_support.rs):sorted_gather_mm_with_a_unit_stride_on_the_singleton_axisandsorted_gather_mm_after_a_biased_expert_add(the Privacy Filter's op chain, donation forced) fail on the unfixed overlay (max |err| 1.19 and 5e-1 against an f64 reference, versus one bf16 ulp) and pass on the fix;sorted_gather_mm_with_a_transposed_layout_planecovers the row-major B instantiation; three history tests run the sorted gather before and after an 8-bitgather_qmmMoE, allocator churn and other sorted shapes and compare byte for byte (they pass before and after: allocation history alone never triggered it).src/models/deberta_v2_tests.rs::real_encoder_first_run_equals_replay(new): the whole trunk on the 306-token fixture, first encode equals replay bit for bit, run in N fresh processes.openai_privacy_filter_layers.rsdropssort_routed(every plane sorts at 64 or more rows, upstream's threshold);moe_block_runs_both_gather_paths_identicallynow compares the sorted and unsorted paths for real.deberta_v2.rsdropsgraph_break_per_layer.mlxcel_core::array_stridesis new (post-eval strides only; before eval they are the shape's defaults).Verification (GB10 sm_121,
--profile test-fast --features cuda,MLX_ENABLE_TF32=0, test binary under gpu-lock with--test-threads=1)sorted_gather6 passed; on a control build with the unfixedmatmul.cppthe unit-stride and biased-add tests fail and the other four pass.privacy_filter_8bitthenprivacy_filter_spansin one process (PR feat(models): support OpenAI Privacy Filter PII tagger in mlxcel tag #2460's failing order): 3 of 3 fail on the control build, 3 of 3 pass on the fix.privacy_filter_checkpoint_tests5 passed on the sorted dense path (the acceptance sentence in the bf16, 8-bit, bf16 order; the 4536-token chunk-invariance check; the log-prob and span fixtures).real_encoder_first_run_equals_replay0 failures in 20 fresh processes; the same binary with the barrier disabled fails 5 of 10, and 13 of 20 withCUDA_MODULE_LOADING=EAGERand the barrier disabled, so lazy module loading is not the trigger. Revalidated after the review fixes: 20 fresh processes with the barrier, 0 failures.deberta_v28,gliner2_522,token_classification86,openai_privacy_filter10 passed.cargo fmt --all -- --checkandcargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests --no-deps -- -D warningsclean. Full lib suite with--test-threads=1: 9373 passed, 0 failed, 166 ignored.5e29de95(161 test binaries run in place under gpu-lock with--test-threads=1): build 0, clippy 0, doctests 0, contract set 0; 160/161 bins pass,mllama_parityfailed once with the known 1-ulpragged_multi_image_states_concatenate_real_rowsflake and passes on rerun (8/8); issue test: fix intermittent mllama exact-zero assert and webui router race #2467. After merging main (PRs docs(install): list every declared Cargo feature in the feature table #2469 to bench: add M3 Ultra baselines for the three large MoE checkpoints #2476, one overlay README conflict resolved with both additions), the same gate on the merged head3ae5e2c1gives the same result: build 0, clippy 0, doctests 0, contract set 0, 160/161 with the same mllama flake passing on rerun.Upstream report drafts (not filed)
A1,
[CUDA] gather_mm with sorted indices reads the stride of a size-1 axis as lda:GatherMM::eval_gpuroutesM == 1 && right_sorted_togather_mm_rhs, which passesensure_batch_contiguous(a)'sstrides(-2)asldatocutlass_grouped_gemm_unaligned;ais[..., 1, K]there, so that is a size-1 axis stride thatcheck_contiguityignores andexpand_dimsor a donating binary op leaves at 1, and every gathered row after the first of a group then reads shifted memory. Repro:a = mx.swapaxes(mx.random.normal((96, 640, 1)), 1, 2)(strides(640, 1, 1)),wbf16(128, 640, 640), sorted expert ids,mx.gather_mm(a.astype(mx.bfloat16), mx.swapaxes(w, -1, -2), rhs_indices=idx, sorted_indices=True)versussorted_indices=False: rows that are first in their group agree, every other row differs by O(1). Fix: makearow-contiguous and uselda = a.shape(-1), asGatherQMMalready does.A2,
[CUDA] stream-captured child graph nodes (cuBLASLt matmuls) race with concurrent kernel nodes of the same graph: GB10 sm_121, driver 580.178.04, CUDA 13, MLX 243bdf09c,MLX_ENABLE_TF32=0, f32 weights (fastino/gliner2.5-small-v1, 12 DeBERTa-v2 layers, hidden 384, 306 tokens). About 40% of fresh processes return a first forward that differs from every later one by 0.1 to 0.6, from a random layer; the bisection is the list in the A2 section above. Each cuBLASLt call has its own workspace, registered inputs and outputs, and correct edges in the dumped graphs. Workaround: captured child graphs as barriers inside a graph. Repro: lablup/mlxcelsrc/models/deberta_v2_tests.rs::real_encoder_first_run_equals_replayin 20 fresh processes withMLXCEL_CUDA_GRAPH_CAPTURE_BARRIER=0.Technical report:
TECHNICAL_REPORTS/pr-2477-cuda-gather-mm-graph-barrier.en.md(Korean.ko.md).Closes #2462