Repository navigation
feat(engine): add opt-in KIVI 2/4-bit KV cache for CUDA rollout - #641
EricChan2028 wants to merge 1 commit into
Conversation
|
Checked this PR against the current How the KIVI path relates to those two changes:
I can rebase the branch onto the latest |
Add RuntimeConfig.kv_cache_dtype ("auto" | "kivi2" | "kivi4") with
kivi_group_size and kivi_residual_length. KIVI quantizes keys per channel
and values per token into packed 2/4-bit codes with FP16 scales and zero
points inside the existing paged blocks, and keeps the most recent tokens of
each rollout slot in a model-dtype residual ring. Triton kernels quantize
completed groups, fuse the decode-time flush with the ring append, and run a
split-K decode attention that dequantizes paged tiles in registers; every
decode launch is CUDA-graph capturable. Fresh prompt attention stays full
precision; a prefill chunk that extends a cached prefix attends over the
dequantized prefix with the backend's dense kernel (the paged tiled kernel
on the native backend). Rollouts keep the log-probabilities of the KIVI
attention that sampled them, and unsupported configurations keep the
model-dtype cache with a RuntimeWarning. The engine logs each KIVI
allocation.
Tests compare the kernels with an independent PyTorch implementation at
1024/4096/8192 cached tokens and across residual-window transitions.
docs/concepts/kivi-kv-cache.rst describes the cache; examples/kivi holds the
benchmark, evaluation and seeded RL harnesses and the measurement report.
d442c65 to
688a2f6
Compare
What does this PR do?
为 CUDA rollout / serving 增加可选的 KIVI 低比特 KV 缓存:key 按 channel、value 按 token 做非对称 2/4-bit 量化,保存 FP16 scale/zero,并为每个 rollout slot 保留最近 R 个 token 的全精度 residual 窗口。默认行为不变(
kv_cache_dtype="auto")。本 PR 已 rebase 到当前main(5f7a976,默认 native 注意力后端),并在 RTX 5090 Laptop GPU(24 GB)上用当前版本重新验证;可复现的测评报告(命令、配置、误差/内存/吞吐表、RL 对照与原始日志)见examples/kivi/README.md,新版本上的复测在第 9 节。Adds an opt-in KIVI KV cache to AReno's CUDA inference engine, as scoped in #590: one GPU, one dense attention family (
qwen3), private per-request caches.Update (rebased onto
main5f7a976)mainnow defaults to the native attention backend with rollout and training log-probabilities aligned (feat: default training to native attention and align rollout logprobs #689, fix: align native CUDA Graph rollout and training logprobs #691) and drops the rollout cache after each session (fix: release CUDA phase state between rollout and training #690). KIVI follows the engine'sattn_backend: a fresh prompt goes through the same tiled kernel as with the BF16 cache, KIVI decode keeps its own kernels, and the rollout teardown releases the KIVI cache throughclear_kv_cache.areno_causal_attentionwith a query offset on the native backend: 4.7 s per layer for an 8008-token chunk after 92 cached tokens, against 10.6 ms for the paged tiled kernel the native backend runs for the BF16 cache. With flash as the old default this path ran flash-attn, so it only showed up after the default changed. KIVI now writes the dequantized prefix, ring residue and fresh tokens into temporary pages and calls that same paged kernel (_paged_prefix_attention). The new path is taken only on the native backend with BF16 and a head dim the kernel supports; other configurations keep the previous path. 64 rollouts with ~8K-token prompts at 8 concurrent sequences took 1031 s with KIVI-4 before the fix and 158 s after it (BF16: 193 s).bench_decode_attention.py --baseline native|flash(default native);rollout_eval.py --attn-backenddefaults to native.Interface (runtime config only; the default is unchanged)
RuntimeConfig.kv_cache_dtype: "auto" | "kivi2" | "kivi4",kivi_group_size(power of two, at least 32; default 32) andkivi_residual_length(default 128), reachable from the SDK throughCudaConfig(runtime={...}).qwen3, speculative decoding, head dims or block sizes the group size does not divide) keep the model-dtype cache and emit aRuntimeWarning.KIVI KV cache: dtype=... group_size=... residual_length=... blocks=... slots=... bytes=....--kv-cache-dtype / --kivi-group-size / --kivi-residual-lengthtoareno trainandareno servein this PR if the names work for you.Implementation
areno/accel/kernels/kivi.py(Triton): group quantize + pack, a fused decode-time flush of the oldest residual group plus ring append, a split-K decode attention that dequantizes paged tiles in registers (no model-dtype copy of the cache), and the split combine. All decode launches are CUDA-graph capturable; cache offsets are 64-bit.areno/engine/layers/attention_backend/kivi.py:KiviSpec/KiviKVCache(packed codes and scales in the existing paged block table, one model-dtype residual ring per rollout slot), prefill planning (fresh prompt attention stays full precision through the dense backend; a chunk that extends a cached sequence dequantizes that row's prefix and attends with the backend's dense kernel for that case) andKiviInferBackend.CausalSelfAttention.forward_inferdispatches to the KIVI backend when a cache is attached;clear_kv_cachereleases it.InferenceManager._init_infer_cacheallocates it with the same block budget plus the rings.train/logp_abs_diff_meanmeasures the cache error.Results
Qwen3-0.6B on one RTX PRO 5000 72GB,
maine17794c, flash backend (G = 32, R = 128; full tables inexamples/kivi/README.md, sections 2-7):train/logp_abs_diff_meanRe-run on the current
main(d9667ad + this change, native backend) on an RTX 5090 Laptop GPU, 24 GB, every run below 20 GB of device memory (section 9):train/logp_abs_diff_mean, GSPO seed 1, steps 1-8 (section 7, same seed and steps)On the current
mainthe native backend gives BF16 rollouts exactly the training log-probabilities, so the KIVI divergence is the error of the cache itself; it matches the original runs. Save at step 4 and resume works on the new base (first resumed step: reward 0.844 vs 0.828, divergence 0.0307 vs 0.0306). Still from the RTX PRO 5000 on e17794c and not repeated: the 100-step multi-seed GSPO comparison and its held-out validation, GSM8K with 1319 x 4 samples, the Qwen3-1.7B checks, the G/R ablations and the 32K-token teacher-forced run.KIVI-4 meets every acceptance target of the issue. KIVI-2 with the default 128-token window misses the RL reward target: its behavior policy diverges far more than BF16's, and since AReno's GSPO loss treats rollouts as on-policy, training stops improving after about 70 steps. With a 512-token residual window KIVI-2 roughly halves that divergence and stays within the 0.05 reward target (-0.036), though its gap widens over the last 20 steps. The report therefore recommends
kivi4for RL rollouts andkivi2withkivi_residual_length=512only where memory is the binding constraint.Related issue
Fixes #590
Type of change
How was it tested?
On the current base (RTX 5090 Laptop GPU, sm_120, torch 2.9.1+cu128, triton 3.5.1, no flash-attn; AReno's CUDA extension built for sm_120 from the unchanged
areno/accel/csrcandsetup.py):pytest tests/test_kivi_kv_cache_cpu.py tests/test_kivi_kv_cache_cuda.py tests/test_logprobs_cuda.pyon this commit's code: 78 passed, 2 skipped (the flash variant of the chunked-prefill test, without flash-attn).tests/test_native_attention_gpu.py,tests/test_cuda_phase_memory_gpu.py,tests/test_logprobs_cuda.py: 61 passed, 5 skipped (flash-attn) both with and without this change.pytest tests/ -k cpuwith triton, flash-attn and CUDA hidden as in the CPU CI job, on the rebase ontomainbc3ee6f: 1920 passed with this change, 1884 without (the 36 new tests make the difference); the same 9 multi-process gloo tests fail on both in this WSL environment. The KIVI CPU tests and the affected scheduler/decode-graph tests pass on this commit.ruff checkandruff format --checkon the changed files.On the original base (RTX PRO 5000, sm_120, torch 2.8.0+cu128, triton 3.4.0, flash-attn 2.8.3): the KIVI tests (61 passed), the CPU suite (only the 8
test_real_gloo_*tests failed, identically on upstream e17794c),pre-commit run --all-files, and the end-to-end runs: 100-step GSPO with 6 seeds for BF16 and KIVI-4 and 3 seeds for KIVI-2 at R = 128 and R = 512, a BF16 repeat arm, save/resume, held-out validation, GSM8K and 8K-context rollouts, teacher-forced quality up to 32K tokens and the decode kernel benchmark.Checklist
pytest tests/ -k cpu).Known limitations
qwen3family, private per-request caches. Tensor-parallel rollout was not measured; other families, speculative decoding and NPU fall back to the model-dtype cache with aRuntimeWarning.areno servecannot enable the cache until a CLI option is agreed (see above).The full list is in section 8 of
examples/kivi/README.md.Notes for reviewers
oss-camp2026; that branch is currently an ancestor ofmainwith no commits of its own, and this change builds onmain's engine, so the PR targetsmainlike the other camp PRs. I can retarget if you prefer.kivi-590-dev; the section 9 runs record local commits whose trees differ from this commit only as listed inruns_5090/README.mdof the raw logs.kivi-590-artifactsholds the training logs, TensorBoard events, evaluation outputs, benchmark JSON, memory traces, driver scripts and environment of every run in the report;runs_5090/covers section 9._decode_partialinareno/accel/kernels/native_attention.py) computes cache offsets in 32-bit integers and faults once one layer's cache holds 2^31 elements. A full model cannot reach that on one GPU, but the one-layer decode benchmark does at 128 rows x 16K tokens, so that BF16 entry is missing from the section 9 table. I can send a separate fix if useful.train_seeded.pythat wrapped onlyTrainerConfig.cuda_config;RolloutTrainerConfigoverrides it, so those runs silently used the BF16 cache. Their first step reproduced the BF16 run exactly, which exposed it. They are kept as a BF16 repeat arm (run-to-run noise control), and the engine now logs every KIVI allocation so a run's cache is visible in its log.