Repository navigation
[feature] LeapQuant for GDN: int8 recurrent state, with prefix caching and MTP - #3101
Open
haoyangli0109 wants to merge 5 commits into
Open
haoyangli0109 wants to merge 5 commits into
haoyangli0109 wants to merge 5 commits into
Conversation
Contributor
🏷️ CI GuideRuns automatically on every eligible PR before approval:
Heavy model tests:
|
LeapQuant (Pan et al., arXiv:2609.38166) stores each GDN head's state
between window flushes as
S_0 = diag(c) Z diag(b) + Kc^T Uc
Z is an int8 residual, b and c are fp32 per-column scales and per-row
smoothing, and Kc, Uc are r fp16 compensator tokens fitted by power
iteration to take the outlier rows and columns that would otherwise set
the quantisation range. A slot holds ~1.19 bytes per state element
instead of 4, and the state is re-quantised once per window instead of
being rounded every token, so the rounding error does not compound.
It is built on ReplaySSM, whose record buffer already is the per-window
form; LeapQuant only changes what the boundary state is.
- fla_ops/leapquant.py: Triton kernels for decode (which never
dequantises the matrix), the window fold (every layer in one launch),
and the prefill quantise / dequantise.
- GDNStateMixin: an int8 `mamba_v_cache` with `leapquant_scale` /
`leapquant_comp` side buffers and fp16 window records. The step's fold
runs in `_attach_replayssm` after the commit, outside the captured
graph, so the layer kernels only decode.
- GatedDeltaNet: a prefill dequantises the state it resumes and
quantises the one it ends with; decode calls
`leapquant_gated_delta_rule`.
Opt in with ATOM_ENABLE_LEAPQUANT=1 (ATOM_LEAPQUANT_RANK, default 4;
ATOM_LEAPQUANT_WINDOW, default 16). It turns ReplaySSM on and covers
non-speculative GDN decode only: KDA, speculative decoding and prefix
caching are refused at startup.
Signed-off-by: Haoyang Li <lihaoyang0109@gmail.com>
GPU tests (tests/test_leapquant_gpu.py) pin the kernels against torch references of the same algorithm: - the quantiser is a torch mirror of `_lq_quantize` and beats plain INT8; - decode across windows follows a shadow running exact fp32 steps from the kernel's own boundary state, and the error against the exact trajectory does not grow from window to window; - one stacked fold over every layer is the per-layer fold, bit for bit; - exactly low-rank, zero and tiny states store and fold to finite values, and a rank-1 window on top of them refits to fp16 rounding; - every kernel returns the same bytes run after run. The degenerate-state cases fail on both bugs fixed during bring-up: the fp16 key overflow of a plain-norm `_lq_unit`, and the warm start that fell back to the old key (3.4e-3 instead of 1e-7 on a zero state). tests/test_leapquant_refusal.py covers the startup checks: KDA, speculative decoding, prefix caching and ATOM_ENABLE_REPLAYSSM=0. Signed-off-by: Haoyang Li <lihaoyang0109@gmail.com>
A LeapQuant slot's state is its int8 residual together with its scales and compensators; the int8 plane alone is no state. Carry all three wherever a prefix-cache checkpoint goes: * PAGE images hold the scale and compensator planes after conv and ssm. The layout id names them and the int8 ssm dtype, the image is priced before the pool exists, and the offload tier's state_entry_views walks the same planes in the same order. * Midstep checkpoints (ATOM_GDN_STATE_MIDSTEP=1) quantise the chunk state into their slot instead of copying h into the int8 pool; the conv half is written as before (write_state_checkpoints(copy_ssm=False)). * A state fork (the FORK transfer of Qwen4Exp) seeds all three planes of its write slot from the source, every layer at once, outside the graph. Checkpoints are kept at prompt positions only. Between two decode steps a ReplaySSM slot is its checkpoint plus the records since the last flush, and neither an image nor a fork carries the records, so a checkpoint kept there resumes from the state at the last flush; under FORK the generating sequence itself continues from that state. Add StateTransfer.decode_checkpoints, False for both GDN transfers under ReplaySSM, and have BlockManager.checkpointers_at keep nothing at a generation position for such a backend. This changes plain ReplaySSM too, which kept those checkpoints; Kimi's KDA transfer is unchanged. Drop the prefix-caching refusal. Speculative decoding still refuses. Signed-off-by: Haoyang Li <lihaoyang0109@gmail.com>
A verify window of T = num_speculative_tokens + 1 tokens reads, for each token, the state after the tokens before it, which the T == 1 kernel's two contractions of the boundary state cannot give. The new verify kernel materialises S_h once in fp32 (the boundary decayed by e^C plus the committed records), walks the window as ReplaySSM's serial route does, and appends every token's record; replayssm_commit then keeps the accepted ones. It launches as ReplaySSM's serial kernel does: one warp per program, so each token's contractions over K reduce inside it, and a 32- or 64-wide V slice by batch size. Four warps measured 3.4x slower at 128 sequences. The flush predicate is h + 2T > cache_len for the configured T, in the fold, the kernels and the commit alike, and the record buffer is p + 2T - 1 long, so a fold still lands every p committed tokens (p + 1 for plain decode, as before). The fold for every layer still runs in the metadata builder, outside the captured graph. Drop the speculative-decoding refusal. The GPU tests run verify windows of 2 and 4 tokens, with random lengths and random accepts, against an exact fp32 shadow across several flushes, and check that each fold's boundary is the shadow's state up to one quantisation; the T == 1 decode test now checks the latter as well. Signed-off-by: Haoyang Li <lihaoyang0109@gmail.com>
A PAGE checkpoint image lives in KV pool units, and paged decode reads KV bytes it then weighs by zero: a fresh block's rows past the context. Those bytes were always finite before images shared the pool. A bf16 state over a bf16 cache still is, but fp32 or int8 state bytes read as bf16 include NaN and Inf patterns, and 0 * NaN is NaN. So once the pool filled and images started trading places with KV, every running request turned to noise at the same step. On Qwen3.5-9B with an fp32 or LeapQuant state and prefix caching on, all 128 concurrent GPQA requests degraded within 70 tokens of each other, at the step the pool ran out of vacant blocks; GPQA fell from 61% to 2%. bf16 and ReplaySSM states, prefix caching off, and a checkpoint interval of 0 were unaffected, and the gluon decode kernel turns NaN in either place into a NaN output. The other way an image reaches attention, the block a block-table row's zeroed tail names, is physical block 0, which the pool already reserves (`reserve_null_block`). This closes the first: BlockPool marks the units an image releases, and reports a marked block through `KVBlockPool.take_dirty`; the split UMBP pool asks its private part, where PAGE units live, and a pool without raw units has none. BlockManager._fresh_block sends a marked block to StateMaintenanceOps.cleared_units, and the batch that first writes it zeroes the whole unit before its stores, restores and block copies, since a unit cleared there may be a copy's destination. The zeroing is a copy out of a unit of zeros through the existing descriptor, kernel and fenced staging, so every PAGE-copy backend gets it. Signed-off-by: Haoyang Li <lihaoyang0109@gmail.com>
haoyangli0109
force-pushed
the
lhy/leapquant_gdn
branch
from
November 27, 2026 11:04
07305f4 to
e8063d1
Compare
haoyangli0109
marked this pull request as ready for review
November 27, 2026 11:54
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What it does
Adds LeapQuant (Pan et al., arXiv:2609.38166) as an opt-in storage format for the GDN recurrent state,
ATOM_ENABLE_LEAPQUANT=1, including prefix caching and MTP speculative decoding, and fixes a prefix-caching bug that any state other than bf16 runs into. On maind325160e9. Five commits, each reviewable on its own:feat(gdn): LeapQuant int8 recurrent state for single-token GDN decodetest(gdn): LeapQuant kernel and startup-refusal testsfeat(gdn): LeapQuant with prefix cachingfeat(gdn): LeapQuant with MTP speculative decodingfix(state): clear a checkpoint unit before it goes back to KVWithout the flag nothing changes, with two exceptions: under plain ReplaySSM the fork transfer no longer keeps a checkpoint at a generation position (commit 3), and every PAGE-copy backend clears a recycled checkpoint unit before it goes back to KV (commit 5).
LeapQuant (commits 1 and 2)
Between window flushes each head's state is held as
Zis an int8 residual,bandcare fp32 per-column scales and per-row smoothing, andKc,Ucare r = 4 fp16 compensator tokens, fitted by power iteration to take the outlier rows and columns that would otherwise set the int8 range. A slot holds 1.19 bytes per state element instead of 4, and the state is re-quantised once per window (p = 16 tokens) instead of rounded every token, so the rounding error does not compound over long generations.It is built on ReplaySSM, whose record buffer (
replay_buf_k/u/g, cursorwrite_pos) already is the per-window form; LeapQuant only changes what the boundary checkpoint is.fla_ops/leapquant.py: Triton kernels.b ⊙ (Zᵀ(c ⊙ x)) + Ucᵀ(Kc x)and replays the window's records on top; the int8 matrix is never dequantised.GDNStateMixin(gdn_attn.py): an int8mamba_v_cachewithleapquant_scale/leapquant_compside buffers, sized into the state pool, and fp16 window records (cache_len = p + 1 = 17). The step's fold runs in_attach_replayssmright afterreplayssm_commit, outside the captured graph, so the per-layer kernels only decode.slot_indexed_cacheslists the side buffers, so slot movers carry them with the state; LMCache's PAGE layout leaves them out with the other recurrent planes.GatedDeltaNet(attention_gdn.py): the prefill load / store and the decode branch.Knobs:
ATOM_LEAPQUANT_RANK(r, default 4) andATOM_LEAPQUANT_WINDOW(p, default 16). LeapQuant turns ReplaySSM on. It refuses at startup KDA (per-channel gates) andATOM_ENABLE_REPLAYSSM=0; commit 1 also refuses prefix caching and speculative decoding, which commits 3 and 4 lift.Prefix caching (commit 3)
A LeapQuant slot's state is the int8 residual together with its scales and compensators; the int8 plane alone is no state. All three now travel wherever a prefix-cache checkpoint goes:
_checkpoint_plane_shapes/_checkpoint_plane_tensorslist the scale and compensator planes after conv and ssm, the layout id names them and the int8 ssm dtype (order=conv-all-layers,ssm-all-layers,scale-all-layers,comp-all-layers:leapquant=r4), the image is priced before the pool exists, andstate_entry_views(the offload tier) walks the same planes in the same order.ATOM_GDN_STATE_MIDSTEP=1): the SSM half quantises the chunk state into its slot (leapquant_write_checkpoints) instead of copyinghinto the int8 pool;write_state_checkpoints(copy_ssm=False)still writes the conv half._attach_replayssmseeds all three planes of a fork's write slot from its source, every layer at once, outside the graph.Where a checkpoint may be kept follows #3404's
StateTransfer.decode_keep:KEEP_SNAPSHOT). LeapQuant's scale and compensator planes have no such builder, so_decode_keepgives a LeapQuant imageKEEP_NONE, as it does for any image with more planes, and LeapQuant keeps checkpoints at prompt positions only.GDNStateMixin.state_transferreturnsKEEP_NONEwhere main keepsKEEP_SETTLED. This changes plain ReplaySSM on the fork transfer (Qwen4Exp, and Qwen3.5 under PP or RapidServe); measured below.MTP (commit 4)
A verify window of
T = num_speculative_tokens + 1tokens reads, for each token, the state after the tokens before it, which the T = 1 kernel's two contractions of the boundary state cannot give._leapquant_verify_kernelmaterialisesS_honce in fp32 (the boundary decayed bye^Cplus the committed records), walks the window as ReplaySSM's serial route does, and appends every token's record;replayssm_commitkeeps the accepted ones. It launches like ReplaySSM's serial kernel: one warp per program and a 32- or 64-wide V slice by batch size.The flush predicate is
h + 2T > cache_lenfor the configured T in the fold, the kernels and the commit alike, and the record buffer isp + 2T - 1long, so a fold still lands every p committed tokens (p + 1 = 17for plain decode, as before).The checkpoint-unit fix (commit 5)
A PAGE image lives in KV pool units, and paged decode reads V rows it then weighs by zero: a fresh block's rows past the context, and the block a block-table row's zeroed tail names. #3508 keeps images out of the second, physical block 0. The first remains: a unit an image releases goes back on the free list still holding the image, and the request that takes it as a KV block reads those bytes under a zero weight. A bf16 state over a bf16 cache is finite there; fp32 or int8 state bytes read as bf16 include NaN and Inf patterns, and
0 * NaNis NaN. Once the pool fills and images start trading places with KV, every running request turns to noise at the same step.BlockPoolmarks the units an image releases and reports a marked block throughKVBlockPool.take_dirty; the split UMBP pool asks its private part, where PAGE units live, and a pool without raw units has none.BlockManager._fresh_blocksends a marked block toStateMaintenanceOps.cleared_units, and the batch that first writes it zeroes the whole unit before its stores, restores and block copies, since a unit cleared there may be a copy's destination. The zeroing is a copy out of a unit of zeros through the existing descriptor, kernel and fenced staging, so every PAGE-copy backend gets it.Measured
Qwen3.5-9B, TP1, MI355X (gfx950), unless noted. The prefix-caching and MTP correctness runs are on main
d325160e9with this PR (aiterfc623e745, FlyDSL 0.5.0); the accuracy, speed and memory tables were measured on earlier bases, named per section, and the LeapQuant kernels have not changed since. The runs carried bench-only changes that are not part of this PR: the dense Qwen3.5 MTP loader fix (get_expert_mappingwithout routed experts), a switch for an FP32 state, and a switch that forces the fork transfer.About the baseline. Upstream stores Qwen3.5's GDN state in the model dtype (BF16):
GDNStateMixin._state_dtypesignores the checkpoint'smamba_ssm_dtype: float32. That costs 15 points on GPQA-Diamond (below). The FP32 rows use a one-line change that honoursmamba_ssm_dtype; I will send it as a separate fix. Qwen3.8-Flash-Next already runs its state in FP32.Accuracy
606aceb11, no prefix caching. Thinking mode, model-card sampling (temperature 1.0, top_p 0.95, top_k 20), 3 samples per question, up to 81,920 tokens. GSM8K is lm_eval, all 1,319 questions, 5-shot chat,max_gen_toks 4096.Qwen3.5-9B, TP1:
Per-question sign tests against FP32: LeapQuant p ≥ 0.34 on all three, BF16 p ≤ 0.001. The paper's Qwen3.5-9B GPQA-Diamond: FP32 81.3, BF16 66.2, LeapQuant 81.8.
Qwen3.8-Flash-Next, TP2 + EP (the paper only ran a truncated 8-layer model, for efficiency):
Sign tests against the default: p ≥ 0.62.
Accuracy on long reasoning, with prefix caching and MTP
1d37f8662with this PR. AIME 2026 (30 questions, 16 samples each) and GPQA-Diamond (198, 8 each), prefix caching on with a checkpoint every 1,024 tokens, temperature 1.0, up to 81,920 tokens, 64 concurrent requests a task.Decode step
606aceb11.benchmark_serving, random 4096 in / 1024 out, one wave of requests per concurrency. The step time is the mean ITL after the last request's first token, so it includes the window flushes.Qwen3.5-9B, ms:
The paper reports 1.02 / 1.13 / 1.23× over FP32 at 32 / 128 / 512 on B200. The GDN kernels alone (the 9B's 24 layers, flushes amortised) are 2.84 / 3.04 / 2.84× faster than the FP32 kernel at batch 32 / 128 / 512. GDN is 23–35% of an FP32 step, and subtracting the kernel saving from the FP32 step lands within 1.1 ms of the measured LeapQuant step.
Qwen3.8-Flash-Next, TP2 + EP:
--gpu-memory-utilization 0.98, where all modes fit 512 requests, it is 1.13 / 1.19× faster at 256 / 512.With MTP 3 (
1d37f8662), output ms per token on the model's own reasoning (GSM8K questions in thinking mode, 1,024 tokens each, temperature 1.0), 2× the concurrency in requests:With MTP the state is read once per verify window, so LeapQuant's bandwidth saving shrinks by the tokens per forward while its fold still costs the same per committed token (1.1 ms a step at 128 sequences, all 24 layers). Kernel alone (one layer, T = 4, Qwen3.5-9B heads): 153 µs against ReplaySSM's 152 µs at 128 sequences, 266 against 276 at 256.
Memory
Per Qwen3.5-9B layer, LeapQuant holds conv 48 KiB, the int8 residual 512 KiB, scales 32 KiB, compensators 64 KiB and 17 fp16 records 274 KiB. One prefix-cache image is 16.1 MB with LeapQuant against 26.3 MB for ReplaySSM's bf16 checkpoint (51.5 MB with the fp32 state).
Dataset-level throughput (the paper's Figure 9 method)
606aceb11. Qwen3.5-9B, replaying FP32's own output lengths for GSM8K (1,319), MMLU-Pro (50 per category) and GPQA-Diamond (594 replies): all requests at once,ignore_eos, each mode paired with LeapQuant on the same GPU, four GPUs. LeapQuant's output throughput over the makespan is 1.06 / 1.08 / 1.09× FP32's, and 1.11–1.15× while 64 or more requests run. The paper reports 1.23 / 1.30 / 1.44× on B200. Memory does not explain the gap: the paper's own code (leapquant/LeapQuant, a vLLM plugin) serves without prefix caching and keeps vLLM's FP32 state slots, so its end-to-end gain can only come from the decode step, and with its serving settings ATOM measures 1.05–1.06× (1d37f8662). With prefix caching and a B200-sized KV budget (gpu-memory-utilization 0.6,1d37f8662), LeapQuant is 1.15 / 1.15 / 1.07× FP32, and on GPQA at two samples a question (396 requests, 0.6, no prefix caching) 1.17×. Against ReplaySSM the gain is the memory: in the same runs LeapQuant is 1.025 / 1.023 / 1.016× and 1.062× ReplaySSM with its bf16 checkpoint (1.4× LeapQuant's state per request), and 1.063 / 1.111 / 1.040× and 1.232× ReplaySSM with an fp32 one (2.5×).Prefix caching: does a resumed request continue from the right state?
d325160e9. Twelve ~3,100-token prompts, one request at a time, greedy, logprobs on. Each prompt is sent twice; the first request's prefill is cut at its prompt-end anchor and checkpointed there, and the repeat resumes from that checkpoint and computes the same suffix. Then a second turn (prompt + answer + follow-up), twice: the first resumes at turn 1's anchor, the second at its own.cccc96a03)Midstep checkpoints come from the chunk kernel's bf16 intermediate states, so they are close rather than bit-exact, as main's are: ReplaySSM's midstep keeps both turns for 7/12 prompts with this PR and 8/12 on main.
Prefix caching under memory pressure
GPQA-Diamond, 198 questions, one sample, up to 32,768 tokens, 128 concurrent, a checkpoint every 1,024 tokens. A generation counts as garbled when most of its last 2,000 characters sit in runs of more than 20 characters without a space.
gpu-memory-utilizationcccc96a03)cccc96a03)Prefix caching: accuracy with real reuse
GSM8K-CoT (lm_eval
gsm8k_cot, 8 fixed exemplars, so every question shares one prefix; 1,319 questions, chat, multiturn,max_gen_toks 4096). lm_eval'sgsm8ksamples its shots per question and shares almost nothing, so it does not exercise resumes. Prefix-cache hit rate 91.5%. Strict / flexible:d325160e9cccc96a03One configuration moves by 1–1.5 points from run to run (the repeated rows), so the rows do not separate.
Generation checkpoints
--state-checkpoint-interval-tokens 64, so generation keeps checkpoints where a backend does. Turn 1 generates 320 tokens greedily; turn 2 sends the prompt plus the first 288 of them as token ids and generates on. Resumed correctly, it reproduces turn 1's tokens 288 onwards. Twelve GSM8K questions; a turn 1 shorter than 312 tokens is skipped.cccc96a03)cccc96a03)cccc96a03)Qwen3.8-Flash-Next (the FORK transfer)
1d37f8662. TP2 + EP; Qwen4Exp checkpoints by forking state slots. GSM8K-CoT strict / flexible:GSM8K (5-shot) with MTP 3: LeapQuant 96.97 / 97.50, ReplaySSM 97.57 / 97.57, at 2.92 and 2.90 tokens a forward.
Prefix caching under the FORK transfer, on Qwen3.5
1d37f8662. Qwen3.5 forks too under PP or RapidServe; these runs force the transfer in a bench-only build. The first requests' outputs under fork equal those under PAGE bit for bit (12/12 prompts, 64 tokens, logprobs). GSM8K-CoT under fork depends on scheduler timing, upstream included: upstream ReplaySSM 79.53, 79.53, 79.00; this PR's ReplaySSM 78.17, 78.32, 78.09 and LeapQuant 78.47, 78.70; PAGE 80.21 for all of them. The checkpoint decisions are identical in every run, and instrumented runs ruled out a resume, a slot read and written by different rows in a forward, a fork on a decode step, a stale fork source, CUDA graphs, and aborts or preemption. I have not found the cause; it predates this PR, and Qwen3.8 does not show it.Tests
tests/test_leapquant_gpu.py(GPU, skipped without one):_lq_quantizeand beats plain INT8;tests/test_leapquant_refusal.py: KDA andATOM_ENABLE_REPLAYSSM=0refuse; prefix caching and speculative decoding start, with the record buffer sized for the verify window.tests/test_kda_checkpoint_slot_copy.py: a LeapQuant PAGE image carries all four planes through a store and restore into another slot, andstate_entry_viewsnames the same bytes in the same order.tests/test_gdn_page_checkpoint.py: the layout id names the LeapQuant planes and the int8 state; a LeapQuant image keepsKEEP_NONEat a decode boundary, midstep or not; the fork transfer keepsKEEP_NONEunder ReplaySSM or LeapQuant andKEEP_SETTLEDotherwise; clearing units zeroes every region of each, pastimage_bytestoo, and touches no other block (GPU).tests/test_state_checkpoint.py,tests/test_state_transfer.py: a fork'sdecode_keepround-trips the wire and a fork cannot build a decode snapshot; a records backend keeps no generation checkpoint under either transfer while its prompt rungs stay; the batch that takes a block an image released clears it, once, and a block no image held is not cleared.tests/test_page_unit_checkpoint.py,tests/test_umbp_block_pool.py: a released unit is dirty until KV takes it, reported once, a store that takes it back clears the mark, and the split UMBP pool reports its private part's._pool_state_dtypesand_leapquant_bytes_per_slot(test_state_transfer_slots_wiring.py,test_gdn_page_checkpoint.py, whose spare-slot stub also gains thestate_transfer_slotsfeat(pd): free a finished request's KDA slot on P through state transfer slots #3571 started calling). Builders made without_init_gdn_statereadleapquantas off from a class default, so the tests that build them that way are unchanged.Each commit passes the GDN / ReplaySSM / KDA / state-checkpoint / UMBP-pool tests on its own on MI355X, apart from two that fail the same way on main there (
test_qwen4_exp_mtp.py::test_qwen_replay_uses_shared_record_dtype_and_preserves_state_dtype, andtest_kda_midstep_checkpoints.py::test_the_state_pool_lends_scratch_only_where_it_is_borrowedonce aiter is importable).blackandruff checkare clean. In a CPU-only environment set up like Pre Checkin (CPU torch, no triton, no aiter), the suite passes excepttest_atomesh_spur_dispatch.py, whose script times out the same way on main on this machine. On MI355X the full suite fails the same tests as main there, most of them because that machine's aiter predates main's.Not in this PR
mamba_ssm_dtype, and the dense Qwen3.5 MTP loader.