Skip to content

Commit 9270aeb

Browse files
nood-co1ashhart
authored andcommitted
fix: the 27B's one-stream CUDA engine keeps K/V buffers within the admitted 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. (cherry picked from commit 8c4c98c)
1 parent c1dca22 commit 9270aeb

5 files changed

Lines changed: 205 additions & 7 deletions

File tree

‎src/tensorfold/families/qwen3_5/cuda/decode.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def _tokens(ids: Sequence[int], device: torch.device) -> torch.Tensor:
3232

3333
@torch.no_grad()
3434
def prefill(w: Weights, prompt: Sequence[int], sampling: Sampling | None,
35-
draft=None, *, state: State | None = None) -> tuple[State, int]:
35+
draft=None, *, state: State | None = None, limit: int = 0) -> tuple[State, int]:
3636
"""Commit the prompt and sample the first token; resuming a prompt-end ``state`` gives a fresh prefill's bits."""
3737

3838
from .forward import _mm
@@ -41,6 +41,8 @@ def prefill(w: Weights, prompt: Sequence[int], sampling: Sampling | None,
4141
if not prompt:
4242
raise ValueError("prefill requires at least one token")
4343
st = clone_state(state) if state is not None else State(w)
44+
if state is None:
45+
st.limit = limit # a fresh state's attention caches stop here; a resumed one keeps its own
4446
if st.pos >= len(prompt):
4547
raise ValueError("a reused state must leave at least one prompt token to process")
4648
normed = prefill_state(w, prompt, st, draft=draft)

‎src/tensorfold/families/qwen3_5/cuda/decode_tp.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def _tokens(ids: Sequence[int], device: torch.device) -> torch.Tensor:
106106

107107
@torch.no_grad()
108108
def prefill_tp(w: Weights, prompt: Sequence[int], sampling: Sampling | None, rank: int,
109-
draft=None, *, state: State | None = None) -> tuple[State, int]:
109+
draft=None, *, state: State | None = None, limit: int = 0) -> tuple[State, int]:
110110
"""Both ranks prefill, from a prompt-end ``state`` with a fresh prefill's bits; rank 0 shares the first token."""
111111

112112
from .forward import _mm
@@ -115,6 +115,8 @@ def prefill_tp(w: Weights, prompt: Sequence[int], sampling: Sampling | None, ran
115115
device = w.norm.device
116116
split = 2 * w.head.n == w.config.vocab # split_weights(..., split_head=True)
117117
st = clone_state(state) if state is not None else State(w)
118+
if state is None:
119+
st.limit = limit # a fresh state's attention caches stop here; a resumed one keeps its own
118120
taps = draft is not None and (rank == 0 or getattr(draft, "world", 1) == 2)
119121
normed = prefill_state(w, prompt, st, tp=True, draft=draft if taps else None)
120122
last = _mm(normed, w.head) if split or rank == 0 else None

‎src/tensorfold/families/qwen3_5/cuda/engine.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,8 @@ def generate(self, prompt: list[int], max_tokens: int, sampling, on_tokens: Call
140140
drafter.restore(hit[2])
141141
elif drafter is not None:
142142
drafter.restore(([None] * drafter.layers, [None] * drafter.layers, 0, 0))
143-
st, pending = prefill(self.w, prompt, sampling, drafter, state=hit[1] if hit else None)
143+
st, pending = prefill(self.w, prompt, sampling, drafter, state=hit[1] if hit else None,
144+
limit=self.context_window)
144145
if draft:
145146
self._remember(list(prompt), st, drafter.snapshot() if drafter else None)
146147
prefill_s = time.perf_counter() - t0
@@ -164,7 +165,8 @@ def _generate_tp(self, prompt, max_tokens, sampling, on_tokens, hit, t0, draft):
164165
drafter.restore(hit[2])
165166
elif drafter is not None:
166167
drafter.restore(([None] * drafter.layers, [None] * drafter.layers, 0, 0))
167-
st, pending = prefill_tp(self.w, prompt, sampling, 0, drafter, state=hit[1] if hit else None)
168+
st, pending = prefill_tp(self.w, prompt, sampling, 0, drafter, state=hit[1] if hit else None,
169+
limit=self.context_window)
168170
if draft:
169171
self._remember(list(prompt), st, drafter.snapshot() if drafter else None)
170172
prefill_s = time.perf_counter() - t0
@@ -199,7 +201,8 @@ def follow(self) -> None:
199201
if drafter is not None: # a two-rank drafter: mirror rank 0's drafter state
200202
drafter.restore(hit[2] if hit is not None else
201203
([None] * drafter.layers, [None] * drafter.layers, 0, 0))
202-
st, pending = prefill_tp(self.w, prompt, sampling, 1, drafter, state=hit[1] if hit else None)
204+
st, pending = prefill_tp(self.w, prompt, sampling, 1, drafter, state=hit[1] if hit else None,
205+
limit=self.context_window)
203206
if draft:
204207
self._remember(list(prompt), st, drafter.snapshot() if drafter else None)
205208
result = decode_tp(self.w, st, prompt, pending, max_tokens, sampling, 1, drafter, max_rows=self.max_rows)

‎tests/cuda/test_qwen27_prefill.py‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88

99
from tensorfold.cuda.kernels import qmm as shared # noqa: E402
1010
from tensorfold.cuda.kernels.prefill_attention import attention # noqa: E402
11-
from tensorfold.families.qwen3_5.cuda.decode import draft_decode, prefill, serial_decode # noqa: E402
12-
from tensorfold.families.qwen3_5.cuda.forward import State # noqa: E402
11+
from tensorfold.families.qwen3_5.cuda.decode import clone_state, draft_decode, prefill, serial_decode # noqa: E402
12+
from tensorfold.families.qwen3_5.cuda.forward import State, commit, tree_forward # noqa: E402
1313
from tensorfold.families.qwen3_5.cuda.prefill import prefill_chunk, prefill_state # noqa: E402
1414
from tensorfold.families.qwen3_5.cuda.qmm_fast import prepare # noqa: E402
1515
from tensorfold.families.qwen3_5.cuda.weights import Attention, Config, GDN, Layer, QLinear, Weights # noqa: E402
@@ -106,6 +106,37 @@ def test_prefix_reuse_through_prefill_equals_fresh_and_drafts_equal_serial():
106106
assert drafted.tokens == serial.tokens
107107

108108

109+
@pytest.mark.parametrize("length,limit", [(9000, 9100), (1000, 1100)])
110+
def test_a_cache_limit_changes_no_bits(length, limit):
111+
"""9,000 rows: the third chunk grows to 9,100 rows, not 12,000; 1,000 rows: the reply grows to 1,100, not 2,048."""
112+
w = _model()
113+
prompt = _prompt(length, seed=9)
114+
free, bounded = State(w), State(w)
115+
bounded.limit = limit
116+
h_free = prefill_state(w, prompt, free)
117+
h_bounded = prefill_state(w, prompt, bounded)
118+
_same_state(free, bounded)
119+
assert torch.equal(h_free, h_bounded)
120+
fresh, first = prefill(w, prompt, None)
121+
kept, first_kept = prefill(w, prompt, None, limit=limit)
122+
assert kept.limit == limit and first_kept == first
123+
sizes = {kv[0].shape[0] for st in (bounded, kept) for kv in st.kv if kv is not None}
124+
assert max(sizes) <= limit
125+
serial = serial_decode(w, fresh, first, 90, None, stop_eos=False)
126+
assert serial_decode(w, kept, first_kept, 90, None, stop_eos=False).tokens == serial.tokens
127+
drafted = draft_decode(w, kept, prompt, first_kept, 90, None, draft=None, stop_eos=False)
128+
assert drafted.tokens == serial.tokens
129+
replied = []
130+
for st in (fresh, kept): # the reply's commits, kept to compare the states after it
131+
st = clone_state(st)
132+
for token in serial.tokens[:-1]:
133+
_, record = tree_forward(w, torch.tensor([token], dtype=torch.int32, device="cuda"), [-1], st)
134+
commit(st, record, [0])
135+
replied.append(st)
136+
_same_state(*replied)
137+
assert max(kv[0].shape[0] for kv in replied[1].kv if kv is not None) <= limit
138+
139+
109140
def test_prefill_matmul_rows_do_not_depend_on_chunking():
110141
gen = torch.Generator(device="cuda").manual_seed(3)
111142
n, k = 1000, 1024

‎tests/test_qwen27_kv_limit.py‎

Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
"""The 27B's one-stream attention caches stay within the admitted window, as its startup estimate assumes."""
2+
3+
import importlib
4+
from types import SimpleNamespace
5+
6+
import pytest
7+
import torch
8+
9+
from tests.test_cuda_geometry import allocations # noqa: F401
10+
11+
Q = "tensorfold.families.qwen3_5.cuda."
12+
WINDOW = 32768
13+
END = WINDOW - 1 # the engine commits at most context_window - 1 rows
14+
_gen = torch.Generator().manual_seed(27)
15+
KEYS, VALUES = torch.randn(END, 1, 2, generator=_gen).bfloat16(), torch.randn(END, 1, 2, generator=_gen).bfloat16()
16+
17+
18+
def _weights(pattern):
19+
"""Enough of ``Weights`` for ``State``: ``pattern`` holds True for a GDN layer, False for an attention layer."""
20+
21+
config = SimpleNamespace(k_heads=1, dk=2, v_heads=1, dv=2, conv_kernel=4, kv_heads=1, head_dim=2, vocab=8)
22+
return SimpleNamespace(config=config, layers=[SimpleNamespace(linear=x) for x in pattern],
23+
norm=torch.ones(1, dtype=torch.bfloat16), head=SimpleNamespace(n=8))
24+
25+
26+
def _host(monkeypatch, pattern=(True, False, True, False)):
27+
"""The three prefill entries on the host, ``prefill_chunk`` cut to its cache writes, and every buffer size left."""
28+
29+
forward = importlib.import_module(Q + "forward")
30+
prefill = importlib.import_module(Q + "prefill")
31+
decode = importlib.import_module(Q + "decode")
32+
decode_tp = importlib.import_module(Q + "decode_tp")
33+
sizes = []
34+
35+
def chunk(w, tokens, st, *, tp=False, capture_taps=False, last=True): # the kernels need a GPU
36+
a, b = st.pos, st.pos + int(tokens.shape[0])
37+
for i, kv in enumerate(st.kv):
38+
if kv is not None:
39+
kbuf, vbuf = prefill._grow(st, i, b)
40+
kbuf[a:b], vbuf[a:b] = KEYS[a:b], VALUES[a:b]
41+
sizes.append(kbuf.shape[0])
42+
st.pos = b
43+
return (torch.zeros((1, 2), dtype=torch.bfloat16) if last else None), None
44+
45+
monkeypatch.setattr(prefill, "prefill_chunk", chunk)
46+
monkeypatch.setattr(forward, "_mm", lambda x, w, xs=None: torch.zeros((1, 8)))
47+
for mod in (decode, decode_tp):
48+
monkeypatch.setattr(mod, "sample_rows", lambda logits, positions, sampling: [3])
49+
monkeypatch.setattr(decode_tp, "_share", lambda values, rank, device: [3] if values is None else list(values))
50+
w = _weights(pattern)
51+
entries = {"one": lambda n, **kw: decode.prefill(w, range(1, n + 1), None, **kw)[0],
52+
"rank 0": lambda n, **kw: decode_tp.prefill_tp(w, range(1, n + 1), None, 0, **kw)[0],
53+
"rank 1": lambda n, **kw: decode_tp.prefill_tp(w, range(1, n + 1), None, 1, **kw)[0]}
54+
return entries, sizes, forward
55+
56+
57+
def _intact(st, end):
58+
for kv in st.kv:
59+
if kv is not None:
60+
assert torch.equal(kv[0][:end], KEYS[:end]) and torch.equal(kv[1][:end], VALUES[:end])
61+
62+
63+
@pytest.mark.parametrize("entry", ["one", "rank 0", "rank 1"])
64+
@pytest.mark.parametrize("prompt,unbounded", [(29815, 59624), (31015, 62024), (31497, 62992)])
65+
def test_a_fresh_prompt_stays_within_the_limit(allocations, monkeypatch, entry, prompt, unbounded): # noqa: F811
66+
entries, sizes, _ = _host(monkeypatch)
67+
st = entries[entry](prompt)
68+
assert st.limit == 0 and max(sizes) == unbounded # without a limit: about twice the window
69+
sizes.clear()
70+
st = entries[entry](prompt, limit=WINDOW)
71+
assert st.limit == WINDOW and max(sizes) == WINDOW
72+
_intact(st, prompt)
73+
74+
75+
def test_a_31015_token_prompt_doubles_on_its_last_three_rows(allocations, monkeypatch): # noqa: F811
76+
entries, sizes, _ = _host(monkeypatch)
77+
entries["one"](31015)
78+
assert list(dict.fromkeys(sizes)) == [3876, 7753, 15506, 31012, 62024]
79+
sizes.clear()
80+
entries["one"](31015, limit=WINDOW)
81+
assert list(dict.fromkeys(sizes)) == [3876, 7753, 15506, 31012, 32768]
82+
83+
84+
@pytest.mark.parametrize("entry", ["one", "rank 0", "rank 1"])
85+
def test_a_resumed_prompt_keeps_its_state_limit(allocations, monkeypatch, entry): # noqa: F811
86+
entries, sizes, _ = _host(monkeypatch)
87+
for limit, largest in ((0, 64000), (WINDOW, WINDOW)):
88+
kept = entries[entry](16000, limit=limit)
89+
sizes.clear()
90+
st = entries[entry](32100, state=kept) # the engine's cached prompt ends carry the limit
91+
assert st.limit == limit and max(sizes) == largest
92+
_intact(st, 32100)
93+
other = entries[entry](4)
94+
other.limit = 777
95+
assert entries[entry](10, state=other, limit=WINDOW).limit == 777 and other.pos == 4
96+
97+
98+
@pytest.mark.parametrize("limit,largest", [(0, 64000), (WINDOW, WINDOW)])
99+
def test_a_reply_committed_to_the_window_end_stays_within_the_limit(allocations, monkeypatch, # noqa: F811
100+
limit, largest):
101+
entries, sizes, forward = _host(monkeypatch, pattern=(False, False)) # commit replays GDN rows on a GPU
102+
st = entries["one"](16000, limit=limit)
103+
width = 12 # the one-stream verify window (max_rows)
104+
while st.pos < END:
105+
n = min(width, END - st.pos)
106+
record = [forward.AttentionRecord(KEYS[st.pos:st.pos + n], VALUES[st.pos:st.pos + n]) for _ in st.kv]
107+
rows = torch.arange(n, dtype=torch.int32)
108+
forward.commit(st, record, list(range(n)), (rows, torch.tensor([n], dtype=torch.int32), rows.long()))
109+
sizes += [kv[0].shape[0] for kv in st.kv]
110+
assert max(sizes) == largest
111+
_intact(st, END)
112+
113+
114+
def _engine(tp, rank):
115+
from tensorfold.families.qwen3_5.cuda.engine import Qwen27Engine
116+
117+
engine = object.__new__(Qwen27Engine)
118+
engine.tp, engine.rank, engine.max_rows, engine.allow_copy = tp, rank, 12, True
119+
engine.w = SimpleNamespace(norm=SimpleNamespace(device="cpu"))
120+
engine.draft, engine.cache, engine.multi, engine.scheduler = None, [], None, None
121+
engine.context_window = WINDOW
122+
return engine
123+
124+
125+
class _Followed(Exception):
126+
pass
127+
128+
129+
def test_engine_prefills_within_its_context_window(allocations, monkeypatch): # noqa: F811
130+
decode = importlib.import_module(Q + "decode")
131+
decode_tp = importlib.import_module(Q + "decode_tp")
132+
limits = []
133+
134+
def prefill(w, prompt, sampling, draft=None, *, state=None, limit=0):
135+
limits.append(("one", limit))
136+
return SimpleNamespace(pos=len(prompt)), 5
137+
138+
def prefill_tp(w, prompt, sampling, rank, draft=None, *, state=None, limit=0):
139+
limits.append((f"rank {rank}", limit))
140+
return SimpleNamespace(pos=len(prompt)), 5
141+
142+
done = SimpleNamespace(seconds=0.0, rounds=0, widths=[])
143+
monkeypatch.setattr(decode, "prefill", prefill)
144+
monkeypatch.setattr(decode, "draft_decode", lambda *a, **kw: done)
145+
monkeypatch.setattr(decode_tp, "prefill_tp", prefill_tp)
146+
monkeypatch.setattr(decode_tp, "decode_tp", lambda *a, **kw: done)
147+
monkeypatch.setattr(decode_tp, "_share", lambda values, rank, device: list(values))
148+
for draft in (True, False):
149+
_engine(1, 0).generate([1, 2, 3], 4, None, lambda tokens: None, draft=draft)
150+
_engine(2, 0).generate([1, 2, 3], 4, None, lambda tokens: None, draft=draft)
151+
shared = iter([[1, 4, 0, 1, *decode_tp.pack_sampling(None)], [1, 2, 3]])
152+
monkeypatch.setattr(decode_tp, "_share", lambda values, rank, device: next(shared))
153+
154+
def follow_once(*a, **kw):
155+
raise _Followed
156+
157+
monkeypatch.setattr(decode_tp, "decode_tp", follow_once)
158+
with pytest.raises(_Followed):
159+
_engine(2, 1).follow()
160+
assert limits == [("one", WINDOW), ("rank 0", WINDOW)] * 2 + [("rank 1", WINDOW)]

0 commit comments

Comments
 (0)