Skip to content

Commit a773c4a

Browse files
authored
Merge pull request #47 from jjang-ai/perf/partial-prefix-tool-loop-cache
dsv41 dspark: prefill cut positions with exact snapshots; a stream ending inside a verify step keeps only emitted tokens
2 parents a45e364 + 5a4c8a7 commit a773c4a

1 file changed

Lines changed: 58 additions & 23 deletions

File tree

‎jang-tools/jang_tools/dsv41/dspark.py‎

Lines changed: 58 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -736,7 +736,7 @@ def stream(self, prompt_ids, max_new, eos_ids=(), stats=None, session=None, samp
736736
PREFILL_CHUNK = 2048
737737

738738
def prefill(self, prompt_ids, session=None, on_boundary=None, chunk_size=None,
739-
clear_cache=True):
739+
clear_cache=True, cuts=None, on_cut=None):
740740
"""Forward ``prompt_ids`` into ``session`` (a runtime Session or the engine's _SeqState duck
741741
type) and seed the draft windows, returning (session, pending_logits, c), c = last prompt pos.
742742
@@ -752,7 +752,17 @@ def prefill(self, prompt_ids, session=None, on_boundary=None, chunk_size=None,
752752
old code snapshotted AFTER the last token, so every hit restored N tokens under an N-1
753753
key and re-fed the last prompt token at position N;
754754
3. the last prompt token in its own forward -> the pending logits for c+1.
755-
Draft windows are seeded only from the last ``win`` positions (all attend can read)."""
755+
Draft windows are seeded only from the last ``win`` positions (all attend can read).
756+
757+
``cuts`` (absolute positions strictly inside the body, i.e. ``sess.pos < cut < N-1``) split the body
758+
into segments; each segment is its own prefill (chunked from its start, ``prompt_end`` = the segment
759+
end), so the state at a cut is exactly the state a prefill of the prompt up to the cut leaves, and
760+
``on_cut(sess, cut)`` sees it (the prefix cache keeps it as an extra reusable boundary). Each segment
761+
seeds the draft windows from its own last ``win`` positions, so ``main_tail()`` at a cut holds the
762+
positions a later prefix hit on that cut reseeds from; the windows at N-1 are the same as without
763+
cuts. No cuts: the single-segment prefill above, unchanged. ``chunk_size`` may be a callable
764+
``(segment_start, segment_end) -> int`` (absolute positions; the last segment ends at N-1) choosing each
765+
segment's chunk, so a prefill restored at a cut chunks its segments exactly as a cold prefill does."""
756766
m, ds = self.m, self.ds
757767
sess = session if session is not None else m.new_session()
758768
ds.reset_windows()
@@ -770,29 +780,37 @@ def prefill(self, prompt_ids, session=None, on_boundary=None, chunk_size=None,
770780
raise ValueError("DSparkRunner.prefill needs at least one prompt token")
771781
end = start + len(ids)
772782
win = int(ds.stages[0].attn.win)
773-
seed_from = max(start, end - win) # first absolute position whose hidden seeds the windows
774-
step = max(1, int(chunk_size or self.PREFILL_CHUNK))
775783
body = ids[:-1]
784+
seg_ends = sorted({int(x) for x in (cuts or ()) if start < int(x) < end - 1}) + [end - 1]
776785
p = start
777-
for i in range(0, len(body), step):
778-
piece = body[i:i + step]
779-
# The next forward's tokens (the next chunk, or the final prompt token): its Engram rows
780-
# are read from SSD while this chunk computes (DSV41.forward engram_lookahead).
781-
nxt = body[i + step:i + 2 * step] or ids[-1:]
782-
kw = {"engram_lookahead": nxt} if _accepts_lookahead(m) else {}
783-
if _accepts_kw(m, "prompt_end"):
784-
kw["prompt_end"] = end - 1 # the body ends at the N-1 boundary (suffix pruning)
785-
if p + len(piece) > seed_from:
786-
logits, mh = m.forward(piece, sess, all_logits=False, return_hidden=True, **kw)
787-
lo = max(0, seed_from - p)
788-
ds.seed_windows(mh[None, lo:], range(p + lo, p + len(piece)))
789-
mx.eval(logits, _session_arrays(sess), [st.attn.window.buf for st in ds.stages])
790-
else:
791-
logits = m.forward(piece, sess, all_logits=False, **kw)
792-
mx.eval(logits, _session_arrays(sess))
793-
p += len(piece)
794-
if clear_cache and hasattr(mx, "clear_cache"):
795-
mx.clear_cache()
786+
for seg_end in seg_ends:
787+
# First absolute position whose hidden seeds the windows: the body's last win - 1 positions (the
788+
# final prompt token adds the win-th), or a cut segment's last win positions (its main_tail).
789+
seed_from = max(p, end - win if seg_end == end - 1 else seg_end - win)
790+
seg = body[p - start:seg_end - start]
791+
step = max(1, int((chunk_size(p, seg_end) if callable(chunk_size) else chunk_size) or self.PREFILL_CHUNK))
792+
for i in range(0, len(seg), step):
793+
piece = seg[i:i + step]
794+
# The next forward's tokens (the next chunk, or the final prompt token): its Engram rows
795+
# are read from SSD while this chunk computes (DSV41.forward engram_lookahead).
796+
q = p - start + len(piece)
797+
nxt = body[q:q + step] or ids[-1:]
798+
kw = {"engram_lookahead": nxt} if _accepts_lookahead(m) else {}
799+
if _accepts_kw(m, "prompt_end"):
800+
kw["prompt_end"] = seg_end # the segment ends here (suffix pruning)
801+
if p + len(piece) > seed_from:
802+
logits, mh = m.forward(piece, sess, all_logits=False, return_hidden=True, **kw)
803+
lo = max(0, seed_from - p)
804+
ds.seed_windows(mh[None, lo:], range(p + lo, p + len(piece)))
805+
mx.eval(logits, _session_arrays(sess), [st.attn.window.buf for st in ds.stages])
806+
else:
807+
logits = m.forward(piece, sess, all_logits=False, **kw)
808+
mx.eval(logits, _session_arrays(sess))
809+
p += len(piece)
810+
if clear_cache and hasattr(mx, "clear_cache"):
811+
mx.clear_cache()
812+
if seg_end < end - 1 and on_cut is not None:
813+
on_cut(sess, seg_end) # exact state of a prefill that ends at this cut
796814
if on_boundary is not None:
797815
on_boundary(sess) # exact N-1 prompt boundary (pos == end - 1)
798816
logits, mh = m.forward(ids[-1:], sess, all_logits=False, return_hidden=True)
@@ -874,6 +892,23 @@ def _rec():
874892
break
875893
n_accepted += k
876894
accept_ema = 0.7 * accept_ema + 0.3 * (k / max(1, W)) # update rolling acceptance
895+
# The stream ends inside this step when an emitted token is an EOS or reaches max_new: commit only
896+
# the tokens up to that one, so the session holds exactly what was emitted (the engine keeps the
897+
# finished session as a reusable prefix: it cannot be trimmed afterwards).
898+
emit_all = [p0] + draft_ids[1 : 1 + k] + ([truth[k]] if k < W and not (k > 0 and self._capture_kw) else [])
899+
end = next((i + 1 for i, t in enumerate(emit_all) if eos_ids and t in eos_ids), len(emit_all))
900+
end = min(end, max(1, max_new - n_emitted))
901+
if end < len(emit_all) or (k == W and end < W + 1):
902+
emit = emit_all[:end]
903+
if self._capture_kw:
904+
m.commit_prefix(sess, ck, len(emit))
905+
else:
906+
sess.restore(ck)
907+
m.forward(emit, sess, all_logits=False)
908+
c += len(emit)
909+
for t in emit:
910+
yield t; n_emitted += 1
911+
_rec(); return
877912
if k == W:
878913
# whole block accepted: the verify forward already wrote exactly-correct causal KV for
879914
# every position (no rejected tail to undo), so skip the restore+refeed commit forward

0 commit comments

Comments
 (0)