Repository navigation
perf(xla): update the decode KV cache in place through module globals (#3043) - #3048
Conversation
…#3043) The single-sequence decode step took the two KV cache tensors as arguments and returned them, so IREE lowered every step as two 16 MiB `stream.cmd.copy` ops: 32 MiB of device traffic that a 4-bit 1B decode does not otherwise need, plus a fresh cache buffer pair for the shim to adopt every invocation. The decode module now declares `util.global private mutable @kcache` and `@vcache`, and the step loads, updates and stores them. IREE lowers that to a read-write binding into one persistent buffer, so the copy is gone, the dispatch count is unchanged, and the ops and values are identical. A private global is not host-visible, so the decode module also exports `decode_step.kv_import(%k, %v)` to seed it from the prefill result once per request. Its absence is the capability probe: Gemma3n's fixed-schedule CUDA decode and older compiled caches keep the full-cache argument ABI. The decode compile also enables `--iree-dispatch-creation-enable-aggressive-fusion`, which removes two elementwise dispatches per layer (309 to 277 flow dispatches) with identical results; prefill compiles keep the default. Returning only the newly written cache row and scattering it in the shim was prototyped first and rejected: the scatter costs about three dispatches per layer, roughly 120 us, against the roughly 130 us of copy it removes. On gfx1151 with llama-3.2-1b-instruct-4bit, native quant, capacity 512 and n=128, an interleaved six-round A/B measures 196.06 tok/s against 179.78 before (5.10 against 5.56 ms per step), ahead in all six rounds, with identical greedy output. The new device gate covers a fresh session, a second session and a re-prefill.
Bilingual report for the decode KV module-global change: the problem, the rejected row-return ABI and the measured reasons, the implementation, the six-round paired A/B and the validation commands.
|
CUDA counterpart of the Command (harness from #3050, Conditions: llama-3.2-1b-instruct-4bit, context capacity 512,
+8.30%, ahead in all six paired rounds, greedy output byte-identical between the arms ( The direction and size match the HIP result (+9.05%, six of six), so the in-place global binding is not a HIP-specific lowering artifact: IREE on CUDA also turns the global read and store into a read-write binding instead of a copy, and the aggressive-fusion flag helps there as well. Two caveats on the absolute figures. |
The report and the CHANGELOG entry described the HIP measurement only. The same paired A/B on a GB10 host over CUDA measures a median 24.47 tok/s against 22.59, ahead in all six rounds with identical greedy output, so the in-place KV update is not a HIP-only lowering effect. Both CUDA arms run the f16 weight path because MLXCEL_XLA_QUANT=native is HIP-only, so those figures are comparable only with each other and not with the native 4-bit HIP row.
) The emitter is right and the goldens were stale. #3048 moved the single-sequence decode KV cache into module globals (`@kcache`, `@vcache`), so `@main` no longer takes or returns the cache. The committed `decode.mlir` files were never re-frozen. All 15 registered families' `decode.mlir` were regenerated with `ArchFixture::emit_all`, the documented re-freeze primitive. Prefill and ragged logits graphs are unchanged. The llama-3.2-1b asset README now describes the new decode inputs. Test plan: `cargo test --profile test-fast -p mlxcel-xla --lib -- emitter:: validation::` passes (220 passed), including the three previously failing tests. `cargo fmt --check` is clean. No CHANGELOG entry, since this is test-asset only. Closes #3075
## Summary The single-sequence XLA decode step passed token, position and cache_len as rank-0 `tensor<i32>` buffer arguments. IREE had to bring their values to the host for slice offsets and mask bounds, so every invocation materialized a 192-byte `!stream.resource<staging>` with three `stream.resource.load`s, which on gfx1151 is a pinned `hipHostMalloc`/`hipHostFree` pair per step. This change moves those three values into the VM call itself, so the staging resource does not exist in the compiled graph. Measured on `gfx1151`: decode rises from 195.56 to 200.25 tok/s (+2.40%, six of six paired rounds, greedy output byte-identical), and the compiled decode graph has no staging resource and no `stream.resource.load`. ## What changed - `emitter/model.rs`: `ArgDecl` gains an `abi_scalar` flag, `render_signature` prints a bare `i32` for a marked argument, and `build_arg_schema` marks token/pos/cache_len only for the 1-D single-sequence decode. The prologue rebuilds the rank-0 tensor operands with `tensor.from_elements`, so the op sequence after it is unchanged. The module exports a no-op `decode_step.scalar_inputs` marker. - M-RoPE keeps its `tensor<3xi32>` position and therefore the whole buffer-argument ABI (with its residual staging); prefill, embeddings prefill, ragged/lockstep batch decode, Gemma3n decode and the `phi4` `adapter_mode` argument are untouched. - `csrc/xla_iree.c`: probes `decode_step.scalar_inputs` exactly like `kv_import`, and on a hit pushes token/pos/cache_len with `iree_vm_list_push_value` instead of buffer views. An artifact without the marker keeps the existing buffer-view path, so the bundle is not versioned. A marked graph that ever meets an M-RoPE call is rejected instead of pushing a wrong value type. The position and cache_len bounds checks stay. - `src/lib/mlxcel-xla/README.md`: documents the decode scalar ABI and the marker's compatibility contract. - Regenerated the 15 committed `assets/*/decode.mlir` goldens for the signature change and the resulting SSA renumbering. A normalized comparison against the previous goldens shows the only op-level deltas are the three `tensor.from_elements` prologue lines, the slice and mask sites that consume their results, and the marker entry. Prefill, ragged and batched goldens are untouched. - Tests: an emitter unit test asserts the 1-D signature, the three rebuilds, the marker, and unchanged M-RoPE/ragged/batched/prefill signatures. `tests/xla_decode_scalar_reuse.rs` loads both a scalar-ABI artifact and a legacy buffer-view artifact in one process, asserts the probe result on each, and compares their token streams; the forced readback fallback expectation moves to `(0, 0)` because inputs no longer allocate views. ## Measurement Compiled the real llama-3.2-1b decode graph to stream IR (`--iree-hal-target-device=hip --iree-rocm-target=gfx1151`, decode flags including aggressive fusion): | | `!stream.resource<staging>` | `stream.resource.load` | stream `@main` tail | |---|---|---|---| | before (`6e2e6810`) | 12 | 3 | `%arg146..148: !hal.buffer_view` | | after | 0 | 0 | `%arg146: i32, %arg147: i32, %arg148: i32` | Paired A/B with `scripts/xla/ab_decode_pair.sh --old 6e2e681 --new HEAD --device hip --quant native --rounds 6 --tokens 128`, capacity 512: | Round | before (tok/s) | after (tok/s) | |---|---|---| | 1 | 198.55 | 200.64 | | 2 | 195.51 | 199.87 | | 3 | 196.46 | 197.89 | | 4 | 195.61 | 198.39 | | 5 | 190.17 | 205.10 | | 6 | 192.84 | 212.58 | | median | 195.56 | 200.25 | +2.40% median, 6/6 rounds, `text EQUAL`. Per step that is about 0.11 ms, less than the roughly 0.35 ms of step-start idle #3048 associated with the 192-byte churn, so part of that idle was not the staging pair itself. The A/B baseline is the #3048 merge, so its decode step already had the KV cache in module globals and no KV copy. ## Verification - `cargo test -p mlxcel-xla --lib`: 417 passed, 0 failed, 19 ignored (after rebasing onto `main`; includes the byte-exact golden guard). - `cargo check -p mlxcel --features xla-iree,test-utils --lib --tests`: clean. - `cargo clippy -p mlxcel --features xla-iree --lib --tests -- -D warnings`: clean. The `test-utils` variant reports four pre-existing `private_interfaces` lints in `IreeRaggedLlama::prefill_*_prepared_slot_logits`, untouched here. - `cargo clippy -p mlxcel-xla --all-targets -- -D warnings`: clean. - `cargo fmt --all -- --check`: clean. - `gcc -fsyntax-only -std=gnu11 -DMLXCEL_XLA_TEST_SUPPORT=1 csrc/xla_iree.c`: clean. - Device gates under `scripts/rocm_gpu_guard.sh --hold --` on gfx1151: `xla_decode_scalar_reuse` 4/4 (scalar ABI, legacy buffer-view artifact, forced fallback, prefill-only) and `xla_greedy_timing` 3/3. ## Follow-ups The scalar path still calls `xla_step_scalars_ensure`, which allocates the three input maps it no longer uses, only to obtain the `decode_result` slot. That is one allocation per context, not per step, so it is left for a later cleanup. M-RoPE keeps the buffer ABI and its staging; teaching the shim a second scalar shape would make the capability probe a two-way signal for no measured gain today. Closes #3060
## Summary Gemma3n could not generate on `MLXCEL_XLA_DEVICE=cuda` because #3048 added `--iree-dispatch-creation-enable-aggressive-fusion` to every decode compile. In the Gemma3n decode graph the AltUp magnitude and a later RMSNorm square the same activation, IREE shares that `x * x`, and aggressive fusion pulls it into the RMSNorm reduction dispatch (`main_dispatch_10_reduction_2048_f32`) as a second, unreduced result that the CUDA `VectorDistribute` pipeline cannot distribute (`'func.func' op failed to distribute`). - `decode_compile_flags` adds aggressive fusion only for `RuntimeConfig::Dense`, the graph #3043 measured it on. Gemma3n keeps the compiler defaults on every device. The doc comment names the failing dispatch and the IREE version so the exemption can be revisited on an upgrade. - The shared bundle flags move into `bundle_compile_flags` unchanged, so the regression test compiles with exactly the production flag set. The Dense decode flag list is byte-identical, so existing cached Dense decode artifacts still hit. ## Test plan - [x] `gemma3n_cuda_decode_compiles`: emits the production gemma-3n-e2b decode and compiles it for CUDA with the production flags. It is skipped without the checkpoint, an NVIDIA driver, or a CUDA-capable iree-compile. With the old flags it fails with the reported error on the same MLIR hash as the sweep's cached graph. - [x] Unit tests: Dense decode flags include aggressive fusion (cuda, local-task), Gemma3n decode flags do not, prefill flags never do. - [x] GB10 real models, eager (`MLXCEL_SDPA_DETERMINISTIC=1`) vs `MLXCEL_BACKEND=xla MLXCEL_XLA_DEVICE=cuda`, `--temp 0 -n 16`, token IDs identical: gemma-3n-e2b text ("Paris"), gemma-3n-e4b text, gemma-3n-e4b audio transcript ("Chapter 1. Mrs. Rachel Lind is Surprised. ...", 16/16 tokens). - [x] Dense: qwen2.5-0.5b-bf16 on cuda matches eager, and the run reused the decode vmfb compiled before the change (no new cache entry), so its flags did not change. - [x] `cargo check --features cuda,xla-iree --all-targets`, `cargo check --no-default-features --features xla-diagnostics --all-targets`, `cargo clippy -p mlxcel-xla --features iree --lib --tests -D warnings`, `cargo fmt --check`. Closes #3363
Closes #3043.
Summary
The single-sequence decode step used to take the two KV cache tensors as arguments and return them as results. IREE lowered that functional signature into two 16 MiB
stream.cmd.copyops per step, 32 MiB of device traffic on a graph whose 4-bit 1B decode does not otherwise move that much data, and the step had to adopt a fresh cache buffer pair every invocation.The decode module now keeps the cache in two module-level mutable globals,
util.global private mutable @kcacheand@vcache. The step loads them, writes its own row at the current position and stores them back. IREE lowers that to a read-write binding into one persistent!stream.resource<variable>buffer, so there is no copy, the dispatch count is unchanged, and the emitted ops and values are the same as before.A private global is not host-visible, so the prefill result has to enter it somehow. The decode module now exports
decode_step.kv_import(%k, %v)for exactly that, and the shim calls it once per prefill boundary. The absence of that entry is the capability probe: Gemma3n's fixed-schedule CUDA decode and any older compiled cache keep the full-cache argument ABI and work unchanged.The decode compile also enables
--iree-dispatch-creation-enable-aggressive-fusion, which removes two elementwise dispatches per layer on this graph (309 to 277 flow dispatches) with bit-identical results. Prefill compiles are untouched.Why not the row-return ABI
The issue originally proposed returning only the newly written cache row (shape
[n_layers, 1, kv_heads, head_dim]) and having the shim scatter it into a persistent cache. Prototyping it in IREE's stream dialect showed the scatter costs about three dispatches per layer, roughly 120 us per step, against the roughly 130 us of copy it removes, so it is close to a wash while adding a rank-5 ABI and a per-layer scatter kernel. The mutable global gets the in-place update with nothing added at all, so that is what landed.The remaining pinned staging churn
The other half of the original issue, the 192-byte
hipHostMalloc/hipHostFreepair per invocation for the three decode scalars, is not addressed here, and the issue's own measurement puts it at about 0.35 ms of GPU-idle time per step. The three scalars land in one 192-byte!stream.resource<staging>and are read back on the host throughstream.resource.loadwith dynamic index arithmetic, so the staging buffer is a genuine host readback, not an implementation detail the compiler can elide. I verified that two candidate flags do not change it:--iree-stream-resource-memory-model=unifiedproduces byte-identical IR, and--iree-stream-resource-alias-mutable-bindingsleaves the IR unchanged. Removing it needs a decode graph that computes its indices statically, or a device-side scan for the sampled token, which is a different change; this PR leaves the behaviour as it is and documents why.Measurements
gfx1151(RADEON 8060S), llama-3.2-1b-instruct-4bit,MLXCEL_XLA_QUANT=native,MLXCEL_XLA_CONTEXT_CAPACITY=512,n=128, one interleaved six-round A/B of the pre-change binary and this one:The new binary is ahead in all six paired rounds (+9.05% on the median). Greedy output is identical between the two binaries on the same prompt.
Stream IR of the emitted decode graph after the change: 277 dispatches, 3 copies (the 192-byte staging buffer plus two small ones), and no 16 MiB copy at all. Before: 309 dispatches and two 16,777,216-byte copies per step.
Validation
cargo test -p mlxcel --features xla-iree,test-utils --test xla_greedy_timing -- --ignored: 3 passed, including the newdecode_threads_kv_through_module_globalsgate, which runs a real session end to end, repeats it on a second session (a fresh module state must reproduce the stream from its own import) and re-prefills the first session (the import must re-seed rather than continue the old cache).single_decode_threads_kv_through_module_globalsasserts the two globals, the absence of the cache arguments, thekv_importentry and that the ragged and prefill graphs keep the full-cache ABI.cargo fmt --all -- --checkandcargo clippy -p mlxcel --features xla-iree --lib --tests -- -D warningsare clean. The clippy run needed a one-linefield-reassign-with-defaultfix insrc/server/batch/xla_worker_tests.rs: that file is unchanged by this PR, the lint fires onmain, and it only compiles with thexla-ireefeature, so the default-feature clippy job never sees it.Notes
kv_import_pendingis set by the single-sequence prefill and by both prefill variants (embedded inputs and deepstack), so a request that reuses a session's cache resumes from the globals rather than re-importing.