Repository navigation
perf(xla): run 4-bit decode projections through a native HIP GEMV - #2890
Merged
Merged
Conversation
MLXCEL_XLA_QUANT=native keeps the checkpoint's packed 4-bit projections resident in the single-sequence decode graph and dispatches csrc/qmv4.hip for each one instead of streaming f16-expanded weights. The kernel is compiled at model load with hipcc --genco for MLXCEL_XLA_ROCM_TARGET, cached by kernel-content hash plus architecture, and embedded as a hal.executable.source @custom_qmv external object, so every projection is one flow.dispatch. The packed weight operand is declared signless i32: the StableHLO input pipeline legalizes unsigned integers away, and a flow.dispatch operand with a ui32 type has no legalization, so the module failed with "failed to legalize operation 'flow.dispatch' that was explicitly marked illegal". The HIP kernel reads the buffer as uint32_t, so the bits are unchanged. Decode on gfx1151 with llama-3.2-1b-instruct-4bit rises from 30.0 to 80.3 tok/s (greedy, n=128, capacity 256, warm vmfb) with a byte-identical greedy token stream on two prompts; identity also holds on the untied qwen2.5-coder-7b-instruct-4bit. Prefill and the ragged batch engine keep the f16 path, and xla_batch_bench stays REFERENCE-EXACT at B=4 and B=8. A missing hipcc, an unsupported architecture, or a packing other than 4-bit group 64 logs a warning and falls back to the f16 path. Refs #2889, #2886
inureyes
force-pushed
the
feat/2889-qmv4-native
branch
from
November 9, 2026 07:05
08daf07 to
1864a45
Compare
This was referenced Nov 9, 2026
This was referenced Nov 9, 2026
9 of 18 tasks
inureyes
pushed a commit
that referenced
this pull request
Nov 15, 2026
## Summary `MLXCEL_XLA_QUANT=native` was inert on `MLXCEL_XLA_DEVICE=cuda`: the loader required the `hip` device, so the decode graph kept the f16-expanded weights. This ports the single-sequence native 4-bit GEMV to CUDA, as #2905 asks. - `src/lib/mlxcel-xla/csrc/qmv4.cu`: the six single-sequence entry points of `csrc/qmv4.hip` (`qmv4_kernel`, `qmv4_row_kernel`, and the fused q/k/v and gate/up pairs from #2895), with one change, `__shfl_down_sync(0xffffffffu, ...)` for `__shfl_down(...)`. Same MLX affine layout, same ABI (i32 constants, read-only bindings, f32 outputs), `__half` activations and scales/biases. - `src/lib/mlxcel-xla/build.rs`: compiles it with `nvcc` to `compute_80` PTX next to the Gemma3n kernel, in the same `IREE_CUDA_HOME` branch. PTX availability is now its own cfg, `xla_iree_cuda_ptx`, emitted only after both kernels compile; `xla_iree_cuda` keeps meaning "CUDA IREE runtime". Without `nvcc` the build prints a warning and carries no PTX instead of failing. A compiler that is found and rejects a source still fails the build. - `src/lib/mlxcel-xla/src/native_qmv.rs`: embeds the PTX under `cfg(xla_iree_cuda_ptx)`, and builds the CUDA target alias (`#hal.executable.target<"cuda", "cuda-nvptx-fb">`) and the three `hal.executable.source` blocks from the same export tables the hip path uses. - `src/lib/mlxcel-xla/src/iree.rs`: the switch now turns on for `cuda` as well as `hip`, and a graph that carries the PTX is compiled with `--iree-cuda-target=sm_80` (the flag the Gemma3n kernel already sets). The 4-bit group-64 gate, the signless `i32` packed operand and the LM head dtype check are the existing shared code. - The emitter is unchanged apart from comments. The CUDA decode graph is the hip graph with the target alias and the embedded object swapped. - Gemma3n: the code that needs its PTX (`gemma3n_qmv.rs`, the native SDPA gate and three test sections) moves from `cfg(xla_iree_cuda)` to `cfg(xla_iree_cuda_ptx)`. Gemma3n CUDA Q4 keeps its existing load-time error when the artifact is missing; it does not fall back to a numerically different path. - `src/lib/mlxcel-xla/csrc/qmv4_cuda_oracle.cu`: a standalone check of the six exports against a host reference. It is not part of the build; the crate README has the two commands. ## Related issues Closes #2905 ## Type of change - [ ] `feat` — new user-visible feature - [ ] `fix` — bug fix - [x] `perf` — performance improvement (include before/after numbers in the PR body) - [ ] `refactor` — internal restructuring without behavior change - [ ] `chore` — build, CI, dependencies, release infrastructure - [ ] `docs` — documentation only - [ ] `test` — tests only ## Measurements DGX Spark GB10 (sm_121, CUDA 13.0, nvcc 13.0.88, driver 580.178.04), IREE 3.12.0rc20260721 from `scripts/iree/setup-cuda.sh`, release build with `--features cuda,xla-iree`, base `955335a3`. Greedy, `-n 128`, `MLXCEL_XLA_CONTEXT_CAPACITY=256`, warm vmfb, one process per run, two timed rounds after a warm-up round. Every number in this section is from the tree in this PR. The premise first, measured before the port on `ce6855bc`: the switch does nothing on `cuda` (19.28 tok/s without it, 19.42 with it, same output, 48 tokens). | checkpoint | prompt | f16-resident (tok/s) | native (tok/s) | output | |---|---|---|---|---| | llama-3.2-1b-instruct-4bit (tied) | 1 | 20.75, 20.18 | 58.41, 62.17 | identical | | llama-3.2-1b-instruct-4bit (tied) | 2 | 20.19, 20.46 | 62.86, 69.20 | identical | | Qwen2.5-7B-Instruct-4bit (untied) | 1 | 5.85, 5.87 | 19.04, 19.56 | identical | | Qwen2.5-7B-Instruct-4bit (untied) | 2 | 5.76, 5.89 | 19.33, 19.02 | identical | About 3.1x on llama-3.2-1b and 3.3x on Qwen2.5-7B. The native rounds on llama-3.2-1b spread more than the f16 ones (58.4 to 69.2); I did not find out why. ### Trace before and after `nsys profile --trace=cuda`, llama-3.2-1b-instruct-4bit, prompt 1, 128 decode steps. Decode-step kernels are the ones whose launch count is a multiple of 128; prefill and one-off kernels are excluded (124.9 ms in the f16 run, 118.5 ms in the native run). | | f16-resident | native | |---|---|---| | tok/s under `nsys` | 20.27 | 55.53 | | launches per decode step | 309 | 309 | | GPU kernel time per decode step | 41.81 ms | 8.28 ms | | projection launches per step | 113 `vecmat` | 65 `qmv4_*` | | projection kernel time per step | 39.57 ms | 5.96 ms | | `batch_matmul` (attention), 32 per step | 1.89 ms | 1.89 ms | | everything else | 164 launches, 0.35 ms | 212 launches, 0.43 ms | Per kernel, f16 graph (name is out x in): | kernel | per step | avg | |---|---|---| | `vecmat_2048x8192` (down) | 16 | 1093.5 us | | `vecmat_8192x2048` (gate, up) | 32 | 303.0 us | | `vecmat_2048x2048` (q, o) | 32 | 274.7 us | | `vecmat_512x2048` (k, v) | 32 | 37.7 us | | `vecmat_128256x2048` (head) | 1 | 2380.2 us | Per kernel, native graph: | kernel | per step | avg | per step total | |---|---|---|---| | `qmv4_gateup_kernel` | 16 | 175.0 us | 2.80 ms | | `qmv4_kernel` (o, head) | 17 | 105.7 us | 1.80 ms | | `qmv4_row_kernel` (down) | 16 | 46.9 us | 0.75 ms | | `qmv4_qkv_kernel` | 16 | 38.5 us | 0.62 ms | Two things differ from the gfx1151 picture in #2890 and #2907. The launch count does not fall: 113 projection launches become 65, and 48 small elementwise launches appear around the external dispatches. And the down projection is the largest single change, 1.09 ms per launch as an f16 `vecmat` against 47 us, which is more than the 4x byte reduction explains; the IREE-generated K=8192 reduction is slow on this device. ### Token identity The four chat-prompt runs above produce identical text. On this base `mlxcel generate` does not print token ids on the XLA path (#2980 addresses that), so I also compared ids with the repository's own tools: `xla_traj_dump` for the f16 and the native trajectory (128 argmax steps, raw prompt, no EOS stop), and `xla_oracle_check` under `MLXCEL_XLA_QUANT=native` against the f16 dump. | checkpoint | 128-token trajectories identical id for id | |---|---| | llama-3.2-1b-instruct-4bit | 6 of 6 | | Qwen2.5-7B-Instruct-4bit | 5 of 6 | The one mismatch is Qwen2.5-7B on "Write a short poem about a lighthouse keeper and the sea.", first differing at token 67 (f16 ` whisper`, native ` story`). What I checked: - Both arms reproduce their own trajectory exactly on a second run. - The XLA f32 path picks the f16 path's token. - The MLX backend, fed the same 80-token prefix (the server's tokenization of it equals the prompt ids plus the first 67 generated ids), returns ` story` and reports the same log-probability for both candidates: -1.28125 and -1.28125, then ` challenge` at -2.328. Position 67 is a tie at the resolution the MLX backend reports, consistent with sensitivity to arithmetic differences. This observation alone does not prove exact equality of the underlying logits or exclude every kernel defect: the native kernel dequantizes each weight in f32, where the f16 graph multiplies weights already rounded to f16. The README states identity as measured, not guaranteed, with this case. ## Builds without nvcc `NVCC=/nonexistent/nvcc` with the CUDA IREE runtime installed, same host: - `cargo test --release -p mlxcel-xla --features iree --lib`: 436 passed, 20 ignored. Two existing Gemma3n emitter tests assumed that a CUDA runtime implies the PTX; their native-only sections now sit behind the artifact cfg and the shared schema assertions still run. - `cargo clippy -p mlxcel-xla --all-targets --features iree -- -D warnings` and `RUSTFLAGS="-D warnings" cargo check --features cuda,xla-iree`: clean, with the one `cargo:warning` that the PTX was omitted. - Real run, llama-3.2-1b-instruct-4bit, "Explain in three sentences why the sky is blue.", 128 tokens, `xla_traj_dump`: the no-PTX binary produces the same token ids with the switch off and on, and with it on prints the fallback warning exactly once. - A compiler that answers `--version` and then rejects the source (a fixture script exiting 23) fails the build with its diagnostic. It is not treated as an absent compiler. The host keeps its already-built MLX CUDA dependencies, so this shows that the XLA PTX step is optional, not that the whole tree builds without a CUDA toolkit. ## Standalone kernel check `csrc/qmv4_cuda_oracle.cu` launches the six exports directly, without IREE or a model, against an FP64 host reference: K from 64 to 18944 on both sides of the 4096 threshold, N of 1, 7, 8, 9 and 17, unequal fused output sizes, and guard slots after each output. On the GB10: 600 launches and 8440 outputs pass, the 300 launches with exactly representable inputs are exact, the largest absolute error on the rest is 1.19e-5 (0.019 of the FP32 error envelope), and `compute-sanitizer --tool memcheck` reports 0 errors. This checks indexing and arithmetic of the kernels. It does not make the token comparison above 12 of 12. ## Acceptance criteria | criterion from #2905 | result | |---|---| | Greedy output token-identical to the f16 path on llama-3.2-1b-instruct-4bit (tied) and one untied checkpoint, on two prompts | Met on the two chat prompts for both checkpoints (identical output, 128 tokens each). On raw-prompt id comparison: 6 of 6 on llama-3.2-1b, 5 of 6 on Qwen2.5-7B; the exception is the tie described above. | | `xla_batch_bench` stays REFERENCE-EXACT | `--device cuda --batch 8 --requests 16 --maxcap 48`: `REFERENCE-EXACT PASS` with and without the switch (420 tokens). With the switch the single-sequence references come from the native path and the batch engine from f16 weights, so this is also an id-for-id match between the two on 16 requests. Batched throughput is unchanged (31.9 tok/s without, 32.4 with), and the single-sequence baseline the harness prints goes from 18.9 to 44.2 tok/s. | | The f16 path, prefill, committed goldens and every non-CUDA device are unchanged | The f16 graph and prefill are not touched. The hip module builders now read the same export tables as CUDA, and the existing hip tests (`module_prefix_embeds_the_object_and_the_abi`, `decode_kinds_embed_only_their_own_exports`, the emitter's `native_decode_emits_the_packed_projection_dispatch`) pass unchanged; a new test holds the CUDA decode graph equal to the hip one apart from the alias and object. `cargo test -p mlxcel-xla --lib` passes with the committed goldens. Not run: any ROCm or Metal device (I have neither). | | Trace before/after pasted: dispatch count, per-kernel time, tok/s at capacity 256, n=128 | Above. | | Builds without nvcc still compile and keep the f16 path | Met. With `NVCC` pointing at a nonexistent path and the CUDA IREE runtime installed: `RUSTFLAGS="-D warnings" cargo check --features cuda,xla-iree` passes with one build warning, the XLA unit suite passes (436), and a real run with the switch on warns once, falls back, and produces the same 128 token ids as the f16 path. See "Builds without nvcc" below. | | Tests and `cargo check --features xla-iree` under `RUSTFLAGS=-D warnings` stay clean | `RUSTFLAGS="-D warnings" cargo check --features cuda,xla-iree` is clean with and without `nvcc`. | ## Test plan - [x] `cargo fmt --all -- --check` - [ ] `cargo clippy --workspace --all-targets --features metal,accelerate -- -D warnings` (not run; Linux host). `cargo clippy -p mlxcel-xla --all-targets --features iree -- -D warnings` is clean with and without `nvcc`. - [ ] `cargo test --workspace --profile test-fast --features metal,accelerate --no-fail-fast -- --test-threads=1` (not run; Linux host) - [ ] `cargo deny check` (not run; no dependency change) - [x] Validated with real checkpoints: `mlx-community/Llama-3.2-1B-Instruct-4bit`, `mlx-community/Qwen2.5-7B-Instruct-4bit` - [x] Before/after numbers and environment are in the PR body Also run on the GB10 host: - `cargo test --release -p mlxcel-xla --lib`: 412 passed, 0 failed, 19 ignored (no IREE environment). - `cargo test --release -p mlxcel-xla --features iree --lib`: 437 passed, 22 ignored (CUDA IREE build, PTX embedded); 436 passed, 20 ignored with `NVCC` pointing at a nonexistent path. - `python3 -m unittest discover -s tests -p 'test_*.py'`: 219 tests, OK. - Repository gates: env-var docs, binary assets, cross-repo refs, CUDA arch lists, kernel dtype keys, kernel port dispatch, license headers. New unit tests: - `cuda_kernels_are_the_hip_single_sequence_kernels`: `qmv4.cu` equals the corresponding `qmv4.hip` lines apart from the one intrinsic, so the two sources cannot drift. - `cuda_kernel_source_matches_the_dispatch_contract`: the entry points and block geometry the dispatch constants assume. - `cuda_module_parts_embed_the_ptx_under_the_cuda_target`: the CUDA module text equals the hip one with the object path swapped. - `cuda_ptx_carries_every_single_sequence_entry` / `cuda_ptx_is_absent_without_a_compiled_artifact`: one per build configuration. - `native_decode_graph_is_the_same_on_cuda_apart_from_the_embedded_object`: the emitted decode graph, 65 dispatches. ## Notes for reviewers - **This changes what a CUDA IREE build without nvcc does, including for Gemma3n.** On `main` such a build fails in `build.rs`. Here it builds with a warning and no PTX. Dense models then keep the f16 path; Gemma3n CUDA Q4 fails at load with its existing "built without the CUDA-IREE PTX" error instead of at build time. I did this because the issue asks for builds without nvcc to compile. If you would rather keep the hard build failure for Gemma3n, the cfg split is the only part to revert. - **Devices below sm_80.** The PTX is `compute_80` and the graph is compiled for `sm_80`, as for Gemma3n. I could not test what the opt-in switch does on an older device; I expect the module to fail to load rather than fall back. - **Ragged engine.** Out of scope per the issue. On `cuda` the batch engine keeps the f16 weights whatever the switch says, and the multi-row exports stay hip-only. - **Only the GB10 was measured.** No other NVIDIA device, and the hip path was not re-run. The kernel bodies are held line-for-line equal to the hip source by a test, but `nvcc` and `hipcc` may contract floating point differently, so I make no claim about cross-vendor bit equality. - **The untied checkpoint is `Qwen2.5-7B-Instruct-4bit`**, not the `Qwen2.5-Coder-7B-Instruct-4bit` used in #2890. Same architecture and shapes (hidden 3584, down K=18944 on the row kernel). ## Checklist - [x] PR title uses a Conventional Commits prefix (`feat:`, `fix:`, etc.) - [x] One logical change per PR (split unrelated changes) - [x] Updated `docs/` if user-facing behavior or supported models changed - [x] Updated `// Used by: ...` comments on any shared function I modified (see `docs/code-guidelines.md`) - [x] No secrets, credentials, or `.env` files committed
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
MLXCEL_XLA_QUANT=nativekeeps the checkpoint's packed 4-bit projections resident in the single-sequence decode graph and dispatches a native HIP GEMV for each one, instead of streaming f16-expanded weights. This is the implementation half of #2889, following the gap analysis in #2886: the f16 decode path moves 2.47 GB of weights per step while the 4-bit checkpoint holds 618 MB, and IREE's packed in-graph dequant materializes the reconstructed weight every step rather than fusing it.src/lib/mlxcel-xla/csrc/qmv4.hip: the kernel (MLX affine layout, 8 nibbles peru32, group 64, f16 activations and scales/biases, f32 accumulate, one 256-thread workgroup per output row, warp shuffle plus shared-memory reduction).src/lib/mlxcel-xla/src/native_qmv.rs: compiles the kernel at model load withhipcc --genco -O3 --offload-arch=$MLXCEL_XLA_ROCM_TARGET, caches the HSACO by kernel-content hash plus architecture (published by rename, so a concurrent load never reads a partial file), and builds thehal.executable.source private @custom_qmvblock that embeds it through#hal.executable.objects.emitter/builder.rs,emitter/model.rs: under the switch,take_weightkeeps the three packed args (weight, scales, biases) and registers them behind the projection handle, and the layout-aware linear helpers emit oneflow.dispatch @custom_qmv::@qmv4_kernelper projection.iree.rs: the switch turns on only forhip, a Dense graph, and a 4-bit group-64 checkpoint; prefill and the ragged batch engine keep the f16 path. A missinghipcc, a failed compile, an unsupported architecture, or any other packing logs a warning and falls back to the f16 path rather than failing the model.Descriptor type: signless
i32, notui32The first end-to-end run failed to compile the decode graph:
The trigger was the packed weight operand's
ui32tensor type: the StableHLO input pipeline legalizes unsigned integers away, and aflow.dispatchcarrying one has no legalization pattern. The fix is to declare the operand as signlessi32, which the HIP kernel reads asuint32_t, so the bits are unchanged. TheMLXCEL_XLA_QUANT=packeddequant path keepsui32, since it stays inside StableHLO ops.Measurements
gfx1151(Ryzen AI Max+ 395 / Radeon 8060S), llama-3.2-1b-instruct-4bit, greedy,n=128,MLXCEL_XLA_CONTEXT_CAPACITY=256, warm vmfb, two rounds each:About 2.7x, and the greedy token stream is byte-identical to the f16 path on two prompts. Identity also holds on the untied
qwen2.5-coder-7b-instruct-4bit, whose separatelm_headkeeps the f16 head operand.Validation
cargo test -p mlxcel-xla --lib: 394 passed. New tests cover the native decode module (dispatch, packedi32operand, alias and source placement, no dispatch without the native module), the kernel/ABI contract, and the 4-bit group-64 gate.cargo check --features xla-backend,xla-ireewithRUSTFLAGS="-D warnings",cargo fmt --all -- --check.xla_batch_benchonhip:REFERENCE-EXACT PASSat B=4 (8 requests) and at B=8 (16 requests) withMLXCEL_XLA_QUANT=nativeset, so the switch leaves the batch engine untouched.HIPCC=/nonexistent/hipcc, load logsnative 4-bit decode projections unavailable (...); falling back to the f16 weight pathand generation continues on the f16 path.hipccand produces the cached HSACO.Follow-ups
Prefill keeps the f16 path (it runs once per request), and the LM head stays an f16
[H, V]operand. Extending the kernel to the head, and a wider-N tiling for the gate/up projections, are the remaining levers on the decode step; they are not part of this change.Refs #2889, #2886