quantuminfer 0.0.0-stage → 0.1.1
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 +34 -4
- package/results/ANALYSIS.md +160 -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_t1_j8_b300.json +340 -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/ctx.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""RowCtx: everything a block needs to process a set of rows (prefill chunk or token tree) and to commit."""
|
|
2
|
+
import torch
|
|
3
|
+
from dev import DEV, CUDA, sync # noqa: F401
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class TreeShape:
|
|
7
|
+
"""Static token-tree topology shared by all users: par[i] < i (par[0] = -1, row 0 = root = last committed-but-
|
|
8
|
+
unprocessed token). Builds the per-node root paths (for recurrent blocks), depths and conv windows."""
|
|
9
|
+
|
|
10
|
+
def __init__(self, par, device=DEV):
|
|
11
|
+
self.par = list(par)
|
|
12
|
+
N = self.N = len(par)
|
|
13
|
+
dep, paths = [], []
|
|
14
|
+
for i in range(N):
|
|
15
|
+
p, path = i, []
|
|
16
|
+
while p >= 0:
|
|
17
|
+
path.append(p)
|
|
18
|
+
p = self.par[p]
|
|
19
|
+
path.reverse()
|
|
20
|
+
paths.append(path)
|
|
21
|
+
dep.append(len(path) - 1)
|
|
22
|
+
self.dep_l, self.paths_l = dep, paths
|
|
23
|
+
self.maxd = max(dep)
|
|
24
|
+
self.MAXL = self.maxd + 1
|
|
25
|
+
P = torch.zeros(N, self.MAXL, dtype=torch.int32)
|
|
26
|
+
for i, pa in enumerate(paths):
|
|
27
|
+
P[i, :len(pa)] = torch.tensor(pa, dtype=torch.int32)
|
|
28
|
+
P[i, len(pa):] = pa[-1]
|
|
29
|
+
self.paths = P.to(device)
|
|
30
|
+
self.plen = torch.tensor([len(p) for p in paths], dtype=torch.int32, device=device)
|
|
31
|
+
self.dep = torch.tensor(dep, dtype=torch.long, device=device)
|
|
32
|
+
self.par_t = torch.tensor(par, dtype=torch.int32, device=device)
|
|
33
|
+
kids = set(p for p in self.par if p >= 0)
|
|
34
|
+
self.leaves = [i for i in range(N) if i not in kids]
|
|
35
|
+
self.lpaths = self.paths[self.leaves].contiguous()
|
|
36
|
+
A = torch.zeros(N, N, dtype=torch.bool)
|
|
37
|
+
for i, pa in enumerate(paths):
|
|
38
|
+
A[i, pa] = True
|
|
39
|
+
self.anc = A.to(device)
|
|
40
|
+
self.lplen = self.plen[self.leaves].contiguous()
|
|
41
|
+
self._cidx = {}
|
|
42
|
+
self.device = device
|
|
43
|
+
|
|
44
|
+
def cidx(self, K):
|
|
45
|
+
"""(N, K) indices into [conv_state (K-1 rows) | tree rows (N)] of each node's conv window, oldest first."""
|
|
46
|
+
if K not in self._cidx:
|
|
47
|
+
idx = torch.zeros(self.N, K, dtype=torch.long)
|
|
48
|
+
for i, pa in enumerate(self.paths_l):
|
|
49
|
+
seq = list(range(K - 1)) + [K - 1 + r for r in pa]
|
|
50
|
+
idx[i] = torch.tensor(seq[-K:])
|
|
51
|
+
self._cidx[K] = idx.to(self.device)
|
|
52
|
+
return self._cidx[K]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def chain(n):
|
|
56
|
+
return TreeShape([-1] + list(range(n - 1)))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class RowCtx:
|
|
60
|
+
"""mode 'prefill': b, pos0. mode 'tree': B, N, lens (B,) int32 committed lengths, shape (TreeShape).
|
|
61
|
+
After acceptance: acc_path (B, MAXL) int32 rows root..leaf (padded with leaf), acc_len (B,), leaf (B,) long."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, mode, **kw):
|
|
64
|
+
self.mode = mode
|
|
65
|
+
self.scratch = {} # per-forward cross-layer state for plug-in blocks (P27 R4: e.g. DSA top-k reuse)
|
|
66
|
+
self.__dict__.update(kw)
|
|
67
|
+
|
|
68
|
+
@staticmethod
|
|
69
|
+
def tree(shape, lens, B):
|
|
70
|
+
c = RowCtx("tree", B=B, N=shape.N, lens=lens, shape=shape, maxd=shape.maxd)
|
|
71
|
+
c.par = shape.par_t[None].expand(B, -1).contiguous()
|
|
72
|
+
c.paths = shape.paths[None].expand(B, -1, -1).contiguous()
|
|
73
|
+
c.plen = shape.plen[None].expand(B, -1).contiguous()
|
|
74
|
+
c.orow = torch.arange(shape.N, dtype=torch.int32, device=lens.device)[None].expand(B, -1).contiguous()
|
|
75
|
+
c.pos = lens.long()[:, None] + shape.dep[None]
|
|
76
|
+
c.lpaths = shape.lpaths[None].expand(B, -1, -1).contiguous()
|
|
77
|
+
c.lplen = shape.lplen[None].expand(B, -1).contiguous()
|
|
78
|
+
return c
|
|
79
|
+
|
|
80
|
+
def cidx_for(self, K):
|
|
81
|
+
return self.shape.cidx(K)
|
|
82
|
+
|
|
83
|
+
def set_accept(self, leaf):
|
|
84
|
+
"""leaf (B,) long local row of the deepest accepted node."""
|
|
85
|
+
self.leaf = leaf
|
|
86
|
+
self.acc_path = self.paths[torch.arange(self.B, device=leaf.device), leaf] # (B, MAXL)
|
|
87
|
+
self.acc_len = self.plen.gather(1, leaf[:, None].to(torch.long))[:, 0]
|
package/engine/dev.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Device helpers: the engine runs on CUDA (Triton kernels, CUDA graphs) and, for tiny models / tests, on CPU through
|
|
2
|
+
torch reference paths of every kernel (no graphs)."""
|
|
3
|
+
import torch
|
|
4
|
+
|
|
5
|
+
DEV = "cuda" if torch.cuda.is_available() else "cpu"
|
|
6
|
+
CUDA = DEV == "cuda"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def sync():
|
|
10
|
+
if CUDA:
|
|
11
|
+
torch.cuda.synchronize()
|
package/engine/ds4.py
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
"""DeepSeek-V4 blocks (declarative, no model-name branches): sliding-window shared-KV MQA with per-head sinks, a
|
|
2
|
+
grouped low-rank output projection and an optional compressed long-range KV series -- HCA (non-overlapping windows of
|
|
3
|
+
r tokens, all complete windows visible) or CSA (overlapping 2r windows, a lightning indexer keeps the top-k complete
|
|
4
|
+
windows per query); hash-routed / sqrtsoftplus MoE with a shared expert and clamped SwiGLU; hyper-connection
|
|
5
|
+
(mHC) residual streams are applied by model.Layer / model.Model (hc_* weights).
|
|
6
|
+
|
|
7
|
+
Compressed entries are a pure function of committed raw projections, so the committed state is: K=V cache (B, Smax,
|
|
8
|
+
hd), raw compressor (+ indexer) projections per position, and the entries of every complete committed window. A tree
|
|
9
|
+
pass rebuilds, per tree row, the few windows that end inside the row's own root path (exact, ancestors only)."""
|
|
10
|
+
import torch
|
|
11
|
+
import torch.nn.functional as F
|
|
12
|
+
|
|
13
|
+
import blocks as Bk
|
|
14
|
+
from blocks import register, LINEAR, make # noqa: F401
|
|
15
|
+
from dev import DEV, CUDA # noqa: F401
|
|
16
|
+
|
|
17
|
+
NEG = float("-inf")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def LIN(x, w):
|
|
21
|
+
return LINEAR(x.reshape(-1, x.shape[-1]), w).view(*x.shape[:-1], -1)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def urms(x, eps):
|
|
25
|
+
return x * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + eps).to(x.dtype)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def wrms(x, w, eps):
|
|
29
|
+
xf = x.float()
|
|
30
|
+
return (w.float() * (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps))).to(x.dtype)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TailRope:
|
|
34
|
+
"""interleaved-pair RoPE on the trailing `rot` dims of each head (DeepSeek-V4 [nope | rope] layout)."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, theta, rot, smax):
|
|
37
|
+
inv = 1.0 / (theta ** (torch.arange(0, rot, 2, dtype=torch.float) / rot))
|
|
38
|
+
fr = torch.arange(smax, dtype=torch.float)[:, None] * inv[None]
|
|
39
|
+
self.c, self.s, self.rot = fr.cos().to(DEV), fr.sin().to(DEV), rot
|
|
40
|
+
|
|
41
|
+
def __call__(self, x, pos, inverse=False):
|
|
42
|
+
"""x (..., H, hd), pos long of shape x.shape[:-2]."""
|
|
43
|
+
r = self.rot
|
|
44
|
+
c = self.c[pos].repeat_interleave(2, -1).unsqueeze(-2)
|
|
45
|
+
s = self.s[pos].repeat_interleave(2, -1).unsqueeze(-2)
|
|
46
|
+
if inverse:
|
|
47
|
+
s = -s
|
|
48
|
+
xr = x[..., -r:]
|
|
49
|
+
rh = torch.stack((-xr[..., 1::2], xr[..., 0::2]), -1).flatten(-2)
|
|
50
|
+
y = (xr.float() * c + rh.float() * s).to(x.dtype)
|
|
51
|
+
return torch.cat([x[..., :-r], y], -1)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class _Comp:
|
|
55
|
+
"""one compressed series (outer compressor or the indexer's): raw (kv, gate) projections -> window entries."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, W, p, r, hd, csa, eps, rope):
|
|
58
|
+
self.wk, self.wg = W.get(p + "wkv.weight"), W.get(p + "wgate.weight")
|
|
59
|
+
self.pb = W.get(p + "ape").float()
|
|
60
|
+
self.nw = W.get(p + "norm.weight")
|
|
61
|
+
self.r, self.hd, self.csa, self.eps, self.rope = r, hd, csa, eps, rope
|
|
62
|
+
self.cw = self.wk.shape[0]
|
|
63
|
+
|
|
64
|
+
def proj(self, x):
|
|
65
|
+
return LIN(x, self.wk), LIN(x, self.wg)
|
|
66
|
+
|
|
67
|
+
def entries(self, kv, g, w0):
|
|
68
|
+
"""kv, g (..., (n+1)*r, cw) raw projections of windows w0-1 .. w0+n-1 (window w0-1 read by CSA only, as its
|
|
69
|
+
Ca half); w0 long (...). Returns (..., n, hd) normed + RoPE'd entries of windows w0 .. w0+n-1."""
|
|
70
|
+
r, hd = self.r, self.hd
|
|
71
|
+
sh = kv.shape[:-2]
|
|
72
|
+
n = kv.shape[-2] // r - 1
|
|
73
|
+
kv = kv.reshape(*sh, n + 1, r, self.cw)
|
|
74
|
+
g = g.reshape(*sh, n + 1, r, self.cw).float() + self.pb
|
|
75
|
+
wi = w0[..., None] + torch.arange(n, device=kv.device) # (..., n)
|
|
76
|
+
if self.csa:
|
|
77
|
+
ks = torch.cat([kv[..., :-1, :, :hd], kv[..., 1:, :, hd:]], -2)
|
|
78
|
+
gs = torch.cat([g[..., :-1, :, :hd], g[..., 1:, :, hd:]], -2)
|
|
79
|
+
first = (wi == 0)[..., None, None] & (torch.arange(2 * r, device=kv.device) < r)[:, None]
|
|
80
|
+
gs = gs.masked_fill(first, NEG)
|
|
81
|
+
ks = ks.masked_fill(first, 0.0)
|
|
82
|
+
else:
|
|
83
|
+
ks, gs = kv[..., 1:, :, :], g[..., 1:, :, :]
|
|
84
|
+
e = (ks * torch.softmax(gs, -2).to(ks.dtype)).sum(-2)
|
|
85
|
+
e = wrms(e, self.nw, self.eps)
|
|
86
|
+
return self.rope(e[..., None, :], (wi * r).clamp(max=self.rope.c.shape[0] - 1))[..., 0, :]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@register("ds4_attn")
|
|
90
|
+
class DS4Attention:
|
|
91
|
+
def __init__(self, s, W, g):
|
|
92
|
+
p = s["prefix"]
|
|
93
|
+
if g["tp"]["world"] > 1:
|
|
94
|
+
raise NotImplementedError("ds4_attn under tensor parallelism")
|
|
95
|
+
self.s = s
|
|
96
|
+
self.nh, self.hd, self.eps = s["nh"], s["hd"], s["eps"]
|
|
97
|
+
self.win, self.r, self.csa = s["window"], s.get("rate"), bool(s.get("csa"))
|
|
98
|
+
self.scale = self.hd ** -0.5
|
|
99
|
+
self.wqa, self.qan, self.wqb = W.get(p + "wq_a.weight"), W.get(p + "q_norm.weight"), W.get(p + "wq_b.weight")
|
|
100
|
+
self.wkv, self.kvn = W.get(p + "wkv.weight"), W.get(p + "norm.weight")
|
|
101
|
+
self.woa, self.wob = W.get(p + "wo_a.weight"), W.get(p + "wo_b.weight")
|
|
102
|
+
self.sink = W.get(p + "attn_sink").float()
|
|
103
|
+
self.G = s["groups"]
|
|
104
|
+
self.W_ = W
|
|
105
|
+
self.p = p
|
|
106
|
+
|
|
107
|
+
def weights(self):
|
|
108
|
+
return {"wqa": self.wqa, "wqb": self.wqb, "wkv": self.wkv, "woa": self.woa, "wob": self.wob}
|
|
109
|
+
|
|
110
|
+
def alloc(self, B, smax):
|
|
111
|
+
A = Bk.ACT
|
|
112
|
+
self.smax = smax
|
|
113
|
+
self.rope = TailRope(self.s["theta"], self.s["rot"], smax)
|
|
114
|
+
self.kc = torch.zeros(B, smax, self.hd, dtype=A, device=DEV)
|
|
115
|
+
self.series = []
|
|
116
|
+
if self.r:
|
|
117
|
+
W, p, r = self.W_, self.p, self.r
|
|
118
|
+
crope = TailRope(self.s["ctheta"], self.s["rot"], smax)
|
|
119
|
+
self.comp = _Comp(W, p + "compressor.", r, self.hd, self.csa, self.eps, crope)
|
|
120
|
+
self.series = [self.comp]
|
|
121
|
+
if self.csa:
|
|
122
|
+
self.ix = _Comp(W, p + "indexer.compressor.", r, self.s["ihd"], True, self.eps, crope)
|
|
123
|
+
self.iwq, self.iwp = W.get(p + "indexer.wq_b.weight"), W.get(p + "indexer.weights_proj.weight")
|
|
124
|
+
self.series.append(self.ix)
|
|
125
|
+
self.C = smax // r + 1 # last slot = scratch for out-of-range writes
|
|
126
|
+
for c in self.series:
|
|
127
|
+
c.bk = torch.zeros(B, smax, c.cw, dtype=A, device=DEV)
|
|
128
|
+
c.bg = torch.zeros(B, smax, c.cw, dtype=A, device=DEV)
|
|
129
|
+
c.ce = torch.zeros(B, self.C, c.hd, dtype=A, device=DEV)
|
|
130
|
+
|
|
131
|
+
def _bufs(self):
|
|
132
|
+
out = [self.kc]
|
|
133
|
+
for c in self.series:
|
|
134
|
+
out += [c.bk, c.bg, c.ce]
|
|
135
|
+
return out
|
|
136
|
+
|
|
137
|
+
def state_bytes(self):
|
|
138
|
+
return sum(t.numel() * t.element_size() for t in self._bufs())
|
|
139
|
+
|
|
140
|
+
def reset(self, b=None):
|
|
141
|
+
pass
|
|
142
|
+
|
|
143
|
+
def reset_rows(self, rows):
|
|
144
|
+
pass
|
|
145
|
+
|
|
146
|
+
def copy_rows(self, src, dst, n=None):
|
|
147
|
+
for t in self._bufs():
|
|
148
|
+
t[dst] = t[src]
|
|
149
|
+
|
|
150
|
+
def fixed_bytes(self):
|
|
151
|
+
return 0
|
|
152
|
+
|
|
153
|
+
def kv_bytes_per_token(self):
|
|
154
|
+
return self.kc.element_size() * (self.hd + sum(2 * c.cw + c.hd / self.r for c in self.series))
|
|
155
|
+
|
|
156
|
+
# ------------------------------------------------------------------ shared math
|
|
157
|
+
def _q(self, x, pos):
|
|
158
|
+
qr = wrms(LIN(x, self.wqa), self.qan, self.eps)
|
|
159
|
+
q = urms(LIN(qr, self.wqb).view(*x.shape[:-1], self.nh, self.hd), self.eps)
|
|
160
|
+
kv = wrms(LIN(x, self.wkv), self.kvn, self.eps)
|
|
161
|
+
return qr, self.rope(q, pos), self.rope(kv[..., None, :], pos)[..., 0, :]
|
|
162
|
+
|
|
163
|
+
def _iscore(self, qr, x, pos, ents):
|
|
164
|
+
"""indexer score (..., E) of every query against entries ents (..., E, ihd) (broadcast on leading dims)."""
|
|
165
|
+
ihd = self.ix.hd
|
|
166
|
+
iq = self.ix.rope(LIN(qr, self.iwq).view(*qr.shape[:-1], -1, ihd), pos).float() # (..., IH, ihd)
|
|
167
|
+
sc = F.relu(torch.matmul(iq, ents.float().transpose(-1, -2))) * ihd ** -0.5 # (..., IH, E)
|
|
168
|
+
w = LIN(x, self.iwp).float() * iq.shape[-2] ** -0.5
|
|
169
|
+
return (sc * w[..., None]).sum(-2)
|
|
170
|
+
|
|
171
|
+
def _attend(self, q, parts):
|
|
172
|
+
"""q (..., H, hd); parts: [(keys (..|1, K, hd), mask (..., K))] -> (..., H, hd) fp32 (sink column dropped)."""
|
|
173
|
+
qf = q.float()
|
|
174
|
+
sc = [torch.matmul(qf, k.float().transpose(-1, -2)).masked_fill(~m[..., None, :], NEG) * self.scale
|
|
175
|
+
for k, m in parts]
|
|
176
|
+
sk = self.sink.view(*([1] * (q.dim() - 2)), self.nh, 1).expand(*q.shape[:-1], 1)
|
|
177
|
+
p = torch.softmax(torch.cat(sc + [sk], -1), -1)
|
|
178
|
+
o, i = 0, 0
|
|
179
|
+
for k, m in parts:
|
|
180
|
+
K = k.shape[-2]
|
|
181
|
+
o = o + torch.matmul(p[..., i:i + K], k.float())
|
|
182
|
+
i += K
|
|
183
|
+
return o
|
|
184
|
+
|
|
185
|
+
def _out(self, o, pos, dt):
|
|
186
|
+
o = self.rope(o.to(dt), pos, inverse=True)
|
|
187
|
+
sh = o.shape[:-2]
|
|
188
|
+
o = o.reshape(*sh, self.G, -1)
|
|
189
|
+
y = torch.einsum("...gi,gri->...gr", o, self.woa.view(self.G, -1, o.shape[-1]).to(o.dtype))
|
|
190
|
+
return LINEAR(y.reshape(-1, y.shape[-2] * y.shape[-1]), self.wob)
|
|
191
|
+
|
|
192
|
+
def _refresh(self, bi, w0, n, wend):
|
|
193
|
+
"""recompute committed entries of windows w0 .. w0+n-1 (those < wend) of users bi from the raw buffers."""
|
|
194
|
+
r = self.r
|
|
195
|
+
P = ((w0[:, None] - 1) * r + torch.arange((n + 1) * r, device=DEV)).clamp(0, self.smax - 1)
|
|
196
|
+
idx = (w0[:, None] + torch.arange(n, device=DEV))
|
|
197
|
+
ok = (idx < wend[:, None])[..., None]
|
|
198
|
+
idx = idx.clamp(max=self.C - 1)
|
|
199
|
+
b2 = bi[:, None]
|
|
200
|
+
for c in self.series:
|
|
201
|
+
e = c.entries(c.bk[b2, P], c.bg[b2, P], w0)
|
|
202
|
+
c.ce[b2, idx] = torch.where(ok, e.to(c.ce.dtype), c.ce[b2, idx])
|
|
203
|
+
|
|
204
|
+
# ------------------------------------------------------------------ entry points
|
|
205
|
+
def prefill(self, x, ctx, chunk=512):
|
|
206
|
+
T, b, p0 = x.shape[0], ctx.b, ctx.pos0
|
|
207
|
+
end = p0 + T
|
|
208
|
+
pos = torch.arange(p0, end, device=x.device)
|
|
209
|
+
qr, q, kv = self._q(x, pos)
|
|
210
|
+
self.kc[b, p0:end] = kv
|
|
211
|
+
bi = torch.tensor([b], device=DEV)
|
|
212
|
+
if self.r:
|
|
213
|
+
for c in self.series:
|
|
214
|
+
c.bk[b, p0:end], c.bg[b, p0:end] = c.proj(x)
|
|
215
|
+
w0, w1 = p0 // self.r, end // self.r
|
|
216
|
+
if w1 > w0:
|
|
217
|
+
self._refresh(bi, torch.tensor([w0], device=DEV), w1 - w0, torch.tensor([w1], device=DEV))
|
|
218
|
+
out = []
|
|
219
|
+
kp = torch.arange(end, device=x.device)
|
|
220
|
+
for s0 in range(0, T, chunk):
|
|
221
|
+
s1 = min(T, s0 + chunk)
|
|
222
|
+
t = pos[s0:s1]
|
|
223
|
+
m = (kp[None] <= t[:, None]) & (kp[None] > t[:, None] - self.win)
|
|
224
|
+
parts = [(self.kc[b, :end][None], m)]
|
|
225
|
+
if self.r:
|
|
226
|
+
nE = end // self.r
|
|
227
|
+
wv = torch.arange(nE, device=x.device)[None] < ((t + 1) // self.r)[:, None] # (Q, nE)
|
|
228
|
+
ents = self.comp.ce[b, :nE]
|
|
229
|
+
if self.csa and nE:
|
|
230
|
+
si = self._iscore(qr[s0:s1], x[s0:s1], t, self.ix.ce[b, :nE]).masked_fill(~wv, NEG)
|
|
231
|
+
ti = si.topk(min(self.s["itopk"], nE), -1).indices
|
|
232
|
+
wv = wv & torch.zeros_like(wv).scatter(-1, ti, True)
|
|
233
|
+
parts.append((ents[None], wv))
|
|
234
|
+
out.append(self._attend(q[s0:s1], parts))
|
|
235
|
+
return self._out(torch.cat(out, 0), pos, x.dtype)
|
|
236
|
+
|
|
237
|
+
def tree(self, x, ctx):
|
|
238
|
+
B, N = ctx.B, ctx.N
|
|
239
|
+
pos = ctx.pos # (B, N)
|
|
240
|
+
L = ctx.lens.long()
|
|
241
|
+
xb = x.view(B, N, -1)
|
|
242
|
+
qr, q, kv = self._q(xb, pos)
|
|
243
|
+
self._tkv = kv
|
|
244
|
+
kp = torch.arange(self.smax, device=x.device)
|
|
245
|
+
mc = (kp[None, None] < L[:, None, None]) & (kp[None, None] > pos[..., None] - self.win) # (B, N, smax)
|
|
246
|
+
anc = ctx.shape.anc[None].expand(B, N, N)
|
|
247
|
+
mt = anc & (pos[:, None, :] > pos[..., None] - self.win)
|
|
248
|
+
parts = [(self.kc[:, None], mc), (kv[:, None], mt)]
|
|
249
|
+
if self.r:
|
|
250
|
+
r = self.r
|
|
251
|
+
raw = [c.proj(x) for c in self.series]
|
|
252
|
+
self._traw = [(k.view(B, N, -1), g.view(B, N, -1)) for k, g in raw]
|
|
253
|
+
X = (ctx.maxd + 1) // r + 1
|
|
254
|
+
w0 = L // r # (B,)
|
|
255
|
+
P = (w0[:, None] - 1) * r + torch.arange((X + 1) * r, device=DEV) # (B, S) source positions
|
|
256
|
+
paths = ctx.shape.paths.long() # (N, MAXL) root..node
|
|
257
|
+
MAXL = paths.shape[1]
|
|
258
|
+
j = (P - L[:, None]).clamp(0, MAXL - 1) # (B, S)
|
|
259
|
+
node = paths[:, j].permute(1, 0, 2) # (B, N, S)
|
|
260
|
+
committed = (P < L[:, None])[:, None, :, None]
|
|
261
|
+
live = (P[:, None, :] <= pos[..., None])[..., None]
|
|
262
|
+
Pc = P.clamp(0, self.smax - 1)
|
|
263
|
+
bi = torch.arange(B, device=DEV)[:, None, None]
|
|
264
|
+
wi = w0[:, None, None] + torch.arange(X, device=DEV) # (B, 1, X)
|
|
265
|
+
xv = wi < ((pos + 1) // r)[..., None] # (B, N, X)
|
|
266
|
+
cv = (torch.arange(self.C, device=DEV)[None] < w0[:, None])[:, None].expand(B, N, self.C)
|
|
267
|
+
ents = []
|
|
268
|
+
for c, (tk, tg) in zip(self.series, self._traw):
|
|
269
|
+
ck, cg = c.bk[bi[..., 0], Pc][:, None], c.bg[bi[..., 0], Pc][:, None] # (B, 1, S, cw)
|
|
270
|
+
sk, sg = tk[bi, node], tg[bi, node] # (B, N, S, cw)
|
|
271
|
+
sk = torch.where(committed, ck, torch.where(live, sk, torch.zeros_like(sk)))
|
|
272
|
+
sg = torch.where(committed, cg, torch.where(live, sg, torch.zeros_like(sg)))
|
|
273
|
+
ents.append(c.entries(sk, sg, w0[:, None].expand(B, N))) # (B, N, X, hd)
|
|
274
|
+
if self.csa:
|
|
275
|
+
si = torch.cat([self._iscore(qr, xb, pos, self.ix.ce[:, None]),
|
|
276
|
+
self._iscore(qr, xb, pos, ents[1])],
|
|
277
|
+
-1)
|
|
278
|
+
vis = torch.cat([cv, xv], -1)
|
|
279
|
+
si = si.masked_fill(~vis, NEG)
|
|
280
|
+
ti = si.topk(min(self.s["itopk"], si.shape[-1]), -1).indices
|
|
281
|
+
vis = vis & torch.zeros_like(vis).scatter(-1, ti, True)
|
|
282
|
+
cv, xv = vis[..., :self.C], vis[..., self.C:]
|
|
283
|
+
parts += [(self.comp.ce[:, None], cv), (ents[0], xv)]
|
|
284
|
+
o = self._attend(q, parts)
|
|
285
|
+
return self._out(o, pos, x.dtype)
|
|
286
|
+
|
|
287
|
+
def commit(self, ctx):
|
|
288
|
+
B, ML = ctx.acc_path.shape
|
|
289
|
+
bi = torch.arange(B, device=DEV)[:, None].expand(B, ML)
|
|
290
|
+
L = ctx.lens.long()
|
|
291
|
+
dst = (L[:, None] + torch.arange(ML, device=DEV)[None]).clamp_(max=self.smax - 1)
|
|
292
|
+
src = ctx.acc_path.long()
|
|
293
|
+
self.kc[bi, dst] = self._tkv[bi, src]
|
|
294
|
+
if self.r:
|
|
295
|
+
for c, (tk, tg) in zip(self.series, self._traw):
|
|
296
|
+
c.bk[bi, dst], c.bg[bi, dst] = tk[bi, src], tg[bi, src]
|
|
297
|
+
r = self.r
|
|
298
|
+
self._refresh(torch.arange(B, device=DEV), L // r, ML // r + 1, (L + ctx.acc_len.long()) // r)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
@register("moe_ds4")
|
|
302
|
+
class MoEDS4:
|
|
303
|
+
"""routed MoE over per-expert w1 (gate) / w3 (up) / w2 (down): scores sqrtsoftplus | sigmoid | softmax of the
|
|
304
|
+
router logits; experts chosen by top-k of score (+ correction bias) or by a frozen token-id table (hash); weights
|
|
305
|
+
= gathered scores renormalised (+1e-20) * routed scale; clamped SwiGLU silu(min(g, l)) * clip(u, -l, l); plus a
|
|
306
|
+
shared expert of the same form."""
|
|
307
|
+
|
|
308
|
+
def __init__(self, s, W, g):
|
|
309
|
+
p = s["prefix"]
|
|
310
|
+
if g["tp"]["world"] > 1:
|
|
311
|
+
raise NotImplementedError("moe_ds4 under tensor parallelism")
|
|
312
|
+
E = s["E"]
|
|
313
|
+
self.gu = torch.stack([torch.cat([W.get(f"{p}experts.{e}.w1.weight"), W.get(f"{p}experts.{e}.w3.weight")], 0)
|
|
314
|
+
for e in range(E)])
|
|
315
|
+
self.dn = torch.stack([W.get(f"{p}experts.{e}.w2.weight") for e in range(E)])
|
|
316
|
+
self.I = self.gu.shape[1] // 2
|
|
317
|
+
self.rw = W.get(p + "gate.weight")
|
|
318
|
+
self.rb = W.get(p + "gate.bias").float() if W.has(p + "gate.bias") else None
|
|
319
|
+
self.tid = W.get(p + "gate.tid2eid").long() if s.get("hash") else None
|
|
320
|
+
self.k, self.score, self.rs, self.lim = s["top_k"], s["score"], s["routed_scale"], s["limit"]
|
|
321
|
+
self.sh = [W.get(p + f"shared_experts.{n}.weight") for n in ("w1", "w3", "w2")] if s.get("shared") else None
|
|
322
|
+
self.g = g
|
|
323
|
+
|
|
324
|
+
def _act(self, gt, up):
|
|
325
|
+
return F.silu(gt.clamp(max=self.lim)) * up.clamp(-self.lim, self.lim)
|
|
326
|
+
|
|
327
|
+
def _ffn(self, x, e):
|
|
328
|
+
h = F.linear(x, self.gu[e].to(x.dtype))
|
|
329
|
+
return F.linear(self._act(h[:, :self.I], h[:, self.I:]), self.dn[e].to(x.dtype))
|
|
330
|
+
|
|
331
|
+
def __call__(self, x):
|
|
332
|
+
lg = F.linear(x, self.rw.to(x.dtype)).float()
|
|
333
|
+
sc = (F.softplus(lg).sqrt() if self.score == "sqrtsoftplus" else torch.sigmoid(lg) if self.score == "sigmoid"
|
|
334
|
+
else torch.softmax(lg, -1))
|
|
335
|
+
if self.tid is not None:
|
|
336
|
+
ti = self.tid[self.g["tok"].long()]
|
|
337
|
+
else:
|
|
338
|
+
ti = (sc + self.rb if self.rb is not None else sc).topk(self.k, -1).indices
|
|
339
|
+
w = sc.gather(1, ti)
|
|
340
|
+
w = (w / (w.sum(-1, keepdim=True) + 1e-20) * self.rs).to(x.dtype)
|
|
341
|
+
out = torch.zeros_like(x)
|
|
342
|
+
if x.is_cuda:
|
|
343
|
+
for e in range(self.gu.shape[0]):
|
|
344
|
+
out += self._ffn(x, e) * (w * (ti == e)).sum(1)[:, None]
|
|
345
|
+
else:
|
|
346
|
+
for e in torch.unique(ti).tolist():
|
|
347
|
+
rows, kk = torch.nonzero(ti == e, as_tuple=True)
|
|
348
|
+
out.index_add_(0, rows, self._ffn(x[rows], e) * w[rows, kk, None])
|
|
349
|
+
if self.sh is not None:
|
|
350
|
+
g_, u_, d_ = self.sh
|
|
351
|
+
out = out + LINEAR(self._act(LINEAR(x, g_), LINEAR(x, u_)), d_)
|
|
352
|
+
return out
|
|
353
|
+
|
|
354
|
+
def weights(self):
|
|
355
|
+
return {"gu": self.gu, "dn": self.dn}
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
class HyperConn:
|
|
359
|
+
"""manifold-constrained hyper-connection: (pre, post, comb) from the flattened normed streams; Sinkhorn comb."""
|
|
360
|
+
|
|
361
|
+
def __init__(self, W, p, n, iters, heps, eps, head=False):
|
|
362
|
+
if head:
|
|
363
|
+
self.fn, self.base, self.sc = (W.get(p + "hc_fn").float(), W.get(p + "hc_base").float(),
|
|
364
|
+
W.get(p + "hc_scale").float())
|
|
365
|
+
else:
|
|
366
|
+
self.fn, self.base, self.sc = (W.get(p + "fn").float(), W.get(p + "base").float(),
|
|
367
|
+
W.get(p + "scale").float())
|
|
368
|
+
self.n, self.iters, self.heps, self.eps = n, iters, heps, eps
|
|
369
|
+
|
|
370
|
+
def _mix(self, x):
|
|
371
|
+
return F.linear(urms(x.reshape(x.shape[0], -1).float(), self.eps), self.fn)
|
|
372
|
+
|
|
373
|
+
def head(self, x):
|
|
374
|
+
pre = torch.sigmoid(self._mix(x) * self.sc + self.base) + self.heps
|
|
375
|
+
return (pre[..., None] * x).sum(1).to(x.dtype)
|
|
376
|
+
|
|
377
|
+
def __call__(self, x, f):
|
|
378
|
+
n, mx = self.n, self._mix(x)
|
|
379
|
+
b = self.base
|
|
380
|
+
pre = torch.sigmoid(mx[:, :n] * self.sc[0] + b[:n]) + self.heps
|
|
381
|
+
post = 2 * torch.sigmoid(mx[:, n:2 * n] * self.sc[1] + b[n:2 * n])
|
|
382
|
+
comb = torch.softmax(mx[:, 2 * n:].view(-1, n, n) * self.sc[2] + b[2 * n:].view(n, n), -1) + self.heps
|
|
383
|
+
comb = comb / (comb.sum(-2, keepdim=True) + self.heps)
|
|
384
|
+
for _ in range(self.iters - 1):
|
|
385
|
+
comb = comb / (comb.sum(-1, keepdim=True) + self.heps)
|
|
386
|
+
comb = comb / (comb.sum(-2, keepdim=True) + self.heps)
|
|
387
|
+
y = f((pre[..., None] * x).sum(1).to(x.dtype))
|
|
388
|
+
dt = x.dtype
|
|
389
|
+
return post.to(dt)[..., None] * y[:, None, :] + torch.matmul(comb.to(dt).transpose(-1, -2), x)
|