Skip to content

perf(xla): reduce decode attention cost in the single-sequence graph #2921

Closed

Description

@inureyes

Problem / Background

On ROCm gfx1151 with llama-3.2-1b-instruct-4bit, single-sequence greedy decode at MLXCEL_XLA_CONTEXT_CAPACITY=256 now runs in about 7.1 ms per step (113 tok/s) after #2890 and #2892 replaced the f16 projection stream with the native packed GEMV. A rocprofv3 decomposition of that step attributes about 3.7 ms to the projection GEMV dispatches, about 1.31 ms (roughly 18 percent) to attention, 0.62 ms to the LM head, and 1.6 to 1.8 ms to host dispatch gaps. The projection block dropped from about 21 ms to 3.7 ms while attention stayed at 1.31 ms, so attention is now the largest remaining kernel block and the next lever on step time. The fused multi-output variant in PR #2907 cut GEMV launches from 113 to 65 but left kernel time and step time nearly flat (5.46 to 5.30 ms kernel, 7.10 to 7.11 ms step), which confirms launch count is no longer the bound and that the remaining work has to reduce attention cost rather than rearrange it.

Current Behavior

The single-token attention block is emitted by AttnLayout::Single in src/lib/mlxcel-xla/src/emitter/model.rs. Per layer, write_read_kv issues two dynamic_update_slice writes into the rank-4 cache [n_layers, context_capacity, n_kv, head_dim] and then slices the whole [context_capacity, n_kv, head_dim] K and V slabs back out (model.rs:1944-1961). raw_scores runs one GQA dot_general (model.rs:2025-2029), apply_scale_and_softcap broadcasts and multiplies the scale (model.rs:2187-2193), add_mask broadcasts and adds the [context_capacity] additive key mask (model.rs:2059-2065), attn_softmax emits max, broadcast, subtract, exponential, reduce-add, broadcast, and divide (model.rs:2172-2182), and context runs the second dot_general (model.rs:2104-2109). That is roughly 18 StableHLO ops per layer between the KV write and the o_proj, and IREE lowers them to a mix of tiny matmuls, reductions, and elementwise kernels. Because context_capacity is a static 256, every attention dispatch runs over all 256 key slots regardless of cache_len.

Proposed Solution

Profile first, then reduce cost inside the existing emitter and graph structure. Do not change the model math, the weight path, or the ragged engine.

  1. Measure. Produce a per-dispatch attention table for one decode step: kernel name, calls per step, per-call time, and bytes, with dispatches grouped by layer and by role (KV write, KV read, scores, mask/scale, softmax, context). Use the same n=1 versus n=128 trace subtraction as perf(xla): close the IREE decode-kernel efficiency gap (small-M vecmats and the serial argmax) #2873 so graph construction and sampling work are excluded, and put the table in the PR.
  2. Decide from the table. Exactly one of these should explain most of the 1.31 ms; record which and why before editing code: per-layer dispatch overhead (many tiny kernels, launch and synchronization cost), softmax and reduction dispatches at these small shapes (256 keys, 32 query heads), or KV cache reads (the full 256-slot slab per layer, per K and V, in a layout that may not suit either dot_general).
  3. Apply the fix the measurement selects, in this order of preference.
    • Remove elementwise work from the per-layer path: fold the attention scale into q once before the layer loop (or into the score constant) and fold the additive mask and the max subtraction into one op, so multiply, broadcast, add, and subtract collapse. Keep the softmax numerically identical: max-subtract before exp is required.
    • Reduce the per-layer dispatch count: combine the K and V updates and the K and V reads where that can be done without changing the rank-4 KV ABI that prefill and the batch engine share, or hoist per-layer constant work out of the loop where the graph allows it.
    • Change the KV layout or static shape only if the table shows the read pattern dominates. Candidates are a head-major layout that makes the dot_general contraction axis contiguous, a separate smaller text capacity bucket (the existing XlaBucketSet machinery), or a decode-specific context_capacity that does not raise the number of valid keys a request needs.

Do not fuse the whole attention block into a new custom HIP kernel in this issue. Measure whether the existing graph can reach the target first; if a custom kernel is the only route, stop and file it separately with the table as evidence.

Scope

In scope: src/lib/mlxcel-xla/src/emitter/model.rs (AttnLayout::Single, write_read_kv, raw_scores, add_mask, attn_softmax, context, emit_decode_with_native) and tests in that module. Only the single-sequence decode graph changes.

Out of scope: the ragged batch engine's attention (AttnLayout::Ragged), prefill attention, the projection GEMV path (#2905, #2886), and any change to src/lib/mlxcel-xla/csrc/qmv4.hip.

Implementation Notes

  • Reuse: the AttnLayout abstraction and emit_attention (model.rs:2688-2727). Do not fork a second attention emitter.
  • Constraints: the decode graph's signature and rank-4 KV layout are shared with prefill and the ragged engine. A layout change needs a matching change in build_arg_schema and the C shim KV validation, and must be justified by the profile. AttnLayout::Ragged and AttnLayout::Prefill emitted text must stay byte-identical so the committed goldens pass.
  • Edge cases: cache_len = 0 (first decode after a one-token prompt), cache_len = context_capacity - 1 (last slot), a sliding-window config (Gemma2), and dual-RoPE configs must keep their current masks and outputs.
  • Error handling: no new runtime failure path. A shape or layout mismatch must fail graph emission with a clear assert, as the existing layout methods do.

Acceptance Criteria

  • A per-dispatch attention table for one decode step is in the PR, with calls per step and per-call time for every attention kernel, compared against the current 1.31 ms.
  • Measured attention time per step is lower than 1.31 ms, and decode step time at n=128 and capacity 256 is lower than 7.1 ms on gfx1151. Report both numbers before and after.
  • Dispatch count per layer for the attention block is reported before and after.
  • Greedy output is byte-identical to the current MLXCEL_XLA_QUANT=native path and to the f16 path on at least two prompts on llama-3.2-1b-instruct-4bit.
  • xla_batch_bench stays REFERENCE-EXACT at B=4 and B=8.
  • The f16 fallback path is unchanged: AttnLayout::Ragged and AttnLayout::Prefill emit byte-identical graphs and the existing golden tests pass.
  • A focused emitter test asserts the new AttnLayout::Single op sequence (for example that the scale left the per-layer loop and that softmax still contains max-subtract).

Verification

eval "$(scripts/iree/setup-rocm.sh --env)"
export IREE_ROCM_HOME MLXCEL_XLA_ROCM_TARGET=gfx1151
cargo build --release --features xla-iree
scripts/rocm_gpu_guard.sh --hold -- bash -lc '
  MLXCEL_BACKEND=xla MLXCEL_XLA_DEVICE=hip MLXCEL_XLA_QUANT=native \
  MLXCEL_XLA_CONTEXT_CAPACITY=256 rocprofv3 --kernel-trace --hip-graph-trace --stats -f csv \
    -d /tmp/xla-attn-trace -o decode -- \
    ./target/release/mlxcel generate -m <llama-3.2-1b-4bit> -p "The capital of France is" -n 128'
scripts/rocm_gpu_guard.sh --hold -- bash -lc '
  MLXCEL_XLA_DEVICE=hip MLXCEL_XLA_QUANT=native \
    cargo run --release --features xla-iree --example xla_batch_bench -- \
      --batch 4 --requests 8 --maxcap 24'
scripts/rocm_gpu_guard.sh --hold -- bash -lc '
  MLXCEL_XLA_DEVICE=hip MLXCEL_XLA_QUANT=native \
    cargo run --release --features xla-iree --example xla_batch_bench -- \
      --batch 8 --requests 16 --maxcap 48'
cargo test -p mlxcel-xla --lib
cargo clippy -p mlxcel-xla --all-targets -- -D warnings
cargo check --features cuda,xla-iree --all-targets

A pass is: the attention table shows the reduced per-step attention time; the n=128 step time and tok/s are better than 7.1 ms and 113 tok/s; both batch sizes print REFERENCE-EXACT PASS; the lib tests and clippy are clean.

Technical Considerations

Refs #2889, #2891, #2895, #2907. The profile protocol and gap accounting are described in scripts/rocm_decode_profile.py and scripts/rocm_decode_gaps.py (#2148); the n=1 versus n=128 subtraction is the protocol from #2873. All GPU runs go under scripts/rocm_gpu_guard.sh --hold, with IREE_ROCM_HOME and MLXCEL_XLA_ROCM_TARGET=gfx1151 set.

Activity

  1. added
    status:ready
    type:performance
    priority:high
    area:inference
    status:in-progress
    status:review
    status:done
    and removed
    status:ready
    status:in-progress
    status:review
    on Nov 10, 2026
  2. added this to the 0.9 milestone on Nov 30, 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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions