AbstractPhil commited on
Commit
7f6ced4
Β·
verified Β·
1 Parent(s): 8130a41

Create acd_attention.py

Browse files
Files changed (1) hide show
  1. acd_attention.py +300 -0
acd_attention.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # acd_attention.py β€” exp_011 Phase 4: composition WHERE INFORMATION IS CREATED
3
+ #
4
+ # The sterility law (Phase 3b) proved a post-backbone conditioner cannot add
5
+ # bits: I(Y;h) >= I(Y;f(h)). So the composition moves INTO the routing: the
6
+ # composed micro-address becomes the attention feature map itself, per layer.
7
+ #
8
+ # The hub equations are width-agnostic (pure GEMMs over pΒ± of width K), so
9
+ # concatenated stage addresses compute an ADDITIVE KERNEL exactly:
10
+ # k(q,x) = sum_i phi_i(q) . phi_i(x), phi_i = stage-i signed address.
11
+ # Budget rule K_i = K_total/m matches codebook floats AND feature width at
12
+ # once β€” every operator emits width K_total (=64 default), fully fair.
13
+ #
14
+ # Operators (kernel-valid subset of the ACD taxonomy):
15
+ # single β€” one stage, K=K_total: EXACTLY the stock AlephRoutedAttention
16
+ # (parity-gated in the smoke; the control)
17
+ # sum β€” m independent codebooks over the SAME x_hat, addresses
18
+ # CONCATENATED: width-fair, codebook-fair, conditioning = NONE
19
+ # (the unconditioned-redundancy control, kernel-valid)
20
+ # prod β€” per-stage projections to m INDEPENDENT Da-spheres (the learned
21
+ # projection IS the subspace split): conjunctive-by-construction
22
+ # res β€” sequential on the Da-sphere: stage t addresses the renormalized
23
+ # residual after soft-reconstruction subtraction
24
+ #
25
+ # Paste order: aleph cells 1-4 -> acd_structures -> acd_probe ->
26
+ # acd_attention -> acd_lm_adapter -> acd_forge.
27
+ # ============================================================
28
+ from __future__ import annotations
29
+ import math
30
+ from dataclasses import dataclass
31
+ from typing import Dict, List, Optional, Tuple
32
+
33
+ import torch
34
+ import torch.nn as nn
35
+ import torch.nn.functional as F
36
+ from torch import Tensor
37
+
38
+ try:
39
+ from aleph_routed_attention import (AlephRoutedAttention,
40
+ AlephAttentionConfig)
41
+ from acd_structures import acd_statute, _acd_max_spread_points
42
+ except ImportError:
43
+ pass # notebook paste mode
44
+
45
+
46
+ def _ns(name: str, module: str):
47
+ """Cross-cell resolver (shared-namespace law): globals first, import second."""
48
+ if name in globals():
49
+ return globals()[name]
50
+ import importlib
51
+ return getattr(importlib.import_module(module), name)
52
+
53
+
54
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
55
+ # BaseConfig
56
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
57
+
58
+ ROUTE_OPS = ("single", "sum", "prod", "res")
59
+
60
+ @dataclass
61
+ class RouteComposeConfig:
62
+ op: str = "single"
63
+ m: int = 1
64
+ K_total: int = 64 # feature width AND codebook-float budget
65
+ freeze: str = "free" # 'free' | 'spread'
66
+ seed: int = 1234
67
+
68
+ def __post_init__(self):
69
+ assert self.op in ROUTE_OPS
70
+ if self.op == "single":
71
+ self.m = 1
72
+ assert self.K_total % self.m == 0, "K_total must divide by m"
73
+
74
+ @property
75
+ def K_stage(self) -> int:
76
+ return self.K_total // self.m
77
+
78
+
79
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
80
+ # ACDRoutedAttention β€” surgical subclass: only the address pathway changes
81
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
82
+
83
+ def acd_routed_attention_cls():
84
+ """Lazy factory (top-level subclassing of an unpasted base is illegal
85
+ in the shared namespace β€” standing law)."""
86
+ if "_ACD_RA_CLS" in globals() and globals()["_ACD_RA_CLS"] is not None:
87
+ return globals()["_ACD_RA_CLS"]
88
+ _ARA = _ns("AlephRoutedAttention", "aleph_routed_attention")
89
+ _statute = _ns("acd_statute", "acd_structures")
90
+ _spread = _ns("_acd_max_spread_points", "acd_structures")
91
+
92
+ class ACDRoutedAttention(_ARA):
93
+ """Stock hub attention with a COMPOSED address. Hub math, streaming
94
+ state, masking, chunking: all inherited untouched (width-blind).
95
+ For op='prod' the q/k address projections widen to H*m*Da so each
96
+ stage owns an independent learned Da-sphere."""
97
+
98
+ def __init__(self, cfg: "AlephAttentionConfig",
99
+ rc: RouteComposeConfig):
100
+ assert cfg.mode == "hub", "composed routing: hub mode v1"
101
+ # stock init builds K=cfg.K codebook + H*Da projections; we
102
+ # rebuild what composition changes afterwards.
103
+ super().__init__(cfg)
104
+ self.rc = rc
105
+ m, Ks, Da = rc.m, rc.K_stage, self.Da
106
+ g = torch.Generator().manual_seed(rc.seed)
107
+ if rc.freeze == "spread":
108
+ books = torch.stack([_spread(Ks, Da, seed=rc.seed + i)
109
+ for i in range(m)])
110
+ else:
111
+ books = F.normalize(torch.randn(m, Ks, Da, generator=g),
112
+ dim=-1)
113
+ del self.codebook # replace stock (K,Da)
114
+ self.stage_books = nn.Parameter(
115
+ books, requires_grad=(rc.freeze == "free"))
116
+ if rc.op == "prod": # widen to per-stage spheres
117
+ d = cfg.dim
118
+ self.q_addr = nn.Linear(d, self.H * m * Da, bias=False)
119
+ nn.init.orthogonal_(self.q_addr.weight)
120
+ if cfg.tied_address:
121
+ self.k_addr = self.q_addr
122
+ else:
123
+ self.k_addr = nn.Linear(d, self.H * m * Da, bias=False)
124
+ nn.init.orthogonal_(self.k_addr.weight)
125
+ if rc.op == "res": # Da-space soft decoders
126
+ self.res_dec = nn.Parameter(
127
+ F.normalize(torch.randn(m, 2 * Ks, Da, generator=g),
128
+ dim=-1) * 0.1)
129
+ # eval-mode address cache (probe contract, conditioner-style)
130
+ self.cache_positions = 2048
131
+ self.cached_addresses: Optional[Tensor] = None
132
+ self.cached_flat_idx: Optional[Tensor] = None
133
+
134
+ # ---- projections ------------------------------------------------
135
+ def _split_addr(self, t: Tensor, B: int, S: int) -> Tensor:
136
+ if self.rc.op == "prod":
137
+ t = t.view(B, S, self.H, self.rc.m, self.Da).transpose(1, 2)
138
+ return F.normalize(t, dim=-1) # (B,H,S,m,Da) per-stage sphere
139
+ return super()._split_addr(t, B, S) # (B,H,S,Da)
140
+
141
+ # ---- the composed address ---------------------------------------
142
+ def _stage_address(self, x_hat: Tensor, i: int
143
+ ) -> Tuple[Tensor, Tensor]:
144
+ A = F.normalize(self.stage_books[i], dim=-1) # (Ks, Da)
145
+ u = (x_hat @ A.t()) * (1.0 / self.tau)
146
+ mm = u.abs().amax(dim=-1, keepdim=True)
147
+ ep, en = torch.exp(u - mm), torch.exp(-u - mm)
148
+ Z = (ep + en).sum(dim=-1, keepdim=True)
149
+ return ep / Z, en / Z
150
+
151
+ def _address(self, x_hat: Tensor) -> Tuple[Tensor, Tensor]:
152
+ rc = self.rc
153
+ ps, ns_ = [], []
154
+ if rc.op == "single":
155
+ p, n = self._stage_address(x_hat, 0)
156
+ ps.append(p); ns_.append(n)
157
+ elif rc.op == "prod": # x_hat: (B,H,S,m,Da)
158
+ for i in range(rc.m):
159
+ p, n = self._stage_address(x_hat[..., i, :], i)
160
+ ps.append(p); ns_.append(n)
161
+ elif rc.op == "sum": # same input, m books
162
+ for i in range(rc.m):
163
+ p, n = self._stage_address(x_hat, i)
164
+ ps.append(p); ns_.append(n)
165
+ else: # res: sphere residual chain
166
+ r = x_hat
167
+ for i in range(rc.m):
168
+ p, n = self._stage_address(r, i)
169
+ ps.append(p); ns_.append(n)
170
+ recon = torch.cat([p, n], -1) @ self.res_dec[i]
171
+ r = F.normalize(r - recon, dim=-1)
172
+ P, N = torch.cat(ps, -1), torch.cat(ns_, -1) # width K_total
173
+ if not self.training and P.dim() == 4:
174
+ B, H, S, W = P.shape
175
+ a = torch.cat([P[:, 0], N[:, 0]], -1).reshape(B * S, 2 * W)
176
+ n_keep = min(self.cache_positions, B * S)
177
+ idx = torch.randperm(B * S, device=P.device)[:n_keep]
178
+ Ks = self.rc.K_stage
179
+ st = torch.stack([torch.cat([a[:, i*Ks:(i+1)*Ks],
180
+ a[:, W+i*Ks:W+(i+1)*Ks]], -1)
181
+ for i in range(self.rc.m)], 1) # (BS,m,2Ks)
182
+ self.cached_addresses = st[idx].detach()
183
+ self.cached_flat_idx = idx
184
+ return P, N
185
+
186
+ def _confidence(self, pq_p: Tensor, pq_m: Tensor) -> Tensor:
187
+ A = F.normalize(self.stage_books, dim=-1).reshape(-1, self.Da)
188
+ return ((pq_p - pq_m) @ A).norm(dim=-1)
189
+
190
+ def stage_codebook_stats(self) -> List[Dict]:
191
+ return [_statute(self.stage_books[i].detach())
192
+ for i in range(self.rc.m)]
193
+
194
+ globals()["_ACD_RA_CLS"] = ACDRoutedAttention
195
+ return ACDRoutedAttention
196
+
197
+
198
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
199
+ # LM surgery β€” swap every layer's attention for the composed variant
200
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━��━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
201
+
202
+ def compose_routing(model, rc: RouteComposeConfig):
203
+ """Replace each layer's stock AlephRoutedAttention with the composed
204
+ class (fresh init β€” arms train from scratch). Returns the model."""
205
+ _Cfg = _ns("AlephAttentionConfig", "aleph_routed_attention")
206
+ CLS = acd_routed_attention_cls()
207
+ for li, layer in enumerate(model.layers):
208
+ old = layer["attn"]
209
+ c = old.cfg
210
+ rc_i = RouteComposeConfig(op=rc.op, m=rc.m, K_total=rc.K_total,
211
+ freeze=rc.freeze, seed=rc.seed + 101 * li)
212
+ layer["attn"] = CLS(c, rc_i).to(next(old.parameters()).device)
213
+ model._route_compose = rc
214
+ return model
215
+
216
+
217
+ def routing_codebook_stats(model) -> List[Dict]:
218
+ out = []
219
+ for layer in model.layers:
220
+ out += layer["attn"].stage_codebook_stats()
221
+ return out
222
+
223
+
224
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
225
+ # Smoke β€” parity crown + all ops fwd/bwd + chunk parity
226
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
227
+
228
+ def _smoke():
229
+ torch.manual_seed(0)
230
+ try:
231
+ _ARA = _ns("AlephRoutedAttention", "aleph_routed_attention")
232
+ except Exception:
233
+ print(" - aleph cells not in namespace yet: attention smoke "
234
+ "DEFERRED (paste cells 1-4, then re-run _smoke()).")
235
+ print("acd_attention smoke: PARTIAL (deferred)")
236
+ return
237
+ _Cfg = _ns("AlephAttentionConfig", "aleph_routed_attention")
238
+ CLS = acd_routed_attention_cls()
239
+ B, S, d = 2, 48, 64
240
+ cfg = _Cfg(dim=d, num_heads=2, mode="hub", K=16, D_addr=4,
241
+ tau=0.1, causal=True)
242
+ x = torch.randn(B, S, d)
243
+
244
+ # ── PARITY CROWN: op='single' must equal stock bit-for-bit ──
245
+ stock = _ARA(cfg).eval()
246
+ single = CLS(cfg, RouteComposeConfig(op="single", m=1,
247
+ K_total=16, seed=7)).eval()
248
+ sd = {k: v for k, v in stock.state_dict().items() if k != "codebook"}
249
+ single.load_state_dict(sd, strict=False)
250
+ with torch.no_grad():
251
+ single.stage_books.copy_(stock.codebook.unsqueeze(0))
252
+ y0, y1 = stock(x), single(x)
253
+ assert torch.allclose(y0, y1, atol=1e-5), \
254
+ (y0 - y1).abs().max().item()
255
+ print(" βœ“ PARITY: composed(single) ≑ stock AlephRoutedAttention "
256
+ f"(max Ξ” {(y0-y1).abs().max().item():.2e})")
257
+
258
+ # ── every op: fwd/bwd finite, width fair, stats live ──
259
+ for op, m in (("sum", 4), ("prod", 4), ("res", 4)):
260
+ rc = RouteComposeConfig(op=op, m=m, K_total=16, seed=7)
261
+ att = CLS(cfg, rc)
262
+ y = att(x)
263
+ loss = y.square().mean()
264
+ loss.backward()
265
+ g = [p.grad for p in att.parameters()
266
+ if p.requires_grad and p.grad is not None]
267
+ assert y.shape == (B, S, d) and torch.isfinite(y).all()
268
+ assert g and all(torch.isfinite(t).all() for t in g)
269
+ st = att.stage_codebook_stats()
270
+ assert len(st) == m and all("eff_rank_ceiling" in s for s in st)
271
+ att.eval(); _ = att(x)
272
+ assert att.cached_addresses is not None \
273
+ and att.cached_addresses.shape[1] == m
274
+ print(f" βœ“ {op:5s} m={m} K_stage={rc.K_stage} fwd/bwd + "
275
+ f"cache ({tuple(att.cached_addresses.shape)}) "
276
+ f"dev0 {st[0]['deviation']:+.3f}")
277
+
278
+ # ── chunk-vs-full parity survives the width change (prod) ──
279
+ cfg_nc = _Cfg(dim=d, num_heads=2, mode="hub", K=16, D_addr=4,
280
+ tau=0.1, causal=False)
281
+ att = CLS(cfg_nc, RouteComposeConfig(op="prod", m=4, K_total=16,
282
+ seed=7)).eval()
283
+ with torch.no_grad():
284
+ qh = att._split_addr(att.q_addr(x), B, S)
285
+ kh = att._split_addr(att.k_addr(x), B, S)
286
+ v = att.v_proj(x).view(B, S, att.H, att.hd).transpose(1, 2)
287
+ pq = att._address(qh); pk = att._address(kh)
288
+ full = att._hub_full(*pq, *pk, v)
289
+ causal, _ = att._hub_causal(*pq, *pk, v)
290
+ prefix = att._hub_full(pq[0][:, :, -1:], pq[1][:, :, -1:],
291
+ pk[0], pk[1], v)
292
+ assert torch.allclose(causal[:, :, -1], prefix[:, :, -1], atol=1e-4)
293
+ print(" βœ“ chunked-causal ≑ full-prefix at the last position "
294
+ "(streaming exactness inherited)")
295
+ print("acd_attention smoke: ALL GREEN")
296
+
297
+
298
+ if __name__ == "__main__":
299
+ # Notebook cells execute as __main__: smoke fires on paste (convention).
300
+ _smoke()