Skip to content

perf(xla): add a native HIP GEMV for 4-bit decode projections #2889

Closed

Description

@inureyes

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=packed is 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: QuantizedMatmulToMatmul is 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.

  1. 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.
  2. Weights: reuse the existing WeightSpec::QuantRaw resolution (packed ui32 plus f16 scales/biases) so the loader keeps the checkpoint's 4-bit tensors resident; no f16 expansion. IreeRaggedLlama and the CPU/CUDA backends keep the current f16 path.
  3. Graph: the InOut single-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.
  4. Build: compile the kernel with hipcc to an HSACO object for MLXCEL_XLA_ROCM_TARGET (or gfx1151 detection), embed or install it, and keep the Python/CLI build path working when hipcc is absent (fallback to the f16 path with a warning, not a hard failure).

Milestones

  1. 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.
  2. Custom-dispatch integration for the down projection only, validated token-exact against the f16 path, then the remaining shapes.
  3. 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-EXACT gate passes, the ragged engine and committed goldens are unchanged, and the f16 path still works on every device.
  • Builds without hipcc still compile and run the f16 path; cargo test -p mlxcel-xla --lib and clippy at default and iree features stay green.

Out of scope

Prefill, the batch/serving engine's own weight path, and non-hip backends. Activation precision changes.

Refs #2886, #2873

Activity

  1. added
    status:ready
    type:performance
    priority:high
    area:inference
    on Nov 9, 2026
  2. inureyes commented on Nov 9, 2026

    @inureyes
    MemberAuthor

    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 into csrc/ 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:

    shape kernel current in-model f16 speedup
    N=8192, K=2048 (gate, up) 40.2 us, 236 GB/s 224 us 5.6x
    N=2048, K=8192 (down) 25.4 us, 372 GB/s 305 us 12x
    N=2048, K=2048 (q, o) 11.6 us, 204 GB/s 190 us 16x
    N=512, K=2048 (k, v) 4.7 us, 127 GB/s 47 us 10x
    N=128256, K=2048 (head) 1091 us, 136 GB/s 3330 us 3.1x

    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_qmv dispatch for the down projection first and checking token-exactness against the f16 path.

  3. inureyes commented on Nov 9, 2026

    @inureyes
    MemberAuthor

    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=gfx1151 on the prototype kernel (exported extern "C" qmv4_kernel, 256 threads, one workgroup per output row) produces a 10208-byte HSACO.
    • The module embeds it with 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_kernel with constants = 2 (K, N) and five bindings (x, packed, scales, biases read-only; [N] f32 writable), workgroup_size = [256, 1, 1], and a workgroup count of (N, 1, 1).
    • The graph calls flow.dispatch @custom_qmv::@qmv4_kernel[%n](%k, %n, %x, %packed, %scales, %biases).
    • iree-compile --iree-hal-target-device=hip --iree-rocm-target=gfx1151 accepts it and the ROCm backend reads the HSACO from the object (ROCMTarget.cpp external-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:

    1. Move the kernel to csrc/ and generate the HSACO at model-load time with hipcc --genco for MLXCEL_XLA_ROCM_TARGET, cached by content hash plus arch, falling back to the f16 path when hipcc is absent.
    2. Emitter: under a new opt-in (MLXCEL_XLA_QUANT=native or reuse of the packed switch) the InOut single-sequence projections emit the custom dispatch with the existing QuantRaw packed/scales/biases argument declarations instead of dequant_affine plus dot_general.
    3. Loader: the same switch uploads the QuantRaw tensors, so the projections stay 4-bit resident.
    4. Prefill keeps the dequant path (it runs once per request), so the graph kinds share one weight list and only decode uses the native kernel.
    5. Fallback and gates: token-exactness against the f16 path, batch REFERENCE-EXACT, f16 path intact on every device, tests and one InOut golden for the native decode graph.
  4. inureyes commented on Nov 9, 2026

    @inureyes
    MemberAuthor

    The integration is up as PR #2890 on feat/2889-qmv4-native. It compiles csrc/qmv4.hip at model load, caches the HSACO by kernel-content hash plus architecture, embeds it as hal.executable.source @custom_qmv, and dispatches it from the single-sequence decode graph under MLXCEL_XLA_QUANT=native; prefill, the ragged batch engine, and non-HIP devices keep the f16 path, and a missing hipcc or a packing other than 4-bit group 64 logs a warning and falls back.

    Two findings worth recording for the follow-ups:

    • A flow.dispatch operand declared ui32 makes the StableHLO input pipeline fail with failed 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 signless i32 compiles, and the kernel reads the buffer as uint32_t, so the bits are identical.
    • The end-to-end gain on gfx1151 (llama-3.2-1b-instruct-4bit, greedy, n=128, capacity 256, warm vmfb) is 30.0 to 80.3 tok/s, about 2.7x, with byte-identical greedy output on the tied llama checkpoint and on untied qwen2.5-coder-7b; xla_batch_bench stays 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.

  5. inureyes commented on Nov 9, 2026

    @inureyes
    MemberAuthor

    Implemented and merged. #2890 (8224641e) brought the custom dispatch up: csrc/qmv4.hip compiled at model load into a cached HSACO, embedded as hal.executable.source @custom_qmv, and dispatched from the single-sequence decode graph under MLXCEL_XLA_QUANT=native, with the QuantRaw weight 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_bench is REFERENCE-EXACT at B=4 and B=8, and both kernels were checked against a double-precision reference through iree-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.

  6. added
    status:done
    and removed
    status:ready
    on Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:inferencepriority:highstatus:donetype:performance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions