Repository navigation
Closed
Labels
area:inferenceGeneration, sampling, decoding (incl. speculative, DRY)priority:highHigh prioritystatus:doneCompletedtype:performancePerformance improvements
Description
Goal
Run the single-sequence decode projections from the checkpoint's MLX affine 4-bit weights directly, instead of uploading f16-resident copies. #2886 measured why this is the dominant remaining lever and why the existing packed path cannot deliver it.
Evidence from #2886
- The step is 24.63 ms for llama-3.2-1b on gfx1151, streaming about 2.47 GB of f16 projection weights at about 100 GB/s. MLX ROCm does the same step in 4.2 ms reading about 618 MB of 4-bit weights at about 167 GB/s.
MLXCEL_XLA_QUANT=packedis 0.07 tok/s: IREE materializes a dequantized-and-transposed f16 operand per weight per step as its own dispatch (18.2 s of 26.3 s in the trace), so the unpack is not fused into the vecmat.- This pin has no reachable narrow-weight contraction:
QuantizedMatmulToMatmulis the int8 path, the ROCm ukernel catalog ships argmax and one int8 MFMA micro-kernel only, and the vector-distribute and tile-and-fuse pipelines do not consume sub-byte weights inside a contraction.
Proposed implementation
A hal.executable.source private @custom_qmv custom dispatch, the mechanism Gemma3n's CUDA qmv already uses (flow.dispatch @custom_qmv::@gemma3n_qmv in emitter/gemma3n_emit.rs), with a HIP C kernel compiled to HSACO for the active gfx target at build time.
- Kernel: one workgroup per output tile, lanes cooperating over the contraction axis, one
ui32(eight 4-bit values) per lane read, group-64 scales and biases applied in the loop, f16 activations, f32 accumulate, cross-lane reduction. Shapes to cover with one kernel or a small set of specializations: N=2048/K=8192 (down), N=8192/K=2048 (gate, up), N=2048/K=2048 (q, o), N=512/K=2048 (k, v), and the 128256/K=2048 head. - Weights: reuse the existing
WeightSpec::QuantRawresolution (packedui32plus f16 scales/biases) so the loader keeps the checkpoint's 4-bit tensors resident; no f16 expansion.IreeRaggedLlamaand the CPU/CUDA backends keep the current f16 path. - Graph: the
InOutsingle-sequence emitter selects the custom dispatch for these projections when the model is quantized and the backend is hip; the f16 vecmat stays as the fallback and for non-quantized checkpoints. - Build: compile the kernel with
hipccto an HSACO object forMLXCEL_XLA_ROCM_TARGET(orgfx1151detection), embed or install it, and keep the Python/CLI build path working whenhipccis absent (fallback to the f16 path with a warning, not a hard failure).
Milestones
- Kernel prototype outside the runtime: a standalone HIP harness that times the five shapes against the current in-model per-call times (0.305 ms down, 0.224 gate, 0.19 q/o, 0.047 k/v, 3.33 head) and reports effective GB/s. Target at least the MLX per-call rate, about 0.04 ms for the projection shapes.
- Custom-dispatch integration for the down projection only, validated token-exact against the f16 path, then the remaining shapes.
- Full single-sequence validation and the batch gate.
Acceptance criteria
- Greedy output token-identical to the f16 path on llama-3.2-1b (tied) and one untied checkpoint, and context/precision edge cases unchanged.
- Per-step device time and throughput measured before/after with the same n=1 vs n=128 trace subtraction; the target is the about 4.2 ms step MLX reaches, or a documented per-shape shortfall.
- The batch
REFERENCE-EXACTgate passes, the ragged engine and committed goldens are unchanged, and the f16 path still works on every device. - Builds without
hipccstill compile and run the f16 path;cargo test -p mlxcel-xla --liband clippy at default andireefeatures stay green.
Out of scope
Prefill, the batch/serving engine's own weight path, and non-hip backends. Activation precision changes.
Metadata
Metadata
Assignees
Labels
area:inferenceGeneration, sampling, decoding (incl. speculative, DRY)priority:highHigh prioritystatus:doneCompletedtype:performancePerformance improvements
Activity
inureyes commentedon Nov 9, 2026
Milestone 1 done: a standalone HIP prototype on gfx1151, with the MLX affine 4-bit format exactly (
w = q * scale + bias, group 64, little-endian nibbles), f16 activations, f32 accumulate, one workgroup per output row and a shuffle-plus-shared reduction. Source and harness are scratch files; they will be moved intocsrc/with the integration.Correctness: kernel output matches a CPU reference using the same formula to a relative error of about 2e-8 on the checked rows (fp16 input, f32 accumulation).
Timing, 200 iterations (50 for the head), effective bandwidth over the weight plus metadata bytes:
Projected per-step projection cost: 16 layers of two gate/up calls, one down, two q/o and two k/v calls is about 2.21 ms, plus the head at 1.09 ms, so roughly 3.3 ms against the current about 21 ms. That would bring the decode step into the range of the MLX path (4.2 ms) once the attention and other work is added.
Two things the head measurement shows: the one-block-per-row scheme is weakest at N=128256 (136 GB/s, 128256 blocks) and at N=512 (127 GB/s), so the integration should either process several rows per workgroup or add a dedicated specialization for the head. That is a kernel-tuning step, not a blocker; even at these numbers the shape is 3x faster than the f16 vecmat.
Next: milestone 2, wiring the kernel as a
hal.executable.source @custom_qmvdispatch for the down projection first and checking token-exactness against the f16 path.inureyes commentedon Nov 9, 2026
Milestone 2's main technical risk is retired: a prebuilt HIP HSACO works as a custom dispatch end to end on this pin.
Test setup (scratch, to be moved into
csrc/with the integration):hipcc --genco -O3 --offload-arch=gfx1151on the prototype kernel (exportedextern "C" qmv4_kernel, 256 threads, one workgroup per output row) produces a 10208-byte HSACO.hal.executable.source private @custom_qmv attributes { objects = #hal.executable.objects<{ #hal.executable.target<"rocm", "rocm-hsaco-fb"> = [#hal.executable.object<{path = "qmv4.hsaco", data = dense<...>}>] }> }and exports@qmv4_kernelwithconstants = 2(K, N) and five bindings (x, packed, scales, biases read-only;[N] f32writable),workgroup_size = [256, 1, 1], and a workgroup count of(N, 1, 1).flow.dispatch @custom_qmv::@qmv4_kernel[%n](%k, %n, %x, %packed, %scales, %biases).iree-compile --iree-hal-target-device=hip --iree-rocm-target=gfx1151accepts it and the ROCm backend reads the HSACO from the object (ROCMTarget.cppexternal-variant path).Result on gfx1151 for N=2048, K=2048 with deterministic inputs: output matches a CPU reference computed with the same affine formula, max abs error 2.9e-6 and relative 1.8e-7 (f32 accumulation order differs from the double-precision reference). The kernel is correct through the real IREE runtime, not just in the standalone harness.
What remains for the integration, in order:
csrc/and generate the HSACO at model-load time withhipcc --gencoforMLXCEL_XLA_ROCM_TARGET, cached by content hash plus arch, falling back to the f16 path whenhipccis absent.MLXCEL_XLA_QUANT=nativeor reuse of the packed switch) theInOutsingle-sequence projections emit the custom dispatch with the existingQuantRawpacked/scales/biases argument declarations instead ofdequant_affineplusdot_general.QuantRawtensors, so the projections stay 4-bit resident.REFERENCE-EXACT, f16 path intact on every device, tests and one InOut golden for the native decode graph.feat(xla): run 4-bit decode projections through a native HIP GEMV
inureyes commentedon Nov 9, 2026
The integration is up as PR #2890 on
feat/2889-qmv4-native. It compilescsrc/qmv4.hipat model load, caches the HSACO by kernel-content hash plus architecture, embeds it ashal.executable.source @custom_qmv, and dispatches it from the single-sequence decode graph underMLXCEL_XLA_QUANT=native; prefill, the ragged batch engine, and non-HIP devices keep the f16 path, and a missinghipccor a packing other than 4-bit group 64 logs a warning and falls back.Two findings worth recording for the follow-ups:
flow.dispatchoperand declaredui32makes the StableHLO input pipeline fail withfailed to legalize operation 'flow.dispatch' that was explicitly marked illegal: the pass legalizes unsigned integers away and has no pattern for a dispatch carrying one. Declaring the packed weight operand as signlessi32compiles, and the kernel reads the buffer asuint32_t, so the bits are identical.xla_batch_benchstays REFERENCE-EXACT at B=4 and B=8.Remaining levers on the decode step, out of this PR: the LM head still streams an f16
[H, V]operand, and the gate/up projections have no wide-N tiling in the kernel.feat(xla): run 4-bit decode projections through a native HIP GEMV (#2890
perf(xla): pack the LM head and retile the native decode GEMV
perf(xla): pack the LM head and retile the native decode GEMV (#2892)
inureyes commentedon Nov 9, 2026
Implemented and merged. #2890 (
8224641e) brought the custom dispatch up:csrc/qmv4.hipcompiled at model load into a cached HSACO, embedded ashal.executable.source @custom_qmv, and dispatched from the single-sequence decode graph underMLXCEL_XLA_QUANT=native, with theQuantRawweight list, the f16 fallback, and the batch engine untouched. #2892 (379a1e29) added the packed LM head and the kernel tiling.Final numbers on gfx1151 with llama-3.2-1b-instruct-4bit (greedy, n=128, capacity 256, warm vmfb): decode goes from 30.0 tok/s on the f16 path to 113 tok/s (109 to 118 across rounds), and the decode step from 24.6 ms at the start of #2873 to 7.1 ms. The remaining step is 5.46 ms of kernel time (projections 3.7 ms including the head at 0.62, attention 1.3) plus 1.6 ms of dispatch gaps, against the 4.2 ms MLX reaches. Greedy output is token-identical on the tied llama checkpoint and untied qwen2.5-coder-7b,
xla_batch_benchis REFERENCE-EXACT at B=4 and B=8, and both kernels were checked against a double-precision reference throughiree-run-module.The remaining levers recorded in #2891 are out of scope here: multi-output kernels for q/k/v and gate/up (113 launches per step), attention cost, and a multi-row GEMV for the ragged batch engine.