Skip to content

perf(xla): run the ragged engine through the native 4-bit GEMV - #2933

Merged
inureyes merged 7 commits into
mainfrom
perf/issue-2922-ragged-native-qmv
Nov 10, 2026
Merged

inureyes merged 7 commits into
mainfrom
perf/issue-2922-ragged-native-qmv

Conversation

@inureyes

@inureyes inureyes commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Summary

The ragged continuous-batching engine (XlaBatchEngine, behind xla_batch_bench and the OpenXLA serve worker) was the last engine on the f16-expanded weight path: its graph is ProjectionLayout::OutIn, no packed operand was registered, and linear_seq_proj fell through to stablehlo.dot_general. It now runs the checkpoint's packed 4-bit projections through the native HIP GEMV, reusing the cumulative-N multi-output ABI merged in #2907, so prefill and decode share the resident packed tensors and the f16 expansion is never uploaded.

  • csrc/qmv4.hip: adds qmv4_multi_kernel and qmv4_multi_row_kernel plus the fused multi-row q/k/v and gate/up variants. Each keeps one accumulator per activation row, so a weight word is dequantized once and multiplied into every row and the streamed weight bytes drop about 4x; per-row accumulation order matches the single-row kernels, so a multi-row row is bit-identical to its single-row form. The block-per-row exports reduce all rows' partials through one shared-memory pass with a single barrier. All six exports live in the existing HSACO.
  • native_qmv.rs: the six multi-row exports and their hal.executable.source blocks, the multi_dispatch / qkv_multi_dispatch / gateup_multi_dispatch selectors (same K >= 4096 width rule and grid rounding as the single-row form), and MAX_BATCH mirrored against QMV4_MAX_B. module_parts (rank-1) and ragged_module_parts (multi-row) are separate, so each decode graph embeds only the export group it dispatches; every embedded block carries a full HSACO copy, so mixing them wasted about 350 KB of object data per module. The supported shapes (B, K % 64 == 0, N granularity, workgroup count) are documented on the helpers and asserted in tests.
  • emitter/builder.rs: native_qmv_rows emits one flow.dispatch per packed operand group over [B, K], with the fused three-output and two-output forms; linear_seq_proj routes a packed rank-2 activation through it and gate_up_proj picks the rank-2 or rank-1 entry by activation rank.
  • emitter/model.rs: the ragged argument schema registers packed operands for OutIn, the rank-2 attention path fuses q/k/v in one launch, and the MLP fuses gate/up. emit_decode_ragged_with_native carries the native module and leaves the f16 graph byte-identical when none is passed; take_weight keeps the logical shape per layout, and the tied LM head stays on the f16 dot_general path in this graph.
  • iree.rs: XlaRaggedLlama::load_inner resolves native mode once, before runtime_ffi_dimensions and the weight upload, so the decision is shared with the prefill graphs. The ragged gate requires both a 4-bit group-64 checkpoint and a layout the packed projections support, and reports the f16 fallback when either fails; the packed-argument check reads the resolved packed_args flag.

Launches per ragged decode step for llama-3.2-1b drop from 113 to 65 (7 rank-2 projections per layer to 4), and the count does not scale with B.

Changes during review

  • 564101b2 docs: the ragged graph keeps its LM head on the f16 dot_general path; only the single-sequence graph packs and dispatches the head.
  • 4f81b375 perf: separate the two graphs' embedded export groups (see the native_qmv.rs bullet above).
  • ec6d7d68 perf: skip the hipcc compile and embedded artifact for a 4-bit group-64 checkpoint whose projection layout registers no packed operand (fused q/k/v, fused gate/up, MoE, MLA, dense MLP), and warn about the fallback instead.
  • 43ca0ef2 test: the emitter test now also emits B=4 and asserts the same four dispatch counts, arith.constant 4 : i32 and tensor<4x8192xf32>, so a launch count that scales with B fails.
  • e107383a docs: record the measurements re-taken at the reviewed tip.

Related issues

Closes #2922

Refs #2889, #2891, #2895, #2907

Type of change

  • perf: performance improvement (before/after numbers below)
  • feat
  • fix
  • refactor
  • chore
  • docs
  • test

Test plan

  • cargo fmt --all -- --check (clean at the final tip)
  • cargo clippy -p mlxcel-xla --features iree --lib --tests -- -D warnings (clean)
  • cargo check -p mlxcel-xla --features iree --lib --tests (clean)
  • cargo test -p mlxcel-xla --lib native_qmv:: (6 passed), native_ragged_decode_emits_multi_row_dispatches (1 passed), validation:: goldens (9 passed), all without the iree feature
  • hipcc --genco -O3 --offload-arch=gfx1151 csrc/qmv4.hip compiles; the HSACO exports all six multi-row kernels
  • Real checkpoint: llama-3.2-1b-instruct-4bit (tied) through xla_batch_bench with MLXCEL_XLA_DEVICE=hip MLXCEL_XLA_QUANT=native MLXCEL_XLA_PRECISION=f16, both B values REFERENCE-EXACT PASS. Same-binary sequential A/B: B=8 measures 74.5 and 76.7 tok/s in two runs against 59.8 for the f16 path (the 69 to 71 tok/s recorded at filing), and B=4 measures 60.0 and 62.2 against 65.6
  • Untied checkpoint: Qwen2.5-7B-Instruct-4bit (untied, 4-bit group-64, no fallback warning, so the native path ran) at B=4: REFERENCE-EXACT PASS at 14.2 tok/s. mistral-7b-instruct-v0.3-4bit cannot serve here because the OpenXLA emitter rejects model_type = "mistral" before any weight handling, native or not
  • Fallback: HIPCC=/nonexistent/hipcc with a fresh kernel cache loads and decodes through f16 with one warning per engine load and prints REFERENCE-EXACT PASS (66.1 tok/s at B=4)

Notes for reviewers

  • The multi-row kernels are launched with the batch size as a push constant and predicate the live accumulators, so one HSACO serves both bundled graphs (B=4 and B=8) with no recompile. That predication is a fixed cost per weight word: at B=4 the native path measures 60.0 to 62.2 tok/s against 65.6 for f16, while at B=8 it measures 74.5 to 76.7 against 59.8. Per-B accumulator specialization would remove the B=4 cost and is the obvious follow-up if that graph matters; the acceptance gate for this issue is B=8, and both B values stay REFERENCE-EXACT.
  • The tied LM head is deliberately left on the f16 path in the ragged graph, as the single-sequence path does when the head is not packed; take_lm_head keeps its OutIn contract, and weight_specs is unchanged.
  • Prefill graphs for a native ragged load now take the packed tensors and dequantize in-graph, exactly as the single-sequence native path already does; the packed list is shared so every graph kind keeps the same argument positions.
  • Fallback behavior: a missing hipcc, an unsupported architecture, or a checkpoint whose quantization or projection layout the packed path does not support logs one warning and emits the previous f16 graph.

Checklist

  • PR title uses a Conventional Commits prefix (perf(xla): ...)
  • One logical change per PR
  • Updated docs/ for the user-facing behavior change (docs/environment-variables.md, src/lib/mlxcel-xla/README.md, CHANGELOG.md)
  • Checked // Used by: comments on the shared functions I modified
  • No secrets, credentials, or .env files committed

@inureyes inureyes added type:performance Performance improvements priority:high High priority area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Nov 10, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Run the ragged continuous-batching engine's packed 4-bit projections through the native multi-row HIP GEMV, keeping the f16 graph as the fallback.

Findings Addressed

  • Docs overstated the LM head joining the ragged native path; corrected in docs/environment-variables.md and src/lib/mlxcel-xla/README.md (MEDIUM, commit 564101b)
  • Builder::with_native_proj doc still said only the single-sequence decode graph sets it (LOW, commit 564101b)

Remaining Items

  • A 4-bit group-64 checkpoint whose layout is not supports_packed_quant (fused qkv, MoE, MLA) embeds the HSACO but registers no packed operand, so the ragged graph stays f16 without a warning (LOW; pre-existing on the single-sequence path, output correct)

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

Validated: full mlxcel-xla lib suite (399 passed, byte-exact goldens included), clippy with iree clean, hipcc gfx1151 compile with all six multi-row exports, xla_batch_bench REFERENCE-EXACT PASS at B=4 and B=8 on llama-3.2-1b-instruct-4bit with no fallback warning, and the HIPCC=/nonexistent/hipcc fresh-cache fallback with one warning and REFERENCE-EXACT PASS.

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review (automated pass)

Scope: the ragged engine wiring in src/lib/mlxcel-xla/src/iree.rs, src/lib/mlxcel-xla/src/native_qmv.rs and the new kernels in src/lib/mlxcel-xla/csrc/qmv4.hip.

Device boundary

The new multi-row kernels were checked against B 1..=8, K % 64 == 0, arbitrary N (including N % ROWS_PER_BLOCK != 0) and the cumulative-N fused row selection. Weight, scale, bias, input and output indices all stay within their tensors, the uint4 loads are 16-byte aligned because K / 8 is a multiple of 8 under K % 64 == 0, and every early return that precedes a shuffle or barrier is warp-uniform or block-uniform, so the single __syncthreads() in qmv4_block_sum_multi is reached by all threads. No memory-safety or barrier issue found.

The HSACO path validates the architecture (gfx plus lowercase alphanumeric) before it reaches --offload-arch, HIPCC is executed as an argument vector rather than a shell, and the cache key covers kernel source plus arch. No injection or path-traversal issue found. Unsupported checkpoints and launch failures surface as engine errors or the existing f16 fallback, never as a silent wrong result.

Fixed

  1. perf(xla): embed only the GEMV exports each decode graph dispatches (4f81b37). Both decode graphs received all six hal.executable.source blocks, and each block embeds a full HSACO copy. The single-sequence module therefore carried three dead multi-row executables and roughly 350 KB of unused object data plus 700 KB of hex text, and the ragged graph carried the three rank-1 blocks. module_parts and the new ragged_module_parts now emit only their own three blocks, with a regression test that asserts neither set contains the other's exports.

  2. perf(xla): skip the native GEMV artifact for unsupported packed layouts (ec6d7d6). The ragged loader compiled and embedded the HSACO for any 4-bit group-64 checkpoint. take_weight registers a packed projection only when supports_packed_quant() also holds, so fused q/k/v, fused gate/up, MoE, MLA and dense MLP layouts paid for a hipcc compile and embedded an unused artifact without the fallback warning the docs promise. The loader now gates on both predicates and warns.

Left as is

The pre-existing shared HSACO cache in /tmp/mlxcel-xla-qmv4 is world-accessible in principle, so a local attacker could poison or clobber entries. The same pattern appears in the repository's other caches, this PR does not introduce it, and a robust fix needs ownership or euid checks that the project cannot do without adding a dependency. The cache key likewise omits the hipcc identity and version. A failed compile leaves the pid-suffixed .hip temp behind. None of these affect correctness under normal use and none is a regression from this PR.

Verification

cargo fmt --all -- --check, cargo test -p mlxcel-xla --lib native_qmv:: (6 passed), cargo check -p mlxcel-xla --features iree --lib --tests and cargo clippy -p mlxcel-xla --features iree --lib --tests -- -D warnings all pass on the pushed tip, run under scripts/rocm_gpu_guard.sh.

@inureyes inureyes added the status:done Completed label Nov 10, 2026
The ragged continuous-batching engine still streamed f16-expanded projection weights: linear_seq_proj found no packed operand in the OutIn graph and fell through to stablehlo.dot_general. It now runs the checkpoint's packed 4-bit projections through the native HIP GEMV, reusing the cumulative-N fused ABI from #2907.

qmv4.hip gains qmv4_multi_kernel and qmv4_multi_row_kernel plus the fused multi-row q/k/v and gate/up variants. Each keeps one accumulator per activation row, so a weight word is dequantized once and multiplied into all B rows and the streamed weight bytes drop about 4x. The block-per-row export reduces every row's partial through one shared-memory pass with a single barrier. native_qmv.rs adds the six exports, their hal.executable.source blocks, and the dispatch helpers with the same K >= 4096 width rule and grid rounding as the single-row form; builder.rs adds native_qmv_rows and routes a packed rank-2 linear_seq_proj through it; model.rs registers packed operands for the ragged schema, fuses q/k/v and gate/up, and keeps the f16 graph byte-identical when no native module is passed; iree.rs decides the mode once in XlaRaggedLlama::load_inner before the FFI dimensions and weight upload, so the packed tensors stay resident and the decision is shared with the prefill graphs.

A ragged decode step for llama-3.2-1b drops from 113 launches to 65 (7 rank-2 projections per layer to 4), independent of B. The f16 fallback is unchanged for a missing hipcc, an unsupported arch, or a checkpoint that is not 4-bit group-64. On gfx1151 with llama-3.2-1b-instruct-4bit, the same binary through xla_batch_bench measures 74.5 tok/s at B=8 against 59.8 on the f16 path and 62.2 against 65.6 at B=4, with REFERENCE-EXACT PASS on every run; the untied Qwen2.5-7B-Instruct-4bit stays exact at B=4.
The MLXCEL_XLA_QUANT row in docs/environment-variables.md and the README native section implied that the LM head joins the native GEMV path on the ragged batch engine too. It does not: the ragged graph keeps the head on the f16 dot_general path regardless of packing, and only the single-sequence graph packs and dispatches it. State that split so the docs match the code, and note it in the ragged README paragraph.

Also update the Builder::with_native_proj doc comment, which still said only the single-sequence decode graph sets it; the ragged decode graph sets it now, and the prefill graphs leave it off so their packed operands dequantize in the graph.
Both decode graphs were handed all six `hal.executable.source` blocks from `native_qmv::module_parts`, so the single-sequence graph embedded the three multi-row blocks and the ragged graph embedded the three rank-1 blocks. Each block carries a full copy of the HSACO (120 KB for the current kernel), which added about 350 KB of unused object data and 700 KB of hex text to the single-sequence module, three dead executables to its iree-compile input, and the same waste in the ragged graph.

Split the list: `module_parts` now carries the rank-1 blocks and `ragged_module_parts` the multi-row blocks, and `IreeRaggedLlama::load_inner` uses the latter. A test pins the split so a later export cannot silently start embedding twice.

Validated with `cargo fmt --all -- --check`, `cargo test -p mlxcel-xla --lib native_qmv::` (6 passed), and `cargo clippy -p mlxcel-xla --features iree --lib --tests -- -D warnings`.
`XlaRaggedLlama::load_inner` compiled and embedded the HSACO whenever the checkpoint was 4-bit group-64. `take_weight` registers a packed projection only when `supports_packed_quant()` also holds, so a checkpoint with fused q/k/v, fused gate/up, MoE, MLA or a dense MLP paid for a hipcc compile and embedded an artifact that no dispatch reached, without the fallback warning the docs promise.

Gate the ragged native decision on both predicates and report the f16 fallback when either fails. The single-sequence loader keeps its own predicate, where a packed LM head can still justify the artifact.

Also correct the packed-gate comment: `MLXCEL_XLA_QUANT=packed` does not set `packed_args` on the ragged path, so the check reflects the native decision there.
The reviewed tip was re-measured end to end: native B=4 60.0 tok/s, B=8 76.7 tok/s, untied Qwen2.5-7B-Instruct-4bit B=4 14.2 tok/s, and the HIPCC-unavailable fallback 66.1 tok/s, all REFERENCE-EXACT PASS. State the two B=8 observations against the same-binary f16 reference and extend the fallback wording to the projection-layout case that the load gate now rejects.
The ragged emitter test exercised only the B=8 bundled graph, so the issue's requirement that the launch count does not scale with the batch, and that the B=4 graph carries its own push constant, was untested. Extend it to emit B=4 with the native module and assert the four multi-row dispatch counts match the B=8 graph, the batch constant is 4, and the fused outputs are shaped [4, N].

Validation: cargo fmt --all -- --check, cargo clippy -p mlxcel-xla --features iree --lib --tests -- -D warnings, and cargo check -p mlxcel-xla --features iree --lib --tests pass; the narrow selectors native_qmv::, native_ragged_decode_emits_multi_row_dispatches, and validation:: pass without the iree feature.

Refs #2922
@inureyes
inureyes force-pushed the perf/issue-2922-ragged-native-qmv branch from 43ca0ef to 78e6564 Compare November 10, 2026 08:39
@inureyes
inureyes marked this pull request as ready for review November 10, 2026 08:43
@inureyes
inureyes merged commit 92c07eb into main Nov 10, 2026
31 checks passed
@inureyes
inureyes deleted the perf/issue-2922-ragged-native-qmv branch November 10, 2026 08:43
inureyes added a commit that referenced this pull request Nov 11, 2026
The ragged loader compiled csrc/qmv4.hip once with QMV4_MAX_B=8 and reused that artifact for the B=4 bucket, so a B=4 step carried the B=8 instruction stream, register allocation and 1 KiB shared-memory reduction buffer while half of its accumulator lanes were dead.

Make the bound an overridable default and add native_qmv::hsaco_multi(arch, b_max), which compiles the same source with -DQMV4_MAX_B=<bucket> and a cache stem that carries the bound. The widest bucket maps to the default artifact, so B=8 takes the same compile as before; the single-sequence loader still calls hsaco(). The emitted graph, the six export names and the push-constant ABI are unchanged.

A controlled interleaved A/B on one binary, swapping only the embedded HSACO, measures a median 42.29 to 43.56 tok/s at B=4 (requests 8, maxcap 24) with the narrow artifact ahead in all five paired rounds, and 50.74 to 52.13 at requests 16. Every run is REFERENCE-EXACT. The absolute #2933 targets are not reproducible on current HEAD because the f16 ragged upload takes about 4.8 s; that is pre-existing and out of scope.

Closes #2955
inureyes added a commit that referenced this pull request Nov 11, 2026
The ragged loader compiled csrc/qmv4.hip once with QMV4_MAX_B=8 and reused that artifact for the B=4 bucket, so a B=4 step carried the B=8 instruction stream, register allocation and 1 KiB shared-memory reduction buffer while half of its accumulator lanes were dead.

Make the bound an overridable default and add native_qmv::hsaco_multi(arch, b_max), which compiles the same source with -DQMV4_MAX_B=<bucket> and a cache stem that carries the bound. The widest bucket maps to the default artifact, so B=8 takes the same compile as before; the single-sequence loader still calls hsaco(). The emitted graph, the six export names and the push-constant ABI are unchanged.

A controlled interleaved A/B on one binary, swapping only the embedded HSACO, measures a median 42.29 to 43.56 tok/s at B=4 (requests 8, maxcap 24) with the narrow artifact ahead in all five paired rounds, and 50.74 to 52.13 at requests 16. Every run is REFERENCE-EXACT. The absolute #2933 targets are not reproducible on current HEAD because the f16 ragged upload takes about 4.8 s; that is pre-existing and out of scope.

Closes #2955
inureyes added a commit that referenced this pull request Nov 11, 2026
Split the ragged load span into module load and weight upload through the existing MLXCEL_XLA_LOAD_TIMING reporter. The parts line now carries the uploaded tensor count, bytes, host dequantize time, f16 pack time and device copy time. A capacity bucket reports zero upload because it shares the base context's views. No new labels are printed when the variable is unset.

Add test-support counters for xla_llama_upload_weight and an ignored root device test that asserts one upload per declared weight spec and none for a capacity bucket.

xla_batch_bench loads the engine before its timed window again. #2936 (311ad93) moved the load under t_run while replacing the pump loop with drive, which is what dropped the f16 B=4 reading from the control's 63.4 tok/s to 20.8 and made the #2933 targets look unverifiable. The pre-#2933 control (fd2a65e) loads the same span in 4.9 s on the same checkpoint, host, IREE distribution and capacity, so the 0.7 s figure in the issue does not reproduce. The f16 ragged load is the host dequantize, f16 pack and 3.0 GB device copy, unchanged from the control, and flat across capacity 256 and 1024.

Measured on gfx1151, medians of three runs: f16 ragged load 5.62 s at B=4 and 5.03 s at B=8, native 1.17 s and 1.15 s. Decode-only medians are 64.0 and 60.4 tok/s for f16 and 61.7 and 75.8 for native at B=4 and B=8.
inureyes added a commit that referenced this pull request Nov 11, 2026
…#2976)

* fix(xla): split ragged load timing, restore decode-only tok/s (#2961)

Split the ragged load span into module load and weight upload through the existing MLXCEL_XLA_LOAD_TIMING reporter. The parts line now carries the uploaded tensor count, bytes, host dequantize time, f16 pack time and device copy time. A capacity bucket reports zero upload because it shares the base context's views. No new labels are printed when the variable is unset.

Add test-support counters for xla_llama_upload_weight and an ignored root device test that asserts one upload per declared weight spec and none for a capacity bucket.

xla_batch_bench loads the engine before its timed window again. #2936 (311ad93) moved the load under t_run while replacing the pump loop with drive, which is what dropped the f16 B=4 reading from the control's 63.4 tok/s to 20.8 and made the #2933 targets look unverifiable. The pre-#2933 control (fd2a65e) loads the same span in 4.9 s on the same checkpoint, host, IREE distribution and capacity, so the 0.7 s figure in the issue does not reproduce. The f16 ragged load is the host dequantize, f16 pack and 3.0 GB device copy, unchanged from the control, and flat across capacity 256 and 1024.

Measured on gfx1151, medians of three runs: f16 ragged load 5.62 s at B=4 and 5.03 s at B=8, native 1.17 s and 1.15 s. Decode-only medians are 64.0 and 60.4 tok/s for f16 and 61.7 and 75.8 for native at B=4 and B=8.

* docs: report the ragged load timing split (#2961)
@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

area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:high High priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(xla): extend the native 4-bit GEMV to the ragged batch engine

1 participant