LisaMegaWatts commited on
Commit
d968181
Β·
verified Β·
1 Parent(s): 588ff7f

Add symbio_model.py for Colab notebook imports

Browse files
Files changed (1) hide show
  1. symbio_model.py +740 -0
symbio_model.py ADDED
@@ -0,0 +1,740 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SymbioGPT β€” Multi-organelle GPT with learned per-channel gating.
2
+
3
+ Ports the Julia SymbioSLM architecture (DavinciDreams/julia-slm) to PyTorch
4
+ and adds CausalSelfAttention as a 4th organelle. Each SymbioBlock contains:
5
+
6
+ 1. CausalDepthwiseConv1d β€” local n-gram detection (O(n))
7
+ 2. MonarchMatrix β€” sub-quadratic global mixing via factored butterfly matrices (O(n√n))
8
+ 3. LongConv β€” dense causal convolution with exponential decay (O(n))
9
+ 4. CausalSelfAttention β€” standard multi-head causal attention with RoPE (O(nΒ²))
10
+
11
+ The OrganelleGate learns a per-channel softmax blend over all organelles with
12
+ learnable temperature, allowing each embedding channel to independently specialize.
13
+
14
+ References:
15
+ - Julia SymbioSLM: DavinciDreams/julia-slm (symbiogenesis.jl, monarch.jl)
16
+ - Monarch Mixer: Dao et al., 2023
17
+ - Hyena: Poli et al., 2023
18
+ - Symbiogenesis: DavinciDreams/symbiogenesis
19
+ - Margulis (1967): Endosymbiotic theory of organelle evolution
20
+ """
21
+ import logging
22
+ import math
23
+ from dataclasses import dataclass, field
24
+ from typing import Dict, List, Optional, Tuple
25
+
26
+ import torch
27
+ import torch.nn as nn
28
+ import torch.nn.functional as F
29
+
30
+ # ═══════════════════════════════════════════════════════════════════
31
+ # Building blocks (inlined from symbiogenesis for portability)
32
+ # ═══════════════════════════════════════════════════════════════════
33
+
34
+
35
+ class RMSNorm(nn.Module):
36
+ """Root Mean Square Layer Normalization."""
37
+
38
+ def __init__(self, dim: int, eps: float = 1e-6):
39
+ super().__init__()
40
+ self.weight = nn.Parameter(torch.ones(dim))
41
+ self.eps = eps
42
+
43
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
44
+ rms = torch.sqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
45
+ return x / rms * self.weight
46
+
47
+
48
+ class RotaryEmbedding(nn.Module):
49
+ """Rotary positional embedding (RoPE)."""
50
+
51
+ def __init__(self, dim: int, max_seq_len: int = 2048):
52
+ super().__init__()
53
+ freqs = 1.0 / (10000.0 ** (torch.arange(0, dim, 2).float() / dim))
54
+ positions = torch.arange(max_seq_len).float()
55
+ angles = torch.outer(positions, freqs)
56
+ self.register_buffer("cos_cache", angles.cos())
57
+ self.register_buffer("sin_cache", angles.sin())
58
+
59
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
60
+ """Apply rotary embedding to x: (batch, n_heads, seq_len, head_dim)."""
61
+ seq_len = x.size(2)
62
+ half = x.size(-1) // 2
63
+ x1, x2 = x[..., :half], x[..., half:]
64
+ cos = self.cos_cache[:seq_len, :half].unsqueeze(0).unsqueeze(0)
65
+ sin = self.sin_cache[:seq_len, :half].unsqueeze(0).unsqueeze(0)
66
+ o1 = x1 * cos - x2 * sin
67
+ o2 = x1 * sin + x2 * cos
68
+ return torch.cat([o1, o2], dim=-1)
69
+
70
+
71
+ class SwiGLU(nn.Module):
72
+ """SwiGLU feed-forward: out = W2(swish(W1Β·x) * VΒ·x)."""
73
+
74
+ def __init__(self, d_model: int, ffn_mult: int = 4):
75
+ super().__init__()
76
+ raw_hidden = 2 * d_model * ffn_mult // 3
77
+ hidden_dim = max(64, (raw_hidden // 64) * 64)
78
+ self.w1 = nn.Linear(d_model, hidden_dim, bias=False)
79
+ self.v = nn.Linear(d_model, hidden_dim, bias=False)
80
+ self.w2 = nn.Linear(hidden_dim, d_model, bias=False)
81
+ self.act = nn.SiLU()
82
+
83
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
84
+ return self.w2(self.act(self.w1(x)) * self.v(x))
85
+
86
+
87
+ class CausalSelfAttention(nn.Module):
88
+ """Multi-head causal self-attention with RoPE."""
89
+
90
+ def __init__(self, d_model: int, n_heads: int, head_dim: int, dropout: float = 0.0):
91
+ super().__init__()
92
+ self.n_heads = n_heads
93
+ self.head_dim = head_dim
94
+ total_dim = n_heads * head_dim
95
+ self.wq = nn.Linear(d_model, total_dim, bias=False)
96
+ self.wk = nn.Linear(d_model, total_dim, bias=False)
97
+ self.wv = nn.Linear(d_model, total_dim, bias=False)
98
+ self.wo = nn.Linear(total_dim, d_model, bias=False)
99
+ self.attn_dropout = nn.Dropout(dropout) if dropout > 0.0 else nn.Identity()
100
+
101
+ def forward(
102
+ self,
103
+ x: torch.Tensor,
104
+ rope: RotaryEmbedding,
105
+ mask: Optional[torch.Tensor] = None,
106
+ ) -> torch.Tensor:
107
+ B, T, D = x.shape
108
+ H, HD = self.n_heads, self.head_dim
109
+ q = self.wq(x).view(B, T, H, HD).transpose(1, 2)
110
+ k = self.wk(x).view(B, T, H, HD).transpose(1, 2)
111
+ v = self.wv(x).view(B, T, H, HD).transpose(1, 2)
112
+ q = rope(q)
113
+ k = rope(k)
114
+ scale = 1.0 / math.sqrt(HD)
115
+ attn = torch.matmul(q, k.transpose(-2, -1)) * scale
116
+ if mask is not None:
117
+ attn = attn + mask
118
+ attn = F.softmax(attn, dim=-1)
119
+ attn = self.attn_dropout(attn)
120
+ out = torch.matmul(attn, v)
121
+ out = out.transpose(1, 2).contiguous().view(B, T, H * HD)
122
+ return self.wo(out)
123
+
124
+ logger = logging.getLogger(__name__)
125
+
126
+
127
+ # ═══════════════════════════════════════════════════════════════════
128
+ # Configuration
129
+ # ═══════════════════════════════════════════════════════════════════
130
+
131
+
132
+ @dataclass
133
+ class SymbioConfig:
134
+ """Configuration for a SymbioGPT model."""
135
+
136
+ d_model: int = 320
137
+ n_layers: int = 8
138
+ n_heads: int = 5 # for CausalSelfAttention organelle
139
+ head_dim: int = 64
140
+ ffn_mult: int = 4
141
+ dropout: float = 0.0
142
+ context_length: int = 256 # must be a perfect square for Monarch
143
+ vocab_size: int = 2000
144
+ weight_tying: bool = True
145
+
146
+ # Organelle configuration
147
+ organelles: Tuple[str, ...] = ("causal_conv", "monarch", "long_conv", "attention")
148
+ conv_kernel_size: int = 4
149
+ n_monarch_heads: int = 1
150
+
151
+ # OrganelleGate
152
+ gate_temperature_init: float = 1.0
153
+
154
+ # Free energy regularization
155
+ free_energy_beta: float = 0.001 # 0 = disabled
156
+
157
+ # Per-layer organelle override (None = use global organelles for all layers)
158
+ per_layer_organelles: Optional[List[Tuple[str, ...]]] = None
159
+
160
+ def __post_init__(self):
161
+ p = int(math.isqrt(self.context_length))
162
+ if p * p != self.context_length:
163
+ raise ValueError(
164
+ f"context_length must be a perfect square for Monarch, "
165
+ f"got {self.context_length}"
166
+ )
167
+ if self.d_model % self.n_monarch_heads != 0:
168
+ raise ValueError(
169
+ f"d_model ({self.d_model}) must be divisible by "
170
+ f"n_monarch_heads ({self.n_monarch_heads})"
171
+ )
172
+ valid = {"causal_conv", "monarch", "long_conv", "attention"}
173
+ for org in self.organelles:
174
+ if org not in valid:
175
+ raise ValueError(f"Unknown organelle: {org!r}, must be one of {valid}")
176
+
177
+ @property
178
+ def p(self) -> int:
179
+ """Block size for Monarch factorization (sqrt of context_length)."""
180
+ return int(math.isqrt(self.context_length))
181
+
182
+ @property
183
+ def n_organelles(self) -> int:
184
+ return len(self.organelles)
185
+
186
+
187
+ # ═══════════════════════════════════════════════════════════════════
188
+ # Organelle 1: CausalDepthwiseConv1d (local n-gram patterns)
189
+ # ═══════════════════════════════════════════════════════════════════
190
+
191
+
192
+ class CausalDepthwiseConv1d(nn.Module):
193
+ """Depthwise causal convolution for local n-gram pattern detection.
194
+
195
+ Each channel has its own 1D convolution kernel.
196
+ Causality enforced via left-padding of (kernel_size - 1).
197
+
198
+ Ports Julia CausalDepthwiseConv1d (monarch.jl).
199
+ Parameters: kernel_size Γ— channels
200
+ """
201
+
202
+ def __init__(self, channels: int, kernel_size: int = 4):
203
+ super().__init__()
204
+ self.channels = channels
205
+ self.kernel_size = kernel_size
206
+ # Shape: (out_channels, in_channels/groups, kernel_size) for groups=channels
207
+ self.weight = nn.Parameter(torch.empty(channels, 1, kernel_size))
208
+ self._init_weights()
209
+
210
+ def _init_weights(self):
211
+ scale = math.sqrt(1.0 / self.kernel_size)
212
+ nn.init.normal_(self.weight, mean=0.0, std=scale)
213
+
214
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
215
+ """x: (B, T, D) -> (B, T, D)"""
216
+ B, T, D = x.shape
217
+ x_t = x.transpose(1, 2) # (B, D, T)
218
+ x_padded = F.pad(x_t, (self.kernel_size - 1, 0)) # (B, D, T+K-1)
219
+ out = F.conv1d(x_padded, self.weight, groups=D) # (B, D, T)
220
+ return out.transpose(1, 2) # (B, T, D)
221
+
222
+
223
+ # ═══════════════════════════════════════════════════════════════════
224
+ # Organelle 2: MonarchMatrix (sub-quadratic global mixing)
225
+ # ═══════════════════════════════════════════════════════════════════
226
+
227
+
228
+ class MonarchMatrix(nn.Module):
229
+ """Monarch factored TΓ—T mixing matrix (sub-quadratic).
230
+
231
+ M = P^T Β· BlockDiag(L1) Β· P Β· BlockDiag(L2)
232
+ where L1, L2 are p blocks of (pΓ—p), T = pΒ².
233
+
234
+ Ports Julia MonarchMatrix (monarch.jl).
235
+ Parameters: 2 Γ— pΒ³ = 2 Γ— T^(3/2)
236
+ """
237
+
238
+ def __init__(self, seq_len: int):
239
+ super().__init__()
240
+ p = int(math.isqrt(seq_len))
241
+ assert p * p == seq_len, f"Monarch requires perfect-square seq_len, got {seq_len}"
242
+ self.seq_len = seq_len
243
+ self.p = p
244
+
245
+ scale = math.sqrt(2.0 / (p + p))
246
+ self.L1 = nn.Parameter(torch.randn(p, p, p) * scale)
247
+ self.L2 = nn.Parameter(torch.randn(p, p, p) * scale)
248
+
249
+ @staticmethod
250
+ def _julia_batched_mul(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
251
+ """Julia NNlib.batched_mul: A(M,N,batch) @ B(N,K,batch) β†’ (M,K,batch).
252
+
253
+ PyTorch bmm uses batch-first, Julia uses batch-last.
254
+ """
255
+ return torch.bmm(
256
+ A.permute(2, 0, 1),
257
+ B.permute(2, 0, 1),
258
+ ).permute(1, 2, 0)
259
+
260
+ def realize(self) -> torch.Tensor:
261
+ """Materialize full TΓ—T Monarch matrix (differentiable).
262
+
263
+ Pushes identity through: L2 β†’ permute β†’ L1 β†’ permute.
264
+ Follows Julia monarch_realize() exactly.
265
+ Returns: (T, T) matrix.
266
+ """
267
+ p = self.p
268
+ T = self.seq_len
269
+
270
+ I_T = torch.eye(T, device=self.L1.device, dtype=self.L1.dtype)
271
+ x = I_T.reshape(p, p, T)
272
+
273
+ # Apply L2 block-diagonal (batch dim = last)
274
+ x = x.permute(0, 2, 1) # (p, T, p)
275
+ x = self._julia_batched_mul(self.L2, x) # (p, T, p)
276
+ x = x.permute(0, 2, 1) # (p, p, T)
277
+
278
+ # Permutation P: transpose the pΓ—p grid
279
+ x = x.permute(1, 0, 2)
280
+
281
+ # Apply L1 block-diagonal
282
+ x = x.permute(0, 2, 1) # (p, T, p)
283
+ x = self._julia_batched_mul(self.L1, x) # (p, T, p)
284
+ x = x.permute(0, 2, 1) # (p, p, T)
285
+
286
+ # Undo permutation
287
+ x = x.permute(1, 0, 2)
288
+
289
+ return x.reshape(T, T)
290
+
291
+ def forward(
292
+ self,
293
+ x: torch.Tensor,
294
+ causal_mask: Optional[torch.Tensor] = None,
295
+ ) -> torch.Tensor:
296
+ """Apply Monarch mixing.
297
+
298
+ x: (B, T, D_head)
299
+ causal_mask: (T_max, T_max) multiplicative 0/1 mask
300
+ Returns: (B, T, D_head)
301
+ """
302
+ B, T, D_head = x.shape
303
+
304
+ M = self.realize() # (T_max, T_max)
305
+ if causal_mask is not None:
306
+ M = M * causal_mask[:T, :T]
307
+ else:
308
+ M = M[:T, :T]
309
+
310
+ # (T, T) @ (T, B*D_head) β†’ (T, B*D_head)
311
+ x_flat = x.permute(1, 0, 2).reshape(T, B * D_head)
312
+ y_flat = M @ x_flat
313
+ return y_flat.reshape(T, B, D_head).permute(1, 0, 2)
314
+
315
+
316
+ # ═══════════════════════════════════════════════════════════════════
317
+ # Organelle 3: LongConv (global dense causal filter)
318
+ # ═══════════════════════════════════════════════════════════════════
319
+
320
+
321
+ class LongConv(nn.Module):
322
+ """Full-length per-channel causal convolution with exponential decay init.
323
+
324
+ Each channel has a kernel of length seq_len. Exponential decay
325
+ initialization so recent positions are weighted more heavily.
326
+
327
+ Ports Julia LongConv (symbiogenesis.jl).
328
+ Parameters: seq_len Γ— channels
329
+ """
330
+
331
+ def __init__(self, channels: int, seq_len: int):
332
+ super().__init__()
333
+ self.channels = channels
334
+ self.seq_len = seq_len
335
+ # Shape: (out_channels, in_channels/groups, kernel_size)
336
+ self.kernel = nn.Parameter(torch.empty(channels, 1, seq_len))
337
+ self._init_weights()
338
+
339
+ def _init_weights(self):
340
+ scale = math.sqrt(1.0 / self.seq_len)
341
+ nn.init.normal_(self.kernel, mean=0.0, std=scale)
342
+ with torch.no_grad():
343
+ decay = torch.exp(-0.1 * torch.arange(self.seq_len, dtype=torch.float32))
344
+ self.kernel.mul_(decay.unsqueeze(0).unsqueeze(0))
345
+
346
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
347
+ """x: (B, T, D) -> (B, T, D)"""
348
+ B, T, D = x.shape
349
+ K = self.seq_len
350
+ x_t = x.transpose(1, 2) # (B, D, T)
351
+ x_padded = F.pad(x_t, (K - 1, 0)) # (B, D, T+K-1)
352
+ out = F.conv1d(x_padded, self.kernel, groups=D) # (B, D, T)
353
+ return out.transpose(1, 2) # (B, T, D)
354
+
355
+
356
+ # ═══════════════════════════════════════════════════════════════════
357
+ # OrganelleGate (per-channel softmax fusion)
358
+ # ═══════════════════════════════════════════════════════════════════
359
+
360
+
361
+ class OrganelleGate(nn.Module):
362
+ """Per-channel softmax gating over N organelle outputs.
363
+
364
+ Each channel independently learns which organelle to rely on via
365
+ softmax over N logits, with a shared learnable temperature.
366
+ Supports organelle masking for ablation studies.
367
+
368
+ Ports Julia OrganelleGate (symbiogenesis.jl).
369
+ Parameters: n_organelles Γ— dim + 1 (temperature)
370
+ """
371
+
372
+ def __init__(self, dim: int, n_organelles: int, temperature_init: float = 1.0):
373
+ super().__init__()
374
+ self.dim = dim
375
+ self.n_organelles = n_organelles
376
+ self.logits = nn.Parameter(torch.zeros(n_organelles, dim))
377
+ self.temperature = nn.Parameter(torch.tensor([temperature_init]))
378
+
379
+ def forward(
380
+ self,
381
+ organelle_outputs: Tuple[torch.Tensor, ...],
382
+ organelle_mask: Optional[Tuple[bool, ...]] = None,
383
+ ) -> torch.Tensor:
384
+ """Blend organelle outputs via per-channel gated softmax.
385
+
386
+ organelle_outputs: tuple of N tensors, each (B, T, D)
387
+ organelle_mask: optional tuple of N bools (True=enabled)
388
+ Returns: (B, T, D)
389
+ """
390
+ logits = self.logits # (N, D)
391
+
392
+ if organelle_mask is not None:
393
+ mask_additive = torch.zeros_like(logits)
394
+ for i in range(self.n_organelles):
395
+ if not organelle_mask[i]:
396
+ mask_additive[i, :] = -1e10
397
+ logits = logits + mask_additive
398
+
399
+ tau = self.temperature.clamp(min=0.01)
400
+ weights = F.softmax(logits / tau, dim=0) # (N, D)
401
+
402
+ out = torch.zeros_like(organelle_outputs[0])
403
+ for i in range(self.n_organelles):
404
+ w = weights[i].unsqueeze(0).unsqueeze(0) # (1, 1, D)
405
+ out = out + w * organelle_outputs[i]
406
+
407
+ return out
408
+
409
+
410
+ # ═══════════════════════════════════════════════════════════════════
411
+ # SkipGate (learnable residual scaling)
412
+ # ═══════════════════════════════════════════════════════════════════
413
+
414
+
415
+ class SkipGate(nn.Module):
416
+ """Learnable scalar gate for residual connections.
417
+
418
+ Scales the residual branch by a single learned parameter init=1.0.
419
+
420
+ Ports Julia SkipGate (symbiogenesis.jl).
421
+ Parameters: 1
422
+ """
423
+
424
+ def __init__(self):
425
+ super().__init__()
426
+ self.scale = nn.Parameter(torch.ones(1))
427
+
428
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
429
+ return self.scale * x
430
+
431
+
432
+ # ═══════════════════════════════════════════════════════════════════
433
+ # SymbioSequenceMixer (all organelles + gate)
434
+ # ═══════════════════════════════════════════════════════════════════
435
+
436
+
437
+ class SymbioSequenceMixer(nn.Module):
438
+ """Multi-organelle sequence mixer with learned gating.
439
+
440
+ Runs all configured organelles in parallel on the input,
441
+ then blends outputs via OrganelleGate.
442
+
443
+ Ports and extends Julia SymbioSequenceMixer (symbiogenesis.jl).
444
+ """
445
+
446
+ def __init__(self, config: SymbioConfig):
447
+ super().__init__()
448
+ self.config = config
449
+ d = config.d_model
450
+ T = config.context_length
451
+
452
+ self.organelle_names = list(config.organelles)
453
+ self.organelle_modules = nn.ModuleDict()
454
+
455
+ for name in self.organelle_names:
456
+ if name == "causal_conv":
457
+ self.organelle_modules[name] = CausalDepthwiseConv1d(
458
+ d, config.conv_kernel_size
459
+ )
460
+ elif name == "monarch":
461
+ self.organelle_modules[name] = nn.ModuleList(
462
+ [MonarchMatrix(T) for _ in range(config.n_monarch_heads)]
463
+ )
464
+ elif name == "long_conv":
465
+ self.organelle_modules[name] = LongConv(d, T)
466
+ elif name == "attention":
467
+ self.organelle_modules[name] = CausalSelfAttention(
468
+ d, config.n_heads, config.head_dim, config.dropout
469
+ )
470
+
471
+ self.gate = OrganelleGate(
472
+ d, len(self.organelle_names), config.gate_temperature_init
473
+ )
474
+
475
+ if "monarch" in self.organelle_names:
476
+ self.register_buffer(
477
+ "monarch_causal_mask", torch.tril(torch.ones(T, T))
478
+ )
479
+
480
+ def forward(
481
+ self,
482
+ x: torch.Tensor,
483
+ rope: RotaryEmbedding,
484
+ attn_mask: Optional[torch.Tensor] = None,
485
+ organelle_mask: Optional[Tuple[bool, ...]] = None,
486
+ ) -> torch.Tensor:
487
+ """Run all organelles in parallel and gate-blend.
488
+
489
+ x: (B, T, D)
490
+ rope: RotaryEmbedding for attention organelle
491
+ attn_mask: (T, T) additive mask for attention (-inf/0)
492
+ organelle_mask: optional per-organelle enable/disable
493
+ Returns: (B, T, D)
494
+ """
495
+ B, T, D = x.shape
496
+ outputs = []
497
+
498
+ for name in self.organelle_names:
499
+ if name == "causal_conv":
500
+ out = self.organelle_modules[name](x)
501
+ elif name == "monarch":
502
+ heads = self.organelle_modules[name]
503
+ n_mh = len(heads)
504
+ hd = D // n_mh
505
+ slices = []
506
+ for i, monarch in enumerate(heads):
507
+ x_slice = x[:, :, i * hd : (i + 1) * hd]
508
+ y_slice = monarch(x_slice, self.monarch_causal_mask)
509
+ slices.append(y_slice)
510
+ out = torch.cat(slices, dim=-1)
511
+ elif name == "long_conv":
512
+ out = self.organelle_modules[name](x)
513
+ elif name == "attention":
514
+ out = self.organelle_modules[name](x, rope, attn_mask)
515
+ outputs.append(out)
516
+
517
+ return self.gate(tuple(outputs), organelle_mask)
518
+
519
+
520
+ # ═══════════════════════════════════════════════════════════════════
521
+ # SymbioBlock (pre-norm residual block)
522
+ # ═══════════════════════════════════════════════════════════════════
523
+
524
+
525
+ class SymbioBlock(nn.Module):
526
+ """Pre-norm residual block with organelle sequence mixing and skip gates.
527
+
528
+ Architecture:
529
+ x β†’ RMSNorm β†’ SymbioSequenceMixer β†’ SkipGate β†’ +residual
530
+ β†’ RMSNorm β†’ SwiGLU β†’ SkipGate β†’ +residual β†’ out
531
+
532
+ Ports Julia SymbioBlock (symbiogenesis.jl).
533
+ """
534
+
535
+ def __init__(self, config: SymbioConfig, layer_organelles: Optional[Tuple[str, ...]] = None):
536
+ super().__init__()
537
+ d = config.d_model
538
+
539
+ if layer_organelles is not None:
540
+ from dataclasses import replace
541
+ layer_config = replace(config, organelles=layer_organelles)
542
+ else:
543
+ layer_config = config
544
+
545
+ self.ln1 = RMSNorm(d)
546
+ self.seq_mixer = SymbioSequenceMixer(layer_config)
547
+ self.skip1 = SkipGate()
548
+
549
+ self.ln2 = RMSNorm(d)
550
+ self.ffn = SwiGLU(d, config.ffn_mult)
551
+ self.skip2 = SkipGate()
552
+
553
+ def forward(
554
+ self,
555
+ x: torch.Tensor,
556
+ rope: RotaryEmbedding,
557
+ attn_mask: Optional[torch.Tensor] = None,
558
+ organelle_mask: Optional[Tuple[bool, ...]] = None,
559
+ ) -> torch.Tensor:
560
+ """x: (B, T, D) -> (B, T, D)"""
561
+ normed = self.ln1(x)
562
+ mixed = self.seq_mixer(normed, rope, attn_mask, organelle_mask)
563
+ x = x + self.skip1(mixed)
564
+
565
+ normed2 = self.ln2(x)
566
+ ffn_out = self.ffn(normed2)
567
+ x = x + self.skip2(ffn_out)
568
+
569
+ return x
570
+
571
+
572
+ # ═══════════════════════════════════════════════════════════════════
573
+ # SymbioGPT (full model)
574
+ # ═══════════════════════════════════════════════════════════════════
575
+
576
+
577
+ class SymbioGPT(nn.Module):
578
+ """SymbioGPT β€” Multi-organelle decoder-only causal language model.
579
+
580
+ tok_emb β†’ [SymbioBlock Γ— n_layers] β†’ ln_f β†’ head (weight-tied)
581
+
582
+ Supports configurable organelle composition per-layer.
583
+ """
584
+
585
+ def __init__(self, config: SymbioConfig):
586
+ super().__init__()
587
+ self.config = config
588
+
589
+ self.tok_emb = nn.Embedding(config.vocab_size, config.d_model)
590
+ self.rope = RotaryEmbedding(config.head_dim, config.context_length)
591
+
592
+ blocks = []
593
+ for i in range(config.n_layers):
594
+ layer_org = None
595
+ if config.per_layer_organelles is not None:
596
+ layer_org = config.per_layer_organelles[i]
597
+ blocks.append(SymbioBlock(config, layer_org))
598
+ self.blocks = nn.ModuleList(blocks)
599
+
600
+ self.ln_f = RMSNorm(config.d_model)
601
+
602
+ if config.weight_tying:
603
+ self.head = None
604
+ else:
605
+ self.head = nn.Linear(config.d_model, config.vocab_size, bias=False)
606
+
607
+ self._init_weights()
608
+
609
+ def _init_weights(self):
610
+ for module in self.modules():
611
+ if isinstance(module, nn.Linear):
612
+ fan_in = module.in_features
613
+ fan_out = module.out_features
614
+ std = math.sqrt(2.0 / (fan_in + fan_out))
615
+ nn.init.normal_(module.weight, mean=0.0, std=std)
616
+ if module.bias is not None:
617
+ nn.init.zeros_(module.bias)
618
+ elif isinstance(module, nn.Embedding):
619
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
620
+
621
+ def forward(
622
+ self,
623
+ input_ids: torch.Tensor,
624
+ organelle_mask: Optional[Tuple[bool, ...]] = None,
625
+ ) -> torch.Tensor:
626
+ """input_ids (B, T) -> logits (B, T, V)"""
627
+ B, T = input_ids.shape
628
+
629
+ x = self.tok_emb(input_ids)
630
+
631
+ attn_mask = torch.triu(
632
+ torch.full((T, T), float("-inf"), device=x.device, dtype=x.dtype),
633
+ diagonal=1,
634
+ )
635
+
636
+ for block in self.blocks:
637
+ x = block(x, self.rope, attn_mask, organelle_mask)
638
+
639
+ x = self.ln_f(x)
640
+
641
+ if self.head is not None:
642
+ logits = self.head(x)
643
+ else:
644
+ logits = F.linear(x, self.tok_emb.weight)
645
+
646
+ return logits
647
+
648
+ def get_gate_logits(self) -> List[torch.Tensor]:
649
+ """Extract gate logits from all blocks for monitoring."""
650
+ return [block.seq_mixer.gate.logits.detach() for block in self.blocks]
651
+
652
+ def get_gate_weights(self) -> List[torch.Tensor]:
653
+ """Extract gate softmax weights for visualization."""
654
+ weights = []
655
+ for block in self.blocks:
656
+ gate = block.seq_mixer.gate
657
+ tau = gate.temperature.clamp(min=0.01)
658
+ w = F.softmax(gate.logits / tau, dim=0)
659
+ weights.append(w.detach())
660
+ return weights
661
+
662
+
663
+ # ═══════════════════════════════════════════════════════════════════
664
+ # Utility functions
665
+ # ═══════════════════════════════════════════════════════════════════
666
+
667
+
668
+ def compute_symbio_params(config: SymbioConfig) -> int:
669
+ """Compute exact parameter count for a SymbioGPT model."""
670
+ d = config.d_model
671
+ V = config.vocab_size
672
+ L = config.n_layers
673
+ T = config.context_length
674
+ p = config.p
675
+
676
+ emb = V * d
677
+
678
+ per_layer = 0
679
+ for org in config.organelles:
680
+ if org == "causal_conv":
681
+ per_layer += config.conv_kernel_size * d
682
+ elif org == "monarch":
683
+ per_layer += config.n_monarch_heads * 2 * p ** 3
684
+ elif org == "long_conv":
685
+ per_layer += T * d
686
+ elif org == "attention":
687
+ total_attn_dim = config.n_heads * config.head_dim
688
+ per_layer += 4 * d * total_attn_dim # wq, wk, wv, wo
689
+
690
+ # OrganelleGate: logits + temperature
691
+ per_layer += config.n_organelles * d + 1
692
+
693
+ # SkipGate Γ— 2
694
+ per_layer += 2
695
+
696
+ # SwiGLU FFN
697
+ raw_hidden = 2 * d * config.ffn_mult // 3
698
+ ffn_hidden = max(64, (raw_hidden // 64) * 64)
699
+ per_layer += 3 * d * ffn_hidden
700
+
701
+ # RMSNorm Γ— 2
702
+ per_layer += 2 * d
703
+
704
+ # Final norm
705
+ final_norm = d
706
+
707
+ total = emb + L * per_layer + final_norm
708
+ if not config.weight_tying:
709
+ total += V * d
710
+
711
+ return total
712
+
713
+
714
+ def complexity_penalty(model: nn.Module) -> torch.Tensor:
715
+ """Free energy regularization: mean of squared log-weight magnitudes.
716
+
717
+ Ports Julia complexity_penalty (free_energy.jl).
718
+ """
719
+ total = torch.tensor(0.0, device=next(model.parameters()).device)
720
+ n_arrays = 0
721
+ for param in model.parameters():
722
+ if param.numel() > 0:
723
+ total = total + (torch.log(param.abs() + 1e-6) ** 2).sum() / param.numel()
724
+ n_arrays += 1
725
+ return total / max(n_arrays, 1)
726
+
727
+
728
+ def compute_gate_entropy(model: SymbioGPT) -> float:
729
+ """Average per-channel entropy of organelle gates across all blocks.
730
+
731
+ Low entropy = strong specialization; high = uniform mixing.
732
+ """
733
+ gate_weights = model.get_gate_weights()
734
+ if not gate_weights:
735
+ return 0.0
736
+ total_entropy = 0.0
737
+ for w in gate_weights:
738
+ H = -(w * torch.log(w + 1e-10)).sum() / w.shape[1]
739
+ total_entropy += H.item()
740
+ return total_entropy / len(gate_weights)