quantuminfer 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +96 -2
  3. package/bin/quantuminfer.js +61 -0
  4. package/c27/adapters.py +161 -0
  5. package/c27/harness27.py +349 -0
  6. package/data/input.txt +40000 -0
  7. package/data/wikitext/test.txt +7249 -0
  8. package/engine/API.txt +208 -0
  9. package/engine/PLUGINS.txt +4 -0
  10. package/engine/__init__.py +82 -0
  11. package/engine/adapter.py +505 -0
  12. package/engine/blocks.py +1180 -0
  13. package/engine/c12.py +324 -0
  14. package/engine/c12cu.py +1074 -0
  15. package/engine/ctx.py +87 -0
  16. package/engine/dev.py +11 -0
  17. package/engine/ds4.py +389 -0
  18. package/engine/kernels.py +833 -0
  19. package/engine/model.py +281 -0
  20. package/engine/record.py +140 -0
  21. package/engine/server.py +183 -0
  22. package/engine/spec.py +1030 -0
  23. package/engine/wcode.py +122 -0
  24. package/p27/SPEC.txt +66 -0
  25. package/p27/STATUS.txt +91 -0
  26. package/p27/bench_glm.py +354 -0
  27. package/p27/bench_multi.py +76 -0
  28. package/p27/mkfinal.py +98 -0
  29. package/p27/modal_comp.py +173 -0
  30. package/p27/modal_dl.py +63 -0
  31. package/p27/modal_p27.py +168 -0
  32. package/p27/modal_probe.py +49 -0
  33. package/p27/p27rules.py +29 -0
  34. package/p27/pblocks.py +1242 -0
  35. package/p27/pmodel.py +402 -0
  36. package/p27/pref.py +151 -0
  37. package/p27/prof_glm.py +34 -0
  38. package/p27/quant.py +850 -0
  39. package/p27/recipes/vllm_b300_single_node_tep_b300_agentx_ep.md +353 -0
  40. package/p27/recipes/vllm_b300_single_node_tp_b300_agentx.md +351 -0
  41. package/p27/recipes/vllm_b300_single_node_tp_baseline.md +250 -0
  42. package/p27/recipes/vllm_default_gb300.md +281 -0
  43. package/p27/recipes/vllm_glm53_h200.md +301 -0
  44. package/p27/run_window1.sh +21 -0
  45. package/p27/run_window2.sh +13 -0
  46. package/p27/sweep_glm.py +64 -0
  47. package/p27/t_align.py +42 -0
  48. package/p27/t_combine.py +28 -0
  49. package/p27/t_echo.py +31 -0
  50. package/p27/t_fp8dense.py +59 -0
  51. package/p27/t_fp8speed.py +48 -0
  52. package/p27/t_glm.py +340 -0
  53. package/p27/t_glu.py +30 -0
  54. package/p27/t_gsuf.py +23 -0
  55. package/p27/t_jac.py +22 -0
  56. package/p27/t_moebm.py +30 -0
  57. package/p27/t_nccl.py +36 -0
  58. package/p27/t_online_jac.py +31 -0
  59. package/p27/t_probe.py +4 -0
  60. package/p27/t_router.py +28 -0
  61. package/p27/t_symm.py +50 -0
  62. package/p27/t_tiny.py +116 -0
  63. package/package.json +10 -4
  64. package/results/ANALYSIS.md +156 -0
  65. package/results/comp_vllm_mtp_k5_b300mtp.json +235 -0
  66. package/results/glm53_b300x8_opt4.json +624 -0
  67. package/results/res_glm_c32w3_b300.json +638 -0
  68. package/results/res_glm_final_c32_b300.json +652 -0
  69. package/results/res_glm_multi_final_b300.json +1821 -0
  70. package/results/res_glm_online_b300.json +638 -0
  71. package/results/res_glm_online_fixed_b300.json +638 -0
  72. package/results/res_glm_opt4_b300.json +624 -0
  73. package/results/res_glm_text_plain_batch_b300.json +5792 -0
  74. package/results/res_glm_text_w1_b300.json +1635 -0
  75. package/results/res_glm_text_w3_b300.json +1639 -0
  76. package/results/res_sweep_echo_b300.json +129 -0
  77. package/results/res_sweep_final_b300.json +153 -0
  78. package/results/res_sweep_glm_b300.json +153 -0
  79. package/results/res_techo.json +29 -0
  80. package/results/res_tgsuf.json +21 -0
  81. package/results/res_tjac.json +17 -0
  82. package/results/res_tonline_jac.json +13 -0
package/engine/spec.py ADDED
@@ -0,0 +1,1030 @@
1
+ """Generic exact speculative decoder over the engine core (any model the adapter builds).
2
+
3
+ Proposers (all generic, any model):
4
+ mtp the model's own MTP head (if the adapter found one): a chain of depth D, each draft = the record
5
+ measurement of the head's own perturbed scores (Gumbel-coupled, exactness never depends on it).
6
+ suffix whole-context suffix lookup (lane S3): longest suffix (<= maxn tokens) of the committed text that occurred
7
+ before; propose the C tokens that followed its latest occurrence. Host side, between graph replays.
8
+ draft (not yet) a same-tokenizer draft model built by the same engine.
9
+ echo (I1, E/EW) the last pass's logits re-measured under the upcoming record field; free, any model (_fill_echo).
10
+ Tree = root + one chain per proposer (the generic rule; depths chosen by rule(), see FINDINGS / API.txt).
11
+ Verify: every row's target record measurement; accept the deepest node whose whole root path matches
12
+ (token == parent's measurement); commit the path in every block (recurrent blocks re-walk it, attention copies
13
+ KV); emit path tokens + the bonus measurement. Every emitted token = the target's record measurement at its own
14
+ prefix -> greedy == plain greedy, T>0 == exact sample (23-bit record), independent of the proposers.
15
+ One CUDA graph per pass: verify + accept + commit + MTP catch-up + MTP chain.
16
+ """
17
+ import time
18
+
19
+ import numpy as np
20
+ import torch
21
+
22
+ import blocks as Bk
23
+ from ctx import RowCtx, TreeShape, chain
24
+ from record import gumbel_argmax
25
+ from dev import DEV, CUDA, sync # noqa: F401
26
+
27
+
28
+ def measure(z, rid, T):
29
+ if T == 0:
30
+ return z.float().argmax(-1)
31
+ if not z.is_cuda: # CPU reference path: the same 23-bit field in float64
32
+ from record import gumbel_ref
33
+ G = gumbel_ref(rid.long()[:, None], torch.arange(z.shape[-1], device=z.device)[None])
34
+ return (z.double() / T + G).argmax(-1)
35
+ return gumbel_argmax(z, rid.to(torch.int32), T)
36
+
37
+
38
+ COMPILE = None # default torch.compile mode for captured passes (set by callers / features)
39
+
40
+
41
+ class Suffix:
42
+ """Whole-context suffix index: for n = maxn..1 the latest earlier position of every n-gram."""
43
+
44
+ def __init__(self, maxn=4):
45
+ self.maxn = maxn
46
+ self.toks = []
47
+ self.idx = [dict() for _ in range(maxn + 1)]
48
+
49
+ def extend(self, toks):
50
+ for t in toks:
51
+ self.toks.append(int(t))
52
+ L = len(self.toks)
53
+ # register n-grams ending at L-2 (so the continuation token at L-1 exists)
54
+ for n in range(1, self.maxn + 1):
55
+ e = L - 1
56
+ if e - n < 0:
57
+ break
58
+ self.idx[n][tuple(self.toks[e - n:e])] = e # continuation starts at e
59
+
60
+ def propose(self, C):
61
+ L = len(self.toks)
62
+ for n in range(min(self.maxn, L), 0, -1):
63
+ j = self.idx[n].get(tuple(self.toks[L - n:]))
64
+ if j is not None:
65
+ out = self.toks[j:j + C]
66
+ # loop extrapolation (S3): a match running into the end continues the repeated block
67
+ while len(out) < C:
68
+ out += out[:C - len(out)] if out else []
69
+ if not out:
70
+ break
71
+ return out[:C], n
72
+ return [], 0
73
+
74
+
75
+ class SpecEngine:
76
+ @staticmethod
77
+ def rows_for(m, D=3, C=8, W=1, J=0, Dd=0, E=0, EW=1, **kw):
78
+ d = D if m.mtp is not None else 0
79
+ return 1 + d * W + C + J + Dd + E * EW
80
+
81
+ def __init__(self, m, D=3, C=8, W=1, T=0.0, uid=0, mtp_hidden="final", B=1, dvocab=None, J=0, draft=None,
82
+ Dd=0, Wobs=1, mask_ids=(), E=0, EW=1, SN=4, in_graph_suffix=False):
83
+ self.m, self.T, self.B = m, T, B
84
+ # record sequence id lives on the device so a captured graph honours per-request seeds (T27 BUG-001)
85
+ self.uid_t = torch.full((B,), int(uid), dtype=torch.long, device=DEV)
86
+ # banned token ids (e.g. stop tokens under min_tokens = max_tokens, as the competitors run the benchmark):
87
+ # their logits are -inf for the target AND the proposers -> exact sampling of the masked distribution
88
+ self.mask = None
89
+ if mask_ids: # per vocabulary size (full head, draft vocab), fixed tensors: no data-dependent ops in graphs
90
+ ids = sorted(int(i) for i in mask_ids)
91
+ sizes = {m.V, dvocab or m.V} | ({draft.V} if draft is not None else set())
92
+ self.mask = {n: torch.tensor([i for i in ids if i < n] or [0], dtype=torch.long, device=DEV)
93
+ for n in sizes}
94
+ self.mask_any = {n: any(i < n for i in ids) for n in sizes}
95
+ # draft vocabulary: the MTP head proposes from token ids [0, dvocab) only (BPE ids are ~frequency ordered);
96
+ # a proposer-side saving of LM-head bytes per draft step -- the verifier always measures the full vocabulary
97
+ self.dhead = m.head if not dvocab or dvocab >= m.V else m.draft_head(dvocab)
98
+ self.D = D if m.mtp is not None else 0
99
+ self.C = C
100
+ self.W = W if self.D else 1
101
+ self.Wobs = Wobs if self.D else 1 # candidates kept for observation (online policy), not placed in the tree
102
+ par = [-1]
103
+ par += [i for i in range(self.D)] # rows 1..D: mtp chain (top-1 at every depth)
104
+ self.sib_rows = []
105
+ for i in range(1, self.D + 1): # W-1 siblings per depth (next-best of the same head logits: free rows)
106
+ for _ in range(self.W - 1):
107
+ self.sib_rows.append(len(par))
108
+ par.append(i - 1)
109
+ if C:
110
+ s0 = len(par)
111
+ par += [0] + [s0 + i for i in range(C - 1)]
112
+ # Jacobi chain (lane Z1): J rows from the root holding the previous pass's record measurements as guesses
113
+ self.J = J
114
+ self.jac_rows = []
115
+ for i in range(J):
116
+ self.jac_rows.append(len(par))
117
+ par.append(0 if i == 0 else self.jac_rows[-2])
118
+ # same-tokenizer draft model (any architecture the adapter builds, recurrent or not): a chain of Dd rows
119
+ self.dm = draft if (draft is not None and Dd) else None
120
+ self.Dd = Dd if self.dm is not None else 0
121
+ self.dr_rows = []
122
+ for i in range(self.Dd):
123
+ self.dr_rows.append(len(par))
124
+ par.append(0 if i == 0 else self.dr_rows[-2])
125
+ # amplitude-echo chain (lane I1): E depths x EW candidates per depth. Drafts are written host-side between
126
+ # passes: the LAST pass's target logits at the row that covered each position, re-measured under THIS
127
+ # position's record field (the acceptance-optimal proposal under a point-estimate posterior over logits;
128
+ # see _fill_echo). No model eval, no training, any model.
129
+ self.E = E
130
+ self.EW = EW if E else 1
131
+ self.SN = SN
132
+ self.echo_rows = []
133
+ self.echo_sib = []
134
+ for i in range(1, self.E + 1):
135
+ base = 0 if i == 1 else self.echo_rows[-1]
136
+ self.echo_rows.append(len(par))
137
+ par.append(base)
138
+ sibs = []
139
+ for _ in range(self.EW - 1):
140
+ sibs.append(len(par))
141
+ par.append(base)
142
+ self.echo_sib.append(sibs)
143
+ self.shape = TreeShape(par)
144
+ self.N = self.shape.N
145
+ self.ML = self.shape.MAXL
146
+ self.mtp_rows = list(range(1, 1 + self.D))
147
+ s0 = 1 + self.D + len(self.sib_rows)
148
+ self.suf_rows = list(range(s0, s0 + C))
149
+ # rep[d] = earliest row at tree depth d (the chain row; siblings share the depth): its logits estimate the
150
+ # distribution predicting the token at lens + d + 1.
151
+ self.rep = {}
152
+ for i, dd in enumerate(self.shape.dep.tolist()):
153
+ self.rep.setdefault(dd, i)
154
+ self.repmax = max(self.rep)
155
+ # esrc[l][dd] = the row at tree depth dd sharing the longest root path with row l (ties: earliest row): after
156
+ # a pass that accepted up to leaf l, its logits are the least-wrongly-conditioned estimate for that depth.
157
+ anc = [[i] for i in range(self.N)]
158
+ for i in range(1, self.N):
159
+ anc[i] = anc[par[i]] + [i]
160
+ bydep = {}
161
+ for i, dd in enumerate(self.shape.dep.tolist()):
162
+ bydep.setdefault(dd, []).append(i)
163
+ self.esrc = []
164
+ for l in range(self.N):
165
+ al = set(anc[l])
166
+ self.esrc.append({dd: max(rows, key=lambda r: (sum(a in al for a in anc[r]), -r))
167
+ for dd, rows in bydep.items()})
168
+ self.esrc_maxdep = max(bydep)
169
+ self.esrc_dense = torch.full((self.N, self.esrc_maxdep + 1), -1, dtype=torch.long, device=DEV)
170
+ for l, mp in enumerate(self.esrc):
171
+ for dd, row in mp.items():
172
+ self.esrc_dense[l, dd] = row
173
+ self.gsuf = bool(in_graph_suffix and C and B == 1 and CUDA)
174
+ self.histlen = 16384
175
+ self.hist = torch.zeros(self.histlen, dtype=torch.long, device=DEV) if self.gsuf else None
176
+ self.keepz = bool(E) # OnlineTree sets it on echo-free shapes too, so a switch hands fresh logits over
177
+ self.zfrom = None # engine whose last pass's logits feed this engine's next echo fill (set by OnlineTree)
178
+ self.zleaf = None
179
+ self.zlast = None # (B*N, V) logits of the previous pass's tree rows
180
+ self.zlens = None # (B,) committed lengths those logits were measured at
181
+ self.zok = False
182
+ dev = DEV
183
+ self.tok = torch.zeros(B, self.N, dtype=torch.long, device=dev)
184
+ self.lens = torch.zeros(B, dtype=torch.int32, device=dev)
185
+ self.em = torch.zeros(B, self.ML, dtype=torch.long, device=dev)
186
+ self.alen = torch.zeros(B, dtype=torch.int32, device=dev)
187
+ self.cand = torch.zeros(B, max(self.D, 1), max(self.Wobs, self.W, 2) - 1, dtype=torch.long, device=dev)
188
+ self.mtp_hidden = mtp_hidden
189
+ if self.D or self.Dd:
190
+ self.cu_shape = chain(self.ML)
191
+ self.one = chain(1)
192
+ if self.Dd:
193
+ self.dchains = [chain(i) for i in range(1, self.Dd + 1)]
194
+ self.graph = None
195
+ self.stats = {"passes": 0, "acc": []}
196
+
197
+ # ------------------------------------------------------------------ in-graph body
198
+ @property
199
+ def uid(self):
200
+ return int(self.uid_t[0])
201
+
202
+ @uid.setter
203
+ def uid(self, v):
204
+ self.uid_t.fill_(int(v))
205
+
206
+ def _rid(self, pos):
207
+ """pos (B,) or (B*N,) absolute positions -> record ids (record.rid_of: (seq mod 2^11) * 2^21 + pos)."""
208
+ u = self.uid_t if pos.shape[0] == self.B else self.uid_t.repeat_interleave(pos.shape[0] // self.B)
209
+ return (u.long() & 2047) * (1 << 21) + pos.long() # = record.rid_of (exp_x1/record may shadow record)
210
+
211
+ def _ban(self, z):
212
+ if self.mask is not None and self.mask_any.get(z.shape[1], False):
213
+ z = z.index_fill(1, self.mask[z.shape[1]], float("-inf"))
214
+ return z
215
+
216
+ def _measure_w(self, z, pos):
217
+ """record measurement at absolute position pos (B,) + the next W-1 candidates of the same scores."""
218
+ z = self._ban(z)
219
+ rid = self._rid(pos)
220
+ Wc = max(self.W, self.Wobs)
221
+ if z.is_cuda:
222
+ from record import gumbel_topk
223
+ tk = gumbel_topk(z, rid, self.T, Wc)
224
+ d = tk[:, 0]
225
+ return d, (tk[:, 1:] if Wc > 1 else None)
226
+ d = measure(z, rid, self.T)
227
+ if Wc == 1:
228
+ return d, None
229
+ if self.T == 0:
230
+ sc = z.float()
231
+ else:
232
+ from record import gumbel_ref
233
+ V = z.shape[-1]
234
+ G = gumbel_ref(rid[:, None], torch.arange(V, device=z.device)[None]).float()
235
+ sc = z.float() / self.T + G
236
+ tk = sc.topk(Wc, -1).indices
237
+ keep = tk != d[:, None]
238
+ order = torch.argsort((~keep).int(), dim=1, stable=True)
239
+ return d, tk.gather(1, order)[:, :Wc - 1]
240
+
241
+ def _mtp_draft(self, hl, newl):
242
+ """hl (B, d): head output at the last catch-up row (position newl - 1); returns drafts (B, D) for positions
243
+ newl+1.., siblings (B, D, W-1) or None."""
244
+ m, B = self.m, self.B
245
+ ds, ss = [], []
246
+ d, sb = self._measure_w(Bk.LINEAR(hl, self.dhead), newl + 1)
247
+ ds.append(d)
248
+ ss.append(sb)
249
+ hp = hl
250
+ for i in range(2, self.D + 1):
251
+ c1 = RowCtx.tree(self.one, newl + (i - 2), B)
252
+ h1 = m.mtp.tree(d[:, None], hp, c1)
253
+ c1.set_accept(torch.zeros(B, dtype=torch.long, device=DEV))
254
+ m.mtp.commit(c1)
255
+ d, sb = self._measure_w(Bk.LINEAR(h1, self.dhead), newl + i)
256
+ ds.append(d)
257
+ ss.append(sb)
258
+ hp = h1
259
+ sib = torch.stack(ss, 1) if ss[0] is not None else None # (B, D, Wc-1)
260
+ if sib is not None and self.Wobs > 1:
261
+ self.cand[:, :self.D, :sib.shape[2]] = sib # counterfactual candidates for the online policy
262
+ return torch.stack(ds, 1), (sib[:, :, :self.W - 1].contiguous() if self.W > 1 else None)
263
+
264
+ def _draft_chain(self, ap, alen, bonus):
265
+ """draft model: commit the rows the target just processed (root..leaf, alen valid), then Dd tree passes
266
+ over [bonus, d1 .. d_{i-1}] from its committed state (never mutated by drafting -> no rollback needed)."""
267
+ dm, B = self.dm, self.B
268
+ lens0 = self.lens.clone()
269
+ ctx = RowCtx.tree(self.cu_shape, lens0, B)
270
+ dm.tree(self.tok.gather(1, ap), ctx)
271
+ ctx.set_accept((alen - 1).long())
272
+ dm.commit(ctx)
273
+ newl = lens0 + alen
274
+ seq = bonus[:, None]
275
+ for i in range(1, self.Dd + 1):
276
+ c = RowCtx.tree(self.dchains[i - 1], newl, B)
277
+ h = dm.tree(seq, c).view(B, i, -1)[:, -1]
278
+ d = measure(self._ban(dm.logits(h)), self._rid(newl.long() + i), self.T)
279
+ seq = torch.cat([seq, d[:, None]], 1)
280
+ self.tok[:, self.dr_rows[0]:self.dr_rows[0] + self.Dd] = seq[:, 1:]
281
+
282
+ def _draft_start(self, P, t0):
283
+ """prefill the draft model on the prompt (+ first token handled as root of pass 1)."""
284
+ dm = self.dm
285
+ dm.reset(0)
286
+ dm.prefill(P, b=0, keep_hidden=False)
287
+ L = P.shape[0]
288
+ newl = torch.full((self.B,), L, dtype=torch.int32, device=DEV)
289
+ seq = t0.view(1, 1)
290
+ for i in range(1, self.Dd + 1):
291
+ c = RowCtx.tree(self.dchains[i - 1], newl, self.B)
292
+ h = dm.tree(seq, c).view(self.B, i, -1)[:, -1]
293
+ d = measure(self._ban(dm.logits(h)), self._rid(newl.long() + i), self.T)
294
+ seq = torch.cat([seq, d[:, None]], 1)
295
+ self.tok[:, self.dr_rows[0]:self.dr_rows[0] + self.Dd] = seq[:, 1:]
296
+
297
+ def _write_drafts(self, drafts, sibs):
298
+ self.tok[:, 1:1 + self.D] = drafts
299
+ if sibs is not None:
300
+ self.tok[:, self.sib_rows[0]:self.sib_rows[0] + len(self.sib_rows)] = sibs.reshape(self.B, -1)
301
+
302
+ def _suffix_body(self, em, lens0, alen):
303
+ """in-graph whole-context suffix lookup for batch 1. The host dictionary version is exact but forces a
304
+ Python/CPU proposal update between replays; this scans at most 16k positions x SN tokens on GPU, which is
305
+ tiny next to a large-model pass and is captured in the same CUDA graph."""
306
+ H, C = self.histlen, self.C
307
+ j = torch.arange(self.ML, device=DEV)
308
+ validw = j < alen[0].long()
309
+ pos = (lens0[0].long() + 1 + j).clamp(0, H - 1)
310
+ old = self.hist[pos]
311
+ new = torch.where(validw, em[0], old)
312
+ self.hist[pos] = new
313
+ Lroot = lens0[0].long() + alen[0].long() # absolute position of the next root token
314
+ Lcur = Lroot + 1 # committed tokens occupy [0, Lcur)
315
+ ep = torch.arange(H, device=DEV)
316
+ coff = torch.arange(C, device=DEV)
317
+ best = torch.zeros(C, dtype=torch.long, device=DEV)
318
+ for n in range(1, self.SN + 1):
319
+ off = torch.arange(n, device=DEV)
320
+ tpos = (Lroot - n + 1 + off).clamp(0, H - 1)
321
+ target = self.hist[tpos]
322
+ spos = (ep[:, None] - n + off[None, :]).clamp(0, H - 1)
323
+ cand = self.hist[spos]
324
+ match = (cand == target[None, :]).all(1)
325
+ ok = match & (ep >= n) & (ep < Lcur) & (Lroot - n + 1 >= 0)
326
+ anyok = ok.any()
327
+ eend = torch.where(ok, ep, torch.zeros_like(ep)).max()
328
+ period = (Lcur - eend).clamp(min=1)
329
+ prop = self.hist[(eend + coff % period).clamp(0, H - 1)]
330
+ best = torch.where(anyok, prop, best)
331
+ s0 = self.suf_rows[0]
332
+ self.tok[0, s0:s0 + C] = best
333
+
334
+ def _echo_body(self, z, leaf, lens0, alen):
335
+ """in-graph echo fill: the source row is tensor-selected from this pass's tree, so next-pass echo drafting
336
+ costs no host synchronisation or eager launch stream (the original lane-I1 bottleneck)."""
337
+ B, E, EW = self.B, self.E, self.EW
338
+ if not hasattr(self, "_echo_rows_t"):
339
+ self._echo_rows_t = torch.tensor(self.echo_rows, device=DEV)
340
+ self._echo_sib_t = (torch.tensor([r for sb in self.echo_sib for r in sb], device=DEV) if EW > 1 else None)
341
+ self._echo_depth = torch.arange(1, E + 1, device=DEV)
342
+ dd = alen.long()[:, None] + self._echo_depth[None, :] - 1
343
+ valid = (dd >= 0) & (dd <= self.esrc_maxdep)
344
+ dc = dd.clamp(0, self.esrc_maxdep)
345
+ src = self.esrc_dense[leaf.long()[:, None], dc]
346
+ valid &= src >= 0
347
+ flat = torch.arange(B, device=DEV)[:, None] * self.N + src.clamp(min=0)
348
+ sc = z[flat].float()
349
+ sc = torch.where(valid[:, :, None], sc, torch.zeros_like(sc))
350
+ newl = lens0.long() + alen.long()
351
+ pos = newl[:, None] + self._echo_depth[None, :]
352
+ rid = ((self.uid_t[:, None] & 2047) * (1 << 21) + pos).reshape(-1).long()
353
+ from record import gumbel_topk
354
+ top = gumbel_topk(sc.reshape(B * E, -1), rid, self.T, EW).view(B, E, EW)
355
+ self.tok[:, self._echo_rows_t] = top[:, :, 0]
356
+ if self._echo_sib_t is not None:
357
+ self.tok[:, self._echo_sib_t] = top[:, :, 1:].reshape(B, -1)
358
+
359
+ def _mtp_chain(self, tok_next, hid, lens0, alen):
360
+ """catch-up rows (tok_next (B, ML), hid (B*ML, d)) at lens0, alen valid; then the draft chain."""
361
+ m, B = self.m, self.B
362
+ ctx = RowCtx.tree(self.cu_shape, lens0, B)
363
+ h = m.mtp.tree(tok_next, hid, ctx) # (B*ML, d)
364
+ leaf = (alen - 1).long()
365
+ ctx.set_accept(leaf)
366
+ m.mtp.commit(ctx)
367
+ hl = h.view(B, self.ML, -1)[torch.arange(B, device=DEV), leaf] # (B, d)
368
+ return self._mtp_draft(hl, lens0 + alen)
369
+
370
+ def _body(self):
371
+ m, B, N, T = self.m, self.B, self.N, self.T
372
+ lens0 = self.lens.clone()
373
+ ctx = RowCtx.tree(self.shape, self.lens, B)
374
+ h = m.tree(self.tok, ctx)
375
+ z = self._ban(m.logits(h))
376
+ if self.keepz: # keep this pass's logits for the next pass's echo drafts (graph-pool tensor on CUDA)
377
+ self.zlast = z
378
+ self.zlens = self.lens.clone()
379
+ pred = measure(z, self._rid(ctx.pos.reshape(-1) + 1), T).view(B, N)
380
+ par = ctx.par.long().clamp(min=0)
381
+ ok = self.tok == pred.gather(1, par)
382
+ ok[:, 0] = True
383
+ pok = ok.gather(1, ctx.paths.reshape(B, -1).long()).view(B, N, self.ML).all(-1)
384
+ score = pok.long() * ((self.shape.dep[None] + 1) * 4096) - torch.arange(N, device=DEV)[None]
385
+ leaf = score.argmax(1)
386
+ if self.keepz:
387
+ self.zleaf = leaf.clone()
388
+ ctx.set_accept(leaf)
389
+ bonus = pred.gather(1, leaf[:, None])[:, 0]
390
+ m.commit(ctx)
391
+ alen = ctx.acc_len
392
+ ap = ctx.acc_path.long() # (B, ML)
393
+ nxt = torch.cat([self.tok.gather(1, ap[:, 1:]), bonus[:, None]], 1) # (B, ML) candidates
394
+ j = torch.arange(self.ML, device=DEV)[None]
395
+ em = torch.where(j < (alen[:, None] - 1), nxt, bonus[:, None])
396
+ self.em.copy_(em)
397
+ self.alen.copy_(alen)
398
+ if self.D:
399
+ hsrc = h if self.mtp_hidden == "final" else m.xpre
400
+ hid = hsrc.view(B, N, -1).gather(1, ap[:, :, None].expand(-1, -1, hsrc.shape[-1])).reshape(B * self.ML, -1)
401
+ drafts, sibs = self._mtp_chain(em, hid, lens0, alen)
402
+ self._write_drafts(drafts, sibs)
403
+ if self.Dd:
404
+ self._draft_chain(ap, alen, bonus)
405
+ if self.J:
406
+ jr = self.jac_rows
407
+ jp = pred[:, jr[0]:jr[0] + self.J] # measurement at Jacobi row i (1-based) -> token at lens + i + 1
408
+ k = torch.arange(1, self.J + 1, device=DEV)[None]
409
+ src = alen.long()[:, None] + k - 2 # 0-based index of row i = a + k - 1
410
+ ok_ = src < self.J
411
+ self.tok[:, jr[0]:jr[0] + self.J] = torch.where(ok_, jp.gather(1, src.clamp(max=self.J - 1)), 0)
412
+ self.lens.add_(alen)
413
+ self.tok[:, 0] = bonus
414
+ if self.gsuf:
415
+ self._suffix_body(em, lens0, alen)
416
+ if self.E and CUDA:
417
+ self._echo_body(z, leaf, lens0, alen)
418
+
419
+ # ------------------------------------------------------------------ graph
420
+ def _blocks(self):
421
+ bl = list(self.m.blocks())
422
+ if self.dm is not None:
423
+ bl += list(self.dm.blocks())
424
+ return bl
425
+
426
+ def _save(self):
427
+ sv = [self.tok.clone(), self.lens.clone()]
428
+ for blk in self._blocks():
429
+ if hasattr(blk, "S"):
430
+ sv += [blk.S.clone(), blk.cs.clone()]
431
+ return sv
432
+
433
+ def _restore(self, sv):
434
+ self.tok.copy_(sv[0])
435
+ self.lens.copy_(sv[1])
436
+ i = 2
437
+ for blk in self._blocks():
438
+ if hasattr(blk, "S"):
439
+ blk.S.copy_(sv[i])
440
+ blk.cs.copy_(sv[i + 1])
441
+ i += 2
442
+
443
+ def capture(self, use_graph=True, compile=None):
444
+ """compile: None/False eager kernels; a torch.compile mode string fuses the elementwise glue (norms, RoPE,
445
+ gates, conv windows) between the GEMM / attention / recurrence kernels."""
446
+ compile = compile if compile is not None else COMPILE
447
+ body = self._body
448
+ if compile:
449
+ import torch._dynamo as _dyn
450
+ _dyn.config.cache_size_limit = 512
451
+ _dyn.config.accumulated_cache_size_limit = 4096
452
+ body = torch.compile(self._body, fullgraph=False, dynamic=False, mode=compile)
453
+ self._run = body
454
+ if not CUDA: # CPU: eager passes, no graphs
455
+ self.graph = None
456
+ return
457
+ sv = self._save()
458
+ s = torch.cuda.Stream()
459
+ s.wait_stream(torch.cuda.current_stream())
460
+ with torch.cuda.stream(s):
461
+ for _ in range(3 if compile else 2):
462
+ body()
463
+ torch.cuda.current_stream().wait_stream(s)
464
+ self._restore(sv)
465
+ if use_graph:
466
+ self.graph = torch.cuda.CUDAGraph()
467
+ with torch.cuda.graph(self.graph):
468
+ body()
469
+ self._restore(sv)
470
+ del sv
471
+
472
+ def prepare(self, prompt):
473
+ """capture the pass graph once (needs a prompt to size the warm-up state)."""
474
+ if self.graph is None:
475
+ self.start(prompt)
476
+ self.capture()
477
+
478
+ def step(self):
479
+ if self.graph is not None:
480
+ self.graph.replay()
481
+ else:
482
+ getattr(self, "_run", self._body)()
483
+ self.zok = True # zlast / zlens now hold this generation's pass (rewritten in place on graph replay)
484
+ self.zfrom = None
485
+
486
+ # ------------------------------------------------------------------ host loop
487
+ @torch.no_grad()
488
+ def start(self, prompt):
489
+ """Prefill user 0 with prompt (list of ids); sample the first token; prime MTP drafts."""
490
+ m, T = self.m, self.T
491
+ P = torch.tensor(prompt, dtype=torch.long, device=DEV)
492
+ L = len(prompt)
493
+ m.reset(0)
494
+ self.zok = False # echo estimates belong to the previous generation (tensors kept: CUDA graph-pool refs)
495
+ h = m.prefill(P, b=0, keep_hidden=self.D > 0)
496
+ z = self._ban(m.logits(h[-1:]))
497
+ t0 = measure(z, self._rid(torch.full((self.B,), L, device=DEV))[:1], T)
498
+ self.lens.fill_(L)
499
+ self.tok.zero_()
500
+ self.tok[:, 0] = t0
501
+ if self.D:
502
+ if self.mtp_hidden != "final":
503
+ raise NotImplementedError
504
+ nxt = torch.cat([P[1:], t0])
505
+ hl = m.mtp.prefill(nxt, h, b=0)
506
+ drafts, sibs = self._mtp_draft(hl, self.lens.clone())
507
+ self._write_drafts(drafts, sibs)
508
+ if self.Dd:
509
+ self._draft_start(P, t0)
510
+ self.out = [int(t0)]
511
+ self.suf = Suffix(self.SN)
512
+ self.suf.extend(list(prompt) + self.out)
513
+ if self.gsuf:
514
+ self.hist.zero_()
515
+ pp = torch.tensor(list(prompt) + self.out, dtype=torch.long, device=DEV)
516
+ self.hist[:pp.numel()] = pp
517
+ self._fill_suffix()
518
+ self._fill_echo()
519
+
520
+ def _fill_suffix(self):
521
+ if not self.C or (self.gsuf and CUDA and self.graph is not None):
522
+ return
523
+ prop, n = self.suf.propose(self.C)
524
+ row = np.zeros(self.C, dtype=np.int64)
525
+ if prop:
526
+ row[:len(prop)] = prop
527
+ self.tok[0, self.suf_rows[0]:self.suf_rows[0] + self.C].copy_(torch.from_numpy(row), non_blocking=True)
528
+
529
+ def _fill_echo(self):
530
+ if self.E and CUDA and self.graph is not None and self.zfrom is None:
531
+ return # captured into the pass graph by _echo_body; cross-shape handoff still needs one host fill
532
+ """Amplitude echo: draft row at depth d holds the token at absolute position lens + d. The previous pass
533
+ measured target logits z at the tree row whose position was lens + d - 1 (its own measurement was the
534
+ committed token, its logits the target's best estimate of this position). Re-measuring that estimate
535
+ under THIS position's record field G(rid) -- the field is deterministic and known in advance -- gives
536
+ argmax(z_hat/T + G): the proposal that maximises P(acceptance) under a point-estimate posterior on z.
537
+ Sibling rows take the next-best scores (EW candidates per depth). When no pass has covered the position
538
+ yet (zhat = 0) the T>0 guess is the pure-field maximum -- still a free, exact proposal."""
539
+ if not self.E:
540
+ return
541
+ from record import gumbel_ref
542
+ src = self.zfrom if self.zfrom is not None else self
543
+ V, E, EW = self.m.V, self.E, self.EW
544
+ have_z = src.zlast is not None and src.zlens is not None and src.zok
545
+ lens = self.lens.tolist()
546
+ if have_z:
547
+ zl = src.zlens.tolist()
548
+ zf = src.zleaf.tolist() if src.zleaf is not None else [0] * self.B
549
+ uids = self.uid_t.tolist()
550
+ ar = torch.arange(V, device=DEV)
551
+ rows_t = torch.tensor(self.echo_rows, device=DEV)
552
+ sib_t = torch.tensor([r for sb in self.echo_sib for r in sb], device=DEV) if EW > 1 else None
553
+ for b in range(self.B):
554
+ Lnew = lens[b]
555
+ idx, ok = [], []
556
+ for d in range(1, E + 1):
557
+ i = src.esrc[zf[b]].get(Lnew + d - 1 - zl[b]) if have_z else None
558
+ idx.append(b * src.N + (i if i is not None else 0))
559
+ ok.append(i is not None)
560
+ if any(ok):
561
+ sc = src.zlast[torch.tensor(idx, device=DEV)].float()
562
+ if not all(ok):
563
+ sc[~torch.tensor(ok, device=DEV)] = 0.0
564
+ else:
565
+ sc = torch.zeros(E, V, device=DEV)
566
+ if self.T != 0:
567
+ rid = torch.tensor([(uids[b] & 2047) * (1 << 21) + Lnew + d for d in range(1, E + 1)], device=DEV)
568
+ sc = sc / self.T + gumbel_ref(rid[:, None], ar[None, :]).float()
569
+ if self.mask is not None and self.mask_any.get(V, False):
570
+ sc = sc.index_fill(1, self.mask[V], float("-inf"))
571
+ top = sc.topk(EW, -1).indices # (E, EW)
572
+ self.tok[b, rows_t] = top[:, 0]
573
+ if sib_t is not None:
574
+ self.tok[b, sib_t] = top[:, 1:].reshape(-1)
575
+
576
+ @torch.no_grad()
577
+ def generate(self, prompt, n_out, on_tokens=None, stop_ids=()):
578
+ """on_tokens(list_of_new_ids) is called after every pass (streaming); generation stops at n_out tokens or
579
+ when a token in stop_ids is emitted (stop_ids=() for benchmarks: ignore EOS)."""
580
+ sync()
581
+ t0 = time.perf_counter()
582
+ self.start(prompt)
583
+ sync()
584
+ t1 = time.perf_counter()
585
+ passes, accs = 0, []
586
+ stop = set(stop_ids)
587
+ if on_tokens:
588
+ on_tokens(list(self.out))
589
+ while len(self.out) < n_out and not (stop and stop.intersection(self.out)):
590
+ self.step()
591
+ a = int(self.alen[0])
592
+ e = self.em[0, :a].tolist()
593
+ if on_tokens:
594
+ on_tokens(e)
595
+ self.out += e
596
+ if not self.gsuf:
597
+ self.suf.extend(e)
598
+ self._fill_suffix()
599
+ self._fill_echo()
600
+ passes += 1
601
+ accs.append(a)
602
+ sync()
603
+ t2 = time.perf_counter()
604
+ out = self.out[:n_out]
605
+ ntok = min(len(self.out), n_out) - 1
606
+ return {"out": out, "prefill_s": t1 - t0, "decode_s": t2 - t1, "passes": passes,
607
+ "tok_per_pass": ntok / max(passes, 1), "decode_tok_s": ntok / (t2 - t1), "acc_hist": accs}
608
+
609
+
610
+ class AdaptiveSpec:
611
+ """Generic online depth rule (no per-model tuning): one captured graph per MTP depth D in Ds (same W, C). After
612
+ every pass the accepted MTP depth updates per-depth conditional acceptance counts; p_i = P(draft i accepted | i-1
613
+ accepted) with a pseudo-count prior pulling depth i toward depth i-1's estimate. Pass times t(D) are measured
614
+ online (EMA). Next pass uses argmax_D (1 + sum_{d<=D} prod_{i<=d} p_i + s) / t(D), s = recent suffix gain.
615
+ Models without an MTP head degrade to one engine (suffix chain only)."""
616
+
617
+ def __init__(self, m, Ds=(1, 2, 3, 4, 5, 6), W=1, C=8, T=0.0, uid=0, prior=4.0):
618
+ Ds = list(Ds) if m.mtp is not None else [0]
619
+ self.E = {D: SpecEngine(m, D=D, C=C, W=W, T=T, uid=uid) for D in Ds}
620
+ self.Ds, self.m, self.T = Ds, m, T
621
+ self.Dmax = max(Ds)
622
+ self.hit = [0.0] * (self.Dmax + 2) # hit[i]: times draft i was accepted
623
+ self.tri = [0.0] * (self.Dmax + 2) # tri[i]: times draft i was offered with drafts 1..i-1 accepted
624
+ self.t = {D: None for D in Ds}
625
+ self.prior = prior
626
+ self.cur = Ds[min(2, len(Ds) - 1)]
627
+ self.log = []
628
+
629
+ def capture(self, prompt):
630
+ for E in self.E.values():
631
+ E.start(prompt)
632
+ E.capture()
633
+
634
+ def p(self):
635
+ ps, prev = [], 0.7
636
+ for i in range(1, self.Dmax + 1):
637
+ v = (self.hit[i] + self.prior * prev) / (self.tri[i] + self.prior)
638
+ ps.append(v)
639
+ prev = v
640
+ return ps
641
+
642
+ def choose(self):
643
+ ps = self.p()
644
+ best, arg = -1, self.cur
645
+ for D in self.Ds:
646
+ e, c = 1.0, 1.0
647
+ for i in range(D):
648
+ c *= ps[i]
649
+ e += c
650
+ t = self.t[D]
651
+ if t is None: # unmeasured: linear model from measured neighbours, else optimistic
652
+ known = [(d, x) for d, x in self.t.items() if x is not None]
653
+ if len(known) >= 2:
654
+ (d0, x0), (d1, x1) = sorted(known)[:1] + sorted(known)[-1:]
655
+ t = x0 + (x1 - x0) * (D - d0) / max(d1 - d0, 1)
656
+ elif known:
657
+ t = known[0][1] * (1 + 0.05 * (D - known[0][0]))
658
+ else:
659
+ t = 1.0
660
+ if e / t > best:
661
+ best, arg = e / t, D
662
+ return arg
663
+
664
+ def _switch(self, a, b):
665
+ Ea, Eb = self.E[a], self.E[b]
666
+ Eb.lens.copy_(Ea.lens)
667
+ Eb.tok.zero_()
668
+ Eb.tok[:, 0] = Ea.tok[:, 0]
669
+ k = min(a, b)
670
+ if k:
671
+ Eb.tok[:, 1:1 + k] = Ea.tok[:, 1:1 + k]
672
+ Eb.out, Eb.suf = Ea.out, Ea.suf
673
+
674
+ @torch.no_grad()
675
+ def generate(self, prompt, n_out):
676
+ E = self.E[self.cur]
677
+ sync()
678
+ t0 = time.perf_counter()
679
+ E.start(prompt)
680
+ E._last_drafts = E.tok[0, 1:1 + self.cur].tolist() if self.cur else []
681
+ sync()
682
+ t1 = time.perf_counter()
683
+ passes, hist = 0, []
684
+ while len(E.out) < n_out:
685
+ ts = time.perf_counter()
686
+ E.step()
687
+ a = int(E.alen[0])
688
+ leaf_path = E.em # noqa
689
+ e = E.em[0, :a].tolist()
690
+ te = time.perf_counter() - ts
691
+ D = self.cur
692
+ # accepted MTP-chain depth: the leaf is on the MTP main chain iff the emitted drafts equal its rows
693
+ md = 0
694
+ if D:
695
+ drafts = E._last_drafts
696
+ for i in range(min(a - 1, D)):
697
+ if drafts[i] == e[i]:
698
+ md += 1
699
+ else:
700
+ break
701
+ for i in range(1, D + 1):
702
+ if i <= md + 1:
703
+ self.tri[i] += 1
704
+ if i <= md:
705
+ self.hit[i] += 1
706
+ self.t[D] = te if self.t[D] is None else 0.8 * self.t[D] + 0.2 * te
707
+ E.out += e
708
+ E.suf.extend(e)
709
+ nD = self.choose() if D else D
710
+ if nD != D:
711
+ self._switch(D, nD)
712
+ E = self.E[nD]
713
+ self.cur = nD
714
+ E._last_drafts = E.tok[0, 1:1 + nD].tolist() if nD else []
715
+ E._fill_suffix()
716
+ E._fill_echo()
717
+ passes += 1
718
+ hist.append((D, a))
719
+ sync()
720
+ t2 = time.perf_counter()
721
+ ntok = min(len(E.out), n_out) - 1
722
+ return {"out": E.out[:n_out], "prefill_s": t1 - t0, "decode_s": t2 - t1, "passes": passes,
723
+ "tok_per_pass": ntok / max(passes, 1), "decode_tok_s": ntok / (t2 - t1), "hist": hist,
724
+ "p": self.p(), "t_ms": {d: (x or 0) * 1e3 for d, x in self.t.items()}}
725
+
726
+
727
+ class OnlineTree:
728
+ """THE GENERIC TREE RULE (no per-model tuning). Candidate shapes: MTP depth D in Ds x siblings W in Ws (+ the
729
+ suffix chain C and Jacobi chain J, fixed). One CUDA graph per shape, each timed once at capture on this GPU
730
+ (t(D, W): a hardware calibration, not a model fit). Online, from every pass's exact emitted tokens (which are the
731
+ target's own measurements at every depth they cover, whichever branch was accepted):
732
+ p_d = P(main draft at depth d correct | depths < d correct) (Beta prior toward p_{d-1})
733
+ s_d,k = P(true token = rank-k candidate | main wrong at depth d) (prior s_{d,k-1} / 2 when unseen)
734
+ E(D, W) = 1 + sum_{d<=D} prod_{i<d} p_i * (p_d + (1 - p_d) * sum_{k=2..W} s_{d,k}); next shape = argmax E / t.
735
+ Models without an MTP head: one shape (suffix + Jacobi chains)."""
736
+
737
+ def __init__(self, m, Ds=(2, 3, 4, 5, 6), Ws=(1, 2, 3), C=8, J=0, T=0.0, uid=0, prior=4.0, dvocab=None,
738
+ start=(3, 2), Cs=None, mask_ids=(), E=0, EW=1, Es=None, SN=4, in_graph_suffix=False):
739
+ if m.mtp is None:
740
+ Ds, Ws = (0,), (1,)
741
+ Cs = tuple(Cs) if Cs else ((0, C) if C else (0,))
742
+ C = max(Cs)
743
+ # echo chain lengths: by default the rule decides per pass whether the echo rows pay for themselves
744
+ Es = tuple(Es) if Es is not None else ((0, E) if E else (0,))
745
+ self.cfgs = [(D, W, c, e) for D in Ds for W in Ws for c in Cs for e in Es]
746
+ self.E = {c: SpecEngine(m, D=c[0], W=c[1], C=c[2], J=J, T=T, uid=uid, dvocab=dvocab, Wobs=max(Ws),
747
+ mask_ids=mask_ids, E=c[3], EW=EW, SN=SN, in_graph_suffix=in_graph_suffix)
748
+ for c in self.cfgs}
749
+ if max(Es):
750
+ for e in self.E.values():
751
+ e.keepz = True
752
+ # echo value: EMA of the tokens the echo chain reaches beyond the MTP tree on passes that place it
753
+ # (optimistic start); re-explored when no echo shape ran for 16 passes
754
+ self.egain = 2.0
755
+ self.elast = 0
756
+ self.npass = 0
757
+ # suffix-chain value, learned per (suffix length C, lookup match length n): EMA of the extra tokens it adds;
758
+ # optimistic start + every 8th matched pass explores the suffix rows (the value is otherwise never re-learned)
759
+ self.sgain = {(c, n): 2.0 for c in Cs for n in range(0, 9)}
760
+ self.nmatch = 0
761
+ self.mlen = 0
762
+ self.m, self.T, self.C = m, T, C
763
+ self.Dmax, self.Wmax = max(Ds), max(Ws)
764
+ self.hit = [0.0] * (self.Dmax + 2)
765
+ self.tri = [0.0] * (self.Dmax + 2)
766
+ self.miss = [0.0] * (self.Dmax + 2)
767
+ self.rk = [[0.0] * (self.Wmax + 2) for _ in range(self.Dmax + 2)]
768
+ self.prior = prior
769
+ st = (start[0], start[1], 0, max(Es))
770
+ self.cur = st if st in self.E else self.cfgs[0]
771
+ self.t = {}
772
+ self.N = max(e.N for e in self.E.values())
773
+ self.D, self.W = "online", "online"
774
+ self.h = 0.0
775
+ self.he = {e: 0.0 for e in Es} # host overhead per pass by echo length (echo fill runs on the host)
776
+
777
+ @staticmethod
778
+ def key(c):
779
+ return f"D{c[0]}W{c[1]}C{c[2]}" + (f"E{c[3]}" if c[3] else "")
780
+
781
+ def prepare(self, prompt):
782
+ if not self.t:
783
+ self.capture(prompt)
784
+
785
+ @property
786
+ def uid(self):
787
+ return next(iter(self.E.values())).uid
788
+
789
+ @uid.setter
790
+ def uid(self, v):
791
+ for E in self.E.values():
792
+ E.uid = v
793
+
794
+ def capture(self, prompt, reps=4):
795
+ """capture every shape and time it at several committed lengths (timing depends on the length only, not on
796
+ the cache content, so no long prefill is needed): t(c, L) is interpolated linearly in L."""
797
+ smax = self.m.layers[0].mix.smax if hasattr(self.m.layers[0].mix, "smax") else 4096
798
+ for L in self.m.layers:
799
+ if hasattr(L.mix, "smax"):
800
+ smax = L.mix.smax
801
+ break
802
+ top = max(64, smax - 64 - max(e.ML for e in self.E.values()))
803
+ self.Lgrid = sorted({len(prompt), min(top, 2048), min(top, 8192), top})
804
+ self.tL = {}
805
+ for c, E in self.E.items():
806
+ E.start(prompt)
807
+ E.capture()
808
+ sv = E._save()
809
+ ts = []
810
+ for Lg in self.Lgrid:
811
+ E.lens.fill_(Lg)
812
+ E.step()
813
+ sync()
814
+ t0 = time.perf_counter()
815
+ for _ in range(reps):
816
+ E.lens.fill_(Lg)
817
+ E.step()
818
+ sync()
819
+ ts.append((time.perf_counter() - t0) / reps)
820
+ E._restore(sv)
821
+ self.tL[c] = ts
822
+ self.t[c] = ts[0]
823
+ del sv
824
+
825
+ def t_at(self, c, L):
826
+ g, ts = self.Lgrid, self.tL[c]
827
+ if L <= g[0]:
828
+ return ts[0]
829
+ for i in range(1, len(g)):
830
+ if L <= g[i]:
831
+ f = (L - g[i - 1]) / max(g[i] - g[i - 1], 1)
832
+ return ts[i - 1] + f * (ts[i] - ts[i - 1])
833
+ return ts[-1]
834
+
835
+ def p(self):
836
+ ps, prev = [], 0.7
837
+ for d in range(1, self.Dmax + 1):
838
+ v = (self.hit[d] + self.prior * prev) / (self.tri[d] + self.prior)
839
+ ps.append(v)
840
+ prev = v
841
+ return ps
842
+
843
+ def s(self, d):
844
+ out, prev = [], 0.3
845
+ for k in range(2, self.Wmax + 1):
846
+ v = (self.rk[d][k] + self.prior * prev) / (self.miss[d] + self.prior)
847
+ out.append(v)
848
+ prev = v / 2
849
+ return out
850
+
851
+ def best(self, match, n=0, L=0):
852
+ """argmax over shapes of E(D, W, C) / (t(D, W, C) + h); h = measured host overhead per pass (EMA);
853
+ suffix rows (C > 0) only when the whole-context lookup has a match this pass, valued at the learned gain."""
854
+ ps = self.p()
855
+ ss = [None] + [self.s(d) for d in range(1, self.Dmax + 1)]
856
+ bestv, arg = -1.0, self.cur
857
+ for c in self.cfgs:
858
+ D, W, Cc, Ec = c
859
+ if Cc and not match:
860
+ continue
861
+ e, reach = 1.0, 1.0
862
+ for d in range(1, D + 1):
863
+ pd = ps[d - 1]
864
+ sd = sum(ss[d][:W - 1])
865
+ e += reach * (pd + (1 - pd) * min(sd, 1.0))
866
+ reach *= pd
867
+ if Cc:
868
+ e += self.sgain[(Cc, min(n, 8))] + (100.0 if self.nmatch % 8 == 0 else 0.0)
869
+ if Ec:
870
+ e += self.egain + (100.0 if self.npass - self.elast >= 16 else 0.0)
871
+ v = e / (self.t_at(c, L) + self.he.get(Ec, self.h))
872
+ if v > bestv:
873
+ bestv, arg = v, c
874
+ return arg
875
+
876
+ def _switch(self, a, b):
877
+ Ea, Eb = self.E[a], self.E[b]
878
+ Eb.lens.copy_(Ea.lens)
879
+ Eb.tok.zero_()
880
+ Eb.tok[:, 0] = Ea.tok[:, 0]
881
+ k = min(a[0], b[0])
882
+ if k:
883
+ Eb.tok[:, 1:1 + k] = Ea.tok[:, 1:1 + k]
884
+ Eb.cand[:, :k] = Ea.cand[:, :k]
885
+ if a[1] == b[1] and a[1] > 1: # same sibling width: keep the sibling rows of the shared depths
886
+ w1 = a[1] - 1
887
+ Eb.tok[:, Eb.sib_rows[0]:Eb.sib_rows[0] + k * w1] = Ea.tok[:, Ea.sib_rows[0]:Ea.sib_rows[0] + k * w1]
888
+ if Ea.J and Eb.J:
889
+ Eb.tok[:, Eb.jac_rows[0]:Eb.jac_rows[0] + Eb.J] = Ea.tok[:, Ea.jac_rows[0]:Ea.jac_rows[0] + Ea.J]
890
+ Eb.out, Eb.suf = Ea.out, Ea.suf
891
+ if Ea.gsuf and Eb.gsuf:
892
+ Eb.hist.copy_(Ea.hist)
893
+ if Eb.E: # echo drafts of the next pass come from the pass that just ran (Ea's rows / logits)
894
+ Eb.zfrom = Ea
895
+
896
+ def _learn_sfx(self, E, prev, cand, e):
897
+ """extra tokens beyond what the MTP tree reached = the suffix chain's contribution this pass."""
898
+ D, W = E.D, E.W
899
+ a = len(e)
900
+ reach = 0
901
+ for d in range(1, min(D, a - 1) + 1):
902
+ if prev[d] == e[d - 1]:
903
+ reach = d
904
+ continue
905
+ if W > 1 and e[d - 1] in [prev[r] for r in E.sib_rows[(d - 1) * (W - 1):d * (W - 1)]]:
906
+ reach = d
907
+ break
908
+ ereach = 0 # echo chain's deepest accepted depth: its tokens are not the suffix chain's gain
909
+ if getattr(E, "E", 0):
910
+ for d in range(1, min(E.E, a - 1) + 1):
911
+ if e[d - 1] == prev[E.echo_rows[d - 1]]:
912
+ ereach = d
913
+ continue
914
+ if e[d - 1] in {prev[s] for s in E.echo_sib[d - 1]}:
915
+ ereach = d
916
+ break
917
+ g = max(0, (a - 1) - max(reach, ereach))
918
+ k = (E.C, min(self.mlen, 8))
919
+ self.sgain[k] = 0.8 * self.sgain[k] + 0.2 * g
920
+
921
+ def _learn_echo(self, E, prev, cand, e):
922
+ """extra tokens the echo chain reached beyond the MTP tree this pass."""
923
+ a = len(e)
924
+ reach = 0
925
+ for d in range(1, min(E.D, a - 1) + 1):
926
+ sib = [prev[r] for r in E.sib_rows[(d - 1) * (E.W - 1):d * (E.W - 1)]] # rows actually placed this pass
927
+ if prev[d] == e[d - 1] or (E.W > 1 and e[d - 1] in sib):
928
+ reach = d
929
+ if prev[d] == e[d - 1]:
930
+ continue
931
+ break
932
+ ereach = 0
933
+ for d in range(1, min(E.E, a - 1) + 1):
934
+ if e[d - 1] == prev[E.echo_rows[d - 1]] or e[d - 1] in {prev[s] for s in E.echo_sib[d - 1]}:
935
+ ereach = d
936
+ if e[d - 1] == prev[E.echo_rows[d - 1]]:
937
+ continue
938
+ break
939
+ self.egain = 0.8 * self.egain + 0.2 * max(0, ereach - reach)
940
+ self.elast = self.npass
941
+
942
+ def _learn(self, E, prev, cand, e):
943
+ """prev: this pass's tree tokens; cand[d-1]: the rank-2.. candidates at depth d (observed for every Ws
944
+ even when not placed in the tree); e: the exact emitted tokens (true tokens at depths 1..len(e))."""
945
+ D = E.D
946
+ a = len(e)
947
+ for d in range(1, min(D, a) + 1):
948
+ self.tri[d] += 1
949
+ if prev[d] == e[d - 1]:
950
+ self.hit[d] += 1
951
+ continue
952
+ self.miss[d] += 1
953
+ sibs = cand[d - 1]
954
+ if e[d - 1] in sibs:
955
+ self.rk[d][2 + sibs.index(e[d - 1])] += 1
956
+ break
957
+
958
+ def _agree(self, c):
959
+ """SPMD tensor parallel: every rank takes rank 0's shape (timings are local; shapes differ in row count and
960
+ hence in their collectives)."""
961
+ dist = torch.distributed
962
+ if not (dist.is_available() and dist.is_initialized()) or dist.get_world_size() == 1:
963
+ return c
964
+ keys = list(self.E) if isinstance(self.E, dict) else list(range(len(self.E)))
965
+ t = torch.tensor([keys.index(c)], device="cuda" if CUDA else "cpu")
966
+ dist.broadcast(t, 0)
967
+ return keys[int(t)]
968
+
969
+ @torch.no_grad()
970
+ def generate(self, prompt, n_out, on_tokens=None, stop_ids=()):
971
+ E = self.E[self.cur]
972
+ sync()
973
+ t0 = time.perf_counter()
974
+ E.start(prompt)
975
+ sync()
976
+ t1 = time.perf_counter()
977
+ passes, hist = 0, []
978
+ stop = set(stop_ids)
979
+ if on_tokens:
980
+ on_tokens(list(E.out))
981
+ pend = None
982
+ while len(E.out) < n_out and not (stop and stop.intersection(E.out)):
983
+ tp = time.perf_counter()
984
+ if pend is not None:
985
+ hh = max(tp - pend[0] - self.t_at(pend[1], pend[2]), 0.0)
986
+ self.h = 0.9 * self.h + 0.1 * hh
987
+ self.he[pend[3]] = 0.9 * self.he[pend[3]] + 0.1 * hh
988
+ prev = E.tok[0].tolist()
989
+ cand = E.cand[0].tolist()
990
+ E.step()
991
+ a = int(E.alen[0])
992
+ e = E.em[0, :a].tolist()
993
+ if on_tokens:
994
+ on_tokens(e)
995
+ self._learn(E, prev, cand, e)
996
+ if E.C:
997
+ self._learn_sfx(E, prev, cand, e)
998
+ if E.E:
999
+ self._learn_echo(E, prev, cand, e)
1000
+ Lnow = int(E.lens[0]) if CUDA else len(E.out)
1001
+ pend = (tp, self.cur, Lnow, E.E) # host cost = whole loop period (incl. this pass's suffix/echo drafting)
1002
+ self.npass += 1
1003
+ E.out += e
1004
+ E.suf.extend(e)
1005
+ prop, nm = E.suf.propose(self.C) if self.C else ([], 0)
1006
+ if prop:
1007
+ self.nmatch += 1
1008
+ self.mlen = nm
1009
+ nc = self._agree(self.best(bool(prop), nm, Lnow))
1010
+ hist.append((self.cur, a))
1011
+ if nc != self.cur:
1012
+ self._switch(self.cur, nc)
1013
+ self.cur = nc
1014
+ E = self.E[nc]
1015
+ E._fill_suffix()
1016
+ E._fill_echo()
1017
+ passes += 1
1018
+ sync()
1019
+ t2 = time.perf_counter()
1020
+ ntok = min(len(E.out), n_out) - 1
1021
+ cnt = {}
1022
+ for c, _ in hist:
1023
+ k = self.key(c)
1024
+ cnt[k] = cnt.get(k, 0) + 1
1025
+ return {"out": E.out[:n_out], "prefill_s": t1 - t0, "decode_s": t2 - t1, "passes": passes,
1026
+ "tok_per_pass": ntok / max(passes, 1), "decode_tok_s": ntok / (t2 - t1), "hist": hist,
1027
+ "p": self.p(), "t_ms": {self.key(c): [round(x * 1e3, 2) for x in v] for c, v in self.tL.items()},
1028
+ "Lgrid": self.Lgrid,
1029
+ "sgain": self.sgain, "egain": self.egain, "h_ms": self.h * 1e3,
1030
+ "he_ms": {e: v * 1e3 for e, v in self.he.items()}, "shape_counts": cnt}