Skip to content

fix(cuda): repack gather_mm operands whose batch axes are not packed - #3761

Merged
inureyes merged 4 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/cuda-gather-mm-batch-stride
Dec 4, 2026
Merged

inureyes merged 4 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/cuda-gather-mm-batch-stride

Conversation

@Jaeyeong-CHOI

@Jaeyeong-CHOI Jaeyeong-CHOI commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #3760.

On CUDA, gather_mm read 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's GatherMM::eval_gpu step from one expert to the next by rows * cols elements, but ensure_batch_contiguous and check_transpose only 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's matmul.cpp. Any operand that fails it is copied into a row-contiguous layout before the grouped GEMM, both in ensure_batch_contiguous (used by the sorted M == 1 arm gather_mm_rhs, and by GroupedMM) and in the general cutlass_gather_mm arm. 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) and mistral4.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 through SwitchGLU, which takes the sorted path once tokens * 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 because astype repacks the weights. Quantized exports hide it because they store packed stacks and route through gather_qmm.

Upstream MLX has the same assumption in its CUDA gather_mm (the sorted M == 1 grouped GEMM and the general M > 1 kernel), so mlx-lm shows the same symptom on CUDA. The Python script below needs only mlx and 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)
import mlx.core as mx

mx.random.seed(0)
E, K, N = 4, 64, 32

fused = mx.random.normal((E, 2 * N, K))
w = mx.split(fused, 2, axis=1)[1]          # [E, N, K] view, expert stride 2*N*K
wt = w.swapaxes(-1, -2)                    # [E, K, N], as SwitchLinear passes it
wt_dense = mx.contiguous(w).swapaxes(-1, -2)

x = mx.random.normal((8, 1, K))
idx = mx.array([0, 0, 1, 1, 2, 2, 3, 3], dtype=mx.uint32)  # sorted
expected = x @ wt_dense[idx]

for name, rhs in (("view", wt), ("dense", wt_dense)):
    for s in (False, True):
        out = mx.gather_mm(x, rhs, rhs_indices=idx, sorted_indices=s)
        print(name, s, mx.abs(out - expected).max().item())

On CUDA with mlx 0.32.5 and MLX_ENABLE_TF32=0, every row is ≤ 6e-6 except view True (30.6). With TF32 left on, dense True is 6.9e-3 (TF32 rounding) and view True is 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 as swap_axes(-1, -2) the way SwitchLinear does. Covers f32 and bf16, and every dispatch arm (sorted m = 1 grouped GEMM, unsorted m = 1 gemv as the control, unsorted and sorted m = 4 general grouped GEMM).
  • gather_mm_general_arm_reads_lhs_cut_from_a_wider_batch: the general arm's a cut 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 only matmul.cpp reverted to main 9402cf8; that tree differs from this PR's only in how rustfmt wraps one assert_close call 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).

test main overlay this PR
gather_mm_reads_expert_planes_cut_from_a_fused_stack FAILED at the first case (f32, first half, sorted m = 1): got 6.60, want −10.16 ok
gather_mm_general_arm_reads_lhs_cut_from_a_wider_batch FAILED: got −8.27, want 9.10 ok
the three existing grouped_gemm_numeric_tests ok ok

Verification

NVIDIA GB10 (sm_121), CUDA 13.0, driver 580.178.04, Rust 1.97.1; base main 9402cf8.

  • 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.sh and every other scripts/ci/*_test.sh: pass, except helm_chart_package_test.sh (helm is 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 are tests/mlx_test_guard_coverage.rs::mlx_evaluating_lib_tests_take_mlx_test_guard (flags src/vision/encoders/nemotron_h_nano_omni_tests.rs:276) and tests/step3p7_parity.rs::text_decode_delegates_sequence_local_native_batching. Both fail identically on unmodified main 9402cf8 (rerun there: same two tests, same assertions); they were pre-existing on the base and current main fixes 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_gemm filter on the lib tests: 9/9. gather filter: 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 and ibm-granite/granite-3.1-3b-a800m-instruct @a0278068, unquantized bf16 as released. #3745's branch at ffaf4d902, 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 with main's matmul.cpp and once with this PR's. Teacher-forced logit traces (examples/logit_trace, docs/architecture.md, 256-token windows × 4 = 1024 positions) were compared with scripts/compare_logit_traces.py against mlx-lm 0.32.2 run in f32 (mlx 0.32.5 CUDA wheel, scripts/mlx_lm_logit_trace.py with the model cast by set_dtype(float32) after load):

candidate top-1 disagreement on decided positions (gap ≥ 2) perplexity (reference)
1b, main overlay 1024 / 1024 366 / 366 16,869,820 (25.676)
1b, this PR 30 / 1024 0 / 366 25.696, +0.08%
3b, main overlay 1024 / 1024 397 / 397 241,089,305 (21.240)
3b, this PR 25 / 1024 0 / 397 21.316, +0.36%

For the 1b model, mlx-lm in bf16 with its switch_mlp weights made contiguous (so its own CUDA gather_mm is 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 0 with "Explain in three sentences why the sky is blue during the day and red at sunset.":

  • 1b, main overlay: ...DBus...DBus ban sight sightingDBus system banuis ...
  • 1b, this PR: During the day, the sun emits light in all visible wavelengths, but blue light is scattered in all directions by the Earth's atmosphere ...
  • 3b, main overlay: impact oil punselcticloverloverseller-seller...
  • 3b, this PR: 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-tree against current main (5bf7b8628): clean. On the merged tree, the Python tooling tests (python3 -m unittest discover -s tests -p 'test_*.py'), the scripts/ci checks CI runs and cargo fmt --all -- --check pass.

Limits

  • The fix and the real-checkpoint runs are CUDA only (GB10). Like their siblings, the new tests run on every GPU backend. On Metal (Apple M4, macOS 26.2) this tree passes them: cargo test --profile test-fast -p mlxcel-core --features metal,accelerate --lib grouped_gemm_numeric gives 5 passed, 0 failed. The ROCm overlay implements GatherMM separately 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.
  • A split-view expert stack is now copied on every grouped-GEMM gather that sees it (prefill, and batched decode once 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.
  • No model family in the tree was run end to end on this fix. The real-checkpoint runs above used an earlier build of the GraniteMoE port in feat(models): port GraniteMoE (granitemoe, GraniteMoeForCausalLM) #3745 that still kept its split halves as views; feat(models): port GraniteMoE (granitemoe, GraniteMoeForCausalLM) #3745 now stores them packed at load and no longer depends on this fix. The in-tree families that still take the split, the bf16 originals of Granite 4 hybrid MoE (granitemoehybrid) and Mistral 4 (mistral4), were not run.

Follow-up commit 15a79fc

  • Split expert stacks are packed at load. The granitemoehybrid (block_sparse_moe.input_linear) and mistral4 (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-arm gather_mm then 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, with mlxcel_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_contiguous now checks only batch_packed. The upstream batch-axis loop it kept compared strides(i + 1) * shape(i) with strides(i), but the right factor is shape(i + 1). As a result, a packed 4-D [A, B, rows, cols] operand with A != B was copied for no reason. batch_packed checks every batch axis, so it now decides alone.
  • New tests:
    • granite_hybrid_sanitize_stores_gate_and_up_batch_packed (granitemoehybrid_tests.rs) and mistral4::split_gate_up_tests::sanitize_weights_stores_gate_and_up_batch_packed assert 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 sorted m == 1 arm against the host reference. It also reads the allocator peak to show that the stack is not copied.
  • The doc comment on the fused-stack test now names the in-tree users (granitemoehybrid, mistral4) and calls GraniteMoE "an earlier feat(models): port GraniteMoE (granitemoe, GraniteMoeForCausalLM) #3745 build".
  • Fail before, pass after (NVIDIA GB10, sm_121, CUDA 13). With only the two sanitizers and matmul.cpp restored 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.
  • On this head merged with main 1675f8854: grouped_gemm_numeric 6/6, granitemoehybrid 25, mistral4:: 5, gather_mm 6 + 7.
  • On main d42e6a4da merged 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, the tests/ Python suites (318 OK) and the scripts/ci checks all pass. helm_chart_package_test cannot run because helm is not installed. make verify-test-cuda: 19156 passed, 0 failed, 591 ignored (207 result blocks).
  • Not run: an unquantized granitemoehybrid or mistral4 checkpoint end to end (none is on the test host), Metal, ROCm.

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.
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:high High priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers labels Dec 4, 2026
Jaeyeong-CHOI and others added 3 commits December 4, 2026 16:19
… 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
@inureyes

inureyes commented Dec 4, 2026

Copy link
Copy Markdown
Member

Hardening review

Reviewed against #3760. No code changes were needed; I merged current main (including #3756, which touches the same overlay directory and grouped_gemm_numeric_tests.rs) into the branch as 00ea598cb. The merge was clean.

Findings:

  • The fix is at the dispatch site. batch_packed checks every batch axis against rows * cols and skips size-1 axes. It is used by ensure_batch_contiguous (sorted M == 1 arm and GroupedMM) and by the general cutlass_gather_mm arm for both a and b. Indices were already made row-contiguous, and the gemv arm was already stride-correct, so it serves as the control. Packed operands, including column-major packed views and packed 4-D stacks, take the zero-copy path.
  • The upstream batch-axis loop compared strides(i + 1) * shape(i) where it should have used shape(i + 1), so packed 4-D stacks were copied for nothing. Replacing it is correct, and the allocator-peak test covers it.
  • GroupedMM still drops the transpose flag from ensure_batch_contiguous, as upstream does. That behavior predates this PR and is unchanged here. b there is always 3-D, and the cuDNN grouped GEMM reads strides directly.
  • The granitemoehybrid and mistral4 sanitizers now pack each half once at load, which matches the GraniteMoE pattern on main. Steady-state prefill therefore never reaches the repack.

Validation on NVIDIA GB10 (CUDA 13), on the merged tree:

  • cargo fmt --check passes. cargo clippy --all-targets -D warnings is clean on default features and with --features cuda.
  • Fail before, pass after: with only matmul.cpp reverted to main, the 3 new grouped_gemm_numeric tests fail (got 6.60, want -10.16 on the sorted m = 1 arm). With the PR they pass, 10/10 grouped_gemm.
  • mlxcel-core gather filter: 57 passed. Main crate granitemoehybrid, mistral4::, switch_layers, gather_qmm, fused_moe: 118 passed. --bin mlxcel family_order: ok. All runs used --test-threads=1.
  • Release A/B, 64 tokens after a ~250-token prompt, alternating main overlay and this PR: qwen3-30b-a3b-4bit 49.97/49.63 vs 50.24/49.86 tok/s, ernie-4.5-21b-a3b-pt (bf16, unquantized gather_mm) 26.29/28.24 vs 28.16/27.36 tok/s. The differences are within noise, and ERNIE output is coherent.

Not run: an unquantized granitemoehybrid or mistral4 checkpoint (none on the host), Metal, ROCm.

@inureyes
inureyes merged commit 670e12b into lablup:main Dec 4, 2026
36 checks passed
@inureyes inureyes added status:done Completed and removed status:review Under review labels Dec 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers priority:high High priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(cuda): gather_mm reads the wrong expert for strided (middle-axis-sliced) expert stacks

2 participants