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.
- package/LICENSE +9 -0
- package/README.md +96 -2
- package/bin/quantuminfer.js +61 -0
- package/c27/adapters.py +161 -0
- package/c27/harness27.py +349 -0
- package/data/input.txt +40000 -0
- package/data/wikitext/test.txt +7249 -0
- package/engine/API.txt +208 -0
- package/engine/PLUGINS.txt +4 -0
- package/engine/__init__.py +82 -0
- package/engine/adapter.py +505 -0
- package/engine/blocks.py +1180 -0
- package/engine/c12.py +324 -0
- package/engine/c12cu.py +1074 -0
- package/engine/ctx.py +87 -0
- package/engine/dev.py +11 -0
- package/engine/ds4.py +389 -0
- package/engine/kernels.py +833 -0
- package/engine/model.py +281 -0
- package/engine/record.py +140 -0
- package/engine/server.py +183 -0
- package/engine/spec.py +1030 -0
- package/engine/wcode.py +122 -0
- package/p27/SPEC.txt +66 -0
- package/p27/STATUS.txt +91 -0
- package/p27/bench_glm.py +354 -0
- package/p27/bench_multi.py +76 -0
- package/p27/mkfinal.py +98 -0
- package/p27/modal_comp.py +173 -0
- package/p27/modal_dl.py +63 -0
- package/p27/modal_p27.py +168 -0
- package/p27/modal_probe.py +49 -0
- package/p27/p27rules.py +29 -0
- package/p27/pblocks.py +1242 -0
- package/p27/pmodel.py +402 -0
- package/p27/pref.py +151 -0
- package/p27/prof_glm.py +34 -0
- package/p27/quant.py +850 -0
- package/p27/recipes/vllm_b300_single_node_tep_b300_agentx_ep.md +353 -0
- package/p27/recipes/vllm_b300_single_node_tp_b300_agentx.md +351 -0
- package/p27/recipes/vllm_b300_single_node_tp_baseline.md +250 -0
- package/p27/recipes/vllm_default_gb300.md +281 -0
- package/p27/recipes/vllm_glm53_h200.md +301 -0
- package/p27/run_window1.sh +21 -0
- package/p27/run_window2.sh +13 -0
- package/p27/sweep_glm.py +64 -0
- package/p27/t_align.py +42 -0
- package/p27/t_combine.py +28 -0
- package/p27/t_echo.py +31 -0
- package/p27/t_fp8dense.py +59 -0
- package/p27/t_fp8speed.py +48 -0
- package/p27/t_glm.py +340 -0
- package/p27/t_glu.py +30 -0
- package/p27/t_gsuf.py +23 -0
- package/p27/t_jac.py +22 -0
- package/p27/t_moebm.py +30 -0
- package/p27/t_nccl.py +36 -0
- package/p27/t_online_jac.py +31 -0
- package/p27/t_probe.py +4 -0
- package/p27/t_router.py +28 -0
- package/p27/t_symm.py +50 -0
- package/p27/t_tiny.py +116 -0
- package/package.json +10 -4
- package/results/ANALYSIS.md +156 -0
- package/results/comp_vllm_mtp_k5_b300mtp.json +235 -0
- package/results/glm53_b300x8_opt4.json +624 -0
- package/results/res_glm_c32w3_b300.json +638 -0
- package/results/res_glm_final_c32_b300.json +652 -0
- package/results/res_glm_multi_final_b300.json +1821 -0
- package/results/res_glm_online_b300.json +638 -0
- package/results/res_glm_online_fixed_b300.json +638 -0
- package/results/res_glm_opt4_b300.json +624 -0
- package/results/res_glm_text_plain_batch_b300.json +5792 -0
- package/results/res_glm_text_w1_b300.json +1635 -0
- package/results/res_glm_text_w3_b300.json +1639 -0
- package/results/res_sweep_echo_b300.json +129 -0
- package/results/res_sweep_final_b300.json +153 -0
- package/results/res_sweep_glm_b300.json +153 -0
- package/results/res_techo.json +29 -0
- package/results/res_tgsuf.json +21 -0
- package/results/res_tjac.json +17 -0
- package/results/res_tonline_jac.json +13 -0
package/engine/model.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""Generic decoder model assembled from adapter spec + block registry. No model-specific code."""
|
|
2
|
+
import torch
|
|
3
|
+
import torch.nn.functional as F
|
|
4
|
+
|
|
5
|
+
import blocks as Bk
|
|
6
|
+
from adapter import build_spec
|
|
7
|
+
from ctx import RowCtx
|
|
8
|
+
from dev import DEV, CUDA, sync # noqa: F401
|
|
9
|
+
|
|
10
|
+
BF = torch.bfloat16
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _nb(w):
|
|
14
|
+
return w.numel() * w.element_size() if isinstance(w, torch.Tensor) else w.nbytes()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
FUSED = CUDA # fused residual-add + RMSNorm (kernels.rms_fused); False = plain torch ops (reference path)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Layer:
|
|
21
|
+
def __init__(self, L, W, g):
|
|
22
|
+
self.n1 = W.get(L["norm1"]) if L.get("norm1") else None
|
|
23
|
+
self.n2 = W.get(L["norm2"]) if L.get("norm2") else None
|
|
24
|
+
self.p1 = W.get(L["post1"]) if L.get("post1") else None # post-sublayer norms (Gemma 2/3, OLMo 2)
|
|
25
|
+
self.p2 = W.get(L["post2"]) if L.get("post2") else None
|
|
26
|
+
self.rm = float(L.get("resid_mult", 1.0)) # Granite residual_multiplier
|
|
27
|
+
self.par = bool(L.get("parallel")) # Cohere: x + mix(n1(x)) + mlp(n1(x))
|
|
28
|
+
self.ln = g.get("norm_type") == "layer"
|
|
29
|
+
bias = {n[:-len("bias")] + "weight": W.get(n) for n in L.get("extra", ())}
|
|
30
|
+
self.nb = {id(w): bias.get(L.get(k)) for k, w in (("norm1", self.n1), ("norm2", self.n2),
|
|
31
|
+
("post1", self.p1), ("post2", self.p2)) if w is not None}
|
|
32
|
+
self.hc = None
|
|
33
|
+
if L.get("hc"): # hyper-connection residual streams (DeepSeek-V4): x is (R, hc_mult, d)
|
|
34
|
+
from ds4 import HyperConn
|
|
35
|
+
h = L["hc"]
|
|
36
|
+
self.hc = [HyperConn(W, h[k], h["n"], h["iters"], h["eps"], g["eps"]) for k in ("attn", "ffn")]
|
|
37
|
+
self.plain = self.hc is None and (self.n1 is not None and self.n2 is not None and self.p1 is None and self.p2 is None
|
|
38
|
+
and self.rm == 1.0 and not self.par and not self.ln)
|
|
39
|
+
self.mix = Bk.make(L["mixer"], W, g)
|
|
40
|
+
self.mlp = Bk.make(L["mlp"], W, g)
|
|
41
|
+
self.eps, self.off = g["eps"], g["norm_offset"]
|
|
42
|
+
self.g = g
|
|
43
|
+
|
|
44
|
+
def run_fused(self, x, pend, ctx, fn):
|
|
45
|
+
"""x (R, d) residual stream, updated IN PLACE (x += pend, x += mixer out); returns the pending MLP output.
|
|
46
|
+
Residual add + RMSNorm are one kernel (kernels.rms_fused), same bf16 roundings as the unfused path."""
|
|
47
|
+
if not self.plain: # non pre-norm layer: unfused, x updated in place, nothing pending
|
|
48
|
+
if pend is not None:
|
|
49
|
+
x += pend
|
|
50
|
+
x.copy_(self.run(x, ctx, fn))
|
|
51
|
+
return None
|
|
52
|
+
from kernels import rms_fused
|
|
53
|
+
h = rms_fused(x, self.n1, self.eps, self.off, y=pend)
|
|
54
|
+
y = Bk.ALLREDUCE(getattr(self.mix, fn)(h, ctx), self.g)
|
|
55
|
+
h2 = rms_fused(x, self.n2, self.eps, self.off, y=y)
|
|
56
|
+
return Bk.ALLREDUCE(self.mlp(h2), self.g)
|
|
57
|
+
|
|
58
|
+
def _n(self, t, w):
|
|
59
|
+
if w is None:
|
|
60
|
+
return t
|
|
61
|
+
if self.ln:
|
|
62
|
+
return Bk.layer_norm(t, w, self.nb.get(id(w)), self.eps)
|
|
63
|
+
return Bk.rms(t, w, self.eps, self.off)
|
|
64
|
+
|
|
65
|
+
def run(self, x, ctx, fn):
|
|
66
|
+
if self.hc:
|
|
67
|
+
x = self.hc[0](x, lambda h: Bk.ALLREDUCE(getattr(self.mix, fn)(self._n(h, self.n1), ctx), self.g))
|
|
68
|
+
return self.hc[1](x, lambda h: Bk.ALLREDUCE(self.mlp(self._n(h, self.n2)), self.g))
|
|
69
|
+
if self.par:
|
|
70
|
+
h = self._n(x, self.n1)
|
|
71
|
+
a = Bk.ALLREDUCE(getattr(self.mix, fn)(h, ctx), self.g)
|
|
72
|
+
return x + a + Bk.ALLREDUCE(self.mlp(h), self.g)
|
|
73
|
+
y = self._n(Bk.ALLREDUCE(getattr(self.mix, fn)(self._n(x, self.n1), ctx), self.g), self.p1)
|
|
74
|
+
x = x + (y * self.rm if self.rm != 1.0 else y)
|
|
75
|
+
y = self._n(Bk.ALLREDUCE(self.mlp(self._n(x, self.n2)), self.g), self.p2)
|
|
76
|
+
return x + (y * self.rm if self.rm != 1.0 else y)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Model:
|
|
80
|
+
"""B users, Smax positions. hidden_mode: which hidden the MTP head consumes ('final' = after the final norm)."""
|
|
81
|
+
|
|
82
|
+
def __init__(self, path, B=1, smax=4096, load_mtp=True, skip=(), tp=None):
|
|
83
|
+
spec, W = build_spec(path)
|
|
84
|
+
self.spec, self.path = spec, path
|
|
85
|
+
self.g = {"eps": spec["eps"], "norm_offset": spec["norm_offset"], "norm_type": spec.get("norm_type", "rms"),
|
|
86
|
+
"tp": tp or {"rank": 0, "world": 1, "group": None}}
|
|
87
|
+
self.embed = W.get(spec["embed"])
|
|
88
|
+
self.head = W.get(spec["head"]) if spec["head"] != spec["embed"] else self.embed
|
|
89
|
+
self.fnorm = W.get(spec["final_norm"])
|
|
90
|
+
self.escale = float(spec.get("embed_scale", 1.0)) # Gemma sqrt(d) / Granite embedding_multiplier
|
|
91
|
+
self.ldiv = float(spec.get("logit_div", 1.0)) # Granite logits_scaling
|
|
92
|
+
self.lcap = spec.get("logit_softcap") # Gemma 2 final_logit_softcapping
|
|
93
|
+
self.lmult = float(spec.get("logit_mult", 1.0)) # Cohere logit_scale
|
|
94
|
+
self.lnorm = spec.get("norm_type") == "layer"
|
|
95
|
+
self.fnorm_b = W.get(spec["final_norm_bias"]) if spec.get("final_norm_bias") else None
|
|
96
|
+
self.layers = [Layer(L, W, self.g) for L in spec["layers"]]
|
|
97
|
+
self.hch = None
|
|
98
|
+
if spec.get("hc_head"):
|
|
99
|
+
from ds4 import HyperConn
|
|
100
|
+
h = spec["hc_head"]
|
|
101
|
+
self.hch = HyperConn(W, h["prefix"], h["n"], 0, h["eps"], self.g["eps"], head=True)
|
|
102
|
+
self.mtp = MTPHead(spec["mtp"], W, self) if (load_mtp and "mtp" in spec) else None
|
|
103
|
+
W.close()
|
|
104
|
+
torch.cuda.empty_cache()
|
|
105
|
+
self.d, self.V = spec["d"], spec["vocab"]
|
|
106
|
+
self.alloc(B, smax)
|
|
107
|
+
|
|
108
|
+
def alloc(self, B, smax):
|
|
109
|
+
self.B, self.smax = B, smax
|
|
110
|
+
for L in self.layers:
|
|
111
|
+
L.mix.alloc(B, smax)
|
|
112
|
+
if self.mtp:
|
|
113
|
+
self.mtp.alloc(B, smax)
|
|
114
|
+
|
|
115
|
+
def reset(self, b=None):
|
|
116
|
+
for L in self.layers:
|
|
117
|
+
L.mix.reset(b)
|
|
118
|
+
if self.mtp:
|
|
119
|
+
for L in self.mtp.layers:
|
|
120
|
+
L.mix.reset(b)
|
|
121
|
+
|
|
122
|
+
def blocks(self):
|
|
123
|
+
return [L.mix for L in self.layers]
|
|
124
|
+
|
|
125
|
+
def weight_bytes(self):
|
|
126
|
+
n = _nb(self.embed) + (_nb(self.head) if self.head is not self.embed else 0) + _nb(self.fnorm)
|
|
127
|
+
for L in self.layers:
|
|
128
|
+
n += sum(_nb(w) for w in L.mix.weights().values()) + sum(_nb(w) for w in L.mlp.weights().values())
|
|
129
|
+
return n
|
|
130
|
+
|
|
131
|
+
def state_bytes(self):
|
|
132
|
+
return sum(L.mix.state_bytes() for L in self.layers)
|
|
133
|
+
|
|
134
|
+
def final(self, x):
|
|
135
|
+
if self.lnorm:
|
|
136
|
+
return Bk.layer_norm(x, self.fnorm, self.fnorm_b, self.g["eps"])
|
|
137
|
+
return Bk.rms(x, self.fnorm, self.g["eps"], self.g["norm_offset"])
|
|
138
|
+
|
|
139
|
+
def draft_head(self, n):
|
|
140
|
+
"""LM head restricted to token ids [0, n) for proposers (cached; a view when the head is bf16)."""
|
|
141
|
+
c = getattr(self, "_dheads", {})
|
|
142
|
+
self._dheads = c
|
|
143
|
+
if n not in c:
|
|
144
|
+
if isinstance(self.head, torch.Tensor):
|
|
145
|
+
c[n] = self.head[:n]
|
|
146
|
+
else: # coded head: decode row blocks (a full decode needs ~10 GB of temporaries)
|
|
147
|
+
import wcode
|
|
148
|
+
c[n] = wcode.C12Weight(self.head.decode_rows(0, n))
|
|
149
|
+
return c[n]
|
|
150
|
+
|
|
151
|
+
logits_hook = None # P27 R2: fn(h, head) -> logits (e.g. vocab-sharded head + all-gather)
|
|
152
|
+
stack_hook = None # P27 R2: fn(model, x, ctx, fn) -> (pre-norm residual, final-normed hidden) (residual schemes)
|
|
153
|
+
|
|
154
|
+
def logits(self, h):
|
|
155
|
+
z = self.logits_hook(h, self.head) if self.logits_hook is not None else Bk.LINEAR(h, self.head)
|
|
156
|
+
return self.post_logits(z)
|
|
157
|
+
|
|
158
|
+
def post_logits(self, z):
|
|
159
|
+
if self.lmult != 1.0:
|
|
160
|
+
z = z * self.lmult
|
|
161
|
+
if self.ldiv != 1.0:
|
|
162
|
+
z = z / self.ldiv
|
|
163
|
+
if self.lcap:
|
|
164
|
+
z = torch.tanh(z / self.lcap) * self.lcap
|
|
165
|
+
return z
|
|
166
|
+
|
|
167
|
+
def emb(self, t):
|
|
168
|
+
e = self.embed[t]
|
|
169
|
+
if self.escale != 1.0: # in the embedding dtype, as HF does
|
|
170
|
+
e = e * torch.tensor(self.escale, dtype=e.dtype, device=e.device)
|
|
171
|
+
return e.to(Bk.ACT)
|
|
172
|
+
|
|
173
|
+
# ---------------------------------------------------------------- prefill (one user, chunked)
|
|
174
|
+
@torch.no_grad()
|
|
175
|
+
def prefill(self, toks, b=0, pos0=0, chunk=4096, keep_hidden=True):
|
|
176
|
+
"""toks (T,) long cuda. Returns final-normed hidden of every row (T, d) (or of the last row)."""
|
|
177
|
+
outs = []
|
|
178
|
+
T = toks.shape[0]
|
|
179
|
+
for s in range(0, T, chunk):
|
|
180
|
+
t = toks[s:s + chunk]
|
|
181
|
+
self.g["tok"] = t # token ids of the rows (hash-routed MoE)
|
|
182
|
+
ctx = RowCtx("prefill", b=b, pos0=pos0 + s)
|
|
183
|
+
x, h = self._stack(self.emb(t), ctx, "prefill")
|
|
184
|
+
outs.append(h if keep_hidden else h[-1:])
|
|
185
|
+
return torch.cat(outs, 0)
|
|
186
|
+
|
|
187
|
+
# ---------------------------------------------------------------- tree verify (B users x N rows)
|
|
188
|
+
def tree(self, tok, ctx):
|
|
189
|
+
"""tok (B, N) long. Returns final-normed hidden (B*N, d). Committed state untouched."""
|
|
190
|
+
self.g["tok"] = tok.reshape(-1)
|
|
191
|
+
x, h = self._stack(self.emb(tok.reshape(-1)), ctx, "tree")
|
|
192
|
+
self.xpre = x
|
|
193
|
+
return h
|
|
194
|
+
|
|
195
|
+
def _stack(self, x, ctx, fn):
|
|
196
|
+
"""returns (pre-norm residual stream, final-normed hidden)."""
|
|
197
|
+
if self.stack_hook is not None:
|
|
198
|
+
return self.stack_hook(self, x, ctx, fn)
|
|
199
|
+
if self.hch is not None:
|
|
200
|
+
x = x[:, None].expand(-1, self.hch.n, -1).contiguous()
|
|
201
|
+
for L in self.layers:
|
|
202
|
+
x = L.run(x, ctx, fn)
|
|
203
|
+
x = self.hch.head(x)
|
|
204
|
+
return x, self.final(x)
|
|
205
|
+
if FUSED and not self.lnorm:
|
|
206
|
+
from kernels import rms_fused
|
|
207
|
+
pend = None
|
|
208
|
+
for L in self.layers:
|
|
209
|
+
pend = L.run_fused(x, pend, ctx, fn)
|
|
210
|
+
return x, rms_fused(x, self.fnorm, self.g["eps"], self.g["norm_offset"], y=pend)
|
|
211
|
+
for L in self.layers:
|
|
212
|
+
x = L.run(x, ctx, fn)
|
|
213
|
+
return x, self.final(x)
|
|
214
|
+
|
|
215
|
+
def commit(self, ctx):
|
|
216
|
+
for L in self.layers:
|
|
217
|
+
L.mix.commit(ctx)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class MTPHead:
|
|
221
|
+
"""Multi-token-prediction head (DeepSeek-V3 / Qwen3-Next style): h' = layers(fc([norm_e(embed(x_{j+1})) ;
|
|
222
|
+
norm_h(h_j)])), logits = head(norm(h')). Row j (position j) predicts x_{j+2}. Its attention layers own their KV
|
|
223
|
+
caches (same block code as the main model)."""
|
|
224
|
+
|
|
225
|
+
def __init__(self, s, W, m):
|
|
226
|
+
self.m = m
|
|
227
|
+
self.fc = W.get(s["fc"])
|
|
228
|
+
self.ne = W.get(s["norm_emb"])
|
|
229
|
+
self.nh = W.get(s["norm_hid"])
|
|
230
|
+
self.nf = W.get(s["norm"])
|
|
231
|
+
self.layers = [Layer(L, W, m.g) for L in s["layers"]]
|
|
232
|
+
|
|
233
|
+
def alloc(self, B, smax):
|
|
234
|
+
for L in self.layers:
|
|
235
|
+
L.mix.alloc(B, smax)
|
|
236
|
+
|
|
237
|
+
def weight_bytes(self):
|
|
238
|
+
n = _nb(self.fc)
|
|
239
|
+
for L in self.layers:
|
|
240
|
+
n += sum(_nb(w) for w in L.mix.weights().values()) + sum(_nb(w) for w in L.mlp.weights().values())
|
|
241
|
+
return n
|
|
242
|
+
|
|
243
|
+
def state_bytes(self):
|
|
244
|
+
return sum(L.mix.state_bytes() for L in self.layers)
|
|
245
|
+
|
|
246
|
+
def _in(self, tok, h):
|
|
247
|
+
g = self.m.g
|
|
248
|
+
e = Bk.rms(self.m.embed[tok.reshape(-1)].to(Bk.ACT), self.ne, g["eps"], g["norm_offset"])
|
|
249
|
+
hh = Bk.rms(h, self.nh, g["eps"], g["norm_offset"])
|
|
250
|
+
return Bk.LINEAR(torch.cat([e, hh], -1), self.fc)
|
|
251
|
+
|
|
252
|
+
def _out(self, x):
|
|
253
|
+
return Bk.rms(x, self.nf, self.m.g["eps"], self.m.g["norm_offset"])
|
|
254
|
+
|
|
255
|
+
@torch.no_grad()
|
|
256
|
+
def prefill(self, tok_next, h, b=0, pos0=0, chunk=4096):
|
|
257
|
+
outs = []
|
|
258
|
+
for s in range(0, tok_next.shape[0], chunk):
|
|
259
|
+
ctx = RowCtx("prefill", b=b, pos0=pos0 + s)
|
|
260
|
+
x = self._in(tok_next[s:s + chunk], h[s:s + chunk])
|
|
261
|
+
x = self._stack(x, ctx, "prefill")
|
|
262
|
+
outs.append(self._out(x[-1:]))
|
|
263
|
+
return outs[-1]
|
|
264
|
+
|
|
265
|
+
def tree(self, tok, h, ctx):
|
|
266
|
+
x = self._in(tok, h)
|
|
267
|
+
return self._out(self._stack(x, ctx, "tree"))
|
|
268
|
+
|
|
269
|
+
def _stack(self, x, ctx, fn):
|
|
270
|
+
if FUSED:
|
|
271
|
+
pend = None
|
|
272
|
+
for L in self.layers:
|
|
273
|
+
pend = L.run_fused(x, pend, ctx, fn)
|
|
274
|
+
return x + pend
|
|
275
|
+
for L in self.layers:
|
|
276
|
+
x = L.run(x, ctx, fn)
|
|
277
|
+
return x
|
|
278
|
+
|
|
279
|
+
def commit(self, ctx):
|
|
280
|
+
for L in self.layers:
|
|
281
|
+
L.mix.commit(ctx)
|
package/engine/record.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Measurement record (hash copied from gpu/exp_quantum/qengine.py; uniform fixed to 23 bits): G(rid, token) i.i.d. Gumbel,
|
|
2
|
+
rid = (seq mod 2^11) * 2^21 + absolute position of the token being sampled (alias-free for positions < 2^21 = 2,097,152;
|
|
3
|
+
T27 BUG-004: the old seq*65536 aliased (seq, pos >= 65536) with (seq + 1, pos - 65536)). Token = argmax(z/T + G) -> exact softmax(z/T) sample."""
|
|
4
|
+
import torch
|
|
5
|
+
|
|
6
|
+
RID_POS_BITS = 21
|
|
7
|
+
RID_SEQ_BITS = 32 - RID_POS_BITS
|
|
8
|
+
RID_MULT = 1 << RID_POS_BITS
|
|
9
|
+
RID_SEQ_MASK = (1 << RID_SEQ_BITS) - 1
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def rid_of(seq, pos):
|
|
13
|
+
"""record id of the token sampled at absolute position pos of sequence seq (ints or tensors)."""
|
|
14
|
+
return (seq & RID_SEQ_MASK) * RID_MULT + pos
|
|
15
|
+
try:
|
|
16
|
+
import triton
|
|
17
|
+
import triton.language as tl
|
|
18
|
+
except ImportError: # CPU-only installs: kernels are never launched there; give @triton.jit a harmless stub
|
|
19
|
+
import types as _types
|
|
20
|
+
|
|
21
|
+
def _jit(fn=None, **kw):
|
|
22
|
+
return fn if fn is not None else (lambda f: f)
|
|
23
|
+
|
|
24
|
+
def _cdiv(a, b):
|
|
25
|
+
return -(-a // b)
|
|
26
|
+
|
|
27
|
+
def _np2(n):
|
|
28
|
+
return 1 << max(int(n) - 1, 0).bit_length()
|
|
29
|
+
triton = _types.SimpleNamespace(jit=_jit, cdiv=_cdiv, next_power_of_2=_np2)
|
|
30
|
+
tl = _types.SimpleNamespace(constexpr=object)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@triton.jit
|
|
34
|
+
def _fmix(x):
|
|
35
|
+
x ^= x >> 16
|
|
36
|
+
x *= 0x85EBCA6B
|
|
37
|
+
x ^= x >> 13
|
|
38
|
+
x *= 0xC2B2AE35
|
|
39
|
+
x ^= x >> 16
|
|
40
|
+
return x
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@triton.jit
|
|
44
|
+
def _gumbel(rid, vid):
|
|
45
|
+
x = _fmix(rid.to(tl.uint32) * 0x9E3779B1)
|
|
46
|
+
x = _fmix(x ^ (vid.to(tl.uint32) * 0x7FEB352D + 0x68E31DA4))
|
|
47
|
+
x = _fmix(x + rid.to(tl.uint32))
|
|
48
|
+
# 23-bit uniform: (k + 0.5) is exact in fp32 for k < 2^23, so u < 1 always (the exp_quantum version used 24 bits:
|
|
49
|
+
# (2^24 - 1) + 0.5 rounds to 2^24 in fp32 -> u = 1 -> G = +inf on ~0.9% of 152k-token rows; see FINDINGS)
|
|
50
|
+
u = ((x >> 9).to(tl.float32) + 0.5) * (1.0 / 8388608.0)
|
|
51
|
+
return -tl.log(-tl.log(u))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@triton.jit
|
|
55
|
+
def _gargmax_k(Z, RID, OV, OI, V, sz, invT, NCH, GREEDY: tl.constexpr, BLOCK: tl.constexpr):
|
|
56
|
+
r = tl.program_id(0)
|
|
57
|
+
c = tl.program_id(1)
|
|
58
|
+
offs = c * BLOCK + tl.arange(0, BLOCK)
|
|
59
|
+
msk = offs < V
|
|
60
|
+
z = tl.load(Z + r * sz + offs, mask=msk, other=0.0).to(tl.float32)
|
|
61
|
+
rid = tl.load(RID + r)
|
|
62
|
+
if GREEDY:
|
|
63
|
+
s = z
|
|
64
|
+
else:
|
|
65
|
+
s = z * invT + _gumbel(rid, offs)
|
|
66
|
+
s = tl.where(msk, s, float("-inf"))
|
|
67
|
+
m = tl.max(s, 0)
|
|
68
|
+
i = tl.argmax(s, 0)
|
|
69
|
+
tl.store(OV + r * NCH + c, m)
|
|
70
|
+
tl.store(OI + r * NCH + c, i + c * BLOCK)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
GB = 4096
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def gumbel_argmax(z, rid, T=1.0):
|
|
77
|
+
"""z (R, V) any float dtype; rid (R,) int32. T=0 -> greedy argmax."""
|
|
78
|
+
R, V = z.shape
|
|
79
|
+
nch = triton.cdiv(V, GB)
|
|
80
|
+
ov = torch.empty(R, nch, device=z.device, dtype=torch.float32)
|
|
81
|
+
oi = torch.empty(R, nch, device=z.device, dtype=torch.int32)
|
|
82
|
+
_gargmax_k[(R, nch)](z, rid, ov, oi, V, z.stride(0), 1.0 / max(T, 1e-6), nch, GREEDY=(T == 0), BLOCK=GB)
|
|
83
|
+
return oi.gather(1, ov.argmax(1, keepdim=True))[:, 0].long()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@triton.jit
|
|
89
|
+
def _gtopk_k(Z, RID, OV, OI, V, sz, invT, NCH, GREEDY: tl.constexpr, K: tl.constexpr, BLOCK: tl.constexpr):
|
|
90
|
+
r = tl.program_id(0)
|
|
91
|
+
c = tl.program_id(1)
|
|
92
|
+
offs = c * BLOCK + tl.arange(0, BLOCK)
|
|
93
|
+
msk = offs < V
|
|
94
|
+
z = tl.load(Z + r * sz + offs, mask=msk, other=0.0).to(tl.float32)
|
|
95
|
+
rid = tl.load(RID + r)
|
|
96
|
+
if GREEDY:
|
|
97
|
+
s = z
|
|
98
|
+
else:
|
|
99
|
+
s = z * invT + _gumbel(rid, offs)
|
|
100
|
+
s = tl.where(msk, s, float("-inf"))
|
|
101
|
+
lane = tl.arange(0, BLOCK)
|
|
102
|
+
for j in tl.static_range(K):
|
|
103
|
+
m = tl.max(s, 0)
|
|
104
|
+
i = tl.argmax(s, 0)
|
|
105
|
+
tl.store(OV + (r * NCH + c) * K + j, m)
|
|
106
|
+
tl.store(OI + (r * NCH + c) * K + j, i + c * BLOCK)
|
|
107
|
+
s = tl.where(lane == i, float("-inf"), s)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def gumbel_topk(z, rid, T=1.0, k=1):
|
|
111
|
+
"""top-k tokens of z/T + deterministic Gumbel without materialising the (R, V) score field."""
|
|
112
|
+
R, V = z.shape
|
|
113
|
+
nch = triton.cdiv(V, GB)
|
|
114
|
+
ov = torch.empty(R, nch * k, device=z.device, dtype=torch.float32)
|
|
115
|
+
oi = torch.empty(R, nch * k, device=z.device, dtype=torch.int32)
|
|
116
|
+
_gtopk_k[(R, nch)](z, rid, ov, oi, V, z.stride(0), 1.0 / max(T, 1e-6), nch,
|
|
117
|
+
GREEDY=(T == 0), K=k, BLOCK=GB)
|
|
118
|
+
tk = ov.topk(k, 1).indices
|
|
119
|
+
return oi.gather(1, tk).long()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _fmix_t(x):
|
|
123
|
+
M = 0xFFFFFFFF
|
|
124
|
+
x = x ^ (x >> 16)
|
|
125
|
+
x = (x * 0x85EBCA6B) & M
|
|
126
|
+
x = x ^ (x >> 13)
|
|
127
|
+
x = (x * 0xC2B2AE35) & M
|
|
128
|
+
return x ^ (x >> 16)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def gumbel_ref(rid, vid):
|
|
132
|
+
"""float64 torch reference of the same field (rid scalar or tensor broadcast against vid)."""
|
|
133
|
+
M = 0xFFFFFFFF
|
|
134
|
+
rid = torch.as_tensor(rid, device=vid.device).long() & M
|
|
135
|
+
vid = vid.long() & M
|
|
136
|
+
x = _fmix_t((rid * 0x9E3779B1) & M)
|
|
137
|
+
x = _fmix_t(x ^ ((vid * 0x7FEB352D + 0x68E31DA4) & M))
|
|
138
|
+
x = _fmix_t((x + rid) & M)
|
|
139
|
+
u = ((x >> 9).double() + 0.5) / 8388608.0
|
|
140
|
+
return -torch.log(-torch.log(u))
|
package/engine/server.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""OpenAI-compatible HTTP server on the one engine (stdlib only).
|
|
2
|
+
|
|
3
|
+
python server.py --model <hf snapshot dir> [--port 8000] [--spec '{"D":3,"C":8}'] [--smax 40960]
|
|
4
|
+
Routes: GET /v1/models, POST /v1/completions, POST /v1/chat/completions (stream true/false, SSE "data:" chunks,
|
|
5
|
+
"[DONE]"). Sampling: temperature (0 = greedy, else exact T sampling through the 23-bit measurement record; seed ->
|
|
6
|
+
record sequence id), max_tokens, stop (strings), ignore_eos. top_p/top_k other than 1/0 are refused (400): the
|
|
7
|
+
engine only samples exactly from softmax(z/T). Requests are served one at a time (single-user engine); batched
|
|
8
|
+
serving plugs in as a feature (API.txt section 5) that sets .serve_batch.
|
|
9
|
+
"""
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
import uuid
|
|
15
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Server:
|
|
19
|
+
def __init__(self, model_path, smax=40960, spec=None, name=None, precision="bf16"):
|
|
20
|
+
from __init__ import Engine
|
|
21
|
+
from transformers import AutoTokenizer
|
|
22
|
+
self.tok = AutoTokenizer.from_pretrained(model_path)
|
|
23
|
+
self.eng = Engine(model_path, B=1, smax=smax, spec=spec, precision=precision)
|
|
24
|
+
self.name = name or model_path.rstrip("/").split("/")[-1]
|
|
25
|
+
self.lock = threading.Lock()
|
|
26
|
+
self.eos = [t for t in [self.tok.eos_token_id] + list(getattr(self.tok, "additional_special_tokens_ids", []) or [])
|
|
27
|
+
if t is not None]
|
|
28
|
+
gc = None
|
|
29
|
+
try:
|
|
30
|
+
import os
|
|
31
|
+
gc = json.load(open(os.path.join(model_path, "generation_config.json")))
|
|
32
|
+
except Exception: # noqa
|
|
33
|
+
pass
|
|
34
|
+
if gc and gc.get("eos_token_id") is not None:
|
|
35
|
+
e = gc["eos_token_id"]
|
|
36
|
+
self.eos = list(e) if isinstance(e, list) else [e]
|
|
37
|
+
|
|
38
|
+
def prompt_ids(self, body, chat):
|
|
39
|
+
if chat:
|
|
40
|
+
kw = {}
|
|
41
|
+
ctk = body.get("chat_template_kwargs") or {}
|
|
42
|
+
kw.update(ctk)
|
|
43
|
+
text = self.tok.apply_chat_template(body["messages"], tokenize=False, add_generation_prompt=True, **kw)
|
|
44
|
+
return self.tok(text, add_special_tokens=False).input_ids
|
|
45
|
+
p = body["prompt"]
|
|
46
|
+
if isinstance(p, list) and p and isinstance(p[0], int):
|
|
47
|
+
return p
|
|
48
|
+
return self.tok(p if isinstance(p, str) else p[0], add_special_tokens=False).input_ids
|
|
49
|
+
|
|
50
|
+
def run_n(self, body, chat, emit):
|
|
51
|
+
"""n > 1 choices: choice i uses record seq id (seed + i), i.e. independent exact samples."""
|
|
52
|
+
n = int(body.get("n", 1) or 1)
|
|
53
|
+
seed = int(body.get("seed", 0) or 0)
|
|
54
|
+
outs = []
|
|
55
|
+
for i in range(n):
|
|
56
|
+
b = dict(body, seed=seed + i)
|
|
57
|
+
outs.append(self.run(b, chat, lambda d, i=i: emit(d, i)))
|
|
58
|
+
return outs
|
|
59
|
+
|
|
60
|
+
def run(self, body, chat, emit):
|
|
61
|
+
if body.get("top_p", 1.0) != 1.0 or body.get("top_k", 0) not in (0, -1, None):
|
|
62
|
+
raise ValueError("only exact softmax(z/T) sampling is served: top_p must be 1 and top_k 0/-1")
|
|
63
|
+
ids = self.prompt_ids(body, chat)
|
|
64
|
+
T = float(body.get("temperature", 1.0))
|
|
65
|
+
n = int(body.get("max_tokens", body.get("max_completion_tokens", 256)))
|
|
66
|
+
stops = body.get("stop") or []
|
|
67
|
+
stops = [stops] if isinstance(stops, str) else stops
|
|
68
|
+
stop_ids = () if body.get("ignore_eos") else tuple(self.eos)
|
|
69
|
+
with self.lock:
|
|
70
|
+
E = self.eng.decoder(T)
|
|
71
|
+
E.uid = int(body.get("seed", 0) or 0) & 2047 # record seq id (record.rid_of: (seq mod 2^11) * 2^21 + pos)
|
|
72
|
+
E.prepare(ids)
|
|
73
|
+
state = {"ids": [], "text": "", "done": False}
|
|
74
|
+
|
|
75
|
+
def on_tok(new):
|
|
76
|
+
if state["done"]:
|
|
77
|
+
return
|
|
78
|
+
for t in new:
|
|
79
|
+
if len(state["ids"]) >= n:
|
|
80
|
+
state["done"] = True
|
|
81
|
+
break
|
|
82
|
+
if t in stop_ids:
|
|
83
|
+
state["done"] = True
|
|
84
|
+
state["finish"] = "stop"
|
|
85
|
+
break
|
|
86
|
+
state["ids"].append(t)
|
|
87
|
+
txt = self.tok.decode(state["ids"], skip_special_tokens=True)
|
|
88
|
+
for s in stops:
|
|
89
|
+
k = txt.find(s)
|
|
90
|
+
if k >= 0:
|
|
91
|
+
txt = txt[:k]
|
|
92
|
+
state["done"] = True
|
|
93
|
+
state["finish"] = "stop"
|
|
94
|
+
delta = txt[len(state["text"]):]
|
|
95
|
+
state["text"] = txt
|
|
96
|
+
if delta:
|
|
97
|
+
emit(delta)
|
|
98
|
+
|
|
99
|
+
r = E.generate(ids, n, on_tokens=on_tok, stop_ids=stop_ids)
|
|
100
|
+
return {"text": state["text"], "n_prompt": len(ids), "n_out": len(state["ids"]),
|
|
101
|
+
"finish": state.get("finish", "length"), "stats": {k: r[k] for k in ("decode_tok_s", "tok_per_pass")}}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def make_handler(S):
|
|
105
|
+
class H(BaseHTTPRequestHandler):
|
|
106
|
+
def _json(self, code, obj):
|
|
107
|
+
b = json.dumps(obj).encode()
|
|
108
|
+
self.send_response(code)
|
|
109
|
+
self.send_header("Content-Type", "application/json")
|
|
110
|
+
self.send_header("Content-Length", str(len(b)))
|
|
111
|
+
self.end_headers()
|
|
112
|
+
self.wfile.write(b)
|
|
113
|
+
|
|
114
|
+
def do_GET(self):
|
|
115
|
+
if self.path.rstrip("/") == "/v1/models":
|
|
116
|
+
return self._json(200, {"object": "list", "data": [{"id": S.name, "object": "model"}]})
|
|
117
|
+
if self.path.rstrip("/") == "/health":
|
|
118
|
+
return self._json(200, {"ok": True})
|
|
119
|
+
self._json(404, {"error": "not found"})
|
|
120
|
+
|
|
121
|
+
def do_POST(self):
|
|
122
|
+
chat = self.path.rstrip("/") == "/v1/chat/completions"
|
|
123
|
+
if not chat and self.path.rstrip("/") != "/v1/completions":
|
|
124
|
+
return self._json(404, {"error": "not found"})
|
|
125
|
+
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
|
|
126
|
+
rid = ("chatcmpl-" if chat else "cmpl-") + uuid.uuid4().hex[:24]
|
|
127
|
+
created = int(time.time())
|
|
128
|
+
obj = "chat.completion" if chat else "text_completion"
|
|
129
|
+
try:
|
|
130
|
+
if body.get("stream"):
|
|
131
|
+
self.send_response(200)
|
|
132
|
+
self.send_header("Content-Type", "text/event-stream")
|
|
133
|
+
self.send_header("Cache-Control", "no-cache")
|
|
134
|
+
self.end_headers()
|
|
135
|
+
|
|
136
|
+
def emit(delta, i=0):
|
|
137
|
+
ch = ({"index": i, "delta": {"content": delta}, "finish_reason": None} if chat else
|
|
138
|
+
{"index": i, "text": delta, "finish_reason": None})
|
|
139
|
+
c = {"id": rid, "object": obj + ".chunk" if chat else obj, "created": created,
|
|
140
|
+
"model": S.name, "choices": [ch]}
|
|
141
|
+
self.wfile.write(b"data: " + json.dumps(c).encode() + b"\n\n")
|
|
142
|
+
self.wfile.flush()
|
|
143
|
+
ress = S.run_n(body, chat, emit)
|
|
144
|
+
chs = [({"index": i, "delta": {}, "finish_reason": res["finish"]} if chat else
|
|
145
|
+
{"index": i, "text": "", "finish_reason": res["finish"]}) for i, res in enumerate(ress)]
|
|
146
|
+
c = {"id": rid, "object": obj + ".chunk" if chat else obj, "created": created, "model": S.name,
|
|
147
|
+
"choices": chs}
|
|
148
|
+
self.wfile.write(b"data: " + json.dumps(c).encode() + b"\n\ndata: [DONE]\n\n")
|
|
149
|
+
self.wfile.flush()
|
|
150
|
+
else:
|
|
151
|
+
ress = S.run_n(body, chat, lambda d, i=0: None)
|
|
152
|
+
chs = [({"index": i, "message": {"role": "assistant", "content": res["text"]},
|
|
153
|
+
"finish_reason": res["finish"]} if chat else
|
|
154
|
+
{"index": i, "text": res["text"], "finish_reason": res["finish"]})
|
|
155
|
+
for i, res in enumerate(ress)]
|
|
156
|
+
npr, nout = ress[0]["n_prompt"], sum(r["n_out"] for r in ress)
|
|
157
|
+
self._json(200, {"id": rid, "object": obj, "created": created, "model": S.name,
|
|
158
|
+
"choices": chs, "usage": {"prompt_tokens": npr, "completion_tokens": nout,
|
|
159
|
+
"total_tokens": npr + nout},
|
|
160
|
+
"engine_stats": [r["stats"] for r in ress]})
|
|
161
|
+
except ValueError as e:
|
|
162
|
+
self._json(400, {"error": {"message": str(e), "type": "invalid_request_error"}})
|
|
163
|
+
|
|
164
|
+
def log_message(self, *a):
|
|
165
|
+
pass
|
|
166
|
+
return H
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def main():
|
|
170
|
+
ap = argparse.ArgumentParser()
|
|
171
|
+
ap.add_argument("--model", required=True)
|
|
172
|
+
ap.add_argument("--port", type=int, default=8000)
|
|
173
|
+
ap.add_argument("--host", default="0.0.0.0")
|
|
174
|
+
ap.add_argument("--smax", type=int, default=40960)
|
|
175
|
+
ap.add_argument("--spec", default='{"online": true, "C": 8, "dvocab": 65536}')
|
|
176
|
+
ap.add_argument("--precision", default="bf16", choices=["bf16", "f32a"])
|
|
177
|
+
a = ap.parse_args()
|
|
178
|
+
S = Server(a.model, smax=a.smax, spec=json.loads(a.spec), precision=a.precision)
|
|
179
|
+
ThreadingHTTPServer((a.host, a.port), make_handler(S)).serve_forever()
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
if __name__ == "__main__":
|
|
183
|
+
main()
|