Repository navigation
fix(cuda): repack gather_mm operands whose batch axes are not packed - #3761
Merged
inureyes merged 4 commits intoDec 4, 2026
Merged
Conversation
The grouped GEMM arms of the CUDA overlay's GatherMM::eval_gpu (the sorted M == 1 arm through gather_mm_rhs and the general cutlass_gather_mm arm) step from one batch matrix to the next by rows * cols elements, but ensure_batch_contiguous and check_transpose only look at the last two axes. A view whose matrices are packed but whose batch axis is not, such as the gate or up half of a fused [experts, 2 * ffn, hidden] expert stack split along axis 1, was taken as packed, and every expert after the first was read from the wrong offset. The Granite 4 hybrid MoE and Mistral 4 sanitizers (and the GraniteMoE port in lablup#3745) split their fused expert stacks that way at load, so an unquantized checkpoint takes wrong expert weights in every sorted (prefill) MoE gather on CUDA. On GraniteMoE that turns the whole output into noise; f32 hid it because astype repacks, and quantized exports store packed stacks. Upstream MLX has the same assumption in its sorted and general CUDA gather_mm paths. Add batch_packed() and copy an operand that fails it before the grouped GEMM, in ensure_batch_contiguous (which also covers GroupedMM) and in the general arm. Packed operands are untouched.
… batch axis The granitemoehybrid and mistral4 sanitizers split the fused [experts, 2 * ffn, hidden] gate/up stack along axis 1 into two views whose expert stride is 2 * ffn * hidden. With the overlay repack from the previous commit those views are correct, but every sorted or general-arm gather_mm on them copied the whole half-stack again, on every prefill and every batched-decode step with 64 or more pairs. Both sanitizers now pack each half into its own buffer once at load (as the GraniteMoE loader in lablup#3745 does) and evaluate it per layer, so the fused buffer is released as the load goes; the overlay repack stays as the safety net. ensure_batch_contiguous kept upstream's batch-axis loop, which compares strides(i + 1) * shape(i) with strides(i) (it should be shape(i + 1)), so a packed 4-D [A, B, rows, cols] operand with A != B was copied for nothing. batch_packed checks every batch axis, so it now decides alone. Tests: granite_hybrid_sanitize_stores_gate_and_up_batch_packed and mistral4 sanitize_weights_stores_gate_and_up_batch_packed assert the stored halves' strides and values; the CUDA-only gather_mm_sorted_rhs_takes_a_packed_four_d_stack_without_a_copy checks a packed [2, 3, k, n] column-major stack against the reference and reads the allocator peak to show it is not copied. The fused-stack test's doc now names the in-tree users. Refs lablup#3760, lablup#3761
Member
Hardening reviewReviewed against #3760. No code changes were needed; I merged current Findings:
Validation on NVIDIA GB10 (CUDA 13), on the merged tree:
Not run: an unquantized granitemoehybrid or mistral4 checkpoint (none on the host), Metal, ROCm. |
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
Closes #3760.
On CUDA,
gather_mmread the wrong expert whenever its expert stack was a view whose matrices are packed but whose expert axis is not. The usual case is the gate or up half of a fused[experts, 2 * ffn, hidden]stack that was split along axis 1 at load. The grouped GEMM arms of the CUDA overlay'sGatherMM::eval_gpustep from one expert to the next byrows * colselements, butensure_batch_contiguousandcheck_transposeonly check the last two axes. Such a view was therefore taken as packed, and every expert after the first was read from the wrong offset.This PR adds
batch_packed()to the overlay'smatmul.cpp. Any operand that fails it is copied into a row-contiguous layout before the grouped GEMM, both inensure_batch_contiguous(used by the sortedM == 1armgather_mm_rhs, and byGroupedMM) and in the generalcutlass_gather_mmarm. Packed operands, which includes every quantized and every pre-split checkpoint, take exactly the path they took before.Who hit it
granitemoehybrid.rs(block_sparse_moe.input_linear) andmistral4.rs(experts.gate_up_proj) split their fused expert stacks this way in their sanitizers. The GraniteMoE port in #3745 did too until it switched to storing the halves packed at load; the real-checkpoint runs below used that earlier build (ffaf4d902), the last one that still kept the halves as views. All of them route experts throughSwitchGLU, which takes the sorted path oncetokens * top_k >= 64. With an unquantized checkpoint, every MoE layer of any prompt longer than a few tokens therefore multiplied by the wrong expert weights during prefill. For that GraniteMoE build it is the measured result below: the KV cache it filled made the output noise from the first generated token. f32 hid the bug becauseastyperepacks the weights. Quantized exports hide it because they store packed stacks and route throughgather_qmm.Upstream MLX has the same assumption in its CUDA
gather_mm(the sortedM == 1grouped GEMM and the generalM > 1kernel), so mlx-lm shows the same symptom on CUDA. The Python script below needs onlymlxand shows it with the stock wheels: max|err| 30.6 against the dense product on CUDA (mlx 0.32.5), 0 on CPU, ≤ 4e-6 on Metal.Repro with stock MLX (Python)
On CUDA with mlx 0.32.5 and
MLX_ENABLE_TF32=0, every row is ≤ 6e-6 exceptview True(30.6). With TF32 left on,dense Trueis 6.9e-3 (TF32 rounding) andview Trueis still 30.6. On Metal (M4, mlx 0.32.5) every row is ≤ 4e-6.Tests
src/lib/mlxcel-core/src/grouped_gemm_numeric_tests.rs(GPU-only, same module and f64 reference as the #1544 checks):gather_mm_reads_expert_planes_cut_from_a_fused_stack: both halves of a fused[4, 128, 128]stack, sliced along axis 1 and passed asswap_axes(-1, -2)the waySwitchLineardoes. Covers f32 and bf16, and every dispatch arm (sortedm = 1grouped GEMM, unsortedm = 1gemv as the control, unsorted and sortedm = 4general grouped GEMM).gather_mm_general_arm_reads_lhs_cut_from_a_wider_batch: the general arm'sacut from a[batch, 2m, k]batch along axis 1.Both fail without the fix and pass with it. The fail-before run used an earlier build of this branch (tree
b90cbdd4) with onlymatmul.cppreverted tomain9402cf8; that tree differs from this PR's only in howrustfmtwraps oneassert_closecall in the test file and in comment and README wording, not in the tests' logic or the fix. The new tests pass inside the full CUDA gate below and on Metal (Limits).mainoverlaygather_mm_reads_expert_planes_cut_from_a_fused_stackm = 1): got 6.60, want −10.16gather_mm_general_arm_reads_lhs_cut_from_a_wider_batchgrouped_gemm_numeric_testsVerification
NVIDIA GB10 (sm_121), CUDA 13.0, driver 580.178.04, Rust 1.97.1; base
main9402cf8.cargo fmt --all -- --check: clean.cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings: clean.python3 scripts/ci/check_used_by.py: OK.bash scripts/ci/check_used_by_test.shand every otherscripts/ci/*_test.sh: pass, excepthelm_chart_package_test.sh(helmis not installed on the host).check_nvrtc_headers.py,check_cuda_arch_lists.py,check_kernel_dtype_keys.py,check_kernel_port_dispatch.py,check_env_var_docs.py,check_cross_repo_refs.py: pass.make verify-test-cuda(cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1) on this branch before the last amend, which only added the issue number to comments and the README: 18,893 passed, 2 failed, 578 ignored. The two failures aretests/mlx_test_guard_coverage.rs::mlx_evaluating_lib_tests_take_mlx_test_guard(flagssrc/vision/encoders/nemotron_h_nano_omni_tests.rs:276) andtests/step3p7_parity.rs::text_decode_delegates_sequence_local_native_batching. Both fail identically on unmodifiedmain9402cf8 (rerun there: same two tests, same assertions); they were pre-existing on the base and currentmainfixes both (feat(speculative): add DeepSeek-V4.1 bundled DSpark drafter (#3262) #3686, test: restore MLX guard scan and no-GPU catalog test gates #3765). This PR touches neither.grouped_gemmfilter on the lib tests: 9/9.gatherfilter: 49 passed, 1 ignored.Real checkpoints (bf16 originals, through an earlier build of the GraniteMoE port in #3745)
ibm-granite/granite-3.0-1b-a400m-instruct@ffec3c35 andibm-granite/granite-3.1-3b-a800m-instruct@a0278068, unquantized bf16 as released. #3745's branch atffaf4d902, which still kept the split gate/up halves as views (its current head stores them packed at load and no longer reaches this path), was built twice in one target dir, once withmain'smatmul.cppand once with this PR's. Teacher-forced logit traces (examples/logit_trace,docs/architecture.md, 256-token windows × 4 = 1024 positions) were compared withscripts/compare_logit_traces.pyagainst mlx-lm 0.32.2 run in f32 (mlx 0.32.5 CUDA wheel,scripts/mlx_lm_logit_trace.pywith the model cast byset_dtype(float32)after load):mainoverlaymainoverlayFor the 1b model, mlx-lm in bf16 with its
switch_mlpweights made contiguous (so its own CUDAgather_mmis not hit) gives 34 / 1024 disagreements, 0 / 366 decided, and perplexity 25.703 against the same f32 reference. Against that bf16 reference, this PR gives 22 / 1024 disagreements, 0 / 368 decided, and −0.03% perplexity.mlxcel generate -n 48 --temp 0with "Explain in three sentences why the sky is blue during the day and red at sunset.":mainoverlay:...DBus...DBus ban sight sightingDBus system banuis ...During the day, the sun emits light in all visible wavelengths, but blue light is scattered in all directions by the Earth's atmosphere ...mainoverlay:impact oil punselcticloverloverseller-seller...The sky appears blue during the day due to a process called Rayleigh scattering, where the Earth's atmosphere scatters short-wavelength light, ...git merge-treeagainst currentmain(5bf7b8628): clean. On the merged tree, the Python tooling tests (python3 -m unittest discover -s tests -p 'test_*.py'), thescripts/cichecks CI runs andcargo fmt --all -- --checkpass.Limits
cargo test --profile test-fast -p mlxcel-core --features metal,accelerate --lib grouped_gemm_numericgives 5 passed, 0 failed. The ROCm overlay implementsGatherMMseparately and, from reading the code, addresses batch strides explicitly (try_sorted_rhs_gather_mm,naive_gemm_gather,gather_mv); it was not run. If it does make the same assumption, the new tests will fail there.tokens * top_k >= 64). For a stack the size of granite-3.0-1b-a400m's that is 64 MiB of gate+up per layer. It was not measured. Storing the halves packed at load in the sanitizers, as feat(models): port GraniteMoE (granitemoe, GraniteMoeForCausalLM) #3745 now does, would remove the copy. That is left out here so that this change stays a correctness fix in one place.granitemoehybrid) and Mistral 4 (mistral4), were not run.Follow-up commit 15a79fc
granitemoehybrid(block_sparse_moe.input_linear) andmistral4(experts.gate_up_proj) sanitizers used to store gate and up as axis-1 slices of the fused[experts, 2 * ffn, hidden]stack. Those slices are correct with the repack above, but every sorted or general-armgather_mmthen copied the whole half-stack again, at every prefill and at every batched-decode step with 64 or more pairs. Each sanitizer now writes each half into its own buffer once, withmlxcel_core::contiguous(&slice_axis(..), false), the pattern GraniteMoE uses in feat(models): port GraniteMoE (granitemoe, GraniteMoeForCausalLM) #3745. It evaluates each layer as it goes, so the fused buffer is freed during the load. The overlay repack stays in place as a safety net.ensure_batch_contiguousnow checks onlybatch_packed. The upstream batch-axis loop it kept comparedstrides(i + 1) * shape(i)withstrides(i), but the right factor isshape(i + 1). As a result, a packed 4-D[A, B, rows, cols]operand withA != Bwas copied for no reason.batch_packedchecks every batch axis, so it now decides alone.granite_hybrid_sanitize_stores_gate_and_up_batch_packed(granitemoehybrid_tests.rs) andmistral4::split_gate_up_tests::sanitize_weights_stores_gate_and_up_batch_packedassert the strides and values of the stored halves, with the strides of the split view as the control.gather_mm_sorted_rhs_takes_a_packed_four_d_stack_without_a_copy(CUDA only,grouped_gemm_numeric_tests.rs) checks a packed column-major[2, 3, 512, 1024]stack on the sortedm == 1arm against the host reference. It also reads the allocator peak to show that the stack is not copied.granitemoehybrid,mistral4) and calls GraniteMoE "an earlier feat(models): port GraniteMoE (granitemoe, GraniteMoeForCausalLM) #3745 build".matmul.cpprestored to the previous head, all three new tests fail. The four-D test reports "gather_mm allocated 12616256 bytes above the 12599328 live before it; a copy of the packed 12582912-byte [2, 3, k, n] stack was made". The sanitizer tests report strides[256, 16, 1]against[128, 16, 1](granitemoehybrid) and[64, 8, 1]against[32, 8, 1](mistral4). With this commit, all three pass.1675f8854:grouped_gemm_numeric6/6,granitemoehybrid25,mistral4::5,gather_mm6 + 7.d42e6a4damerged with this head, perf(cuda): raise the MoE grouped-GEMM prefill gate to 22 rows per expert #3756 and the feat(distributed): add tensor-parallel support for Qwen3 MoE #3730 follow-up:cargo fmt --check,cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings, thetests/Python suites (318 OK) and thescripts/cichecks all pass.helm_chart_package_testcannot run because helm is not installed.make verify-test-cuda: 19156 passed, 0 failed, 591 ignored (207 result blocks).