AbstractPhil commited on
Commit
1f66e32
·
verified ·
1 Parent(s): 7ccad85

mini-beatrix-2s automodel: attention.py (mission final 16.101B, alephllm 0.8.6)

Browse files
Files changed (1) hide show
  1. attention.py +336 -0
attention.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Attention blocks: CausalSDPA (the workhorse) and CausalSplatHUB (the
2
+ instrumented aleph read).
3
+
4
+ CausalSplatHUB is causal linear attention through the oriented address:
5
+ prefix-sum memories over the two K-wide halves of the 2K softmax, read by
6
+ the query's halves and normalized by the scalar agreement mass. O(n·K·d)
7
+ compute, no softmax over positions, no selection event anywhere.
8
+
9
+ The naive cumsum form materializes (B, n, K, d) — fine on probe beds,
10
+ fatal at mission scale. forward() therefore uses an exact chunked scan:
11
+ within-chunk causal affinity (B, C, C) + cross-chunk carried states
12
+ (B, K, d). `forward_naive()` is kept verbatim as the equivalence oracle
13
+ for the test array.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+
21
+ from .address import AlephAddress, dtype_floor
22
+
23
+
24
+ class CausalSDPA(nn.Module):
25
+ def __init__(self, d: int, heads: int = 8):
26
+ super().__init__()
27
+ assert d % heads == 0
28
+ self.h = heads
29
+ self.qkv = nn.Linear(d, 3 * d, bias=False)
30
+ self.o = nn.Linear(d, d, bias=False)
31
+ nn.init.orthogonal_(self.qkv.weight)
32
+ nn.init.orthogonal_(self.o.weight)
33
+
34
+ def forward(self, x):
35
+ B, n, d = x.shape
36
+ q, k, v = self.qkv(x).chunk(3, dim=-1)
37
+ q, k, v = (t.view(B, n, self.h, d // self.h).transpose(1, 2)
38
+ for t in (q, k, v))
39
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
40
+ return self.o(y.transpose(1, 2).reshape(B, n, d))
41
+
42
+ # ---------------------------------------------------- incremental decode
43
+ def prefill(self, x):
44
+ """Full causal pass that also returns the decode cache (K/V)."""
45
+ B, n, d = x.shape
46
+ q, k, v = self.qkv(x).chunk(3, dim=-1)
47
+ q, k, v = (t.view(B, n, self.h, d // self.h).transpose(1, 2)
48
+ for t in (q, k, v))
49
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
50
+ return self.o(y.transpose(1, 2).reshape(B, n, d)), {"k": k, "v": v}
51
+
52
+ def step(self, x_t, cache):
53
+ """One new position attending over everything cached (KV cache)."""
54
+ B, _, d = x_t.shape
55
+ q, k, v = self.qkv(x_t).chunk(3, dim=-1)
56
+ q, k, v = (t.view(B, 1, self.h, d // self.h).transpose(1, 2)
57
+ for t in (q, k, v))
58
+ cache["k"] = torch.cat([cache["k"], k], dim=2)
59
+ cache["v"] = torch.cat([cache["v"], v], dim=2)
60
+ y = F.scaled_dot_product_attention(q, cache["k"], cache["v"])
61
+ return self.o(y.transpose(1, 2).reshape(B, 1, d))
62
+
63
+
64
+ class _Constellation(nn.Module):
65
+ """One codebook with its own routing-owned q/k frames (v2 form).
66
+
67
+ The multi-constellation hub is the PRODUCT-CODE form (B2: independent
68
+ frames compose, .859 -> .955 monotone in members) at lawful supply
69
+ (ROUND 5e: K <= 2*D per address space — v1's single 512-anchor book in
70
+ 32 dims ran 16x and crowded into 333-646 duplicate pairs)."""
71
+
72
+ def __init__(self, d: int, K: int, D: int, tau: float):
73
+ super().__init__()
74
+ self.addr = AlephAddress(K, D, tau)
75
+ self.q = nn.Linear(d, D, bias=False)
76
+ self.k = nn.Linear(d, D, bias=False)
77
+ nn.init.orthogonal_(self.q.weight)
78
+ nn.init.orthogonal_(self.k.weight)
79
+
80
+
81
+ class CausalSplatHUB(nn.Module):
82
+ def __init__(self, d: int, K: int = 512, D: int = 32, tau: float = 0.1,
83
+ chunk: int = 256, n_const: int = 1):
84
+ super().__init__()
85
+ if K > 2 * D:
86
+ import warnings
87
+ warnings.warn(
88
+ f"CausalSplatHUB supply K={K} exceeds 2*D={2*D}: anchors on "
89
+ f"a {D}-dim sphere past ~2x supply CROWD (measured — ROUND "
90
+ "5e shape ladder + the mini-beatrix-1 hub census: duplicate "
91
+ "pairs by the hundreds, consumed erank collapse). Provision "
92
+ "K <= 2*D or raise D.", stacklevel=2)
93
+ self.n_const = n_const
94
+ if n_const == 1:
95
+ # v1 layout, bit-for-bit: state-dict keys addr/q/k unchanged so
96
+ # every shipped checkpoint and the HF automodel mirror load.
97
+ self.addr = AlephAddress(K, D, tau)
98
+ self.q = nn.Linear(d, D, bias=False)
99
+ self.k = nn.Linear(d, D, bias=False)
100
+ nn.init.orthogonal_(self.q.weight)
101
+ nn.init.orthogonal_(self.k.weight)
102
+ else:
103
+ self.consts = nn.ModuleList(
104
+ _Constellation(d, K, D, tau) for _ in range(n_const))
105
+ self.chunk = chunk # 256 measured best at ctx 2048 (bench)
106
+ self.v = nn.Linear(d, d, bias=False)
107
+ self.o = nn.Linear(d, d, bias=False)
108
+ for m in (self.v, self.o):
109
+ nn.init.orthogonal_(m.weight)
110
+ self._mask_cache: dict = {}
111
+ self._den_raw = None # (den tensor, floor) until read
112
+ self._den_stats = None # cached floats after first read
113
+
114
+ # den stats are LAZY: the reference forward paid three .item() GPU
115
+ # syncs per call just to keep this attribute warm; instruments read
116
+ # it at most once per health interval. Property keeps the tuple API.
117
+ @property
118
+ def last_den_stats(self):
119
+ if self._den_stats is None and self._den_raw is not None:
120
+ den, cl = self._den_raw
121
+ with torch.no_grad():
122
+ self._den_stats = (den.min().item(), den.mean().item(),
123
+ (den <= cl).float().mean().item())
124
+ return self._den_stats
125
+
126
+ @last_den_stats.setter
127
+ def last_den_stats(self, value):
128
+ self._den_stats = value
129
+ self._den_raw = None
130
+
131
+ def _mask(self, C: int, device, dtype):
132
+ key = (C, device, dtype)
133
+ m = self._mask_cache.get(key)
134
+ if m is None:
135
+ m = torch.tril(torch.ones(C, C, device=device, dtype=dtype))
136
+ self._mask_cache[key] = m
137
+ return m
138
+
139
+ def _prefix(self, nc: int, device, dtype):
140
+ """Strictly-lower-triangular ones (nc, nc): the exclusive prefix sum
141
+ as ONE tensor-core GEMM. The cumsum scan kernel ran ~6x off its
142
+ memory roofline on the (B, nc, 2K·H, d) layout (C2d, Blackwell
143
+ 2026-08-26) and its backward is flip+cumsum+flip; matmul accumulates
144
+ fp32 inside the GEMM — strictly MORE precise than a bf16 cumsum."""
145
+ key = ("prefix", nc, device, dtype)
146
+ m = self._mask_cache.get(key)
147
+ if m is None:
148
+ m = torch.tril(torch.ones(nc, nc, device=device, dtype=dtype),
149
+ diagonal=-1)
150
+ self._mask_cache[key] = m
151
+ return m
152
+
153
+ # ------------------------------------------------ constellation access
154
+ def _code_cat_qk(self, x):
155
+ """BOTH oriented codes (q and k, every book) in one batched pass.
156
+
157
+ Stack all 2H frame weights, one projection einsum, one address
158
+ einsum, ONE fused softmax. The oriented address IS softmax over the
159
+ 2K half-axes — exp(cat[u−m, −u−m])/Σ with m = max|u| is bit-the-same
160
+ quantity as F.softmax(cat[u, −u]) (softmax subtracts its own max,
161
+ which is exactly m). This is a KERNEL substitution, not a mechanism
162
+ change: no softmax over positions, no softmax across books —
163
+ composition stays budget. The old chain was ~8 unfused GB-scale
164
+ elementwise passes per call, twice per forward (C2d: 24.6 ms).
165
+
166
+ AUTOCAST TRAP (measured, Blackwell 2026-08-26): torch.einsum is in
167
+ autocast's PROMOTE category, and F.normalize / exp / softmax are on
168
+ its fp32 list — one fp32 operand drags the whole downstream scan to
169
+ fp32. Operands are cast to the autocast dtype explicitly; the
170
+ softmax accumulates fp32 inside the kernel (standard attention
171
+ practice) and the returned CODE is in the compute dtype so the
172
+ num/S/P scan and its backward run bf16. DELIBERATE exception: den's
173
+ reductions (kc.sum, att.sum) stay fp32 by autocast policy — the
174
+ agreement mass keeps v1's fp32 dtype_floor semantics at ~5% of
175
+ scan traffic (dtype audit 2026-08-26).
176
+
177
+ Returns (qc, kc), each (B, n, H*2K), per-book layout [K pos | K neg]
178
+ matching oriented()/forward_naive."""
179
+ units = self._units()
180
+ dt = (torch.get_autocast_dtype("cuda")
181
+ if torch.is_autocast_enabled() and x.is_cuda else x.dtype)
182
+ W = torch.stack([q.weight for _, q, _ in units]
183
+ + [k.weight for _, _, k in units]).to(dt) # (2H, D, d)
184
+ tau = units[0][0].tau
185
+ # tau folds into the codebook (a few-MB fp32 tensor op, MORE precise
186
+ # than dividing bf16 u afterwards), and the query-side row
187
+ # normalization folds into ONE post-GEMM scale: a per-row scalar
188
+ # commutes through the linear map, so (xh/||xh||) @ A^T / tau ==
189
+ # (xh @ (A/tau)^T) * (1/||xh||) exactly (fp reorder). Kills the
190
+ # fp32 normalize-div + cast + separate tau-div passes (perf audit
191
+ # 2026-08-26). Same 1e-12 floor as F.normalize.
192
+ A = (F.normalize(torch.stack([a.codebook for a, _, _ in units]),
193
+ dim=-1) / tau).to(dt) # (H, K, D)
194
+ A = torch.cat([A, A]) # (2H, K, D)
195
+ xh = torch.einsum("bnd,hkd->bnhk", x.to(dt), W) # (B,n,2H,D)
196
+ inv = torch.linalg.vector_norm( # fp32 by autocast
197
+ xh, dim=-1, keepdim=True).clamp_min(1e-12) \
198
+ .reciprocal().to(dt) # policy; cast back
199
+ u = torch.einsum("bnhd,hkd->bnhk", xh, A) * inv # (B,n,2H,K)
200
+ B, n = x.shape[:2]
201
+ H = len(units)
202
+ # Split-axis-first WITHOUT a copy: the permute is a view, and the
203
+ # cat (which must write a fresh tensor anyway) absorbs it — so the
204
+ # q/k split below is a pure view instead of two GB-scale reshape
205
+ # copies. Layout per book stays [K pos | K neg], book-major.
206
+ u = u.view(B, n, 2, H, -1).permute(2, 0, 1, 3, 4)
207
+ # softmax: the explicit dtype arg opts out of autocast's fp32
208
+ # override (fp32_set_opt_dtype policy) while the CUDA kernel still
209
+ # accumulates fp32 internally — bf16-in/bf16-out, no fp32 e pass,
210
+ # and the softmax BACKWARD chain halves too.
211
+ e = F.softmax(torch.cat([u, -u], dim=-1), dim=-1, dtype=dt)
212
+ return e[0].reshape(B, n, -1), e[1].reshape(B, n, -1)
213
+
214
+ def _units(self):
215
+ """Uniform view: [(addr, q, k)] whether single- or multi-book."""
216
+ if self.n_const == 1:
217
+ return [(self.addr, self.q, self.k)]
218
+ return [(c.addr, c.q, c.k) for c in self.consts]
219
+
220
+ def _halves(self, x):
221
+ """Per-constellation oriented halves + shared values."""
222
+ outs = []
223
+ for addr, q, k in self._units():
224
+ qp, qn = addr.oriented(q(x))
225
+ kp, kn = addr.oriented(k(x))
226
+ outs.append((qp, qn, kp, kn))
227
+ return outs, self.v(x)
228
+
229
+ def _scan_cat(self, qc, kc, v, mask, B, n, nc, C, d):
230
+ """The exact chunked scan for one 2K-wide constellation."""
231
+ K2 = qc.shape[-1]
232
+ qc = qc.view(B, nc, C, K2)
233
+ kc = kc.view(B, nc, C, K2)
234
+ S = torch.einsum("bick,bicd->bikd", kc, v) # per-chunk 2KxD sums
235
+ L = self._prefix(nc, qc.device, qc.dtype)
236
+ P = torch.matmul(L, S.reshape(B, nc, -1)).view_as(S) # excl. prefix
237
+ zS = kc.sum(dim=2) # (B, nc, 2K)
238
+ zP = torch.matmul(L, zS)
239
+ att = torch.einsum("bick,bijk->bicj", qc, kc) * mask # (B,nc,C,C)
240
+ num = torch.einsum("bick,bikd->bicd", qc, P) + att @ v
241
+ den = torch.einsum("bick,bik->bic", qc, zP).unsqueeze(-1) \
242
+ + att.sum(dim=-1, keepdim=True)
243
+ return num.reshape(B, nc * C, d)[:, :n], den.reshape(B, nc * C, 1)[:, :n]
244
+
245
+ def forward(self, x):
246
+ """Fast path: the two oriented halves run as ONE 2K-wide pass —
247
+ every term is a sum of bilinear forms over the halves, so one
248
+ pass over cat(p, n) is the same arithmetic in half the kernels
249
+ (equal to forward_naive to fp reorder, ~1.5e-06; speed-harness
250
+ verdict 2026-08-15: 1.7x eager, 4.0x under torch.compile).
251
+ Multi-constellation (n_const > 1): each book scans independently
252
+ and the reads compose BY BUDGET — numerators and agreement masses
253
+ sum across books before the single divide (never softmax over
254
+ books; B4 measured comparative composition at -.10)."""
255
+ B, n, d = x.shape
256
+ v = self.v(x)
257
+ C = min(self.chunk, n)
258
+ pad = (-n) % C
259
+ vp = F.pad(v, (0, 0, 0, pad)) if pad else v
260
+ nc = (n + pad) // C
261
+ vc = vp.view(B, nc, C, d)
262
+ mask = self._mask(C, x.device, v.dtype)
263
+ # BATCHED path, both n_const cases (2026-08-26 Blackwell verdicts:
264
+ # the per-book Python loop was 512 sequential little scans —
265
+ # launch-bound; then the split q/k exp chains were ~8 unfused
266
+ # GB-scale passes each). Budget composition is algebraically ONE
267
+ # scan over the concatenated code: num and den are sums of per-book
268
+ # bilinear forms, so scanning cat_h(qc_h) against cat_h(kc_h)
269
+ # equals summing H separate scans (fp reorder).
270
+ qc, kc = self._code_cat_qk(x) # (B, n, H*2K)
271
+ if qc.dtype != v.dtype: # einsum-promote guard (belt-and-braces;
272
+ qc = qc.to(v.dtype) # _code_cat_qk already returns the
273
+ kc = kc.to(v.dtype) # compute dtype)
274
+ if pad:
275
+ qc = F.pad(qc, (0, 0, 0, pad))
276
+ kc = F.pad(kc, (0, 0, 0, pad))
277
+ num, den = self._scan_cat(qc, kc, vc, mask, B, n, nc, C, d)
278
+ cl = dtype_floor(den)
279
+ self._den_raw = (den.detach(), cl)
280
+ self._den_stats = None
281
+ return self.o(num / den.clamp_min(cl))
282
+
283
+ # ---------------------------------------------------- incremental decode
284
+ def prefill(self, x):
285
+ """Full causal pass plus the decode cache. The hub's cache is the
286
+ CONSTANT-SIZE prefix state (Sp, Sn, zp, zn) per constellation —
287
+ O(n_const·K·d) regardless of sequence length; this is the
288
+ linear-attention decode advantage. n_const == 1 keeps the exact
289
+ v1 cache shape (arms and the Space depend on it)."""
290
+ out = self.forward(x)
291
+ halves, v = self._halves(x)
292
+ caches = [{"Sp": torch.einsum("bnk,bnd->bkd", kp, v),
293
+ "Sn": torch.einsum("bnk,bnd->bkd", kn, v),
294
+ "zp": kp.sum(dim=1), "zn": kn.sum(dim=1)}
295
+ for (qp, qn, kp, kn) in halves]
296
+ return out, (caches[0] if self.n_const == 1 else {"consts": caches})
297
+
298
+ def step(self, x_t, cache):
299
+ """One new position: fold it into each prefix state, read once,
300
+ compose by budget across constellations."""
301
+ halves, v = self._halves(x_t) # (B,1,K)/(B,1,d)
302
+ caches = [cache] if self.n_const == 1 else cache["consts"]
303
+ v1 = v.squeeze(1)
304
+ num = den = None
305
+ for (qp, qn, kp, kn), c in zip(halves, caches):
306
+ kp1, kn1 = kp.squeeze(1), kn.squeeze(1)
307
+ c["Sp"] = c["Sp"] + kp1.unsqueeze(-1) * v1.unsqueeze(1)
308
+ c["Sn"] = c["Sn"] + kn1.unsqueeze(-1) * v1.unsqueeze(1)
309
+ c["zp"] = c["zp"] + kp1
310
+ c["zn"] = c["zn"] + kn1
311
+ qp1, qn1 = qp.squeeze(1), qn.squeeze(1)
312
+ nu = torch.einsum("bk,bkd->bd", qp1, c["Sp"]) \
313
+ + torch.einsum("bk,bkd->bd", qn1, c["Sn"])
314
+ de = ((qp1 * c["zp"]).sum(-1)
315
+ + (qn1 * c["zn"]).sum(-1)).unsqueeze(-1)
316
+ num = nu if num is None else num + nu
317
+ den = de if den is None else den + de
318
+ return self.o((num / den.clamp_min(dtype_floor(den))).unsqueeze(1))
319
+
320
+ def forward_naive(self, x):
321
+ """Reference cumsum form (the validated probe-bed implementation).
322
+ O(n·K·d) memory — test oracle only. Sums constellations by budget,
323
+ matching forward()."""
324
+ halves, v = self._halves(x)
325
+ num = den = None
326
+ for qp, qn, kp, kn in halves:
327
+ Sp = torch.cumsum(torch.einsum("bnk,bnd->bnkd", kp, v), dim=1)
328
+ Sn = torch.cumsum(torch.einsum("bnk,bnd->bnkd", kn, v), dim=1)
329
+ zp = torch.cumsum(kp, dim=1)
330
+ zn = torch.cumsum(kn, dim=1)
331
+ nu = torch.einsum("bnk,bnkd->bnd", qp, Sp) \
332
+ + torch.einsum("bnk,bnkd->bnd", qn, Sn)
333
+ de = (qp * zp).sum(-1, keepdim=True) + (qn * zn).sum(-1, keepdim=True)
334
+ num = nu if num is None else num + nu
335
+ den = de if den is None else den + de
336
+ return self.o(num / den.clamp_min(dtype_floor(den)))