Syamsuddin commited on
Commit
101da0d
·
verified ·
1 Parent(s): f9331fa

Upload n-transformer.py

Browse files
Files changed (1) hide show
  1. n-transformer.py +708 -0
n-transformer.py ADDED
@@ -0,0 +1,708 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ N‑Transformers v1.0 — Python Reference Implementation (single‑file)
3
+ Noetic Affective Field Self‑Integration (NAFSI) on a Transformer Base
4
+
5
+ NOTE
6
+ ----
7
+ • Framework: PyTorch ≥ 2.2 (CUDA optional).
8
+ • This file focuses on the parallel PF path, coupling modules, and wrappers needed to augment a standard decoder‑only Transformer.
9
+ • The core Transformer (token path) can be any decoder‑only model that exposes hidden states h_t and base logits z_t (e.g., GPT‑like).
10
+ • All tensors are batch‑first unless noted.
11
+
12
+ Status: Research‑grade reference code (trainable with additional plumbing).
13
+ Author: Prometheus (Cognitive Systems Architect) — with Syams Ideris
14
+ """
15
+ from __future__ import annotations
16
+ import math
17
+ from dataclasses import dataclass
18
+ from typing import Optional, Tuple, Dict
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+
25
+ # ===============================
26
+ # Utilities & Small Helpers
27
+ # ===============================
28
+
29
+ def pairwise_cosine(x: torch.Tensor, y: Optional[torch.Tensor] = None, eps: float = 1e-8) -> torch.Tensor:
30
+ """Compute pairwise cosine similarity between rows of x and (optionally) y.
31
+ x: (B, N, D); y: (B, M, D) or None (then y=x)
32
+ returns: (B, N, M)
33
+ """
34
+ if y is None:
35
+ y = x
36
+ x_norm = F.normalize(x, dim=-1, eps=eps)
37
+ y_norm = F.normalize(y, dim=-1, eps=eps)
38
+ return torch.matmul(x_norm, y_norm.transpose(-1, -2))
39
+
40
+
41
+ def knn_indices(x: torch.Tensor, K: int) -> torch.Tensor:
42
+ """Return K nearest neighbor indices per row using cosine similarity (excluding self).
43
+ x: (B, J, D) -> indices: (B, J, K)
44
+ """
45
+ with torch.no_grad():
46
+ sim = pairwise_cosine(x) # (B,J,J)
47
+ B, J, _ = sim.shape
48
+ sim = sim - torch.eye(J, device=sim.device).unsqueeze(0) * 2.0 # push self to very low
49
+ topk = torch.topk(sim, k=K, dim=-1).indices # (B,J,K)
50
+ return topk
51
+
52
+
53
+ def build_adjacency(indices: torch.Tensor, J: int) -> torch.Tensor:
54
+ """Build symmetric adjacency from KNN indices.
55
+ indices: (B, J, K)
56
+ returns A: (B, J, J) with {0,1} entries.
57
+ """
58
+ B, J_, K = indices.shape
59
+ assert J == J_, "J mismatch"
60
+ A = torch.zeros(B, J, J, device=indices.device)
61
+ arangeJ = torch.arange(J, device=indices.device).view(1, J, 1).expand(B, J, K)
62
+ A.scatter_(dim=-1, index=indices, value=1.0)
63
+ # symmetrize
64
+ A = torch.maximum(A, A.transpose(-1, -2))
65
+ # zero diagonal
66
+ A = A * (1.0 - torch.eye(J, device=A.device).unsqueeze(0))
67
+ return A
68
+
69
+
70
+ def normalized_graph_laplacian(A: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
71
+ """Compute normalized Laplacian L = I - D^{-1/2} A D^{-1/2}.
72
+ A: (B, J, J) adjacency (nonnegative)
73
+ return L: (B, J, J)
74
+ """
75
+ B, J, _ = A.shape
76
+ d = A.sum(-1) + eps # (B,J)
77
+ d_isqrt = (1.0 / torch.sqrt(d)).unsqueeze(-1) # (B,J,1)
78
+ Dn = d_isqrt * A * d_isqrt.transpose(-1, -2) # (B,J,J)
79
+ I = torch.eye(J, device=A.device).unsqueeze(0).expand(B, J, J)
80
+ L = I - Dn
81
+ return L
82
+
83
+
84
+ def sym_spd_from_cholesky(L_tri: torch.Tensor, eps: float = 1e-4) -> torch.Tensor:
85
+ """Build SPD matrix g = L L^T + eps I from lower-triangular parameterization.
86
+ L_tri: (B, k, k) lower-triangular with positive diagonal (apply softplus outside)
87
+ Return g: (B, k, k)
88
+ """
89
+ B, k, _ = L_tri.shape
90
+ I = torch.eye(k, device=L_tri.device).unsqueeze(0).expand(B, k, k)
91
+ return L_tri @ L_tri.transpose(-1, -2) + eps * I
92
+
93
+
94
+ def batched_geodesic_sq(x: torch.Tensor, y: torch.Tensor, g: torch.Tensor) -> torch.Tensor:
95
+ """Compute squared geodesic distance under metric g:
96
+ d^2 = (x - y)^T g (x - y)
97
+ x: (B,J,k); y: (B,J,k) broadcastable to pairs; g: (B,k,k)
98
+ Returns pairwise (B,J,J)
99
+ """
100
+ B, J, k = x.shape
101
+ # reshape for pairwise differences
102
+ x_ = x.unsqueeze(2) # (B,J,1,k)
103
+ y_ = y.unsqueeze(1) # (B,1,J,k)
104
+ diff = x_ - y_ # (B,J,J,k)
105
+ # (B,J,J,k) @ (B,k,k) -> (B,J,J,k)
106
+ gd = torch.matmul(diff, g.unsqueeze(1).unsqueeze(1))
107
+ val = (diff * gd).sum(-1) # (B,J,J)
108
+ return val.clamp_min(0.0)
109
+
110
+
111
+ def safe_eigvalsh(L: torch.Tensor, k_smallest: int = 3) -> torch.Tensor:
112
+ """Compute few smallest eigenvalues of symmetric L with safety.
113
+ L: (B,J,J)
114
+ Return: (B, k_smallest)
115
+ """
116
+ # For moderate J (<=512) this is fine; for large J use Lanczos.
117
+ try:
118
+ vals = torch.linalg.eigvalsh(L) # (B,J)
119
+ vals, _ = torch.topk(vals, k=k_smallest, largest=False, sorted=True)
120
+ return vals
121
+ except RuntimeError:
122
+ # fallback: add jitter
123
+ jitter = 1e-4 * torch.eye(L.shape[-1], device=L.device).unsqueeze(0)
124
+ vals = torch.linalg.eigvalsh(L + jitter)
125
+ vals, _ = torch.topk(vals, k=k_smallest, largest=False, sorted=True)
126
+ return vals
127
+
128
+
129
+ # ===============================
130
+ # PF Components (Phenomenal Field Path)
131
+ # ===============================
132
+
133
+ @dataclass
134
+ class PFConfig:
135
+ J: int = 256 # number of PF nodes
136
+ k: int = 16 # channels per node
137
+ K: int = 16 # k-NN degree
138
+ alpha: float = 0.05 # diffusion step
139
+ noise_eps: float = 1e-3
140
+ lambda_out: float = 1.0
141
+ lambda_tv: float = 0.1
142
+ lambda_mw: float = 0.05
143
+ metric_eps: float = 1e-4
144
+ metric_rank: Optional[int] = None # not used in this v1; kept for future low-rank IME
145
+
146
+
147
+ class PFAdapterOut(nn.Module):
148
+ """Adapter A_out: map token hidden h_t (B,d) -> target PF pattern F_tilde (B,J,k)."""
149
+ def __init__(self, d: int, J: int, k: int):
150
+ super().__init__()
151
+ self.proj = nn.Linear(d, J * k)
152
+
153
+ def forward(self, h_t: torch.Tensor) -> torch.Tensor:
154
+ B, d = h_t.shape
155
+ out = self.proj(h_t) # (B, J*k)
156
+ return out.view(B, -1, d // d * 0 + 1) # placeholder to force shape check (will be replaced)
157
+
158
+ # Fix: Provide a safer reshape using known sizes
159
+ class PFAdapterOut(nn.Module):
160
+ def __init__(self, d: int, J: int, k: int):
161
+ super().__init__()
162
+ self.J, self.k = J, k
163
+ self.proj = nn.Linear(d, J * k)
164
+
165
+ def forward(self, h_t: torch.Tensor) -> torch.Tensor:
166
+ B, d = h_t.shape
167
+ out = self.proj(h_t) # (B, J*k)
168
+ return out.view(B, self.J, self.k)
169
+
170
+
171
+ class PFIntrinsicMetricEngine(nn.Module):
172
+ """IME: learn SPD metric g_t from PF state statistics via Cholesky parameterization."""
173
+ def __init__(self, k: int, hidden: int = 128, metric_eps: float = 1e-4):
174
+ super().__init__()
175
+ self.k = k
176
+ self.metric_eps = metric_eps
177
+ in_dim = 2 * k # mean + std over nodes
178
+ self.mlp = nn.Sequential(
179
+ nn.Linear(in_dim, hidden), nn.GELU(),
180
+ nn.Linear(hidden, hidden), nn.GELU(),
181
+ nn.Linear(hidden, k * k)
182
+ )
183
+ # initialize near identity
184
+ with torch.no_grad():
185
+ for m in self.mlp:
186
+ if isinstance(m, nn.Linear):
187
+ nn.init.xavier_uniform_(m.weight)
188
+ nn.init.zeros_(m.bias)
189
+
190
+ def forward(self, F_t: torch.Tensor) -> torch.Tensor:
191
+ B, J, k = F_t.shape
192
+ mean = F_t.mean(dim=1) # (B,k)
193
+ std = F_t.std(dim=1).clamp_min(1e-6) # (B,k)
194
+ feat = torch.cat([mean, std], dim=-1) # (B,2k)
195
+ L_flat = self.mlp(feat) # (B, k*k)
196
+ L = L_flat.view(B, k, k)
197
+ # enforce lower-triangular with softplus diagonal
198
+ tril_mask = torch.tril(torch.ones(k, k, device=F_t.device)).unsqueeze(0)
199
+ L = L * tril_mask
200
+ diag = torch.diagonal(L, dim1=-2, dim2=-1)
201
+ diag = F.softplus(diag) + 1e-3
202
+ L = L.clone()
203
+ L.diagonal(dim1=-2, dim2=-1).copy_(diag)
204
+ g = sym_spd_from_cholesky(L, eps=self.metric_eps)
205
+ return g # (B,k,k)
206
+
207
+
208
+ class PFFieldCore(nn.Module):
209
+ """Evolve PF state per token step with diffusion + energy gradient + small noise."""
210
+ def __init__(self, cfg: PFConfig):
211
+ super().__init__()
212
+ self.cfg = cfg
213
+ # learnable weights for Mexican-hat style potential
214
+ self.mw_scale = nn.Parameter(torch.tensor(1.0))
215
+ self.register_buffer('zero', torch.tensor(0.0))
216
+
217
+ def total_variation(self, F_t: torch.Tensor, A: torch.Tensor) -> torch.Tensor:
218
+ # TV_g ≈ sum_{(i,j)∈E} ||F_i - F_j||_2
219
+ B = F_t.shape[0]
220
+ # use adjacency to compute neighbor diffs
221
+ # Expand for pairwise gather: (B,J,J, k)
222
+ Fi = F_t.unsqueeze(2)
223
+ Fj = F_t.unsqueeze(1)
224
+ diff = (Fi - Fj).norm(dim=-1) # (B,J,J)
225
+ tv = (diff * A).sum(dim=(-1, -2)) / (A.sum(dim=(-1, -2)).clamp_min(1.0))
226
+ return tv.mean() # scalar
227
+
228
+ def omega_mexican_hat(self, F_t: torch.Tensor) -> torch.Tensor:
229
+ # Encourage metastability: penalize both collapse and explosion around a preferred radius
230
+ # Using mean pairwise distance towards a target radius r0.
231
+ B, J, k = F_t.shape
232
+ # sample subset for efficiency if J large
233
+ if J > 128:
234
+ idx = torch.randperm(J, device=F_t.device)[:128]
235
+ X = F_t[:, idx, :]
236
+ else:
237
+ X = F_t
238
+ pd = pairwise_cosine(X, X) # (B,m,m) in [-1,1]
239
+ # convert similarity to a pseudo-distance in [0,2]
240
+ dist = (1.0 - pd).clamp_min(0.0) * 2.0
241
+ r = dist.mean(dim=(-1, -2)) # (B,)
242
+ r0 = 0.8 # preferred radius (tunable)
243
+ loss = ((r - r0) ** 2).mean()
244
+ return self.mw_scale.abs() * loss
245
+
246
+ def forward(self, F_t: torch.Tensor, h_t: torch.Tensor, g_t: torch.Tensor,
247
+ A: torch.Tensor, F_tilde: torch.Tensor) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
248
+ cfg = self.cfg
249
+ # Laplacian term (graph-based diffusion)
250
+ L = normalized_graph_laplacian(A) # (B,J,J)
251
+ diffusion = torch.matmul(L, F_t) # (B,J,k)
252
+ # Content energy gradient: d/dF [λ_out ||F - F~||^2] = 2λ_out (F - F~)
253
+ grad_out = 2.0 * cfg.lambda_out * (F_t - F_tilde)
254
+ # Structural energies
255
+ tv = self.total_variation(F_t, A)
256
+ omega = self.omega_mexican_hat(F_t)
257
+ # Approx gradient for TV (use Laplacian as proxy) and omega via autograd
258
+ # Update step
259
+ noise = cfg.noise_eps * torch.randn_like(F_t)
260
+ F_next = F_t + cfg.alpha * diffusion - grad_out + noise
261
+ stats = {
262
+ 'tv': tv.detach(),
263
+ 'omega': omega.detach(),
264
+ }
265
+ return F_next, stats
266
+
267
+
268
+ class PFIntrospection(nn.Module):
269
+ """Valence (V), Self/Now Anchor (a), and Γ summarizer for gating."""
270
+ def __init__(self, d: int, k: int, r_gamma: int = 32):
271
+ super().__init__()
272
+ self.aligner = nn.Sequential(
273
+ nn.Linear(d + k, 128), nn.GELU(),
274
+ nn.Linear(128, 64), nn.GELU(),
275
+ )
276
+ self.val_head = nn.Linear(64, 1)
277
+ self.sna_head = nn.Linear(64, 1)
278
+ self.gamma_head = nn.Sequential(
279
+ nn.Linear(64 + 2, 64), nn.GELU(),
280
+ nn.Linear(64, r_gamma)
281
+ )
282
+
283
+ def forward(self, F_t: torch.Tensor, h_t: torch.Tensor,
284
+ syn: torch.Tensor, conn: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
285
+ # Pool PF to k-dim via mean
286
+ F_pool = F_t.mean(dim=1) # (B,k)
287
+ x = torch.cat([h_t, F_pool], dim=-1)
288
+ z = self.aligner(x)
289
+ V = torch.sigmoid(self.val_head(z)).squeeze(-1)
290
+ a = torch.sigmoid(self.sna_head(z)).squeeze(-1)
291
+ # Attach syn/conn scalars
292
+ sc = torch.stack([syn, conn], dim=-1)
293
+ g_in = torch.cat([z, sc], dim=-1)
294
+ Gamma = self.gamma_head(g_in) # (B, r_gamma)
295
+ return V, a, Gamma
296
+
297
+
298
+ class LogitGate(nn.Module):
299
+ """Additive bias to logits based on PF summary Γ."""
300
+ def __init__(self, vocab_size: int, r_gamma: int):
301
+ super().__init__()
302
+ self.proj = nn.Linear(r_gamma, vocab_size, bias=False)
303
+ nn.init.zeros_(self.proj.weight)
304
+
305
+ def forward(self, z_base: torch.Tensor, Gamma: torch.Tensor) -> torch.Tensor:
306
+ # z_base: (B, V), Gamma: (B, rγ)
307
+ bias = self.proj(Gamma) # (B, V)
308
+ return z_base + bias
309
+
310
+
311
+ # ===============================
312
+ # Metrics: Synchrony & Connectivity; GIW
313
+ # ===============================
314
+ class PFIntegrationMeter(nn.Module):
315
+ """Compute Syn, Conn (algebraic connectivity proxy), κ and broadcast flag."""
316
+ def __init__(self, J: int, kappa_thresh: float = 0.6):
317
+ super().__init__()
318
+ self.kappa_thresh = kappa_thresh
319
+ self.score = nn.Sequential(
320
+ nn.Linear(2 + 2, 64), nn.GELU(),
321
+ nn.Linear(64, 1)
322
+ )
323
+
324
+ @staticmethod
325
+ def synchrony(F_t: torch.Tensor, A: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
326
+ # mean cosine similarity across neighboring nodes as a proxy for phase synchrony
327
+ B, J, k = F_t.shape
328
+ cos = pairwise_cosine(F_t) # (B,J,J)
329
+ num = (cos * A).sum(dim=(-1, -2))
330
+ den = A.sum(dim=(-1, -2)).clamp_min(1.0)
331
+ syn = (num / den).mean() # scalar across batch
332
+ return syn.expand(B) # broadcast scalar per batch
333
+
334
+ @staticmethod
335
+ def connectivity(A: torch.Tensor) -> torch.Tensor:
336
+ # algebraic connectivity (second-smallest eigenvalue) of normalized Laplacian
337
+ L = normalized_graph_laplacian(A) # (B,J,J)
338
+ eigs = safe_eigvalsh(L, k_smallest=3) # (B,3)
339
+ lambda2 = eigs[:, 1] # (B,)
340
+ # smaller λ2 => weaker connectivity; invert & normalize
341
+ conn = torch.sigmoid(1.0 / (lambda2 + 1e-3))
342
+ return conn
343
+
344
+ def forward(self, F_t: torch.Tensor, A: torch.Tensor,
345
+ V: torch.Tensor, a: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
346
+ syn = self.synchrony(F_t, A) # (B,)
347
+ conn = self.connectivity(A) # (B,)
348
+ feat = torch.stack([syn, conn, V, a], dim=-1) # (B,4)
349
+ kappa = torch.sigmoid(self.score(feat)).squeeze(-1) # (B,)
350
+ broadcast = (kappa >= self.kappa_thresh).float()
351
+ return syn, conn, kappa, broadcast
352
+
353
+
354
+ # ===============================
355
+ # Lightcone Attention (LCA) Wrapper
356
+ # ===============================
357
+ class LCAParams(nn.Module):
358
+ def __init__(self, beta: float = 0.7, gamma: float = 0.3, lambda_time: float = 0.2, lambda_dir: float = 0.3, tau: int = 64):
359
+ super().__init__()
360
+ self.beta = nn.Parameter(torch.tensor(beta))
361
+ self.gamma = nn.Parameter(torch.tensor(gamma))
362
+ self.lambda_time = nn.Parameter(torch.tensor(lambda_time))
363
+ self.lambda_dir = nn.Parameter(torch.tensor(lambda_dir))
364
+ self.tau = tau
365
+
366
+
367
+ class LCAWrapper(nn.Module):
368
+ """Modify attention scores: e_ij = dot - β d_g(i,j) - γ D_lc(i,j)."""
369
+ def __init__(self, params: LCAParams):
370
+ super().__init__()
371
+ self.params = params
372
+
373
+ def forward(self, Q: torch.Tensor, K: torch.Tensor,
374
+ F_t: torch.Tensor, g_t: torch.Tensor,
375
+ positions: Optional[torch.Tensor] = None,
376
+ u_dir: Optional[torch.Tensor] = None) -> torch.Tensor:
377
+ """Compute modified attention scores.
378
+ Q,K: (B, H, T, d_head)
379
+ F_t: PF nodes (B, J, k)
380
+ g_t: metric (B, k, k)
381
+ positions: (T,) or (B,T) 0..T-1
382
+ u_dir: (B, d_head) approximate episode direction (can be from Γ PCA; here optional)
383
+ Return scores: (B, H, T, T)
384
+ """
385
+ B, H, T, Dh = Q.shape
386
+ scale = 1.0 / math.sqrt(Dh)
387
+ # base dot-product scores
388
+ dots = torch.matmul(Q, K.transpose(-1, -2)) * scale # (B,H,T,T)
389
+ # map token positions to nearest PF nodes indices (coarse): use a simple modulo mapping
390
+ J = F_t.shape[1]
391
+ token_nodes = torch.arange(T, device=Q.device) % J
392
+ # geodesic distance between node features -> (B, J, J)
393
+ d_geo_sq = batched_geodesic_sq(F_t, F_t, g_t) # (B,J,J)
394
+ # gather distances for token pairs using mapped nodes
395
+ idx_i = token_nodes.view(1, 1, T, 1).expand(B, H, T, 1)
396
+ idx_j = token_nodes.view(1, 1, 1, T).expand(B, H, 1, T)
397
+ d_geo_tok = d_geo_sq.unsqueeze(1).gather(2, idx_i.repeat(1,1,1,J)).gather(3, idx_j.repeat(1,1,J,1))
398
+ d_geo_tok = d_geo_tok.squeeze(-1).squeeze(-2) # (B,H,T,T) approx
399
+ # lightcone cost: temporal + directional
400
+ if positions is None:
401
+ positions = torch.arange(T, device=Q.device).view(1, T).expand(B, T)
402
+ pos_i = positions.unsqueeze(1) # (B,1,T)
403
+ pos_j = positions.unsqueeze(2) # (B,T,1)
404
+ d_time = (pos_j - pos_i).abs().float() / max(1, self.params.tau) # (B,T,T)
405
+ d_time = d_time.unsqueeze(1).expand(B, H, T, T)
406
+ if u_dir is None:
407
+ u_dir = torch.zeros(B, Dh, device=Q.device)
408
+ # direction penalty via 1 - cos(angle(u, ΔK)) as proxy
409
+ # ΔK ~ K_j (we ignore i to keep cheap): compute sim between u and K
410
+ Ku = F.normalize(K.mean(dim=2), dim=-1) # (B,H,Dh)
411
+ u_n = F.normalize(u_dir, dim=-1).unsqueeze(1) # (B,1,Dh)
412
+ dir_cost = (1.0 - (Ku * u_n).sum(-1, keepdim=True)).clamp_min(0.0) # (B,H,1)
413
+ dir_cost = dir_cost.expand(B, H, T) # (B,H,T)
414
+ dir_cost = dir_cost.unsqueeze(-1).expand(B, H, T, T)
415
+ # combine
416
+ scores = dots - self.params.beta.abs() * d_geo_tok - self.params.gamma.abs() * (
417
+ self.params.lambda_time.abs() * d_time + self.params.lambda_dir.abs() * dir_cost
418
+ )
419
+ return scores
420
+
421
+
422
+ # ===============================
423
+ # NTI Controller (episodic intent offset)
424
+ # ===============================
425
+ class NTIController(nn.Module):
426
+ def __init__(self, d: int, vocab_size: int, r_gamma: int = 32, offset_scale: float = 0.5, tau: int = 64):
427
+ super().__init__()
428
+ self.tau = tau
429
+ self.offset_scale = offset_scale
430
+ self.proj = nn.Sequential(
431
+ nn.Linear(d + r_gamma, 128), nn.GELU(),
432
+ nn.Linear(128, vocab_size)
433
+ )
434
+
435
+ def forward(self, H_seg: torch.Tensor, Gamma_seg: torch.Tensor,
436
+ attn_entropy: Optional[torch.Tensor] = None,
437
+ path_dev: Optional[torch.Tensor] = None) -> torch.Tensor:
438
+ """Compute Δz episodic offset for a segment.
439
+ H_seg: (B, τ, d), Gamma_seg: (B, τ, rγ)
440
+ attn_entropy/path_dev: optional scalars per batch
441
+ Return Δz: (B, V)
442
+ """
443
+ h_bar = H_seg.mean(dim=1) # (B,d)
444
+ g_bar = Gamma_seg.mean(dim=1) # (B,rγ)
445
+ x = torch.cat([h_bar, g_bar], dim=-1)
446
+ dz = self.proj(x) * self.offset_scale
447
+ return dz
448
+
449
+
450
+ # ===============================
451
+ # Top-level: N‑Transformers Coupler
452
+ # ===============================
453
+ @dataclass
454
+ class NTCfg:
455
+ d: int = 2048
456
+ vocab_size: int = 50000
457
+ r_gamma: int = 32
458
+ J: int = 256
459
+ k: int = 16
460
+ K: int = 16
461
+ alpha: float = 0.05
462
+ noise_eps: float = 1e-3
463
+ kappa_thresh: float = 0.6
464
+ nti_tau: int = 64
465
+ nti_period: int = 16
466
+ offset_scale: float = 0.5
467
+
468
+
469
+ class NTransformerCoupler(nn.Module):
470
+ """Parallel PF path + couplings to augment any decoder‑only LM.
471
+
472
+ Exposes step() for single‑step inference/training and segment_update() for NTI updates.
473
+ """
474
+ def __init__(self, cfg: NTCfg):
475
+ super().__init__()
476
+ self.cfg = cfg
477
+ pf_cfg = PFConfig(J=cfg.J, k=cfg.k, K=cfg.K, alpha=cfg.alpha, noise_eps=cfg.noise_eps)
478
+ self.adapter_out = PFAdapterOut(d=cfg.d, J=cfg.J, k=cfg.k)
479
+ self.ime = PFIntrinsicMetricEngine(k=cfg.k, hidden=128, metric_eps=1e-4)
480
+ self.pf_core = PFFieldCore(cfg=pf_cfg)
481
+ self.introspect = PFIntrospection(d=cfg.d, k=cfg.k, r_gamma=cfg.r_gamma)
482
+ self.integrator = PFIntegrationMeter(J=cfg.J, kappa_thresh=cfg.kappa_thresh)
483
+ self.gate = LogitGate(vocab_size=cfg.vocab_size, r_gamma=cfg.r_gamma)
484
+ self.lca = LCAWrapper(LCAParams(beta=0.7, gamma=0.3, lambda_time=0.2, lambda_dir=0.3, tau=cfg.nti_tau))
485
+ self.nti = NTIController(d=cfg.d, vocab_size=cfg.vocab_size, r_gamma=cfg.r_gamma,
486
+ offset_scale=cfg.offset_scale, tau=cfg.nti_tau)
487
+
488
+ def initial_state(self, batch_size: int, device: Optional[torch.device] = None) -> Dict[str, torch.Tensor]:
489
+ device = device or next(self.parameters()).device
490
+ F0 = torch.randn(batch_size, self.cfg.J, self.cfg.k, device=device) * 0.02
491
+ # Build initial KNN on PF nodes (use features themselves for init)
492
+ idx = knn_indices(F0, self.cfg.K)
493
+ A0 = build_adjacency(idx, self.cfg.J)
494
+ g0 = self.ime(F0)
495
+ return {"F": F0, "A": A0, "g": g0}
496
+
497
+ @torch.no_grad()
498
+ def rebuild_graph(self, F_t: torch.Tensor) -> torch.Tensor:
499
+ idx = knn_indices(F_t, self.cfg.K)
500
+ A = build_adjacency(idx, self.cfg.J)
501
+ return A
502
+
503
+ def step(self, state: Dict[str, torch.Tensor], h_t: torch.Tensor,
504
+ z_base_t: torch.Tensor,
505
+ Q: Optional[torch.Tensor] = None, K: Optional[torch.Tensor] = None,
506
+ positions: Optional[torch.Tensor] = None,
507
+ u_dir: Optional[torch.Tensor] = None) -> Tuple[Dict[str, torch.Tensor], torch.Tensor, Dict[str, torch.Tensor]]:
508
+ """Single decoding step coupling.
509
+ state: dict with F (B,J,k), A (B,J,J), g (B,k,k)
510
+ h_t: (B,d) token hidden; z_base_t: (B,V)
511
+ Q,K: attention tensors (B,H,T,dh) for optional LCA modulation; if None, gating only
512
+ Returns: new_state, z_final, logs
513
+ """
514
+ F_t, A_t, g_t = state["F"], state["A"], state["g"]
515
+ F_tilde = self.adapter_out(h_t) # (B,J,k)
516
+ # evolve PF one step
517
+ F_next, pf_stats = self.pf_core(F_t, h_t, g_t, A_t, F_tilde)
518
+ # update metric and (optionally) graph
519
+ g_next = self.ime(F_next)
520
+ with torch.no_grad():
521
+ A_next = self.rebuild_graph(F_next)
522
+ # introspection & integration
523
+ # compute Syn/Conn
524
+ syn = self.integrator.synchrony(F_next, A_next)
525
+ conn = self.integrator.connectivity(A_next)
526
+ V, a, Gamma = self.introspect(F_next, h_t, syn, conn)
527
+ syn, conn, kappa, broadcast = self.integrator(F_next, A_next, V, a)
528
+ # gating logits
529
+ z_final = self.gate(z_base_t, Gamma)
530
+ # optional: LCA on attention scores (external model must accept these scores)
531
+ lca_scores = None
532
+ if Q is not None and K is not None:
533
+ lca_scores = self.lca(Q, K, F_next, g_next, positions=positions, u_dir=u_dir)
534
+ new_state = {"F": F_next, "A": A_next, "g": g_next,
535
+ "V": V.detach(), "a": a.detach(), "Gamma": Gamma.detach(),
536
+ "kappa": kappa.detach(), "broadcast": broadcast.detach()}
537
+ logs = {"tv": pf_stats["tv"], "omega": pf_stats["omega"],
538
+ "syn": syn.mean().detach(), "conn": conn.mean().detach(),
539
+ "V": V.mean().detach(), "a": a.mean().detach(), "kappa": kappa.mean().detach()}
540
+ if lca_scores is not None:
541
+ logs["lca_min"] = lca_scores.min().detach()
542
+ logs["lca_max"] = lca_scores.max().detach()
543
+ return new_state, z_final, logs
544
+
545
+ def segment_update(self, H_seg: torch.Tensor, Gamma_seg: torch.Tensor,
546
+ attn_entropy: Optional[torch.Tensor] = None,
547
+ path_dev: Optional[torch.Tensor] = None) -> torch.Tensor:
548
+ """Every r steps, compute episodic Δz via NTI.
549
+ H_seg: (B, τ, d); Gamma_seg: (B, τ, rγ)
550
+ Return: Δz (B,V) to be added to subsequent logits (late‑fusion)
551
+ """
552
+ dz = self.nti(H_seg, Gamma_seg, attn_entropy, path_dev)
553
+ return dz
554
+
555
+
556
+ # ===============================
557
+ # Losses (PF‑side; to be combined with LLM next‑token loss)
558
+ # ===============================
559
+ class PFLosses(nn.Module):
560
+ def __init__(self, lambda_coh: float = 0.5, lambda_gauge: float = 0.5,
561
+ lambda_val: float = 0.2, lambda_self: float = 0.2, lambda_meta: float = 0.4):
562
+ super().__init__()
563
+ self.lambda_coh = lambda_coh
564
+ self.lambda_gauge = lambda_gauge
565
+ self.lambda_val = lambda_val
566
+ self.lambda_self = lambda_self
567
+ self.lambda_meta = lambda_meta
568
+
569
+ @staticmethod
570
+ def tv_loss(F_t: torch.Tensor, A: torch.Tensor) -> torch.Tensor:
571
+ Fi = F_t.unsqueeze(2)
572
+ Fj = F_t.unsqueeze(1)
573
+ diff = (Fi - Fj).pow(2).sum(-1).sqrt() # (B,J,J)
574
+ return (diff * A).mean()
575
+
576
+ @staticmethod
577
+ def incoh_loss(H_t: torch.Tensor, F_t: torch.Tensor) -> torch.Tensor:
578
+ # penalize low alignment between pooled F and h
579
+ F_pool = F_t.mean(dim=1)
580
+ cos = F.cosine_similarity(F.normalize(F_pool, dim=-1), F.normalize(H_t, dim=-1))
581
+ return (1.0 - cos).mean()
582
+
583
+ @staticmethod
584
+ def pathdev_loss() -> torch.Tensor:
585
+ # placeholder; requires tracking best path proxy; return small constant to avoid zero grads
586
+ return torch.tensor(0.0, device=next(PFLosses().parameters()).device)
587
+
588
+ def forward(self, H_t: torch.Tensor, F_t: torch.Tensor, A_t: torch.Tensor,
589
+ V_t: torch.Tensor, a_t: torch.Tensor,
590
+ V_target: Optional[torch.Tensor] = None,
591
+ a_target: Optional[torch.Tensor] = None,
592
+ meta_pos: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
593
+ meta_neg: Optional[Tuple[torch.Tensor, torch.Tensor]] = None) -> torch.Tensor:
594
+ # coherence
595
+ L_coh = self.tv_loss(F_t, A_t)
596
+ # gauge
597
+ L_gauge = self.incoh_loss(H_t, F_t) + self.pathdev_loss()
598
+ # valence (regression to target if provided)
599
+ if V_target is not None:
600
+ L_val = F.mse_loss(V_t, V_target)
601
+ else:
602
+ L_val = torch.zeros((), device=F_t.device)
603
+ # self/now
604
+ if a_target is not None:
605
+ L_self = F.binary_cross_entropy(a_t.clamp(1e-4, 1-1e-4), a_target)
606
+ else:
607
+ L_self = torch.zeros((), device=F_t.device)
608
+ # meta (contrastive on PF signatures; here use pooled F as proxy)
609
+ L_meta = torch.zeros((), device=F_t.device)
610
+ if (meta_pos is not None) and (meta_neg is not None):
611
+ F_pos1, F_pos2 = meta_pos # both (B,J,k)
612
+ F_neg1, F_neg2 = meta_neg
613
+ # cosine distance between pooled features
614
+ def pool(Fx):
615
+ return F.normalize(Fx.mean(dim=1), dim=-1)
616
+ pos = 1.0 - F.cosine_similarity(pool(F_pos1), pool(F_pos2)).mean()
617
+ neg = F.cosine_similarity(pool(F_neg1), pool(F_neg2)).mean()
618
+ margin = 0.3
619
+ L_meta = F.relu(pos + neg - margin)
620
+ L = (self.lambda_coh * L_coh + self.lambda_gauge * L_gauge +
621
+ self.lambda_val * L_val + self.lambda_self * L_self + self.lambda_meta * L_meta)
622
+ return L
623
+
624
+
625
+ # ===============================
626
+ # Example Integration Skeleton (with a generic LM)
627
+ # ===============================
628
+ class DummyDecoderOnlyLM(nn.Module):
629
+ """Placeholder LM exposing hidden and logits for demonstration only.
630
+ Replace with your actual Transformer decoder (e.g., GPT‑like) and wire the coupler around it.
631
+ """
632
+ def __init__(self, d: int, vocab_size: int):
633
+ super().__init__()
634
+ self.d = d
635
+ self.emb = nn.Embedding(vocab_size, d)
636
+ self.ff = nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.Linear(d, d))
637
+ self.head = nn.Linear(d, vocab_size)
638
+
639
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
640
+ H = self.emb(x) # (B,T,d)
641
+ H = self.ff(H)
642
+ logits = self.head(H) # (B,T,V)
643
+ return H, logits
644
+
645
+
646
+ class NTransformersModel(nn.Module):
647
+ """Full model wrapper: LM + N‑Transformers coupler.
648
+ This is a minimal training‑ready scaffold; extend as needed.
649
+ """
650
+ def __init__(self, lm: nn.Module, coupler: NTransformerCoupler, losses: PFLosses):
651
+ super().__init__()
652
+ self.lm = lm
653
+ self.coupler = coupler
654
+ self.losses = losses
655
+
656
+ def forward(self, x: torch.Tensor, y: Optional[torch.Tensor] = None) -> Dict[str, torch.Tensor]:
657
+ B, T = x.shape
658
+ device = x.device
659
+ # initialize PF state
660
+ state = self.coupler.initial_state(B, device=device)
661
+ H, logits_base = self.lm(x) # (B,T,d), (B,T,V)
662
+ logits = torch.empty_like(logits_base)
663
+ Gamma_hist = []
664
+ # step through time
665
+ for t in range(T):
666
+ h_t = H[:, t, :]
667
+ z_base_t = logits_base[:, t, :]
668
+ state, z_t, logs = self.coupler.step(state, h_t, z_base_t)
669
+ logits[:, t, :] = z_t
670
+ if "Gamma" in state:
671
+ Gamma_hist.append(state["Gamma"]) # (B,rγ)
672
+ # NTI every nti_period (here apply once at end for demo)
673
+ if len(Gamma_hist) >= self.coupler.cfg.nti_tau:
674
+ Gamma_seg = torch.stack(Gamma_hist[-self.coupler.cfg.nti_tau:], dim=1) # (B,τ,rγ)
675
+ H_seg = H[:, -self.coupler.cfg.nti_tau:, :]
676
+ dz = self.coupler.segment_update(H_seg, Gamma_seg)
677
+ logits[:, -1, :] = logits[:, -1, :] + dz # late‑fusion on final step (demo)
678
+ out = {"logits": logits}
679
+ if y is not None:
680
+ # next-token CE loss
681
+ loss_llm = F.cross_entropy(logits[:, :-1, :].reshape(-1, logits.size(-1)), y[:, 1:].reshape(-1))
682
+ # PF‑side loss (using last step as example)
683
+ H_last = H[:, -1, :]
684
+ F_last, A_last = state["F"], state["A"]
685
+ V_last, a_last = state["V"], state["a"]
686
+ loss_pf = self.losses(H_last, F_last, A_last, V_last, a_last)
687
+ loss = loss_llm + loss_pf
688
+ out.update({"loss": loss, "loss_llm": loss_llm, "loss_pf": loss_pf})
689
+ return out
690
+
691
+
692
+ # ===============================
693
+ # Quick smoke test (CPU)
694
+ # ===============================
695
+ if __name__ == "__main__":
696
+ torch.manual_seed(42)
697
+ cfg = NTCfg(d=256, vocab_size=8192, J=64, k=8, K=8, nti_tau=16, nti_period=8)
698
+ lm = DummyDecoderOnlyLM(d=cfg.d, vocab_size=cfg.vocab_size)
699
+ coupler = NTransformerCoupler(cfg)
700
+ losses = PFLosses()
701
+ model = NTransformersModel(lm, coupler, losses)
702
+
703
+ B, T = 4, 24
704
+ x = torch.randint(0, cfg.vocab_size, (B, T))
705
+ y = x.clone()
706
+
707
+ out = model(x, y)
708
+ print({k: float(v) if torch.is_tensor(v) and v.dim()==0 else v.shape for k, v in out.items() if k.startswith('loss') or k=='logits'})