Repository navigation
perf(xla): port the native 4-bit GEMV to the CUDA device - #2984
Merged
inureyes merged 1 commit intoNov 15, 2026
Merged
Conversation
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
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. |
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=nativewas inert onMLXCEL_XLA_DEVICE=cuda: the loader required thehipdevice, 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 ofcsrc/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),__halfactivations and scales/biases.src/lib/mlxcel-xla/build.rs: compiles it withnvcctocompute_80PTX next to the Gemma3n kernel, in the sameIREE_CUDA_HOMEbranch. PTX availability is now its own cfg,xla_iree_cuda_ptx, emitted only after both kernels compile;xla_iree_cudakeeps meaning "CUDA IREE runtime". Withoutnvccthe 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 undercfg(xla_iree_cuda_ptx), and builds the CUDA target alias (#hal.executable.target<"cuda", "cuda-nvptx-fb">) and the threehal.executable.sourceblocks from the same export tables the hip path uses.src/lib/mlxcel-xla/src/iree.rs: the switch now turns on forcudaas well aship, 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 signlessi32packed operand and the LM head dtype check are the existing shared code.gemma3n_qmv.rs, the native SDPA gate and three test sections) moves fromcfg(xla_iree_cuda)tocfg(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 featurefix— bug fixperf— performance improvement (include before/after numbers in the PR body)refactor— internal restructuring without behavior changechore— build, CI, dependencies, release infrastructuredocs— documentation onlytest— tests onlyMeasurements
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, base955335a3. 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 oncuda(19.28 tok/s without it, 19.42 with it, same output, 48 tokens).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).nsysvecmatqmv4_*batch_matmul(attention), 32 per stepPer kernel, f16 graph (name is out x in):
vecmat_2048x8192(down)vecmat_8192x2048(gate, up)vecmat_2048x2048(q, o)vecmat_512x2048(k, v)vecmat_128256x2048(head)Per kernel, native graph:
qmv4_gateup_kernelqmv4_kernel(o, head)qmv4_row_kernel(down)qmv4_qkv_kernelTwo 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
vecmatagainst 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 generatedoes not print token ids on the XLA path (#2980 addresses that), so I also compared ids with the repository's own tools:xla_traj_dumpfor the f16 and the native trajectory (128 argmax steps, raw prompt, no EOS stop), andxla_oracle_checkunderMLXCEL_XLA_QUANT=nativeagainst the f16 dump.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, nativestory). What I checked:storyand reports the same log-probability for both candidates: -1.28125 and -1.28125, thenchallengeat -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/nvccwith 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 warningsandRUSTFLAGS="-D warnings" cargo check --features cuda,xla-iree: clean, with the onecargo:warningthat the PTX was omitted.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.--versionand 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.culaunches 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), andcompute-sanitizer --tool memcheckreports 0 errors.This checks indexing and arithmetic of the kernels. It does not make the token comparison above 12 of 12.
Acceptance criteria
xla_batch_benchstays REFERENCE-EXACT--device cuda --batch 8 --requests 16 --maxcap 48:REFERENCE-EXACT PASSwith 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.module_prefix_embeds_the_object_and_the_abi,decode_kinds_embed_only_their_own_exports, the emitter'snative_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 --libpasses with the committed goldens. Not run: any ROCm or Metal device (I have neither).NVCCpointing at a nonexistent path and the CUDA IREE runtime installed:RUSTFLAGS="-D warnings" cargo check --features cuda,xla-ireepasses 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.cargo check --features xla-ireeunderRUSTFLAGS=-D warningsstay cleanRUSTFLAGS="-D warnings" cargo check --features cuda,xla-ireeis clean with and withoutnvcc.Test plan
cargo fmt --all -- --checkcargo clippy --workspace --all-targets --features metal,accelerate -- -D warnings(not run; Linux host).cargo clippy -p mlxcel-xla --all-targets --features iree -- -D warningsis clean with and withoutnvcc.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)mlx-community/Llama-3.2-1B-Instruct-4bit,mlx-community/Qwen2.5-7B-Instruct-4bitAlso 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 withNVCCpointing at a nonexistent path.python3 -m unittest discover -s tests -p 'test_*.py': 219 tests, OK.New unit tests:
cuda_kernels_are_the_hip_single_sequence_kernels:qmv4.cuequals the correspondingqmv4.hiplines 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
mainsuch a build fails inbuild.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.compute_80and the graph is compiled forsm_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.cudathe batch engine keeps the f16 weights whatever the switch says, and the multi-row exports stay hip-only.nvccandhipccmay contract floating point differently, so I make no claim about cross-vendor bit equality.Qwen2.5-7B-Instruct-4bit, not theQwen2.5-Coder-7B-Instruct-4bitused 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
feat:,fix:, etc.)docs/if user-facing behavior or supported models changed// Used by: ...comments on any shared function I modified (seedocs/code-guidelines.md).envfiles committed