Skip to content

feat(engine): add opt-in KIVI 2/4-bit KV cache for CUDA rollout - #641

Open
EricChan2028 wants to merge 1 commit into
inclusionAI:mainfrom
EricChan2028:kivi-590
Open

EricChan2028 wants to merge 1 commit into
inclusionAI:mainfrom
EricChan2028:kivi-590

Conversation

@EricChan2028

@EricChan2028 EricChan2028 commented Oct 30, 2026 •

Copy link
Copy Markdown

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 main 5f7a976)

  • main now 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's attn_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 through clear_kv_cache.
  • Fix found while re-measuring: a prefill chunk that extends a cached prefix (prompts are split at the 8192-token prefill budget) went through areno_causal_attention with 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).
  • Tests and harnesses follow the native default: the CUDA tests run on the native backend and their flash variants skip without flash-attn; the chunked-prefill test compares a fresh prompt against the dense backend's varlen prefill and a chunk after a cached prefix against the paged tiled kernel on independently dequantized inputs (bit for bit), plus an fp32 reference; bench_decode_attention.py --baseline native|flash (default native); rollout_eval.py --attn-backend defaults 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) and kivi_residual_length (default 128), reachable from the SDK through CudaConfig(runtime={...}).
  • Unsupported configurations (non-CUDA devices, model families other than qwen3, speculative decoding, head dims or block sizes the group size does not divide) keep the model-dtype cache and emit a RuntimeWarning.
  • When the KIVI cache is allocated, the engine logs one line: KIVI KV cache: dtype=... group_size=... residual_length=... blocks=... slots=... bytes=....
  • No CLI flags yet: AGENTS.md asks to confirm CLI surfaces first. I can add --kv-cache-dtype / --kivi-group-size / --kivi-residual-length to areno train and areno serve in 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) and KiviInferBackend.
  • CausalSelfAttention.forward_infer dispatches to the KIVI backend when a cache is attached; clear_kv_cache releases it. InferenceManager._init_infer_cache allocates it with the same block budget plus the rings.
  • Rollouts keep the log-probabilities produced by the KIVI attention that sampled the tokens; training recomputes with the BF16 forward, so the native train/logp_abs_diff_mean measures the cache error.

Results

Qwen3-0.6B on one RTX PRO 5000 72GB, main e17794c, flash backend (G = 32, R = 128; full tables in examples/kivi/README.md, sections 2-7):

BF16 KIVI-4 KIVI-2
Cache bytes at 8192 tokens, scales and residual ring included 1 0.331x 0.206x
Decode attention step, 128 rows x 16K tokens, CUDA graph 7.01 ms 3.95 ms (1.78x) 4.06 ms (1.73x)
GSM8K test accuracy, 1319 x 4 samples at T = 1 72.16% 72.25% 68.82% (72.25% with R = 512)
8K-token prompts, 32 concurrent: accuracy / peak device memory 70.7% / 45.1 GiB 70.5% / 19.5 GiB 64.7% / 14.7 GiB
Most concurrent 8K-token rollouts measured on the 72 GB GPU 48 (64: out of memory) 128 256
GSPO final-window reward (change vs BF16) 0.806 (6 seeds) 0.806, +0.000 (6 seeds) 0.708, -0.097 (3 seeds); R = 512: 0.769, -0.036
Native train/logp_abs_diff_mean 0.015 0.032 0.209; R = 512: 0.117
Validation loss of the trained policies (change vs BF16) - +0.20% +1.28%; R = 512: +1.22%

Re-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):

BF16 KIVI-4 KIVI-2
Decode attention step vs the native BF16 kernel, CUDA graph, 128 rows x 8K tokens 6.80 ms 3.05 ms (2.23x) 3.60 ms (1.89x)
Decode step speedup with 8 or more rows, 1K-32K tokens - 1.5-2.6x 1.1-2.4x
WikiText-2 perplexity change, 4 x 16K tokens (section 4 on the RTX PRO 5000) - +0.17-0.58% (+0.26-0.54%) +7.9-11.7% (+7.3-11.7%)
Native train/logp_abs_diff_mean, GSPO seed 1, steps 1-8 (section 7, same seed and steps) 0.0000 (0.0156) 0.0319 (0.0326) 0.1933 (0.1911); R = 512: 0.1154 (0.1183)
~8K-token prompts, same KV memory (9.5-9.7 GiB): concurrent rollouts / tokens per s 8 / 306 24 / 415 40 / 425
GSM8K test, first 512 problems, T = 1: accuracy / peak device memory 74.6% / 13.4 GiB 73.4% / 8.2 GiB 69.1% / 7.1 GiB

On the current main the 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 kivi4 for RL rollouts and kivi2 with kivi_residual_length=512 only where memory is the binding constraint.

GSPO reward per step, three seeds per arm

Related issue

Fixes #590

Type of change

  • 🐛 Bug fix
  • ✨ New feature
  • 💥 Breaking change (public API / CLI behavior changes in a non-backward-compatible way)
  • 📝 Documentation update
  • ♻️ Refactoring
  • ⚡ Performance improvement
  • ✅ Test coverage improvement

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/csrc and setup.py):

  • pytest tests/test_kivi_kv_cache_cpu.py tests/test_kivi_kv_cache_cuda.py tests/test_logprobs_cuda.py on this commit's code: 78 passed, 2 skipped (the flash variant of the chunked-prefill test, without flash-attn).
  • Upstream 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 cpu with triton, flash-attn and CUDA hidden as in the CPU CI job, on the rebase onto main bc3ee6f: 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 check and ruff format --check on the changed files.
  • Fork CI on this commit: CPU Unit Tests passed, Lint passed.

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

  • The PR title summarizes the contribution.
  • Linked the related issue in the description (if any).
  • Existing tests pass (pytest tests/ -k cpu).
  • New behavior is covered by tests.
  • Described the test commands run and any hardware limitations.
  • Public API / CLI changes are additive and backward-compatible (see CONTRIBUTING.md).

Known limitations

  • KIVI-2 with the default 128-token window misses the RL reward target; with 512 tokens it passes, but its gap to BF16 widens over the last 20 of 100 steps, so longer runs still need checking.
  • Scope as in the issue: one GPU, the qwen3 family, private per-request caches. Tensor-parallel rollout was not measured; other families, speculative decoding and NPU fall back to the model-dtype cache with a RuntimeWarning.
  • Prefill attention over fresh prompt tokens stays full precision, so prefill cost is unchanged; a chunk after a cached prefix first dequantizes that row's prefix. The gains are in decode and cache memory.
  • With a single sequence the decode kernel is slower than the BF16 kernel below 16K tokens: the split-K grid cannot fill the GPU.
  • areno serve cannot 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

  • Base branch. The issue asks for oss-camp2026; that branch is currently an ancestor of main with no commits of its own, and this change builds on main's engine, so the PR targets main like the other camp PRs. I can retarget if you prefer.
  • Experiment provenance. The original measurements ran on development commits kept on kivi-590-dev; the section 9 runs record local commits whose trees differ from this commit only as listed in runs_5090/README.md of the raw logs.
  • Raw logs: kivi-590-artifacts holds 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.
  • Upstream observation (not changed here). The native BF16 decode kernel (_decode_partial in areno/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.
  • A harness bug worth knowing about. The first KIVI RL launches went through a version of train_seeded.py that wrapped only TrainerConfig.cuda_config; RolloutTrainerConfig overrides 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.

@EricChan2028

Copy link
Copy Markdown
Author

Checked this PR against the current main (99ea181, which includes #642 and #643). It applies without conflicts, and the CPU suite, run the way the CI job runs it (CPU-only torch, no triton or flash-attn), gives the same result with and without this change: the 8 test_real_gloo_* tests fail in my environment on both trees, and every other selected test passes or is skipped the same way on both, including the new chunked-prefill and decode-metadata tests. The CUDA tests listed in the description ran on the original base e17794c and were not re-run on this one; the notes below are why I expect them to hold.

How the KIVI path relates to those two changes:

  • fix(attention): include cached prefixes in chunked prefill #642: KIVI keeps its own cached-prefix prefill, which dequantizes each row's prefix and runs the dense kernel on it. The new paged varlen call in FlashAttnInferBackend only serves the model-dtype cache; KIVI reaches the dense backend only for fresh prompt rows, with cache_seqlens=None.
  • perf(inference): persist decode scheduling metadata #643: KIVI decode reads the block table and recurrent slots that DecodeMetadata now keeps persistent. They keep the same dtype and layout (int32 table, int64 slots). KIVI only touches blocks R or more tokens behind the current position, so lazily appended blocks do not affect it.

I can rebase the branch onto the latest main if you prefer, and the CI workflows are waiting for approval to run.

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

【2026 开源轻训营专属 Issue】KIVI 低比特 KV 缓存 / KIVI Low-Bit KV Cache

1 participant