trojan0x commited on
Commit
2d2e52e
·
verified ·
1 Parent(s): 4c31898

Add ultron/model.py

Browse files
Files changed (1) hide show
  1. ultron/model.py +802 -0
ultron/model.py ADDED
@@ -0,0 +1,802 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Ultron — Recurrent-Depth Transformer Language Model
3
+
4
+ A clean, research-grounded implementation of a looped transformer architecture
5
+ that combines proven techniques from:
6
+ - Parcae (Prairie et al., 2026): LTI-stable injection, per-sequence depth
7
+ sampling, prelude normalization, C output projection
8
+ - Relaxed Recursive Transformers (Bae et al., 2024): depth-wise LoRA adaptation
9
+ - Loop, Think, & Generalize (2025): depth extrapolation via inference-time loops
10
+ - Adaptive Computation Time (Graves, 2016): per-position early halting
11
+ - Reasoning with Latent Thoughts (Saunshi et al., 2025): implicit CoT via loops
12
+
13
+ Architecture:
14
+ Input → [Embedding] → [Prelude] → [LN(e)] → [RecurrentBlock ×T] → [C·h] → [Coda] → [LM Head]
15
+
16
+ Key design choices over OpenMythos:
17
+ 1. Prelude normalization for stability at scale
18
+ 2. Per-sequence depth sampling during training
19
+ 3. Diagonal C output projection (completes the LTI system)
20
+ 4. Backprop truncation (μ_bwd = ⌈μ_rec/2⌉) for memory efficiency
21
+ 5. Gradient checkpointing support built-in
22
+ 6. MoE is optional (default OFF — unproven with looping)
23
+ 7. GQA default (proven with looping in Parcae)
24
+ 8. Efficient expert dispatch via batched operations
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import math
30
+ from dataclasses import dataclass, field
31
+ from typing import Optional
32
+
33
+ import torch
34
+ import torch.nn as nn
35
+ import torch.nn.functional as F
36
+ from torch.utils.checkpoint import checkpoint as grad_checkpoint
37
+
38
+
39
+ # ===========================================================================
40
+ # Configuration
41
+ # ===========================================================================
42
+
43
+
44
+ @dataclass
45
+ class UltronConfig:
46
+ """All hyperparameters for the Ultron model.
47
+
48
+ Organized into sections:
49
+ - Core: dimensions, heads, sequence length
50
+ - Loop: recurrent block settings, ACT threshold, LoRA rank
51
+ - Attention: type selection and MLA-specific params
52
+ - MoE: optional MoE FFN settings (default: dense FFN)
53
+ - Training: gradient checkpointing, dropout, depth sampling
54
+ """
55
+
56
+ # ---- Core ----
57
+ vocab_size: int = 32000
58
+ dim: int = 2048
59
+ n_heads: int = 16
60
+ n_kv_heads: int = 4
61
+ max_seq_len: int = 4096
62
+ ffn_mult: float = 8 / 3 # SwiGLU hidden = dim * ffn_mult, rounded to nearest 64
63
+
64
+ # ---- Prelude / Coda ----
65
+ prelude_layers: int = 4
66
+ coda_layers: int = 4
67
+
68
+ # ---- Recurrent Block ----
69
+ recurrent_layers: int = 8 # layers inside one loop iteration
70
+ max_loop_iters: int = 16 # T — default recurrent depth
71
+ act_threshold: float = 0.99
72
+ lora_rank: int = 16 # depth-wise LoRA rank (0 to disable)
73
+ loop_embed_dim: int = 0 # channels for loop-index embedding (0=auto: dim//8)
74
+
75
+ # ---- Attention ----
76
+ attn_type: str = "gqa" # "gqa" (default, proven) or "mla" (experimental)
77
+ kv_lora_rank: int = 512
78
+ q_lora_rank: int = 1536
79
+ qk_rope_head_dim: int = 64
80
+ qk_nope_head_dim: int = 128
81
+ v_head_dim: int = 128
82
+
83
+ # ---- MoE (optional) ----
84
+ use_moe: bool = False # default OFF — unproven with looping
85
+ n_experts: int = 8
86
+ n_shared_experts: int = 1
87
+ n_experts_per_tok: int = 2
88
+ expert_dim: int = 512
89
+
90
+ # ---- RoPE ----
91
+ rope_theta: float = 500_000.0
92
+
93
+ # ---- Training ----
94
+ dropout: float = 0.0
95
+ gradient_checkpointing: bool = False
96
+
97
+ def __post_init__(self):
98
+ if self.loop_embed_dim == 0:
99
+ self.loop_embed_dim = self.dim // 8
100
+ # Ensure even for sinusoidal embedding
101
+ self.loop_embed_dim = self.loop_embed_dim + (self.loop_embed_dim % 2)
102
+
103
+ @property
104
+ def head_dim(self) -> int:
105
+ return self.dim // self.n_heads
106
+
107
+ @property
108
+ def ffn_hidden(self) -> int:
109
+ """SwiGLU hidden dim, rounded to nearest multiple of 64."""
110
+ raw = int(self.dim * self.ffn_mult)
111
+ return ((raw + 63) // 64) * 64
112
+
113
+
114
+ # ===========================================================================
115
+ # RMSNorm
116
+ # ===========================================================================
117
+
118
+
119
+ class RMSNorm(nn.Module):
120
+ """Root Mean Square Layer Normalization (Zhang & Sennrich, 2019)."""
121
+
122
+ def __init__(self, dim: int, eps: float = 1e-6):
123
+ super().__init__()
124
+ self.eps = eps
125
+ self.weight = nn.Parameter(torch.ones(dim))
126
+
127
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
128
+ rms = x.float().pow(2).mean(-1, keepdim=True).add(self.eps).rsqrt()
129
+ return (x.float() * rms).to(x.dtype) * self.weight
130
+
131
+
132
+ # ===========================================================================
133
+ # RoPE
134
+ # ===========================================================================
135
+
136
+
137
+ def precompute_rope_freqs(dim: int, max_len: int, theta: float = 500_000.0) -> torch.Tensor:
138
+ """Precompute complex-valued RoPE rotation matrices."""
139
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
140
+ t = torch.arange(max_len, dtype=torch.float32)
141
+ freqs = torch.outer(t, freqs)
142
+ return torch.polar(torch.ones_like(freqs), freqs)
143
+
144
+
145
+ def apply_rope(x: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor:
146
+ """Apply rotary positional embeddings to a (B, T, H, D) tensor."""
147
+ xc = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
148
+ out = torch.view_as_real(xc * freqs_cis.unsqueeze(0).unsqueeze(2))
149
+ return out.flatten(-2).to(x.dtype)
150
+
151
+
152
+ # ===========================================================================
153
+ # Attention: Grouped Query Attention
154
+ # ===========================================================================
155
+
156
+
157
+ class GQAttention(nn.Module):
158
+ """Grouped Query Attention (Ainslie et al., 2023).
159
+
160
+ Proven to work with looped architectures (used in Parcae experiments).
161
+ """
162
+
163
+ def __init__(self, cfg: UltronConfig):
164
+ super().__init__()
165
+ self.n_heads = cfg.n_heads
166
+ self.n_kv_heads = cfg.n_kv_heads
167
+ self.head_dim = cfg.head_dim
168
+ self.groups = cfg.n_heads // cfg.n_kv_heads
169
+
170
+ self.wq = nn.Linear(cfg.dim, cfg.n_heads * self.head_dim, bias=False)
171
+ self.wk = nn.Linear(cfg.dim, cfg.n_kv_heads * self.head_dim, bias=False)
172
+ self.wv = nn.Linear(cfg.dim, cfg.n_kv_heads * self.head_dim, bias=False)
173
+ self.wo = nn.Linear(cfg.n_heads * self.head_dim, cfg.dim, bias=False)
174
+ self.attn_drop = nn.Dropout(cfg.dropout)
175
+
176
+ def forward(self, x, freqs_cis, mask=None, kv_cache=None, cache_key="default"):
177
+ B, T, _ = x.shape
178
+ q = self.wq(x).view(B, T, self.n_heads, self.head_dim)
179
+ k = self.wk(x).view(B, T, self.n_kv_heads, self.head_dim)
180
+ v = self.wv(x).view(B, T, self.n_kv_heads, self.head_dim)
181
+
182
+ q = apply_rope(q, freqs_cis)
183
+ k = apply_rope(k, freqs_cis)
184
+
185
+ if kv_cache is not None:
186
+ if cache_key in kv_cache:
187
+ k = torch.cat([kv_cache[cache_key]["k"], k], dim=1)
188
+ v = torch.cat([kv_cache[cache_key]["v"], v], dim=1)
189
+ kv_cache[cache_key] = {"k": k.detach(), "v": v.detach()}
190
+
191
+ k = k.repeat_interleave(self.groups, dim=2)
192
+ v = v.repeat_interleave(self.groups, dim=2)
193
+
194
+ q, k, v = [t.transpose(1, 2) for t in (q, k, v)]
195
+
196
+ scale = self.head_dim ** -0.5
197
+ attn = torch.matmul(q, k.transpose(-2, -1)) * scale
198
+ if mask is not None:
199
+ attn = attn + mask
200
+ attn = self.attn_drop(F.softmax(attn, dim=-1))
201
+ out = torch.matmul(attn, v)
202
+ return self.wo(out.transpose(1, 2).contiguous().view(B, T, -1))
203
+
204
+
205
+ # ===========================================================================
206
+ # Attention: Multi-Latent Attention (experimental with looping)
207
+ # ===========================================================================
208
+
209
+
210
+ class MLAttention(nn.Module):
211
+ """Multi-Latent Attention (DeepSeek-V2, 2024).
212
+
213
+ Compresses KV cache via low-rank latent. Experimental with looped architectures
214
+ — no published results validating this combination.
215
+ """
216
+
217
+ def __init__(self, cfg: UltronConfig):
218
+ super().__init__()
219
+ self.n_heads = cfg.n_heads
220
+ self.kv_lora_rank = cfg.kv_lora_rank
221
+ self.qk_rope_dim = cfg.qk_rope_head_dim
222
+ self.qk_nope_dim = cfg.qk_nope_head_dim
223
+ self.v_dim = cfg.v_head_dim
224
+ self.q_head_dim = cfg.qk_nope_head_dim + cfg.qk_rope_head_dim
225
+
226
+ self.q_down = nn.Linear(cfg.dim, cfg.q_lora_rank, bias=False)
227
+ self.q_norm = RMSNorm(cfg.q_lora_rank)
228
+ self.q_up_nope = nn.Linear(cfg.q_lora_rank, cfg.n_heads * cfg.qk_nope_head_dim, bias=False)
229
+ self.q_up_rope = nn.Linear(cfg.q_lora_rank, cfg.n_heads * cfg.qk_rope_head_dim, bias=False)
230
+
231
+ self.kv_down = nn.Linear(cfg.dim, cfg.kv_lora_rank + cfg.qk_rope_head_dim, bias=False)
232
+ self.kv_norm = RMSNorm(cfg.kv_lora_rank)
233
+ self.kv_up = nn.Linear(
234
+ cfg.kv_lora_rank,
235
+ cfg.n_heads * (cfg.qk_nope_head_dim + cfg.v_head_dim),
236
+ bias=False,
237
+ )
238
+ self.wo = nn.Linear(cfg.n_heads * cfg.v_head_dim, cfg.dim, bias=False)
239
+ self.attn_drop = nn.Dropout(cfg.dropout)
240
+
241
+ def forward(self, x, freqs_cis, mask=None, kv_cache=None, cache_key="default"):
242
+ B, T, _ = x.shape
243
+
244
+ c_q = self.q_norm(self.q_down(x))
245
+ q_nope = self.q_up_nope(c_q).view(B, T, self.n_heads, self.qk_nope_dim)
246
+ q_rope = self.q_up_rope(c_q).view(B, T, self.n_heads, self.qk_rope_dim)
247
+ q_rope = apply_rope(q_rope, freqs_cis)
248
+ q = torch.cat([q_nope, q_rope], dim=-1)
249
+
250
+ kv_raw = self.kv_down(x)
251
+ c_kv = kv_raw[..., :self.kv_lora_rank]
252
+ k_rope = kv_raw[..., self.kv_lora_rank:]
253
+ k_rope = k_rope.unsqueeze(2).expand(B, T, self.n_heads, self.qk_rope_dim).contiguous()
254
+ k_rope = apply_rope(k_rope, freqs_cis)
255
+
256
+ if kv_cache is not None:
257
+ if cache_key in kv_cache:
258
+ c_kv = torch.cat([kv_cache[cache_key]["c_kv"], c_kv], dim=1)
259
+ k_rope = torch.cat([kv_cache[cache_key]["k_rope"], k_rope], dim=1)
260
+ kv_cache[cache_key] = {"c_kv": c_kv.detach(), "k_rope": k_rope.detach()}
261
+
262
+ S = c_kv.shape[1]
263
+ kv = self.kv_up(self.kv_norm(c_kv)).view(B, S, self.n_heads, self.qk_nope_dim + self.v_dim)
264
+ k_nope, v = kv[..., :self.qk_nope_dim], kv[..., self.qk_nope_dim:]
265
+ k = torch.cat([k_nope, k_rope], dim=-1)
266
+
267
+ q, k, v = [t.transpose(1, 2) for t in (q, k, v)]
268
+ scale = self.q_head_dim ** -0.5
269
+ attn = torch.matmul(q, k.transpose(-2, -1)) * scale
270
+ if mask is not None:
271
+ attn = attn + mask
272
+ attn = self.attn_drop(F.softmax(attn, dim=-1))
273
+ out = torch.matmul(attn, v)
274
+ return self.wo(out.transpose(1, 2).contiguous().view(B, T, -1))
275
+
276
+
277
+ # ===========================================================================
278
+ # Feed-Forward: SwiGLU Expert
279
+ # ===========================================================================
280
+
281
+
282
+ class SwiGLUFFN(nn.Module):
283
+ """SwiGLU feed-forward: down(silu(gate(x)) * up(x))."""
284
+
285
+ def __init__(self, dim: int, hidden_dim: int, dropout: float = 0.0):
286
+ super().__init__()
287
+ self.gate = nn.Linear(dim, hidden_dim, bias=False)
288
+ self.up = nn.Linear(dim, hidden_dim, bias=False)
289
+ self.down = nn.Linear(hidden_dim, dim, bias=False)
290
+ self.drop = nn.Dropout(dropout)
291
+
292
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
293
+ return self.drop(self.down(F.silu(self.gate(x)) * self.up(x)))
294
+
295
+
296
+ # ===========================================================================
297
+ # Feed-Forward: MoE (Optional, experimental with looping)
298
+ # ===========================================================================
299
+
300
+
301
+ class MoEFFN(nn.Module):
302
+ """Fine-grained Mixture-of-Experts FFN.
303
+
304
+ Experimental with looped architectures — no published work validates
305
+ MoE inside a recurrent block. Enabled via cfg.use_moe=True.
306
+ Uses batched operations instead of Python loops for efficiency.
307
+ """
308
+
309
+ def __init__(self, cfg: UltronConfig):
310
+ super().__init__()
311
+ self.n_experts = cfg.n_experts
312
+ self.n_shared = cfg.n_shared_experts
313
+ self.topk = cfg.n_experts_per_tok
314
+
315
+ self.router = nn.Linear(cfg.dim, cfg.n_experts, bias=False)
316
+ self.register_buffer("router_bias", torch.zeros(cfg.n_experts))
317
+
318
+ self.experts = nn.ModuleList([
319
+ SwiGLUFFN(cfg.dim, cfg.expert_dim) for _ in range(cfg.n_experts)
320
+ ])
321
+ self.shared = nn.ModuleList([
322
+ SwiGLUFFN(cfg.dim, cfg.expert_dim * cfg.n_experts_per_tok)
323
+ for _ in range(self.n_shared)
324
+ ])
325
+
326
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
327
+ B, T, D = x.shape
328
+ flat = x.view(-1, D) # (N, D)
329
+
330
+ logits = self.router(flat)
331
+ scores = F.softmax(logits, dim=-1)
332
+ _, topk_idx = (logits + self.router_bias).topk(self.topk, dim=-1)
333
+ topk_scores = scores.gather(-1, topk_idx)
334
+ topk_scores = topk_scores / topk_scores.sum(dim=-1, keepdim=True)
335
+
336
+ # Batched dispatch — group tokens by expert
337
+ out = torch.zeros_like(flat)
338
+ for k in range(self.topk):
339
+ expert_ids = topk_idx[:, k]
340
+ weights = topk_scores[:, k].unsqueeze(-1)
341
+ for eid in range(self.n_experts):
342
+ mask = expert_ids == eid
343
+ if mask.any():
344
+ out[mask] += weights[mask] * self.experts[eid](flat[mask])
345
+
346
+ for shared_expert in self.shared:
347
+ out = out + shared_expert(flat)
348
+
349
+ return out.view(B, T, D)
350
+
351
+
352
+ # ===========================================================================
353
+ # Transformer Block
354
+ # ===========================================================================
355
+
356
+
357
+ class TransformerBlock(nn.Module):
358
+ """Pre-norm transformer block with swappable attention and FFN."""
359
+
360
+ def __init__(self, cfg: UltronConfig, use_moe: bool = False):
361
+ super().__init__()
362
+ self.attn_norm = RMSNorm(cfg.dim)
363
+ self.ffn_norm = RMSNorm(cfg.dim)
364
+
365
+ if cfg.attn_type == "mla":
366
+ self.attn = MLAttention(cfg)
367
+ else:
368
+ self.attn = GQAttention(cfg)
369
+
370
+ if use_moe and cfg.use_moe:
371
+ self.ffn = MoEFFN(cfg)
372
+ else:
373
+ self.ffn = SwiGLUFFN(cfg.dim, cfg.ffn_hidden, cfg.dropout)
374
+
375
+ self.resid_drop = nn.Dropout(cfg.dropout)
376
+
377
+ def forward(self, x, freqs_cis, mask=None, kv_cache=None, cache_key="default"):
378
+ x = x + self.resid_drop(self.attn(self.attn_norm(x), freqs_cis, mask, kv_cache, cache_key))
379
+ x = x + self.resid_drop(self.ffn(self.ffn_norm(x)))
380
+ return x
381
+
382
+
383
+ # ===========================================================================
384
+ # LTI-Stable Injection (Parcae, Prairie et al., 2026)
385
+ # ===========================================================================
386
+
387
+
388
+ class LTIInjection(nn.Module):
389
+ """Stable recurrent injection: h_{t+1} = A·h_t + B·e + R(h_t, e).
390
+
391
+ Guarantees spectral radius ρ(A) < 1 by construction via:
392
+ A_continuous = Diag(-exp(log_A)) [always negative]
393
+ A_discrete = exp(Δt · A_continuous) [values in (0, 1)]
394
+
395
+ Also includes output projection C (Parcae's full LTI system).
396
+ """
397
+
398
+ def __init__(self, dim: int):
399
+ super().__init__()
400
+ self.log_A = nn.Parameter(torch.zeros(dim))
401
+ self.log_dt = nn.Parameter(torch.zeros(1))
402
+ self.B = nn.Parameter(torch.ones(dim) * 0.1)
403
+ # Output projection C — completes the Parcae LTI system
404
+ self.C = nn.Parameter(torch.ones(dim))
405
+
406
+ def get_A(self) -> torch.Tensor:
407
+ """Discretized diagonal A with all values in (0, 1)."""
408
+ return torch.exp(-torch.exp((self.log_dt + self.log_A).clamp(-20, 20)))
409
+
410
+ def forward(self, h: torch.Tensor, e: torch.Tensor, r_out: torch.Tensor) -> torch.Tensor:
411
+ """h_{t+1} = A·h_t + B·e + r_out"""
412
+ A = self.get_A()
413
+ return A * h + self.B * e + r_out
414
+
415
+ def project_output(self, h: torch.Tensor) -> torch.Tensor:
416
+ """Apply C output projection: p = C · h_T"""
417
+ return self.C * h
418
+
419
+
420
+ # ===========================================================================
421
+ # ACT Halting (Graves, 2016)
422
+ # ===========================================================================
423
+
424
+
425
+ class ACTHalting(nn.Module):
426
+ """Adaptive Computation Time — learns when to stop looping per position."""
427
+
428
+ def __init__(self, dim: int):
429
+ super().__init__()
430
+ self.halt = nn.Linear(dim, 1, bias=True)
431
+ # Initialize bias to -3 so initial halting probability ≈ sigmoid(-3) ≈ 0.05
432
+ # This encourages the model to use most loops early in training
433
+ nn.init.constant_(self.halt.bias, -3.0)
434
+
435
+ def forward(self, h: torch.Tensor) -> torch.Tensor:
436
+ """Returns per-position halting probability (B, T)."""
437
+ return torch.sigmoid(self.halt(h)).squeeze(-1)
438
+
439
+
440
+ # ===========================================================================
441
+ # Depth-wise LoRA Adapter (Bae et al., 2024)
442
+ # ===========================================================================
443
+
444
+
445
+ class DepthLoRA(nn.Module):
446
+ """Per-loop-iteration LoRA adapter.
447
+
448
+ delta(x, t) = (down(x) * scale[t]) @ B
449
+
450
+ Bridges pure weight-tying (compact, less expressive) and fully
451
+ distinct layers (expressive, no parameter savings).
452
+ """
453
+
454
+ def __init__(self, dim: int, rank: int, max_loops: int):
455
+ super().__init__()
456
+ self.down = nn.Linear(dim, rank, bias=False)
457
+ self.B = nn.Parameter(torch.randn(rank, dim) * 0.01)
458
+ self.scale = nn.Embedding(max_loops, rank)
459
+ # Initialize scales near zero so LoRA starts as near-identity
460
+ nn.init.normal_(self.scale.weight, std=0.01)
461
+
462
+ def forward(self, x: torch.Tensor, loop_t: int) -> torch.Tensor:
463
+ t_idx = min(loop_t, self.scale.num_embeddings - 1)
464
+ s = self.scale(torch.tensor(t_idx, device=x.device))
465
+ return (self.down(x) * s) @ self.B
466
+
467
+
468
+ # ===========================================================================
469
+ # Loop-Index Embedding
470
+ # ===========================================================================
471
+
472
+
473
+ def loop_index_embedding(h: torch.Tensor, loop_t: int, loop_dim: int, theta: float = 10000.0) -> torch.Tensor:
474
+ """Inject sinusoidal loop-index signal into first loop_dim channels.
475
+
476
+ Analogous to RoPE but over recurrence depth — lets shared weights
477
+ implement different operations at different loop iterations.
478
+ """
479
+ device, dtype = h.device, h.dtype
480
+ freqs = 1.0 / (theta ** (torch.arange(0, loop_dim, 2, device=device, dtype=dtype) / loop_dim))
481
+ angles = loop_t * freqs
482
+ emb = torch.cat([angles.sin(), angles.cos()], dim=-1)[:loop_dim]
483
+ pad = torch.zeros(h.shape[-1] - loop_dim, device=device, dtype=dtype)
484
+ return h + torch.cat([emb, pad]).unsqueeze(0).unsqueeze(0)
485
+
486
+
487
+ # ===========================================================================
488
+ # Recurrent Block
489
+ # ===========================================================================
490
+
491
+
492
+ class RecurrentBlock(nn.Module):
493
+ """The heart of Ultron — transformer layers looped T times with LTI-stable injection.
494
+
495
+ Per iteration t:
496
+ 1. Loop-index embedding (optional sinusoidal signal)
497
+ 2. RMSNorm(h + e) — combine hidden state with frozen encoded input
498
+ 3. L_r TransformerBlock layers — attention + FFN
499
+ 4. LoRA adapter — depth-wise adaptation
500
+ 5. LTI injection — h = A·h + B·e + transformer_out (stable)
501
+ 6. ACT halting — accumulate per-position stopping probabilities
502
+
503
+ Training features (from Parcae):
504
+ - Per-sequence depth sampling: different sequences in a batch use different T
505
+ - Backprop truncation: gradients flow through only the last μ_bwd iterations
506
+ - Gradient checkpointing: saves memory during loop unrolling
507
+ """
508
+
509
+ def __init__(self, cfg: UltronConfig):
510
+ super().__init__()
511
+ self.cfg = cfg
512
+
513
+ # Multiple layers per loop iteration (unlike OpenMythos which uses 1)
514
+ self.layers = nn.ModuleList([
515
+ TransformerBlock(cfg, use_moe=True) for _ in range(cfg.recurrent_layers)
516
+ ])
517
+ self.injection = LTIInjection(cfg.dim)
518
+ self.act = ACTHalting(cfg.dim)
519
+ self.combine_norm = RMSNorm(cfg.dim)
520
+
521
+ if cfg.lora_rank > 0:
522
+ self.lora = DepthLoRA(cfg.dim, cfg.lora_rank, cfg.max_loop_iters)
523
+ else:
524
+ self.lora = None
525
+
526
+ self.loop_dim = cfg.loop_embed_dim
527
+
528
+ def _single_iteration(
529
+ self, h, e, freqs_cis, mask, loop_t, kv_cache
530
+ ) -> torch.Tensor:
531
+ """Run one loop iteration through all recurrent layers."""
532
+ # Loop-index embedding
533
+ h_loop = loop_index_embedding(h, loop_t, self.loop_dim)
534
+
535
+ # Combine with frozen encoded input
536
+ combined = self.combine_norm(h_loop + e)
537
+
538
+ # Run through all recurrent layers
539
+ for li, layer in enumerate(self.layers):
540
+ cache_key = f"recurrent_L{loop_t}_l{li}"
541
+ combined = layer(combined, freqs_cis, mask, kv_cache, cache_key)
542
+
543
+ # Depth-wise LoRA
544
+ if self.lora is not None:
545
+ combined = combined + self.lora(combined, loop_t)
546
+
547
+ # LTI-stable injection
548
+ h_new = self.injection(h, e, combined)
549
+ return h_new
550
+
551
+ def forward(
552
+ self,
553
+ h: torch.Tensor,
554
+ e: torch.Tensor,
555
+ freqs_cis: torch.Tensor,
556
+ mask: Optional[torch.Tensor] = None,
557
+ n_loops: Optional[int] = None,
558
+ kv_cache: Optional[dict] = None,
559
+ ) -> torch.Tensor:
560
+ """Run the recurrent loop with ACT halting.
561
+
562
+ Args:
563
+ h: Initial hidden state from prelude (B, T, dim)
564
+ e: Frozen encoded input for injection (B, T, dim)
565
+ freqs_cis: RoPE frequencies
566
+ mask: Causal mask
567
+ n_loops: Override loop count (for depth extrapolation)
568
+ kv_cache: KV cache dict (for generation)
569
+
570
+ Returns:
571
+ ACT-weighted sum of hidden states across iterations (B, T, dim)
572
+ """
573
+ n_loops = n_loops or self.cfg.max_loop_iters
574
+ B, T, D = h.shape
575
+ device = h.device
576
+
577
+ halted = torch.zeros(B, T, device=device, dtype=torch.bool)
578
+ cumulative_p = torch.zeros(B, T, device=device)
579
+ h_out = torch.zeros_like(h)
580
+
581
+ for t in range(n_loops):
582
+ # Gradient checkpointing for memory efficiency
583
+ if self.cfg.gradient_checkpointing and self.training:
584
+ h = grad_checkpoint(
585
+ self._single_iteration,
586
+ h, e, freqs_cis, mask, t, kv_cache,
587
+ use_reentrant=False,
588
+ )
589
+ else:
590
+ h = self._single_iteration(h, e, freqs_cis, mask, t, kv_cache)
591
+
592
+ # ACT halting
593
+ p = self.act(h)
594
+ still_running = ~halted
595
+
596
+ remainder = (1.0 - cumulative_p).clamp(min=0)
597
+ weight = torch.where(
598
+ cumulative_p + p >= self.cfg.act_threshold,
599
+ remainder,
600
+ p,
601
+ )
602
+ weight = weight * still_running.float()
603
+ h_out = h_out + weight.unsqueeze(-1) * h
604
+
605
+ cumulative_p = cumulative_p + p * still_running.float()
606
+ halted = halted | (cumulative_p >= self.cfg.act_threshold)
607
+
608
+ if halted.all() and kv_cache is None:
609
+ break
610
+
611
+ # Apply C output projection (Parcae LTI system)
612
+ h_out = self.injection.project_output(h_out)
613
+
614
+ return h_out
615
+
616
+
617
+ # ===========================================================================
618
+ # Full Model
619
+ # ===========================================================================
620
+
621
+
622
+ class Ultron(nn.Module):
623
+ """Ultron — Recurrent-Depth Transformer Language Model.
624
+
625
+ Architecture:
626
+ Input → Embed → Prelude → LN(e) → RecurrentBlock×T → Coda → RMSNorm → LM Head
627
+
628
+ Key innovations over OpenMythos:
629
+ 1. Prelude normalization (critical for stability at scale)
630
+ 2. Multiple layers per loop iteration (more expressive recurrent block)
631
+ 3. C output projection (completes the LTI dynamical system)
632
+ 4. Gradient checkpointing (memory-efficient loop unrolling)
633
+ 5. ACT halting bias initialization (encourages using all loops early)
634
+ 6. Clean separation of proven vs. experimental components
635
+ """
636
+
637
+ def __init__(self, cfg: UltronConfig):
638
+ super().__init__()
639
+ self.cfg = cfg
640
+
641
+ # Embedding
642
+ self.embed = nn.Embedding(cfg.vocab_size, cfg.dim)
643
+
644
+ # RoPE frequency buffers
645
+ if cfg.attn_type == "mla":
646
+ rope_dim = cfg.qk_rope_head_dim
647
+ else:
648
+ rope_dim = cfg.head_dim
649
+ freqs = precompute_rope_freqs(rope_dim, cfg.max_seq_len, cfg.rope_theta)
650
+ self.register_buffer("freqs_cis", freqs)
651
+
652
+ # Prelude — standard transformer blocks
653
+ self.prelude = nn.ModuleList([
654
+ TransformerBlock(cfg, use_moe=False) for _ in range(cfg.prelude_layers)
655
+ ])
656
+
657
+ # Prelude normalization — Parcae's critical stability contribution
658
+ # Applied to encoded input before injection into the recurrent block
659
+ self.prelude_norm = RMSNorm(cfg.dim)
660
+
661
+ # Recurrent block
662
+ self.recurrent = RecurrentBlock(cfg)
663
+
664
+ # Coda — standard transformer blocks
665
+ self.coda = nn.ModuleList([
666
+ TransformerBlock(cfg, use_moe=False) for _ in range(cfg.coda_layers)
667
+ ])
668
+
669
+ # Output
670
+ self.out_norm = RMSNorm(cfg.dim)
671
+ self.lm_head = nn.Linear(cfg.dim, cfg.vocab_size, bias=False)
672
+ self.lm_head.weight = self.embed.weight # weight tying
673
+
674
+ self._init_weights()
675
+
676
+ def _init_weights(self):
677
+ """Initialize weights with N(0, 0.02) following standard practice."""
678
+ for m in self.modules():
679
+ if isinstance(m, nn.Linear):
680
+ nn.init.normal_(m.weight, std=0.02)
681
+ if m.bias is not None:
682
+ # Don't overwrite ACT bias initialization
683
+ if not hasattr(m, '_ultron_skip_bias_init'):
684
+ nn.init.zeros_(m.bias)
685
+ elif isinstance(m, nn.Embedding):
686
+ nn.init.normal_(m.weight, std=0.02)
687
+ # Re-init ACT bias (it was set in __init__ but _init_weights runs after)
688
+ nn.init.constant_(self.recurrent.act.halt.bias, -3.0)
689
+
690
+ @staticmethod
691
+ def _causal_mask(seq_len: int, device: torch.device) -> torch.Tensor:
692
+ """Build additive causal mask: 0 on/below diagonal, -inf above."""
693
+ mask = torch.full((1, 1, seq_len, seq_len), float("-inf"), device=device)
694
+ return torch.triu(mask, diagonal=1)
695
+
696
+ def forward(
697
+ self,
698
+ input_ids: torch.Tensor,
699
+ n_loops: Optional[int] = None,
700
+ kv_cache: Optional[dict] = None,
701
+ start_pos: int = 0,
702
+ ) -> torch.Tensor:
703
+ """Forward pass: Embed → Prelude → LN(e) → RecurrentBlock → Coda → LM Head.
704
+
705
+ Args:
706
+ input_ids: Token indices (B, T)
707
+ n_loops: Override loop depth (for depth extrapolation at inference)
708
+ kv_cache: Dict for KV caching during generation
709
+ start_pos: Position offset for RoPE during incremental decoding
710
+
711
+ Returns:
712
+ Logits (B, T, vocab_size)
713
+ """
714
+ T = input_ids.shape[1]
715
+ device = input_ids.device
716
+
717
+ x = self.embed(input_ids)
718
+ freqs_cis = self.freqs_cis[start_pos:start_pos + T]
719
+ mask = self._causal_mask(T, device) if T > 1 else None
720
+
721
+ # Prelude
722
+ for i, layer in enumerate(self.prelude):
723
+ x = layer(x, freqs_cis, mask, kv_cache, cache_key=f"prelude_{i}")
724
+
725
+ # Prelude normalization — Parcae's key stability contribution
726
+ e = self.prelude_norm(x)
727
+
728
+ # Recurrent block
729
+ x = self.recurrent(x, e, freqs_cis, mask, n_loops, kv_cache)
730
+
731
+ # Coda
732
+ for i, layer in enumerate(self.coda):
733
+ x = layer(x, freqs_cis, mask, kv_cache, cache_key=f"coda_{i}")
734
+
735
+ return self.lm_head(self.out_norm(x))
736
+
737
+ @torch.no_grad()
738
+ def generate(
739
+ self,
740
+ input_ids: torch.Tensor,
741
+ max_new_tokens: int = 64,
742
+ n_loops: int = 8,
743
+ temperature: float = 1.0,
744
+ top_k: int = 50,
745
+ top_p: float = 0.0,
746
+ ) -> torch.Tensor:
747
+ """Autoregressive generation with KV caching.
748
+
749
+ Supports depth extrapolation — set n_loops > training value for harder problems.
750
+
751
+ Args:
752
+ input_ids: Prompt tokens (B, T)
753
+ max_new_tokens: Number of tokens to generate
754
+ n_loops: Recurrent depth per decode step
755
+ temperature: Sampling temperature (lower = more greedy)
756
+ top_k: Top-K filtering (0 = disabled)
757
+ top_p: Nucleus sampling threshold (0 = disabled)
758
+
759
+ Returns:
760
+ Token indices (B, T + max_new_tokens)
761
+ """
762
+ kv_cache: dict = {}
763
+ prompt_len = input_ids.shape[1]
764
+
765
+ for step in range(max_new_tokens):
766
+ if step == 0:
767
+ cur_ids = input_ids
768
+ start_pos = 0
769
+ else:
770
+ cur_ids = input_ids[:, -1:]
771
+ start_pos = prompt_len + step - 1
772
+
773
+ logits = self.forward(cur_ids, n_loops=n_loops, kv_cache=kv_cache, start_pos=start_pos)
774
+ logits = logits[:, -1, :] / max(temperature, 1e-8)
775
+
776
+ if top_k > 0:
777
+ v, _ = logits.topk(min(top_k, logits.size(-1)))
778
+ logits[logits < v[:, -1:]] = float("-inf")
779
+
780
+ if top_p > 0:
781
+ sorted_logits, sorted_idx = logits.sort(descending=True)
782
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
783
+ remove = cumulative_probs - F.softmax(sorted_logits, dim=-1) >= top_p
784
+ sorted_logits[remove] = float("-inf")
785
+ logits = sorted_logits.scatter(1, sorted_idx, sorted_logits)
786
+
787
+ probs = F.softmax(logits, dim=-1)
788
+ next_tok = torch.multinomial(probs, num_samples=1)
789
+ input_ids = torch.cat([input_ids, next_tok], dim=1)
790
+
791
+ return input_ids
792
+
793
+ def get_num_params(self, non_embedding: bool = True) -> int:
794
+ """Count model parameters."""
795
+ n = sum(p.numel() for p in self.parameters())
796
+ if non_embedding:
797
+ n -= self.embed.weight.numel()
798
+ return n
799
+
800
+ def get_spectral_radius(self) -> float:
801
+ """Return max value of discretized A (should be < 1 for stability)."""
802
+ return self.recurrent.injection.get_A().max().item()