Skip to content

fix(rocm): widen gather QMV output offsets to 64 bits - #2624

Merged
inureyes merged 4 commits into
mainfrom
fix/issue-2620-gather-qmv-int64
Oct 26, 2026
Merged

inureyes merged 4 commits into
mainfrom
fix/issue-2620-gather-qmv-int64

Conversation

@inureyes

@inureyes inureyes commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Summary

Widens the remaining 32-bit offsets in the ROCm gather QMV paths to int64_t (follow-up to ml-explore/mlx#4738) and settles the suspected grid-z launch limit: z cap ruled out on gfx1151, so launch geometry is unchanged.

Grid-z result

The decisive test (unsorted gather_qmm, bf16, affine 4-bit, group 64, E=128, M=1, N=K=64, B=65,537, every element against a host reference) passes with the launch geometry unchanged, as does the same shape through the bf16 8-bit warp-shared, bf16 mxfp4 and f32 per-row kernels. The first pre-fix run of the bf16 affine cases quantized the weights in f32, so gather_qmm promoted them to the f32 per-row kernel; review fixed the weights to quantize in the activation dtype and each case now asserts the output dtype, and the corrected bf16 cases pass. The widening touches none of the bf16 kernels those cases reach, so they exercise the same batch-in-z launch the code had before. A standalone hipLaunchKernel probe (ROCm 7.15, HIP runtime 71526333) ran grids of 65,537, 262,144 and 16,777,216 blocks in z and 65,537 and 262,144 in y, every block executing, although hipDeviceProp_t::maxGridSize and rocminfo report 65535 for y and z. The limit that applies is 2^32 - 1 threads per dimension (LOCAL_FIXES item 11). The B = 65,537 tests stay as a regression guard.

Changes

  • gather_qmv_kernel (qmm.hip), gather_qmv_tiled_kernel and gather_qmv_tiled_6bit_kernel (qmv_tiled_kernel.hip) compute the output index in int64_t; the opt-in 4/8-bit tiled kernel also widens rhs_idx * N * w_stride and lhs_idx * M * K.
  • gemv_gather_impl (gemms/gemv.hip) offsets its output by int64_t(indices_idx) * rows.
  • The dead quantized/qmv_kernel.hip is dropped, and the stale comment in qdequant.hpp now names its real user. README backend count is 110.
  • LOCAL_FIXES.md item 61 (60 was taken by fix(rocm): match MLX in eager complex64 and bool casts #2623). No core file changed, so CORE_RESIDUAL.diff is untouched.
  • New tests/rocm_hip_grid_clamp/gather_qmv.rs module: the four B = 65,537 cases, plus an #[ignore] f32 test (N=65,536, K=64, B=32,769, 2^31 + 2^16 output elements) checking rows 0, 32,767 and 32,768 against the host.

Test plan

  • rocm_hip_grid_clamp, all 13 fast tests pass under rocm_gpu_guard.sh --hold; after the review fix and the rebase onto main, the gather filter (5 fast tests) passes again
  • The ignored >2^31 test passes with the fix (5.8 s). Negative control: with gather_qmv_kernel's 32-bit index restored, it fails with hipErrorIllegalAddress in gather_qmv_kernel<float, float, 4, 64, true> (dispatch grid [256, 256, 32769])
  • mlxcel-core lib gather (41) and quantized (42) filters, and rocm_gather_qmm_expert_batched (2), pass
  • make verify-llama-compat verify-env-var-docs verify-kernel-port-dispatch verify-kernel-dtype-keys verify-rocm-overlay and rocm_overlay.py drift pass
  • cargo clippy --profile test-fast --features rocm -p mlxcel -p mlxcel-core --lib --tests -- -D warnings is clean

The full fast set and the ignored test ran on the pre-rebase base (1cb18cc); the rebase onto main added #2622 and #2623, which do not touch these kernels. The overlay and contract checks were re-run after the rebase. The item 46 record says HIP refuses y grids past 65535 blocks; this runtime did not reproduce that, and item 61 and the test header now say so while leaving the item 46 caps in place.

Follow-ups not in scope: gemv_batched and gemv_batched_inline in gemms/gemv.hip still form batch_idx * rows in int (not gather paths); no B = 65,537 case covers the bf16 6-bit tiled gather kernel; the tiled gather kernels clamp an out-of-range expert to 0 where the other gather kernels write zeros.

Closes #2620

Follow-up to ml-explore/mlx#4738. gather_qmv_kernel, both tiled gather kernels and gemv_gather_impl still formed their output offset (and, in the opt-in 4/8-bit tiled kernel, the expert and activation offsets from uint32_t indices) in 32 bits, so an output past 2^31 elements wrapped. Each offset is now int64_t, the pattern of gather_qmv_warp_shared_kernel.

The suspected 65535-block grid-z cap is ruled out on gfx1151 with ROCm 7.15: an unsorted gather_qmm at B = 65537 ran correctly through the wide, warp-shared (affine and mxfp4) and per-row kernels on the unmodified overlay, and a hipLaunchKernel probe ran grids of up to 16777216 blocks in z and 262144 in y although maxGridSize reports 65535. Launch geometry is unchanged; the B = 65537 tests stay as a guard, and an ignored test checks a gather_qmv_kernel output of 2^31 + 2^16 elements across element 2^31.

The dead quantized/qmv_kernel.hip (built and included by nothing) is dropped. LOCAL_FIXES.md item 61 records the change.

Closes #2620
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:low Low priority labels Oct 26, 2026
The bf16 affine cases in tests/rocm_hip_grid_clamp/gather_qmv.rs quantized their weights from f32, so the affine scales and biases were f32. gather_qmm promotes the activations to the affine scales' dtype, so both bf16 affine cases ran the f32 per-row gather_qmv_kernel instead of gather_qmv_wide_kernel and gather_qmv_warp_shared_kernel, and the decisive B = 65537 case never reached the default bf16 4-bit kernel.

Weights::new now quantizes from the activation dtype, and each fast case asserts that the output dtype equals the activation dtype, which fails if the dispatch falls back to f32. The ignored >2^31 test keeps f32.

The five gather tests in rocm_hip_grid_clamp pass on gfx1151 under the GPU guard on the rebased branch, and clippy with -D warnings is clean.

Refs #2620
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Widen the remaining 32-bit offsets in the ROCm gather QMV kernels to int64 and settle whether grid z is capped at 65535 on gfx1151.

Findings Addressed

  • The bf16 affine B = 65537 cases quantized weights from f32, so gather_qmm promoted the activations to f32 and both ran the f32 per-row gather_qmv_kernel, not the wide and warp-shared kernels. Weights are now quantized in the activation dtype and each case asserts the output dtype (HIGH, 9d010c4)

Remaining Items

  • The PR body says the bf16 4-bit decisive case passed on the unmodified kernels; that run used the f32 kernel. The z-cap conclusion still stands (standalone probe, plus the corrected bf16 cases now passing with unchanged launch geometry), but the sentence should be corrected (MEDIUM)
  • Item 61 and the new module doc paragraph say HIP runs 65537+ blocks in y, while item 46 and the existing module doc say a y grid over 65535 blocks is refused. The two records need reconciling (MEDIUM)
  • gemv_batched and gemv_batched_inline in gemms/gemv.hip still offset the output by batch_idx * rows in int; not gather paths and not listed in the issue (MEDIUM, follow-up)
  • No B = 65537 case covers the default-on bf16 6-bit gather_qmv_tiled_6bit_kernel, and the >2^31 test covers only gather_qmv_kernel (LOW)

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (5 gather tests in rocm_hip_grid_clamp on gfx1151 after the rebase; clippy clean)

Item 61 and the grid-clamp test header now say that the ROCm 7.15 probe did not reproduce the y-grid refusal recorded in item 46 and that the item 46 caps stay. Item 61 also states that the gather cases assert the activation dtype, so the bf16 cases cannot fall back to the f32 kernel.
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

No CRITICAL or HIGH findings, so nothing was changed. Every widened offset in gather_qmv_kernel, gather_qmv_tiled_kernel, gather_qmv_tiled_6bit_kernel and gemv_gather_impl is computed once before the K loop. The inner loops still index with 32-bit offsets from 64-bit base pointers, so there is no new 64-bit arithmetic in the hot path. The tiled path only takes unit-stride 1D indices, which makes lhs_indices[batch] safe. Out-of-range rhs_idx either writes zero or is clamped to 0 before any pointer is formed.

Remaining (LOW, pre-existing, follow-up only):

  • The tiled kernels clamp an out-of-range expert or lhs index to 0 and compute with expert 0, but gather_qmv_kernel writes zero and does not bound lhs_idx. This is memory-safe for rhs_idx, and the indices come from the router, not from callers.
  • gather_qmv_kernel keeps the 64-bit out_offset live across the K loop (two VGPRs). This only affects the f32 fallback kernel, and the cost is negligible.
  • gemv_impl still forms row * cols in int for each matrix.

All five contract targets pass, including verify-rocm-overlay.

@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 10:10
@inureyes
inureyes merged commit 2a1f1e8 into main Oct 26, 2026
28 checks passed
@inureyes
inureyes deleted the fix/issue-2620-gather-qmv-int64 branch October 26, 2026 10:11
inureyes added a commit that referenced this pull request Oct 26, 2026
…2627)

## Summary

The ROCm per-row launchers (softmax, logsumexp, rms_norm plain/strided/VJP, layer_norm forward/VJP) put one block per row in grid x with an `int` `n_rows`. HIP refuses `gridDim.x * blockDim.x >= 2^32`, so 2^24 + 1 rows at 256 threads failed to launch. This is the ROCm side of ml-explore/mlx#4717.

- Each launcher caps grid x at `UINT32_MAX / BLOCK_DIM` and spills into y (the `arg_reduce.hip` pattern of LOCAL_FIXES item 11). Kernels take `n_rows`, compute a 64-bit row from `blockIdx.x + blockIdx.y * gridDim.x`, and return past it before any barrier. Below the cap the grid is `dim3(n_rows)` as before.
- The strided rms_norm kernel decomposes its row in 64 bits.
- LOCAL_FIXES item 62 (61 was taken by #2624 while this was in flight).
- Two test-only FFI entries, `fast_rms_norm_vjp_for_test` and `fast_layer_norm_vjp_for_test`, run the VJP primitives through `mlx::core::vjp`; the crate had no VJP entry point.

## Tests (gfx1151)

New `row_grid` module in `tests/rocm_hip_grid_clamp.rs`: seven launches on 2^24 + 1 x 4 f32, every element compared on the GPU with an f64 host reference, plus `#[ignore]`d tests for the 512 and 1024-thread softmax arms (about 17 GiB each).

Before the fix (overlay reverted, same tests): `0 passed; 7 failed; 2 ignored`, each with:

```
GPU launch failed: hipLaunchKernel( func, grid_dim, block_dim, params, smem_bytes, stream_) failed: invalid configuration argument
```

After: `7 passed; 0 failed; 2 ignored; finished in 7.12s`. The whole `rocm_hip_grid_clamp` file after rebasing onto #2624: `20 passed; 0 failed; 7 ignored`.

A CPU-stream reference was tried first and dropped: about 5 minutes a test from host reads of device memory, and its f32 sum over 2^24 rows for the layer_norm weight gradient was 2.7e5 off the GPU value, which is within 1.7e3 of the f64 sum. The weight gradients use rtol 1e-3 for that reason; the per-row `dx` checks that every row ran.

Existing tests, post-fix, under `rocm_gpu_guard.sh --hold`: mlxcel-core lib filters `softmax` (10), `rms_norm` (15), `layer_norm` (2), `fused_norm_parity` (10), all pass. `make verify-llama-compat verify-env-var-docs verify-kernel-port-dispatch verify-kernel-dtype-keys verify-rocm-overlay` and clippy (`-p mlxcel-core --lib --tests`, `-p mlxcel --test rocm_hip_grid_clamp`) are clean.

Not run: the two ignored softmax arm tests (17 GiB on a 31 GiB shared host), `layer_norm_multiwave_mean_snapshot_is_stable` (needs the `mlxcel` lib test build).

Closes #2619
@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

priority:low Low 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(rocm): gather QMV large-batch launch and 64-bit output offsets

1 participant