Skip to content

perf(xla): port the native 4-bit GEMV to the CUDA device - #2984

Merged
inureyes merged 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:perf/2905-xla-native-gemv-cuda
Nov 15, 2026
Merged

inureyes merged 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:perf/2905-xla-native-gemv-cuda

Conversation

@Jaeyeong-CHOI

@Jaeyeong-CHOI Jaeyeong-CHOI commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

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 perf(xla): fuse q/k/v and gate/up into multi-output native GEMV dispatches #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
  • 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

  • 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)
  • Validated with real checkpoints: mlx-community/Llama-3.2-1B-Instruct-4bit, mlx-community/Qwen2.5-7B-Instruct-4bit
  • 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 perf(xla): run 4-bit decode projections through a native HIP GEMV #2890. Same architecture and shapes (hidden 3584, down K=18944 on the row kernel).

Checklist

  • PR title uses a Conventional Commits prefix (feat:, fix:, etc.)
  • One logical change per PR (split unrelated changes)
  • Updated docs/ if user-facing behavior or supported models changed
  • Updated // Used by: ... comments on any shared function I modified (see docs/code-guidelines.md)
  • No secrets, credentials, or .env files committed

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.

Add csrc/qmv4.cu, the six single-sequence entry points of csrc/qmv4.hip with
__shfl_down_sync in place of __shfl_down, and compile it to compute_80 PTX
in build.rs next to the Gemma3n kernel when the crate builds against a CUDA
IREE runtime and nvcc is available. The loader enables the switch on cuda,
embeds the PTX for the cuda-nvptx-fb target and compiles the graph for
sm_80. The emitter is unchanged: the CUDA graph is the hip graph with the
target alias and the embedded object swapped. The 4-bit group-64 gate, the
signless i32 packed operand and the LM head dtype check are shared with hip.
The ragged engine's multi-row exports are not ported, so it keeps the f16
weights on cuda.

PTX availability gets its own cfg, xla_iree_cuda_ptx, separate from the
runtime cfg xla_iree_cuda. A CUDA IREE build without nvcc now compiles with
a warning and no PTX: dense models keep the f16 path, and Gemma3n CUDA Q4
keeps its load-time error for the missing artifact. A compiler that is found
and rejects a source still fails the build.

On a DGX Spark GB10 (llama-3.2-1b-instruct-4bit, greedy, n=128, capacity
256, warm vmfb) decode goes from 20.2-20.8 to 58.4-69.2 tok/s, and from
5.8-5.9 to 19.0-19.6 tok/s on the untied qwen2.5-7b-instruct-4bit, with
identical output on two prompts each. GPU kernel time per decode step falls
from 41.8 to 8.3 ms at 309 launches per step in both graphs.

Unit tests hold the CUDA source line-for-line equal to the hip kernels, the
CUDA module text equal to the hip one apart from the object, and the emitted
decode graph equal apart from the alias and object. csrc/qmv4_cuda_oracle.cu
checks the six exports against a host reference outside the build.

Closes lablup#2905
@inureyes inureyes added priority:medium Medium priority status:review Under review type:performance Performance improvements labels Nov 15, 2026
@inureyes

Copy link
Copy Markdown
Member

Implementation hardening verified the CUDA native qmv path against #2905, including opt-in routing, packing, dispatch limits, and the missing-nvcc fallback. No additional blocking defect was found.

Validation on GB10: isolated default XLA tests 412 passed; CUDA IREE tests 437 passed; IREE build with NVCC=/nonexistent/nvcc 436 passed. The standalone CUDA oracle covered 600 launches and 8,440 outputs, with maximum absolute error 1.18613243e-5. Compute Sanitizer reported zero memory errors. IREE test linking used a local test wrapper with the same runtime archives as the root build script.

Checkpoint throughput and the ROCm path were not re-run in this audit; existing benchmark evidence was reviewed.

@inureyes
inureyes merged commit 0afe403 into lablup:main Nov 15, 2026
31 checks passed
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 15, 2026
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority:medium Medium priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(xla): port the native 4-bit GEMV to the CUDA device

2 participants