Skip to content

Commit 0768f8d

Browse files
nood-co1ashhart
authored andcommitted
perf(qwen3_5 cuda): keep the prompt-end cache entry one token before the prompt's end
A chat prompt ends in the generation prompt, <think> and a newline (token 198). When the next request sends that turn back without its reasoning, its history renders an empty reasoning block, <think> and two newlines (token 271), so the entry kept for the whole prompt differs from the next prompt in its last token and does not match: the follow-up is prefilled from the last shorter entry or from scratch. Both prefix caches now keep a prompt's entry at len(prompt) - 1 (engine.entry_end; a one-token prompt keeps its whole prompt): the one-stream cache (two entries, one GPU and both ranks of two) and the concurrent PrefixCache (KEEP entries, private copies). An identical prompt sent again now resumes with one token to prefill; a prompt that extends the whole last prompt prefills one token more; stats["cached"] reports the entry's length. prefill, prefill_tp and prefill_state take keep_at and also return the state after prompt[:keep_at] and the drafter's snapshot there. The spans do not change and no forward is added: the chunk that holds the point runs each GDN chain as two launches, rows [0, cut) then [cut, W). The chain kernel steps one row at a time on fp32 state that it loads and stores as fp32, so the two launches give one launch's output rows and final state; the prompt's own state, last logits and first token keep their bits. The state between the launches, the conv rows before the cut and the key/value rows below it are the state a prefill of the first keep_at tokens commits (prefill bits do not depend on chunking). The kept state takes the prompt state's key/value buffers after the last chunk, so a buffer grown past the point is never held twice. The drafter's taps start where its window reaches back from the kept point; it absorbs the chunk's rows before the cut, is snapshotted, then absorbs the rest. Two ranks add no collective. Tests: tests/cuda/test_qwen27_prompt_end_cache.py (a cut chunk against one launch; keep_at against none, one and several spans; the kept state against a fresh prefill of the prefix; the next turn, a resumed prefill, longer and repeated prompts resumed against fresh prefills, greedy and sampled; buffers grown inside the cut chunk; the drafter's taps; the engine and the concurrent decoder end to end against the serial reference), tests/test_qwen27_prompt_end_cache_host.py (both caches' entries and resumes with stand-ins, both ranks of two; prefill_state's spans, cuts and drafter calls with a stand-in chunk; the prefill on row-wise CPU stand-ins for the kernels). tests/cuda/test_qwen27_multi.py: a prompt extending a finished reply now resumes one token earlier. Not yet run on a GPU. (cherry picked from commit 9b2021a)
1 parent 914f2d9 commit 0768f8d

8 files changed

Lines changed: 1406 additions & 45 deletions

File tree

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

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,23 +31,23 @@ def _tokens(ids: Sequence[int], device: torch.device) -> torch.Tensor:
3131

3232

3333
def prefill_stops(w: Weights, prompt: Sequence[int], st: State, draft=None, *, stops: Sequence[int] = (),
34-
keep: Callable | None = None, tp: bool = False) -> torch.Tensor:
35-
"""Commit the rest of the prompt into ``st``, handing ``keep(p, state, drafter context)`` the state after each stop."""
34+
keep: Callable | None = None, tp: bool = False, keep_at: int | None = None):
35+
"""Commit the rest of the prompt into ``st``, handing ``keep(p, state, drafter context)`` the state after each stop (``keep_at``: ``prefill_state``'s)."""
3636

3737
from .prefill import prefill_state
3838

3939
for p in stops:
4040
if st.pos < p < len(prompt) and keep is not None:
4141
prefill_state(w, prompt[:p], st, tp=tp, draft=draft)
4242
keep(p, clone_state(st), draft.snapshot() if draft is not None else None)
43-
return prefill_state(w, prompt, st, tp=tp, draft=draft)
43+
return prefill_state(w, prompt, st, tp=tp, draft=draft, keep_at=keep_at)
4444

4545

4646
@torch.no_grad()
4747
def prefill(w: Weights, prompt: Sequence[int], sampling: Sampling | None,
4848
draft=None, *, state: State | None = None, limit: int = 0, stops: Sequence[int] = (),
49-
keep: Callable | None = None) -> tuple[State, int]:
50-
"""Commit the prompt and sample the first token; resuming a kept ``state`` gives a fresh prefill's bits."""
49+
keep: Callable | None = None, keep_at: int | None = None):
50+
"""Commit the prompt and sample the first token; resuming a kept ``state`` gives a fresh prefill's bits (``keep_at`` adds a third item: the state after prompt[:keep_at] and the drafter's snapshot there)."""
5151

5252
from .forward import _mm
5353

@@ -58,9 +58,10 @@ def prefill(w: Weights, prompt: Sequence[int], sampling: Sampling | None,
5858
st.limit = limit # a fresh state's attention caches stop here; a resumed one keeps its own
5959
if st.pos >= len(prompt):
6060
raise ValueError("a reused state must leave at least one prompt token to process")
61-
normed = prefill_stops(w, prompt, st, draft, stops=stops, keep=keep)
61+
out = prefill_stops(w, prompt, st, draft, stops=stops, keep=keep, keep_at=keep_at)
62+
normed = out if keep_at is None else out[0]
6263
pending = sample_rows(_mm(normed, w.head), [len(prompt)], sampling)[0]
63-
return st, pending
64+
return (st, pending) if keep_at is None else (st, pending, out[1])
6465

6566

6667
@dataclass

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

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -124,17 +124,18 @@ def first_token(w: Weights, normed: torch.Tensor, n: int, sampling: Sampling | N
124124
@torch.no_grad()
125125
def prefill_tp(w: Weights, prompt: Sequence[int], sampling: Sampling | None, rank: int,
126126
draft=None, *, state: State | None = None, limit: int = 0, stops: Sequence[int] = (),
127-
keep: Callable | None = None) -> tuple[State, int]:
128-
"""Both ranks prefill, from a kept ``state`` with a fresh prefill's bits; rank 0 shares the first token."""
127+
keep: Callable | None = None, keep_at: int | None = None):
128+
"""Both ranks prefill, from a kept ``state`` with a fresh prefill's bits; rank 0 shares the first token (``keep_at``: a third item, as ``decode.prefill``'s; the split chains are each rank's own)."""
129129

130130
from .decode import prefill_stops
131131

132132
st = clone_state(state) if state is not None else State(w)
133133
if state is None:
134134
st.limit = limit # a fresh state's attention caches stop here; a resumed one keeps its own
135135
taps = draft is not None and (rank == 0 or getattr(draft, "world", 1) == 2)
136-
normed = prefill_stops(w, prompt, st, draft if taps else None, stops=stops, keep=keep, tp=True)
137-
return st, first_token(w, normed, len(prompt), sampling, rank, 2)
136+
out = prefill_stops(w, prompt, st, draft if taps else None, stops=stops, keep=keep, tp=True, keep_at=keep_at)
137+
first = first_token(w, out if keep_at is None else out[0], len(prompt), sampling, rank, 2)
138+
return (st, first) if keep_at is None else (st, first, out[1])
138139

139140

140141
def _accept(tokens: list[int], parents: list[int], sampled: list[int], room: int,

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

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,22 @@
44

55
import time
66
from pathlib import Path
7-
from typing import Callable
7+
from typing import Callable, Sequence
88

99

1010
KEEP = 3 # prompt states a concurrent decoder keeps to resume from (each holds a DeltaNet copy)
1111
KEEP_ONE = 4 # prompt states one stream keeps (they share its attention buffers)
1212

1313

14+
def entry_end(prompt: Sequence[int]) -> int:
15+
"""Where a prompt's prefix-cache entry ends: one token before the prompt's end (a one-token prompt: at its end).
16+
A chat prompt ends in the generation prompt, ``<think>`` and a newline; the next turn renders that reply with an
17+
empty reasoning block, ``<think>`` and two newlines (another token), so it extends all of the prompt but its last
18+
token."""
19+
20+
return max(1, len(prompt) - 1)
21+
22+
1423
class Qwen27Engine:
1524
"""Qwen3.8-27B on one GPU or two ranks (rank 0 here), DFlash2 drafting, prefix reuse."""
1625

@@ -165,10 +174,11 @@ def generate(self, prompt: list[int], max_tokens: int, sampling, on_tokens: Call
165174
elif drafter is not None:
166175
drafter.restore(([None] * drafter.layers, [None] * drafter.layers, 0, 0))
167176
stops, keep = self._stops(prompt, hit, draft)
168-
st, pending = prefill(self.w, prompt, sampling, drafter, state=hit[1] if hit else None,
169-
limit=self.context_window, stops=stops, keep=keep)
170-
if draft and self._ends(prompt, stops):
171-
self._remember(list(prompt), st, drafter.snapshot() if drafter else None)
177+
end = entry_end(prompt) if draft and self._ends(prompt, stops) else None
178+
st, pending, *kept = prefill(self.w, prompt, sampling, drafter, state=hit[1] if hit else None,
179+
limit=self.context_window, stops=stops, keep=keep, keep_at=end)
180+
if end is not None:
181+
self._remember(list(prompt[:end]), *kept[0])
172182
prefill_s = time.perf_counter() - t0
173183
if on_tokens([pending]):
174184
return {"prefill_s": prefill_s, "cached": hit[1].pos if hit else 0}
@@ -192,10 +202,11 @@ def _generate_tp(self, prompt, max_tokens, sampling, on_tokens, hit, t0, draft,
192202
elif drafter is not None:
193203
drafter.restore(([None] * drafter.layers, [None] * drafter.layers, 0, 0))
194204
stops, keep = self._stops(prompt, hit, draft)
195-
st, pending = prefill_tp(self.w, prompt, sampling, 0, drafter, state=hit[1] if hit else None,
196-
limit=self.context_window, stops=stops, keep=keep)
197-
if draft and self._ends(prompt, stops):
198-
self._remember(list(prompt), st, drafter.snapshot() if drafter else None)
205+
end = entry_end(prompt) if draft and self._ends(prompt, stops) else None
206+
st, pending, *kept = prefill_tp(self.w, prompt, sampling, 0, drafter, state=hit[1] if hit else None,
207+
limit=self.context_window, stops=stops, keep=keep, keep_at=end)
208+
if end is not None:
209+
self._remember(list(prompt[:end]), *kept[0])
199210
prefill_s = time.perf_counter() - t0
200211
stop_now = bool(on_tokens([pending]))
201212
# rank 0 alone decides where a reply ends; rank 1 follows its windows (no header field needed)
@@ -230,8 +241,9 @@ def follow(self) -> None:
230241
drafter.restore(hit[2] if hit is not None else
231242
([None] * drafter.layers, [None] * drafter.layers, 0, 0))
232243
stops, keep = self._stops(prompt, hit, draft)
233-
st, pending = prefill_tp(self.w, prompt, sampling, 1, drafter, state=hit[1] if hit else None,
234-
limit=self.context_window, stops=stops, keep=keep)
235-
if draft and self._ends(prompt, stops):
236-
self._remember(list(prompt), st, drafter.snapshot() if drafter else None)
244+
end = entry_end(prompt) if draft and self._ends(prompt, stops) else None # the same entries as rank 0
245+
st, pending, *kept = prefill_tp(self.w, prompt, sampling, 1, drafter, state=hit[1] if hit else None,
246+
limit=self.context_window, stops=stops, keep=keep, keep_at=end)
247+
if end is not None:
248+
self._remember(list(prompt[:end]), *kept[0])
237249
result = decode_tp(self.w, st, prompt, pending, max_tokens, sampling, 1, drafter, max_rows=self.max_rows)

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

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from .decode import CopyIndex, clone_state
1414
from .decode_tp import _sample_split, _share, first_token, pack_sampling, unpack_sampling
1515
from .draft_tree import allocate
16+
from .engine import entry_end
1617
from .forward import State, _paths, commit_streams, multi_tree_forward, path_indices, reserve
1718
from .prefill import prefill_state
1819
from .weights import Weights
@@ -36,6 +37,13 @@ def own(snap):
3637
return None if snap is None else (list(snap[0]), list(snap[1]), snap[2], snap[3])
3738

3839

40+
def viewed(st: State) -> State:
41+
"""A kept state whose DeltaNet states are its own already: attention rows below ``pos`` viewed in place."""
42+
43+
st.kv = [None if kv is None else (kv[0][:st.pos], kv[1][:st.pos]) for kv in st.kv]
44+
return st
45+
46+
3947
def kept(st: State) -> State:
4048
"""A cached state: attention rows below ``pos`` viewed in place (commits only write past a stream's ``pos``), DeltaNet states copied (decoding replays them in place)."""
4149

@@ -153,15 +161,19 @@ def _step(self, s: Stream, stop: int) -> int | None:
153161
try:
154162
if drafter is not None:
155163
drafter.restore(s.snap)
156-
normed = prefill_state(self.w, s.prompt[:stop], s.st, tp=self.world == 2, draft=drafter)
164+
n = len(s.prompt) # the prompt end is kept one token early, unless a message start covers it
165+
end = entry_end(s.prompt) if stop == n and s.draft and not (s.stops and n - s.stops[-1] < MIN_GAP) \
166+
else None
167+
out = prefill_state(self.w, s.prompt[:stop], s.st, tp=self.world == 2, draft=drafter, keep_at=end)
168+
normed = out if end is None else out[0]
157169
if drafter is not None:
158170
s.snap = drafter.snapshot()
159171
if stop in s.stops:
160172
self.cache.add(list(s.prompt[:stop]), kept(s.st), own(s.snap))
161-
first = None if stop < len(s.prompt) else \
162-
first_token(self.w, normed, len(s.prompt), s.sampling, self.rank, self.world)
163-
if first is not None and s.draft and not (s.stops and len(s.prompt) - s.stops[-1] < MIN_GAP):
164-
self.cache.add(list(s.prompt), kept(s.st), own(s.snap)) # a message start just before the end covers it
173+
first = None if stop < n else first_token(self.w, normed, n, s.sampling, self.rank, self.world)
174+
if end is not None:
175+
at, snap = out[1]
176+
self.cache.add(list(s.prompt[:end]), viewed(at) if end < n else kept(at), own(snap))
165177
except Exception as exc:
166178
if self.world == 2:
167179
self.broken = exc

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

Lines changed: 57 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
from . import glue
1515
from . import prefill_bf16, prefill_glue
16+
from .decode import clone_state
1617
from .forward import State
1718
from .qmm_fast import matmul, matmul_partial, tile
1819
from .weights import QLinear, Weights
@@ -55,12 +56,14 @@ def _grow(st: State, i: int, need: int) -> tuple[torch.Tensor, torch.Tensor]:
5556

5657
@torch.no_grad()
5758
def prefill_chunk(w: Weights, tokens: torch.Tensor, st: State, *, tp: bool = False, capture_taps: bool = False,
58-
last: bool = True, every: bool = False):
59-
"""Commit ``tokens`` at [st.pos, st.pos + W) into ``st``, replacing its list entries, never writing through them (``every``: all rows' final normed states)."""
59+
last: bool = True, every: bool = False, cut: int = 0):
60+
"""Commit ``tokens`` at [st.pos, st.pos + W) into ``st`` without writing through its entries (``every``: all rows' final normed states; ``cut``: also the state after the first ``cut`` rows, the GDN chains run as two launches with one launch's bits)."""
6061

6162
c = w.config
6263
pg = prefill_glue if w.fast_prefill else prefill_bf16 # FP8 inputs only where every projection is 4-bit g64
6364
W = int(tokens.shape[0])
65+
if not 0 <= cut < W:
66+
raise ValueError(f"cut {cut} is not inside a chunk of {W} rows")
6467
p0 = st.pos
6568
keep = c.conv_kernel - 1
6669
dev = tokens.device
@@ -70,6 +73,9 @@ def prefill_chunk(w: Weights, tokens: torch.Tensor, st: State, *, tp: bool = Fal
7073
x = glue.embedding(tokens.to(torch.int32), w.embed)
7174
pending: torch.Tensor | None = None
7275
taps: list[torch.Tensor] = []
76+
part = clone_state(st) if cut else None
77+
if part is not None:
78+
part.kv = [] # the chunk's final buffers, set below: these would outlive a grow that replaces them
7379
for i, layer in enumerate(w.layers):
7480
x, h = pg.add_rmsnorm(x, pending, layer.input_norm, c.eps)
7581
if layer.linear:
@@ -88,7 +94,13 @@ def prefill_chunk(w: Weights, tokens: torch.Tensor, st: State, *, tp: bool = Fal
8894
q, k, v, g, beta = glue.gdn_pre(qkv, st.conv[i], gdn.conv, windows, a, b, gdn.A_log, gdn.dt_bias,
8995
kh=c.k_heads, vh=c.v_heads, dk=c.dk)
9096
final = torch.empty_like(st.rec[i])
91-
yr = deltanet.chain(q, k, v, g, beta, st.rec[i], final)
97+
if part is None:
98+
yr = deltanet.chain(q, k, v, g, beta, st.rec[i], final)
99+
else:
100+
part.rec[i] = torch.empty_like(st.rec[i])
101+
yr = torch.cat([deltanet.chain(q[:cut], k[:cut], v[:cut], g[:cut], beta[:cut], st.rec[i], part.rec[i]),
102+
deltanet.chain(q[cut:], k[cut:], v[cut:], g[cut:], beta[cut:], part.rec[i], final)])
103+
part.conv[i] = torch.cat([st.conv[i], qkv[max(0, cut - keep):cut]])[-keep:].contiguous()
92104
r = _row_mm(pg.gated_norm(yr, z, gdn.norm, c.eps), gdn.out, tp)
93105
st.conv[i] = torch.cat([st.conv[i], qkv[-keep:]])[-keep:].contiguous()
94106
st.rec[i] = final
@@ -124,7 +136,11 @@ def prefill_chunk(w: Weights, tokens: torch.Tensor, st: State, *, tp: bool = Fal
124136
_, normed, _ = glue.add_rmsnorm(x, pending, w.norm, c.eps)
125137
elif last:
126138
_, normed, _ = glue.add_rmsnorm(x[-1:].contiguous(), pending[-1:].contiguous(), w.norm, c.eps)
127-
return normed, (torch.cat(taps, dim=-1) if capture_taps else None)
139+
taps_out = torch.cat(taps, dim=-1) if capture_taps else None
140+
if part is None:
141+
return normed, taps_out
142+
part.pos, part.kv = p0 + cut, st.kv.copy() # the chunk's buffers: their rows below part.pos stay as committed
143+
return normed, taps_out, part
128144

129145

130146
def chunks(start: int, end: int, size: int = CHUNK) -> list[tuple[int, int]]:
@@ -136,20 +152,47 @@ def chunks(start: int, end: int, size: int = CHUNK) -> list[tuple[int, int]]:
136152

137153
@torch.no_grad()
138154
def prefill_state(w: Weights, prompt: Sequence[int], st: State, *, tp: bool = False, draft=None,
139-
size: int = CHUNK) -> torch.Tensor:
140-
"""Commit prompt[st.pos:] into ``st``; the drafter gets taps only for rows its window keeps at the prompt's end."""
155+
size: int = CHUNK, keep_at: int | None = None):
156+
"""Commit prompt[st.pos:] into ``st``; the drafter gets taps only for rows its window keeps at the prompt's end.
157+
158+
``keep_at`` returns ``(normed, (state, snapshot))``: also the state after prompt[:keep_at], on the prompt state's
159+
key/value buffers, and the drafter's snapshot there. The spans do not change; the one holding the point splits
160+
its GDN chains there (``prefill_chunk(cut=...)``)."""
141161

142162
dev = w.norm.device
143-
ids = torch.tensor(list(prompt[st.pos:]), dtype=torch.int32, device=dev)
144-
base, normed = st.pos, None
163+
base, n = st.pos, len(prompt)
164+
if keep_at is not None and not base <= keep_at <= n:
165+
raise ValueError(f"keep_at {keep_at} is outside the prefilled range [{base}, {n}]")
166+
ids = torch.tensor(list(prompt[base:]), dtype=torch.int32, device=dev)
167+
normed, kept = None, None
168+
end = n if keep_at is None else keep_at # the drafter's window then also covers the kept point
145169
tap_from = base
146-
if draft is not None and len(prompt) - draft.window > base:
147-
tap_from = len(prompt) - draft.window
170+
if draft is not None and end - draft.window > base:
171+
tap_from = end - draft.window
148172
draft.skip(tap_from - base)
149-
spans = chunks(base, len(prompt), size)
173+
spans = chunks(base, n, size)
150174
for j, (a, b) in enumerate(spans):
175+
if keep_at == a:
176+
kept = (clone_state(st), draft.snapshot() if draft is not None else None)
177+
kept[0].kv = [] # the final buffers, set below, as for a cut
178+
cut = keep_at - a if keep_at is not None and a < keep_at < b else 0
151179
want = draft is not None and b > tap_from
152-
normed, taps = prefill_chunk(w, ids[a - base:b - base], st, tp=tp, capture_taps=want, last=j == len(spans) - 1)
180+
normed, taps, *part = prefill_chunk(w, ids[a - base:b - base], st, tp=tp, capture_taps=want,
181+
last=j == len(spans) - 1, cut=cut)
182+
snap = None
153183
if want:
154-
draft.add_taps(taps[max(0, tap_from - a):])
155-
return normed
184+
rows = taps[max(0, tap_from - a):]
185+
if cut: # the drafter at the point, then the rest of the chunk
186+
split = keep_at - max(a, tap_from)
187+
if split:
188+
draft.add_taps(rows[:split])
189+
snap, rows = draft.snapshot(), rows[split:]
190+
draft.add_taps(rows)
191+
if part:
192+
kept = (part[0], snap)
193+
if keep_at is None:
194+
return normed
195+
if keep_at == n:
196+
kept = (clone_state(st), draft.snapshot() if draft is not None else None)
197+
kept[0].kv = st.kv.copy() # grown buffers copy the committed rows: never hold the old ones
198+
return normed, kept

‎tests/cuda/test_qwen27_multi.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -166,13 +166,14 @@ def go(i):
166166
t.join(timeout=120)
167167
assert {i: results[i][0] for i in results} == {i: refs[tuple(PROMPTS[i])] for i in range(len(PROMPTS))}
168168
assert all(stats["min_rows"] >= 2 for _, stats in results.values())
169-
# a prompt extending a finished reply resumes from that request's prompt end and decodes a fresh prefill's tokens
169+
# a prompt extending a finished reply resumes from that request's prompt entry (all but its last token) and
170+
# decodes a fresh prefill's tokens
170171
longer = PROMPTS[1] + refs[tuple(PROMPTS[1])][:-1] + [42, 43]
171172
want = _serial(w, longer, SAMPLINGS[1], 12)
172173
sched.decoder.truth[tuple(longer)] = want
173174
got: list[int] = []
174175
stats = sched.submit(longer, 12, SAMPLINGS[1], draft=True, emit=lambda new: got.extend(new) or False)
175-
assert got == want and stats["cached"] == len(PROMPTS[1]), stats
176+
assert got == want and stats["cached"] == len(PROMPTS[1]) - 1, stats
176177
serial: list[int] = []
177178
stats = sched.submit(longer, 12, SAMPLINGS[1], draft=False, emit=lambda new: serial.extend(new) or False)
178179
assert serial == want and stats["cached"] == 0 and stats["min_rows"] == 1

0 commit comments

Comments
 (0)