Skip to content

perf(xla): keep the decode KV cache in the contraction precision - #3106

Merged
inureyes merged 5 commits into
mainfrom
perf/issue-2886-f16-decode-kv-cache
Nov 16, 2026
Merged

inureyes merged 5 commits into
mainfrom
perf/issue-2886-f16-decode-kv-cache

Conversation

@inureyes

@inureyes inureyes commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Summary

Settle what remains of the gfx1151 decode gap on the native 4-bit path, and remove the one reachable per-step cost the breakdown exposed: the decode KV globals are now stored in the contraction precision, so the 32 per-step cache dispatches stop converting each full f32 slab to f16.

What changed

  • emitter/model.rs: the single-sequence decode declares its kcache/vcache globals in the contraction precision (f16 on hip/cuda, bf16 under MLXCEL_XLA_PRECISION=bf16, f32 on the CPU) and narrows the new row at the update site through one narrow_cache_row helper, used by the ordinary K/V path and by the MLA latent/PE path. decode_step.kv_import keeps its f32 signature and converts once per request, so the C shim ABI is unchanged.
  • emitter/builder.rs: Precision::dot_elt is crate-visible for the cache element type.
  • emitter/mod.rs: tests pin the global, import and row-conversion shapes for f32/f16/bf16, the native packed graph, the MLA write sites, and the ragged f32 cache ABI.
  • src/lib/mlxcel-xla/README.md: the measured per-kernel breakdown of the native step, its roofline and launch-gap attribution, the perf(xla): close the IREE decode-kernel efficiency gap (small-M vecmats and the serial argmax) #2873 boundary, and the change above.
  • docs/environment-variables.md: the MLXCEL_XLA_PRECISION row now records what it changes for the decode cache, which graphs keep f32 caches, and that the f32 import converts once per request.

Changes during review

  • 044eded6: the MLA single-decode path wrote f32 latent and PE rows into the newly narrowed globals, which makes that graph uncompilable under an explicit f16/bf16 precision. It now goes through the same helper, with a regression test that emits the MLA decode at f16.
  • 0e4374b7: single_decode_threads_kv_through_module_globals was sensitive to MLXCEL_XLA_PRECISION, because it asserted f32 globals; it is pinned to f32 and the narrowed-global case is covered by its own test.
  • efaf4335: test coverage for every graph kind that reaches these globals (f32/f16/bf16 imports, the native packed graph, the ragged f32 cache ABI), plus the environment-variable documentation.

Measured (gfx1151, Llama-3.2-1B-Instruct-4bit, MLXCEL_XLA_QUANT=native, capacity 512, greedy)

The trace protocol is the n=1 / n=128 rocprofv3 --kernel-trace subtraction (shared prefill cancels; 127 steps remain).

  • Traced decode step: 5.054 to 4.895 ms. Untraced single-run samples were 190.2 tok/s before and 196.1 tok/s after; the paired protocol below is the reportable figure.
  • Per-step GPU kernel time 3.976 to 3.913 ms; dispatch gaps 1.077 to 0.982 ms; dispatches 281 to 263.
  • Each KV cache dispatch drops from 5.78 to 3.90 us (a 10.5 MB to 5.3 MB f32-plus-f16 traffic cut per step). The 32 layout transposes remain; they are the batched score/context operand layout the perf(xla): reduce decode attention cost in the single-sequence graph #2921/perf(xla): cut the decode KV read convert and context matmul #2956 tuning spec matches.
  • The step streams 695 MB of packed weights at 199 GB/s aggregate. Gate/up and the head are at the 240 GB/s roofline; down (151 GB/s), q/k/v (172) and o (163) leave about 0.49 ms of headroom, 0.35 ms in the down projection.

Paired A/B at capacity 512 and 2048 (scripts/xla/ab_decode_pair.sh, text EQUAL in every run)

  • Capacity 512, four runs, 50 paired rounds: medians 197.01 to 200.14 (+1.59%, 3/6), 199.43 to 200.20 (+0.39%, 4/8), 200.07 to 201.87 (+0.90%, 8/12), 201.01 to 199.78 (-0.61%, 12/24). 27 of 50 rounds favor the new arm and the medians straddle zero, so at this slab size the saving is inside the host's noise.
  • Capacity 2048, 12 rounds: 178.02 to 183.09 tok/s, +2.85%, 9 of 12 rounds. The removed conversion scales with the KV slab, so the gain becomes visible at the capacity a long-context decode uses.

The step-level attribution above is the mechanism (18 fewer dispatches and a 10.5 MB to 5.3 MB cache-traffic cut per step); the capacity-512 paired runs bound how much of the step that mechanism actually buys on this host.

What remains

  • Down projection vectorization: the largest kernel-side item, and it changes the f32 reduction grouping, so it needs the token-identity gate on a tied and an untied checkpoint.
  • Dispatch gaps over ~263 small dispatches: only further graph fusion moves this.
  • perf(xla): close the IREE decode-kernel efficiency gap (small-M vecmats and the serial argmax) #2873's small-M vecmats and serial argmax are absent from the native path (no vecmat; the argmax is a two-stage reduce at 0.033 ms). They still apply to the default f16 graph.

Test plan

  • cargo test -p mlxcel-xla --lib emitter::tests:: (69 passed)
  • cargo fmt -p mlxcel-xla -- --check
  • clippy at default and iree features with -D warnings
  • untied qwen2.5-coder-7b-instruct-4bit smoke run on hip with the narrowed cache
  • Paired A/B at capacity 512 (four runs, 50 rounds) and 2048 (12 rounds), results above
  • Batch REFERENCE-EXACT gate on hip (xla_batch_bench --batch 8 --requests 16 --maxcap 48): REFERENCE-EXACT PASS, 16 of 16 requests matching their single-sequence reference, 56.38 tok/s batched against a 36.84 tok/s sequential baseline
  • Review follow-up: 044eded6 narrows the MLA single-decode latent and PE rows through the same helper (they wrote f32 into the narrowed global and made the MLA decode graph uncompilable under an explicit f16/bf16 precision), with a regression test

Closes #2886

The single-sequence decode compiles its two KV module globals as f32, and each layer's score and context contractions read them through a `stablehlo.convert` to the contraction precision. IREE materializes that convert inside the batched operand's layout transpose, so 32 dispatches per step (K and V per layer) streamed a full 1 MB f32 slab to write a 0.5 MB f16 one.

The globals now carry the contraction precision directly (f16 on hip and cuda, bf16 under `MLXCEL_XLA_PRECISION=bf16`, f32 on the CPU). The new K/V row is narrowed at the update site, and the f32 `decode_step.kv_import` signature is unchanged, with the conversion done once per request inside the graph. The matmul operands are bit-identical because each cached f32 value was already rounded to f16 on every read.

Measured on gfx1151 with the n=1 / n=128 `rocprofv3` subtraction at capacity 512: the traced decode step falls from 5.054 to 4.895 ms (197.9 to 204.3 tok/s) and each cache dispatch from 5.78 to 3.90 us; untraced, three rounds measure 196.1 tok/s median against 190.2 before. The remaining f16 transpose is the batched score/context operand layout, the shape the #2921/#2956 tuning spec matches.

The XLA README now records the full per-kernel breakdown of the native step, its roofline attribution, and what is left to follow-up.

Refs #2886
@inureyes inureyes added status:review Under review type:performance Performance improvements priority:high High priority area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Nov 16, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Paired A/B, gfx1151, llama-3.2-1b-instruct-4bit, native quant, n=128, greedy

Interleaved paired rounds through scripts/xla/ab_decode_pair.sh, baseline 1bd27968 against 6ac7fd37. Every run reported text EQUAL.

Capacity 512: no measurable difference

Run Rounds old median (tok/s) new median (tok/s) delta rounds won by new
1 6 197.01 200.14 +1.59% 3/6
2 8 199.43 200.20 +0.39% 4/8
3 12 200.07 201.87 +0.90% 8/12
4 24 201.01 199.78 -0.61% 12/24

Fifty paired rounds, 27 won by the new arm, medians straddling zero. At this slab size the removed conversion is inside the host's noise: the step moves less than the round-to-round spread.

Capacity 2048: +2.85%

Run Rounds old median (tok/s) new median (tok/s) delta rounds won by new
5 12 178.02 183.09 +2.85% 9/12

The removed cost scales with the KV slab, so a four-times larger cache is where it becomes visible: +5.07 tok/s, and the round record is clean (9 of 12, the three losses 0.3 to 1.5 percent against wins of 1.5 to 5.2 percent).

Reading

The trace attribution was right about the mechanism (18 fewer dispatches per step and a 10.5 MB to 5.3 MB cache-traffic cut) and wrong about the size of the effect at capacity 512: the per-step saving there is smaller than the paired protocol can resolve on this shared host. It is a real saving at capacity 2048, which is the capacity a long-context decode actually runs at, and it costs no throughput anywhere measured.

The single-sequence decode now declares its KV globals in the contraction precision, but the MLA attention path writes its latent/PE rows straight into those globals without the conversion the ordinary K/V path got. Under an explicit `MLXCEL_XLA_PRECISION=f16` or `bf16` on an MLA model (Youtu-VL; the runtime otherwise defaults MLA to f32), `stablehlo.dynamic_update_slice` then mixes an f16 operand with an f32 update and the decode graph cannot compile.

Both write sites now call one `narrow_cache_row` helper, so the ordinary and MLA paths cannot drift apart again, and a regression test emits the Youtu-VL decode at f16, bf16-adjacent f32 and asserts the row conversion is present only when the global is narrowed. The README gains the paired A/B results that bound the saving: capacity 512 is inside the host noise (27 of 50 rounds ahead) and capacity 2048 is +2.85% (9 of 12).

Refs #2886
`single_decode_threads_kv_through_module_globals` calls `emit_decode`, which resolves the contraction precision from `MLXCEL_XLA_PRECISION`, then asserts the decode globals are f32. Once #2886 narrowed those globals to f16/bf16, setting that documented override made the test fail on correct code (`decode must declare the K global: tensor<16x256x8x64xf32>`).

Pin the test to `Precision::F32` so it asserts the cache ABI rather than the ambient precision; `single_decode_cache_global_uses_the_contraction_precision` already covers the narrowed global. Verified the selector passes with and without `MLXCEL_XLA_PRECISION=f16`.

Refs #2886
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review of the narrowed decode KV cache (#2886). One LOW finding, fixed in 0e4374b7. No CRITICAL or HIGH finding.

What I checked and found sound:

  • Conversion precision. Every read of the cache goes through dot_general, which demotes f32 operands to the contraction type and leaves already-narrow operands alone. Rounding once at the write site therefore produces bit-identical matmul operands to the previous per-read conversion, including the first step after kv_import. emit_attention and emit_mla_attention are the only consumers; no elementwise op touches the cache slab, so no f32/f16 type mismatch survives.
  • Overflow and NaN range. The f16/bf16 range limit is unchanged in effect: a value that would overflow f16 already became inf inside the old per-read convert. Persisting it narrowed changes no downstream value.
  • Wrong-type reads. The C shim still validates and passes f32 prefill caches (xla_validate_kv_pair), matching the unchanged f32 kv_import signature; the shim never reads the globals directly. Prefill and ragged keep f32 cache arguments.
  • MLA path. The review commit covers both write sites. I lowered the emitted graphs with iree-compile (--iree-input-type=stablehlo, llvm-cpu): llama f16, MLA f16 and MLA bf16 all compile cleanly, so no dynamic_update_slice dtype mixing remains.
  • Graph precision. resolve_precision keys the vmfb cache on the emitted MLIR, and the f32 emit is byte-identical to before, so the fixture goldens still pass.

The LOW finding: single_decode_threads_kv_through_module_globals called emit_decode, which honors MLXCEL_XLA_PRECISION, while asserting f32 globals. Under the documented f16/bf16 override it failed on correct code. It is now pinned to Precision::F32; the narrowed global stays covered by single_decode_cache_global_uses_the_contraction_precision.

Tests: emitter::tests::single_decode* and emitter::tests::mla_single_decode_narrows_the_cache_row pass with and without MLXCEL_XLA_PRECISION=f16; validation::tests::registered_fixtures_are_byte_exact passes; cargo fmt -p mlxcel-xla -- --check and cargo clippy -p mlxcel-xla --lib --tests -- -D warnings pass.

The #2886 change narrowed the single-sequence decode KV globals, but only the default globals and the ordinary row write were asserted. Cover the parts a regression would break silently: both caches and the import conversion under bf16, the exact f32 import signature and the narrowing stores on every precision, the native packed graph that actually ships on hip/cuda, the MLA latent and PE write sites, and the ragged decode's unchanged f32 cache ABI.

Document that `MLXCEL_XLA_PRECISION` now also selects the single-sequence decode cache element type in `docs/environment-variables.md`, and drop two stray blank lines the new README section left before its neighbours.

Validation:

- `cargo test -p mlxcel-xla --lib emitter::tests::` (69 passed, was 67)
- `cargo fmt -p mlxcel-xla -- --check`
- `cargo clippy -p mlxcel-xla --lib --tests -- -D warnings` (default and `iree`)

Refs #2886
@inureyes

Copy link
Copy Markdown
Member Author

PR finalization

  • Tests: extended the perf(xla): close the remaining decode gap by running projections from narrow weights instead of f16-resident copies #2886 coverage to bf16 globals and import conversion, the exact f32 import signature for f32/f16/bf16, the native packed graph that ships on hip/cuda, the MLA import and row narrowing, and a ragged decode regression that keeps the f32 cache ABI. cargo test -p mlxcel-xla --lib emitter::tests:: is 69 passed (was 67); the byte-exact fixture test still passes.
  • Docs: the MLXCEL_XLA_PRECISION entry in docs/environment-variables.md now states that the single-sequence decode cache is stored in that precision, with kv_import keeping the f32 prefill signature. This README and env-var page have no Korean counterpart in the repository, so no translation applies.
  • Lint/format: cargo fmt -p mlxcel-xla -- --check and cargo clippy -p mlxcel-xla --lib --tests -- -D warnings clean at default and iree features.

Committed as efaf4335.

Records why the single-sequence decode KV globals now carry the contraction precision: the whole-slab conversion each layer ran per step (32 layout transposes, 10.5 MB of cache traffic where 5.3 MB suffice), the two review findings it produced (the MLA row dtype mismatch and the precision-sensitive globals test), and the paired A/B that bounds the saving, inside the noise at capacity 512 and +2.85% at capacity 2048.

Refs #2886
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 16, 2026
@inureyes
inureyes merged commit b21825c into main Nov 16, 2026
32 checks passed
@inureyes
inureyes deleted the perf/issue-2886-f16-decode-kv-cache branch November 16, 2026 03:58
inureyes added a commit that referenced this pull request Nov 18, 2026
The #3116 report counted the pre-report surface (4 files, +305/-27) and the already-merged #3106 report said 6 files, +156/-24 where its code-only surface is 5 files, +342/-12; both disagreed with the squash statistics of their own PRs. Each now states the surface it covers and excludes the report files explicitly.
inureyes added a commit that referenced this pull request Nov 18, 2026
… (#3116)

* perf(xla): give the narrow decode vecmats one output per thread (#2873)

The compiler default for a rank-1 vecmat is `thread = [8, 0]`, `workgroup = [256, 0]` for every output width at or above 2048, so the decode projections launched N/256 one-warp workgroups: 8 for the 2048-wide q, o and down projections and 32 for gate/up. That is under one wave on a 20-WGP gfx1151 and the serial K reduction (default chunk 4) cannot hide memory latency, so q/o ran at 42 GB/s where the 128256-wide LM head, which launches 501 workgroups, reached 153 GB/s in the same trace. The 512-wide k and v, where the compiler already picks one output per thread, sat at 44 GB/s on the 4-wide chunk.

The tuning spec now gives every single-row vecmat whose output width is between 128 and 8192 one output per thread with `reduction = [0, 32]`, whatever K is. The tile does not depend on the reduction length (each output still walks K serially; only the output count sets the occupancy), so one matcher covers both hidden sizes that were measured. The LM head and wider long-K shapes keep the previous config because their activation re-read grows with N. On llama-3.2-1b-instruct-4bit at capacity 256 the untraced decode step drops from 24.06 to 13.54 ms (41.6 to 73.5-74.5 tok/s) and traced kernel time from 24.44 to 12.48 ms at the same 279 dispatches: q/o 42 -> 219 GB/s, down 104 -> 230, gate/up 140 -> 196. On the untied qwen2.5-coder-7b-instruct-4bit the step goes from 12.28 to 15.44-15.46 tok/s; the first version of the matcher bounded K at the 1b model's 2048 and reached only that checkpoint's down projection, which made 12.94.

No dispatch is added and no weight layout changes. IREE's split-reduction path cannot express a workgroup-level K split for these rank-1 generics (it needs a matmul-like op with at least two parallel loops), and a lowering config can only tile the reduction inside a workgroup. The k/v projections stay at 81 GB/s useful, 162 counting the re-read, because N = 512 caps one output per thread at 16 warps; a concatenated k/v upload-time layout is left to a follow-up.

The issue's argmax item was already fixed on this main by #2875: the traced two-stage reduce measures 0.030 ms per step, well under the 0.2 ms target, so this change does not touch it. Greedy output is unchanged on llama-3.2-1b-instruct-4bit and qwen2.5-coder-7b-instruct-4bit.

* test(xla): pin the wide vecmat predicates and correct the tuning notes

Review of the #2873 split found the wide fallback's K >= 4096 gate and its output-width axis unasserted, so a later edit could put the wide tile on every LM head (including llama's K = 2048 one that is deliberately left on the compiler default) without failing a test. The test now pins both bounds on %rhs with their axes, next to the narrow matcher's assertions.

The docs said a 3584-wide projection launches 8 workgroups where 3584/256 is 14, and presented gate/up's 140 to 196 GB/s as a gain although the unchanged head moves 153 to 228 GB/s between the same two traces. The head-relative ratios are now recorded, the 7b paragraph notes its 48-token greedy output is unchanged, and the stale long-K comments in iree.rs and the spec header name all four matchers.

Validation: cargo test -p mlxcel-xla --lib tuning:: (4 pass) and --lib emitter:: (216 pass) under scripts/rocm_gpu_guard.sh --hold. No behavior change: the spec's matchers and lowering configs are untouched.

* docs(xla): name the authoritative figure for the #2873 breakdown

The trace pair behind the per-kernel table is not interleaved, and the unchanged LM head moves 1.49x between the two runs on its own. The README now says which reading it asserts: the trace total overstates the change, and the paired interleaved A/B is the figure that carries it, at 41.05 to 73.98 tok/s over 6 rounds with identical greedy text.

* test(xla): observe the vecmat tuning spec on the emitted decode graph

The tuning-spec assertions are textual, and the failure this asset can produce silently is a matcher that still parses but stops matching: the graph compiles on the compiler default and only throughput changes, so those assertions stay green.

This adds an ignored test that emits the single-sequence decode graph the hip backend compiles (InOut layout, f16 projections), runs the content-addressed spec through the version-matched iree-compile with --iree-hal-dump-executable-configurations-to, and asserts every vecmat dispatch with 128 <= N <= 8192 carries reduction = [0, 32], thread = [1, 0], workgroup = [32, 0] while the 128256-wide LM head does not. It cross-compiles for gfx1151 unless MLXCEL_XLA_ROCM_TARGET names another arch.

Verified: cargo test -p mlxcel-xla --lib tuning:: (4 pass, 1 ignored); the ignored test passes against the pinned 3.12.0rc20260721 compiler and fails with "lost the narrow tile" when umax is temporarily narrowed to 64, so it observes the matcher rather than restating it.

Refs #2873

* docs(xla): record the #2873 decode tuning and refresh the f16 baseline

The crate README and the tuning asset describe the new narrow single-row tile, but the change had no technical report and the environment-variable reference still presented 31.5 tok/s as the current f16 decode rate. Add the report in English and Korean following the recent PR convention, and state the measured 74 tok/s baseline where `MLXCEL_XLA_QUANT` is documented. Add the Unreleased changelog entry for the default-path improvement and note in the native GEMV entry that its comparison baseline moved.

No test or source change: the tuning, emitter and lint gates are unchanged from 838c19c.

Validation:
- cargo fmt -p mlxcel-xla -- --check (clean)
- cargo clippy -p mlxcel-xla --all-targets -- -D warnings (clean)
- cargo test -p mlxcel-xla --lib tuning:: (4 passed, 1 ignored as documented)

Refs #3116, #2873

* docs(reports): state the change statistics the PRs actually merged

The #3116 report counted the pre-report surface (4 files, +305/-27) and the already-merged #3106 report said 6 files, +156/-24 where its code-only surface is 5 files, +342/-12; both disagreed with the squash statistics of their own PRs. Each now states the surface it covers and excludes the report files explicitly.
@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): close the remaining decode gap by running projections from narrow weights instead of f16-resident copies

1 participant