Skip to content

fix: the 27B's one-stream CUDA engine keeps K/V buffers within the admitted window - #58

Closed
nood-co1 wants to merge 1 commit into
ashhart:mainfrom
blockbrain-ai:contrib/qwen27-single-stream-kv-limit
Closed

nood-co1 wants to merge 1 commit into
ashhart:mainfrom
blockbrain-ai:contrib/qwen27-single-stream-kv-limit

Conversation

@nood-co1

@nood-co1 nood-co1 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The one-stream Qwen3.8-27B CUDA engine (one GPU or two ranks, with --parallel at its CUDA default of one stream) never sets State.limit, so its attention caches grow to max(need, 2 × rows, 1024) with no upper bound. Once a buffer holds more than half the window, its next growth passes the window. At --context 32768, a fresh 31,015-token prompt leaves 62,024 rows per attention layer, where the startup admission prices each buffer at 32,768.

prefill and prefill_tp now take limit= and set it on a fresh State. Qwen27Engine passes its context_window at all three call sites. With the limit, every buffer stays at or below the admission estimate's row count.

Why

Q/ is src/tensorfold/families/qwen3_5/cuda/. References are at main (34bae79).

  • State.limit defaults to 0, meaning no bound (Q/forward.py:94). Growth in _grow (Q/prefill.py:39-49) and in commit (Q/forward.py:375-388) caps a buffer only when it is set. Only the concurrent decoder sets it (Q/multi.py:107).
  • The one-stream admission prices four K/V buffers per attention layer: two kept prompt ends, the live state and a growth copy. Each is priced at next_power_of_two(max(1024, window)) rows (src/tensorfold/cuda/geometry.py:163-165).
  • Prompts prefill in even chunks of up to 4,096 rows (Q/prefill.py:120-124). For 31,015 tokens the buffer grows 3,876 → 7,753 → 15,506 → 31,012 → 62,024 rows. The last chunk needs three rows more than 31,012, and the buffer doubles.
  • At --context 32768, 3,072 of the 32,767 fresh prompt lengths leave a buffer above 32,768 rows, all between 28,673 and 32,767 tokens. The largest is 65,528 rows. Replies and resumes grow the same way: a 16,000-token prompt whose reply passes 32,000 rows reaches 64,000.
  • For the 27B, a row across the 16 attention layers is 65,536 B: K and V, 4 KV heads of 256, bf16 (the checkpoint's config.json: 64 layers, a full-attention layer every 4). That prompt's buffer set is 3.8 GiB where admission assumes 2.0 GiB. The engine keeps two prompt ends (Q/engine.py:119-120), so two or three distinct long prompts in a row hold several such sets.

Change

  • Q/decode.py prefill and Q/decode_tp.py prefill_tp take a keyword limit: int = 0. A fresh state gets st.limit = limit. A resumed state keeps its own limit (clone_state copies it, Q/decode.py:22). Other callers see no change.
  • Q/engine.py passes limit=self.context_window on one GPU (generate, with or without drafts), on rank 0 (_generate_tp) and on rank 1 (follow). Cached prompt ends come from these prefills, so resumed states carry the limit too.
  • The limit is context_window, not cache_slots. cache_slots is window + 12 (src/tensorfold/cuda/capacity.py:56), which is 12 rows above the estimate's power of two when the window is itself a power of two.
  • The concurrent decoder is unchanged. It already bounds its states, and its own estimate prices them row for row (geometry.py:243-260).

One keyword on two functions and three call sites. No kernel, admission or cache-policy change.

Exactness

The change alters buffer capacity only, never a key or value row or the order of any sum.

  • Rows. Growth copies every committed row into the new buffer (Q/prefill.py:46-47, Q/forward.py:386-387).
  • Decode attention. It addresses each cache by its data pointer (src/tensorfold/cuda/kernels/attention.py:223-236) and splits keys into 512-key chunks by committed count and absolute position (:171-190). Capacity is not an input.
  • Prefill attention. It checks that the cache holds p0 + W rows and reads keys up to each row's position (src/tensorfold/cuda/kernels/prefill_attention.py:41-54, :64). Capacity is not an input.
  • Room. Growth keeps max(need, …), so a commit always gets every row it needs. The engine refuses prompts of context_window tokens or more and caps a reply at context_window - len(prompt) tokens (Q/engine.py:128-131). The last sampled token is not committed, so no state passes context_window - 1 rows.
  • Reallocations. A limited buffer either has the unlimited size or holds context_window rows. No commit needs more, so the limit adds no reallocation.
  • Same path as --parallel. The capped growth path is the one the concurrent decoder already runs (Q/multi.py:107).

This is argued from the code. The GPU test below checks it.

Tests

Host: macOS, Python 3.13.5, PyTorch 2.11.0 CPU.

tests/test_qwen27_kv_limit.py (new, 16 tests) uses the allocations fixture of tests/test_cuda_geometry.py for its Triton stand-in. prefill_chunk is replaced by its cache writes (_grow, then the chunk's rows), since the kernels need a GPU. The chunking, _grow, State, prefill, prefill_tp and commit are the real ones.

  • Fresh prompts of 29,815, 31,015 and 31,497 tokens through prefill and both ranks of prefill_tp. Without a limit they reach 59,624, 62,024 and 62,992 rows. With limit=32768 they stay at 32,768, and every committed row is intact.
  • The 31,015-token growth sequence, with and without the limit.
  • A prompt resumed from a limited state keeps the bound (32,100 tokens from 16,000: 64,000 rows unlimited, 32,768 limited). A resumed state's own limit wins over the keyword.
  • A 16,000-token prompt, then a reply committed through commit in 12-row windows up to 32,767 rows: 64,000 rows unlimited, 32,768 limited, every row intact.
  • Qwen27Engine passes limit=context_window on one GPU (with and without drafts), on rank 0 and on rank 1 (follow).
Run Result
New file on this branch 16 passed, with and without an import-only Triton stand-in
New file on main's sources 16 failed: 15 raise TypeError on the new limit keyword; in the engine test the three call sites pass 0
Whole host suite (tests without tests/cuda), main (34bae79) 133 failed, 1,319 passed, 298 skipped, 4 xfailed, 18 errors
Same, this branch merged into main (34bae79) 133 failed, 1,335 passed, 298 skipped, 4 xfailed, 18 errors

The whole-suite runs had an import-only Triton stand-in. The same 151 ids fail or error on both, for host reasons: no transformers tokenizer, no Triton backends, MLX 0.31.1 where GLM-5.3-Flash needs 0.32.2, and two tests that read tools/ and CHANGELOG.md, which the test tree used here did not include. ruff check on the three source files reports the same two findings as on main (an E731 and an F841 in engine.py).

tests/cuda/test_qwen27_prefill.py::test_a_cache_limit_changes_no_bits (new, GPU) uses the file's toy model in two cases: 9,000 rows with limit 9,100 (the third chunk grows to 9,100 rows, not 12,000), and 1,000 rows with limit 1,100 (the reply grows the buffer to 1,100 rows, not 2,048). It checks that:

  • a limited prefill_state equals an unlimited one (state and last-row normed);
  • prefill(..., limit=) gives the same first token;
  • serial and drafted replies from the limited state equal the unlimited serial reply (90 tokens);
  • the states after the reply are equal, and the limited one stays within its limit.

GPU status

One DGX Spark (GB10, sm_121); container: Python 3.12.3, PyTorch 2.13.0a0 (NVIDIA 26.07), CUDA 13.3, Triton 3.7.1. TORCH_CUDA_ARCH_LIST=12.1 was set: without it the 0.3.5 extensions do not build in this container (the failure #56 reports, fixed on main in 0.3.6.1). Branch head 8c4c98c.

Run Result
tests/cuda/test_qwen27_prefill.py 14 passed, including test_a_cache_limit_changes_no_bits (2 cases)
tests/cuda 290 passed, 7 skipped; main (beddbb7): 288 passed, the same 7 skipped

Still pending:

  1. The 27B on one GB10 at --context 32768, main against this branch, a fresh 31,015-token prompt: the reply's token_sha (equal expected), and torch.cuda.memory_allocated after the prefill.
  2. Two ranks (two GB10s): the same reply hashes on both branches.

Evidence

Surface: the engine's growth rule run on CPU tensors. No GPU, no model.

  • One prompt. The real chunks and _grow, run over every fresh prompt length below 32,768, give the figures above. A fresh 31,015-token prompt leaves a 62,024-row K/V buffer per attention layer where admission assumes 32,768: 3.8 GiB against 2.0 GiB at 65,536 B a row.
  • Request sequences. A replay of the one-stream engine's rules on buffer sizes: _grow, commit's growth, the two-entry prompt-end cache and _drop_extensions. It matches the real _grow on single prompts. It ran 4,000 random sequences of one to four requests, each a fresh prompt or a continuation of the previous one, with prompt and reply lengths drawn within the window. Rows are counted as the estimate counts them: kept entries, the live state and one growth copy, the copy as a whole buffer set. For a fresh prompt the copy term is the estimate's accounting, not allocated memory, since a fresh state's old buffers are freed one layer at a time.
--context Estimate (4 buffers) Peak, no limit Peak, with the limit
32,768 131,072 rows (8.0 GiB) 216,136 rows (13.2 GiB), 1.65× 131,012 rows, 1.00×
262,144 1,048,576 rows (64.0 GiB) 1,560,192 rows (95.2 GiB), 1.49× 1,046,304 rows, 1.00×

With the limit the peak was at most 1.00× at every window tried: 8,192, 32,768, 65,536, 100,000, 131,072 and 262,144.

  • The worst sequence at 32,768 is three fresh prompts of 31,015, 29,815 and 31,497 tokens. At the third prompt's last chunk, the two kept entries hold 62,024 and 59,624 rows and the live state 62,992: 184,640 rows (11.3 GiB) before any growth copy, 1.41× the whole estimate.
  • One long chat stays within the estimate. Each turn resumes the previous prompt end; at the 262,144 window the worst of 300 simulated chats peaked at 0.75×. The overshoot needs two or three distinct long prompts.
  • Which window a DGX Spark admits by default was not checked.

Overlaps

Not in this change: the drafter's caches, which have their own bounded estimate (draft_geometry(..., bounded=True)), and the other families (glm5_next, qwen4_exp, nemotron_h), which were not checked.


Submitted by an agent from Blockbrain Labs (https://x.com/blockbrain_labs, https://github.com/blockbrain-ai).

…mitted window

The one-stream engine never set State.limit (only the concurrent decoder does), so its
attention caches grew to max(need, 2x, 1024) rows with no cap. Once a buffer holds more
than half the window, its next growth passes the window: a fresh 31,015-token prompt at
--context 32768 leaves a 62,024-row buffer per attention layer, where the startup estimate
prices each at 32,768. A 16,000-token prompt whose reply passes 32,000 rows reaches 64,000.

- prefill and prefill_tp take limit= and set it on a fresh State; a resumed state keeps its
  own (clone_state copies it).
- Qwen27Engine passes its context_window on one GPU and on both ranks.

Growth still gives a commit every row it needs, and nothing commits past context_window - 1,
so the cap never shortens a request. Attention addresses keys by absolute position and growth
copies every committed row, so outputs keep their bits.

Tests: tests/test_qwen27_kv_limit.py runs the real chunking, _grow, prefill, prefill_tp and
commit on CPU tensors, and the engine's three call sites (all 16 fail without the change). A
CUDA test checks that a limited prefill and reply equal an unlimited one.
@ashhart

ashhart commented Sep 28, 2026

Copy link
Copy Markdown
Owner

Thank you, @nood-co1, this is a sharp catch. The one-stream 27B engine sized its admission for the window
but let its attention caches double past it: a 31,015-token prompt grew them to 62,024 rows. Your limit keeps
a fresh prompt inside the window, leaves a resumed prompt's own limit alone, and your tests pin both, down to
the exact growth steps.

We rebased it onto next-0.3.6.2 unchanged. On a DGX Spark, a 31,105-token prompt at a 32,768-token window
gives the same reply as before, and the four decode cells are within 1%. It ships in 0.3.6.2 (9270aeb5), and it shaped
the concurrency work landing beside it: concurrent streams now size their caches once, at admission. Thank
you, and please keep them coming.

@ashhart ashhart closed this Sep 28, 2026
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