Skip to content

feat: a quantized KV cache for Flash Next on CUDA (--kv-dtype int8 or int4) - #47

Closed
vcruz305 wants to merge 8 commits into
ashhart:mainfrom
vcruz305:kv-dtype
Closed

vcruz305 wants to merge 8 commits into
ashhart:mainfrom
vcruz305:kv-dtype

Conversation

@vcruz305

Copy link
Copy Markdown
Contributor

TensorFold's Flash Next CUDA engine can now keep its KV cache in 8 or 4 bits instead of bf16, behind a flag. The command is tensorfold serve MODEL --kv-dtype int8 (or int4). The default stays bf16, so nothing changes for an existing command, and the MLX path refuses anything but bf16 because this only exists on CUDA.

What you get is memory, not speed. On one DGX Spark the 8-bit cache is 1.68x smaller than bf16 and decodes at the same speed on short prompts, a few percent faster once the prompt is a few thousand tokens. The 4-bit cache is 3.17x smaller, costs about 12% decode speed at short context, and is roughly even by 4,000 tokens. Both change the output. I measured how much, and the numbers are below rather than summarized.

This is the same scheme ExLlamaV3 uses for -cq 8 and -cq 4 (the default grid, no companding): groups of 32 along the head dim, the group rotated by a 32-point Hadamard, one fp16 scale per group taken as the group's absmax, and a midpoint grid. 4-bit packs two codes per byte. The indexer keys and the pooled block keys stay bf16, so the saving applies to the K and V tensors only. The query is rotated on the way in and the merged attention output on the way out, which lets the stored keys and values stay in the rotated domain instead of being rotated back on every read.

What changed

  • cd90ecc, the 8-bit cache. src/tensorfold/families/qwen4_exp/cuda/kvcache.py is new and holds the storage, the Hadamard, and the quantize and dequantize kernels, plus a pure-torch reference quantizer that the tests check against. glue.py quantizes keys and values as it writes the cache and rotates the query. attention.py dequantizes inside the attention kernel and rotates the merged output back. forward.py, decode.py and engine.py thread the dtype through, and the MTP drafter's own cache uses the same dtype as the main cache, so drafts and verification see the same representation. cli.py gains --kv-dtype {bf16,int8,int4}, CUDA only.
  • 710ad04, the 4-bit cache, on the same path. One bits parameter runs through the kernels rather than a second copy of them. The quantize and dequantize each had to be split into per-width kernels: Triton compiles every branch of a function, and a shared function returned a different shape at 4 bits (two codes per byte) than at 8, which broke compilation of the 8-bit path. attention.py loads the packed nibbles and unpacks before the dot.
  • 09eb756, --mtp-confidence on the CUDA serve path. The draft chain stops early once a draft's probability drops below this, and the default is 0.3. I added it because the speed numbers people quote for this model were measured at 0.6, and there was no way to ask for that. It is included here because the measurements below depend on it.
  • 33a151e and 05b49a8, the tests. tests/cuda/test_flashnext_kvquant.py checks both widths: the kernels write the reference quantizer's bits exactly, the scales match ExLlamaV3's own quantizer, the cache round-trips inside the grid, attention output stays within a stated tolerance of bf16, a window of rows matches the same rows computed one at a time, chunked prefill matches one shot, drafted decoding matches serial by token-id SHA-256, and the end-to-end logits stay close to bf16. tests/test_cuda_cli.py covers the flag parsing, including the refusal on the MLX path.
  • 139b0a4 and 1f4131e, the docs. docs/recipes/qwen3.8-flash-next.md gains a section on the flag, the README's option list names it, and THIRD_PARTY_NOTICES.md credits the scheme to ExLlamaV3 (MIT, Copyright (c) 2025 Turboderp).

13 files, +920 / -49, 8 commits, no merge commits, based on bb4b4a3.

Measured on a GB10 (DGX Spark)

One DGX Spark (GB10, driver 580.178.04, CUDA 13.0, torch 2.11, 128 GB unified). Every timing arm ran in an exclusive session with the GPU otherwise idle. The model is Vontra/Qwen3.8-Flash-Next-MLX-4bit-MTP, the MLX 4-bit affine checkpoint (group size 32) with MTP drafting. It is not an EXL3 checkpoint. This branch is cut from upstream main, and upstream cannot load EXL3 packs. That is what #42 adds, so the EXL3 numbers and these are not comparable and I have not mixed them.

Memory

Bytes per token for one attention layer's K and V plus the fp16 scales, head dim 256, 2 KV heads. The scales are included. Leaving them out overstates the saving, and the whole-cache figure is the one that matters:

cache bytes/token/layer vs bf16
bf16 2,048 1.00x
int8 1,088 1.88x
int4 576 3.56x

Across the whole model the saving is smaller, because the indexer keys and the pooled block keys stay bf16 either way. For Flash Next that works out to 1.68x at int8 (30,784 bytes per token down to 18,304) and 3.17x at int4. At a 262,144-token context the K and V pool drops from 7.52 GiB to 4.47 GiB at int8.

Speed

Drafted decode, greedy, 400 tokens, median of 3 reps, thinking off. Depth 6 with confidence 0.6 is the policy, and depth 7 at 0.75 is the single best point I measured. SM clock was 2502 to 2528 MHz of a 3003 max during decode, so these are not peak-clock numbers. The client is the same for every arm.

Short prompts, 8,192-token context, tok/s:

cache code devops prose
bf16 86.76 64.45 52.27
int8 85.17 64.25 53.84
int4 76.73 59.79 50.61

Depth 7 at confidence 0.75, code prompt only: bf16 88.16, int8 87.16, int4 77.88.

A 4,121-token prompt in a 32,768-token context, depth 6 at confidence 0.6. Here the reps are tight enough to trust the gap, so I list them:

cache median the three reps prefill, tok/s
bf16 75.44 74.18, 75.44, 75.60 158.3
int8 79.72 78.14, 79.72, 79.78 158.0
int4 76.14 74.74, 76.14, 76.22 158.4

Read together: at short context the dequantize costs more than the bandwidth saves, so int8 is a wash (about 98% of bf16) and int4 gives up about 12% on code. By 4,000 tokens of context int8 is 5.7% faster and its slowest rep beat bf16's fastest, while int4 is even with bf16, inside the noise. Prefill is identical across all three, which is what you would expect, since prefill is dominated by the weights and not the cache.

Quality

Teacher-forced, 2,048 positions from the pack's own bench corpus, full vocabulary, the KL summed in fp32. The same weights in every arm, only the cache dtype changes. NLL is in bits per token.

cache NLL top-1 KL vs bf16, mean KL p50 KL p95 KL max top-1 agreement vs bf16
bf16 2.7613 0.6680 0 0 0 0 1
int8 2.8217 0.6665 0.2093 0.0119 1.133 11.31 0.8916
int4 2.7198 0.6636 0.3911 0.0244 2.146 17.44 0.8662

The floor of this measurement is zero in the only sense I could test. I scored the bf16 cache, reloaded the model, and scored it again: same NLL to the digit, KL of 0. The engine is deterministic, so the KL above is the cache and not run-to-run noise. I had first tried to get a floor by varying the prefill chunk size, and that came back as zero too, but for a bad reason: the chunk size never reaches the forward pass, so the two arms were the same run. I am not using that zero.

Two things about this table that are easy to misread. The median KL is small (0.012 bits at int8, 0.024 at int4) while the mean is large, which means most positions barely move and a few move a lot. And int4's NLL is lower than bf16's. That is not int4 being more accurate. A quantized cache shifts the distribution, and a lower NLL on one corpus is a sign of that shift, not a quality win. Top-1 agreement is the cleaner summary: int8 keeps the bf16 top token on 89.2% of positions, int4 on 86.6%.

Tests

PYTHONPATH=src python -m pytest -q tests/cuda/test_flashnext_kvquant.py   # 30 collected
PYTHONPATH=src python -m pytest -q tests/cuda/test_flashnext_forward.py   # 16 passed
PYTHONPATH=src python -m pytest -q tests/cuda/test_flashnext_kernels.py   # 35 passed

test_flashnext_kvquant.py holds 30 tests across the two widths. The checks that matter:

  • the kernels write exactly the bits the reference quantizer does, at 8 and at 4 bits, and the scales match ExLlamaV3's own quantizer on the same groups;
  • the cache round-trips inside the grid, and packing then unpacking 4-bit codes returns the same codes;
  • attention over a quantized cache stays within a stated tolerance of attention over bf16;
  • a window of rows matches the same rows computed one at a time (torch.equal), and chunked prefill matches one shot;
  • drafted decoding matches serial decoding by token-id SHA-256, through tensorfold serve, at both widths;
  • the end-to-end logits stay close to the bf16 cache.

The host suite, run with the same exclusions as upstream (--ignore=tests/test_alternating_kv.py --ignore=tests/test_dflash_tree_search.py), shows the same 4 failures and 130 passes as upstream/main. Those 4 are environmental (this box has no MLX) and are present on main.

Overlap with open PRs

git merge-tree is clean against upstream/main. It is also clean against #42 (pr/exl3), even though the two branches both edit docs/recipes/qwen3.8-flash-next.md, README.md, src/tensorfold/families/qwen4_exp/cuda/forward.py, src/tensorfold/families/qwen4_exp/__init__.py and THIRD_PARTY_NOTICES.md. The edits are in different regions and merge without help. I will rebase on #42 if it lands first.

#40 also touches families/qwen4_exp/cuda/{attention,decode,engine,forward}.py, and #29 touches docs/recipes/qwen3.8-flash-next.md and the MLX-side decode path. I have not merge-tested those two. Both are small overlaps and I will rebase on whichever lands first.

This also answers the request in #23, partly. That issue is a GLM model running out of memory at 64k on two Sparks and asks for an fp8 cache or a --kv-dtype. The flag is the one asked for, but the implementation covers Flash Next only. GLM, the 27B and MiMo are not included, and I do not have a GLM checkpoint here to test against.

What is not claimed

  • No long context past 4,121 tokens. I measured at short prompts and at one 4,121-token prompt. 24k, 128k and 262k are not measured. The memory math above says they fit, and the speed there is an extrapolation from the 4k result, not a measurement.
  • No EXL3 checkpoint. Everything here is the MLX 4-bit pack. The EXL3 packs need feat: read EXL3 checkpoints on CUDA (any codebook, 1 to 8 bits, mixed-K packs) #42, and the speeds in feat: read EXL3 checkpoints on CUDA (any codebook, 1 to 8 bits, mixed-K packs) #42 and the speeds here are different models measured on different branches.
  • No peak-clock numbers. The SM clock sat at 2502 to 2528 MHz of a 3003 max during these runs. A pinned clock would read higher, and I have not measured by how much.
  • int4 is not faster. It is smaller. At short context it is slower than bf16 by about 12% on code, and at 4,000 tokens it is even. Its reason to exist is the 3.17x memory cut, and it costs 13.4 points of top-1 agreement to get there.
  • The quality numbers are one corpus of 2,048 positions, teacher-forced. They say how far the distribution moves, not how that shows up in generated text. I did not run a side-by-side generation comparison.
  • The indexer keys and pooled block keys are not quantized, so a model whose cache is dominated by those would see a smaller saving than the table suggests. Flash Next is not such a model, but GLM might be, and I have not checked.

--kv-dtype int8 stores each attention layer's keys and values as 8-bit codes with one fp16 scale per 32 values, the same arithmetic as ExLlamaV3's -cq 8 (H32 rotation, midpoint grid). The default stays bf16. The MLX path and the other CUDA families refuse anything else. Indexer keys and pooled block keys stay bf16. The query rides the rotation, so a group is read as stored.
…izer

Codes and scales match a torch reference of the same arithmetic, bit for bit. Attention stays within a stated tolerance of the bf16 cache. Windows match serial steps, chunks match one shot, and drafted token ids match serial.
The recipe, the serve option table, and the third-party notice name the ExLlamaV3 cache scheme the int8 path follows.
Same scheme as the int8 cache, one bits parameter: groups of 32, one fp16
absmax scale, H32, midpoint grid. Two unsigned codes per byte, low nibble
first. Indexer keys and pooled block keys stay bf16. The MLX path still
refuses anything but bf16.
The int8 tests are parametrized over both widths. Scales match ExLlamaV3's
own quantizer bit for bit at 4 and at 8. H32 matches their butterfly. The
rotation trick matches an explicit un-rotate, including a window that crosses
a chunk boundary and a group size other than 16. The MTP cache is the same
dtype and the same write path.
Flash Next's CUDA default stops a draft chain under 0.30. The measured
policies are 0.60 and 0.75, so the serve command has to be able to say so.
Byte counts include the fp16 scales and the MTP head's cache. 11,648 bytes
a token at int4 is 2.64x on the whole cache, not 4x, because indexer keys
and pooled block keys stay bf16.
@ashhart

ashhart commented Sep 27, 2026

Copy link
Copy Markdown
Owner

Thanks @vcruz305, a flag-gated int8/int4 KV cache for Flash Next on CUDA is a useful option for long contexts on a single Spark, and keeping bf16 the default is the right call. 0.3.5 is out as of tonight, so we'll review this against it and run our Spark checks: drafted replies equal serial ones and concurrent streams equal their solo runs at each KV dtype, plus the memory and speed trade you describe. It's targeted with #42 for 0.3.6, and your commits will land under your name.

@vcruz305

Copy link
Copy Markdown
Contributor Author

Added one commit to this branch, 43c9349: a stop-token fix for Flash Next on EXL3 checkpoints.

On 0.3.6 the CUDA engine takes its stop ids from config.json only (the top-level eos_token_id, else text_config's). The EXL3 packs of Flash Next have no top-level id, and text_config names <|endoftext|> (248044) only; the end of the chat turn, <|im_end|> (248046), is listed in generation_config.json alone. Config.read returns (248044,) for turboderp's 3.05bpw_h5_ng5 pack and for CYBER-FROST-3.8 SAGE 3.5 bpw. So a served reply does not stop at the end of its turn. On a thinking-on tool request we saw <|im_end|>\n<|im_start|>user... streamed as content, the same get_weather call three times, and <think> in the answer.

Config.read now adds generation_config.json's eos_token_id after config.json's, in order and without duplicates. The MLX checkpoint already lists both ids at the top level, so it reads the same as before. tests/test_flashnext_eos.py covers the three cases on CPU.

Checked on one DGX Spark (GB10) serving the SAGE 3.5 bpw pack on 0.3.6 with this change: a ~16k-token prompt with thinking on, then a get_weather tool request, gives one tool call, finish_reason: tool_calls and no leaked tags. The reply's token hash matches 0.3.6 served from a copy of the pack whose config.json lists both ids. On this branch, the new test and tests/test_cuda_cli.py pass (11 tests, CPU).

The commit also applies cleanly to main (0.3.6.1). If you would rather take it on its own, the same change sits on 0.3.6 as vcruz305:fix/exl3-eos-generation-config. This PR still needs a rebase onto 0.3.6; I am happy to do that if it helps.

@vcruz305

Copy link
Copy Markdown
Contributor Author

I moved the stop-token fix out of this PR and into its own, #69, which also covers the 27B's EXL3 packs. This branch is back to 1f4131e, so the KV cache change stands alone again, as it was before this morning.

@ashhart

ashhart commented Sep 28, 2026

Copy link
Copy Markdown
Owner

Thank you, @vcruz305. The quantized KV cache is in 0.3.6.2, all eight commits under your name (549b7a72 to 5f4e940f). On the same
memory, --kv-dtype int8 holds about 1.65x the default window and int4 about 2.6x, with drafted replies equal to
"draft": false at both. On top of your commits:

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.

2 participants