Kye Gomez commited on
Commit
fb2939b
·
1 Parent(s): 0699c00

[DOCS] [LICENSE]

Browse files
Files changed (2) hide show
  1. README.md +91 -1
  2. docs/open_mythos.md +471 -0
README.md CHANGED
@@ -1,7 +1,73 @@
1
  # OpenMythos
2
 
3
- A theoretical reconstruction of the Claude Mythos architecture, built from first principles using the available research literature.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
 
 
 
 
 
 
 
5
 
6
  ## The Central Hypothesis
7
 
@@ -42,6 +108,8 @@ Where:
42
 
43
  The injection of `e` at every step is what prevents the model from drifting — it keeps the original input signal alive throughout the entire recurrence depth.
44
 
 
 
45
  ---
46
 
47
  ## Why This Explains Mythos
@@ -222,3 +290,25 @@ Theoretical analysis suggests 2-3x improvements in inference throughput. For a d
222
  - Reasoning with Latent Thoughts — On the Power of Looped Transformers: https://arxiv.org/abs/2502.17416
223
  - Training Large Language Models to Reason in a Continuous Latent Space: https://arxiv.org/abs/2412.06769
224
  - Relaxed Recursive Transformers — Effective Parameter Sharing with Layer-wise LoRA: https://arxiv.org/pdf/2410.20672
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # OpenMythos
2
 
3
+ An open-source and theoretically grounded reconstruction of the Claude Mythos architecture, built from first principles using the available research literature.
4
+
5
+
6
+ ## Usage
7
+
8
+ ```python
9
+
10
+ import torch
11
+ from open_mythos.main import OpenMythos, MythosConfig
12
+
13
+
14
+ attn_type = "mla" # or "gqa"
15
+
16
+ base = {
17
+ "vocab_size": 1000,
18
+ "dim": 256,
19
+ "n_heads": 8,
20
+ "max_seq_len": 128,
21
+ "max_loop_iters": 4,
22
+ "prelude_layers": 1,
23
+ "coda_layers": 1,
24
+ "n_experts": 8,
25
+ "n_shared_experts": 1,
26
+ "n_experts_per_tok": 2,
27
+ "expert_dim": 64,
28
+ "lora_rank": 8,
29
+ "attn_type": attn_type,
30
+ }
31
+
32
+ if attn_type == "gqa":
33
+ cfg = MythosConfig(**base, n_kv_heads=2)
34
+ else:
35
+ cfg = MythosConfig(
36
+ **base,
37
+ n_kv_heads=8,
38
+ kv_lora_rank=32,
39
+ q_lora_rank=64,
40
+ qk_rope_head_dim=16,
41
+ qk_nope_head_dim=16,
42
+ v_head_dim=16,
43
+ )
44
+
45
+ model = OpenMythos(cfg)
46
+ total = sum(p.numel() for p in model.parameters())
47
+ print(f"\n[{attn_type.upper()}] Parameters: {total:,}")
48
+
49
+ ids = torch.randint(0, cfg.vocab_size, (2, 16))
50
+ logits = model(ids, n_loops=4)
51
+ print(f"[{attn_type.upper()}] Logits shape: {logits.shape}")
52
+
53
+ out = model.generate(ids, max_new_tokens=8, n_loops=8)
54
+ print(f"[{attn_type.upper()}] Generated shape: {out.shape}")
55
+
56
+ A = model.recurrent.injection.get_A()
57
+ print(
58
+ f"[{attn_type.upper()}] Spectral radius ρ(A) max: {A.max().item():.4f} (must be < 1)"
59
+ )
60
+ ```
61
+
62
+
63
 
64
+ ## Documentation
65
+
66
+ | Page | Description |
67
+ |---|---|
68
+ | [`docs/open_mythos.md`](docs/open_mythos.md) | Full API reference for the `OpenMythos` class — constructor, `forward`, `generate`, all sub-modules, configuration reference, and usage examples |
69
+
70
+ ---
71
 
72
  ## The Central Hypothesis
73
 
 
108
 
109
  The injection of `e` at every step is what prevents the model from drifting — it keeps the original input signal alive throughout the entire recurrence depth.
110
 
111
+ The full implementation is in [`open_mythos/main.py`](open_mythos/main.py). See the [`OpenMythos` class reference](docs/open_mythos.md) for a detailed API walkthrough, configuration options, and usage examples.
112
+
113
  ---
114
 
115
  ## Why This Explains Mythos
 
290
  - Reasoning with Latent Thoughts — On the Power of Looped Transformers: https://arxiv.org/abs/2502.17416
291
  - Training Large Language Models to Reason in a Continuous Latent Space: https://arxiv.org/abs/2412.06769
292
  - Relaxed Recursive Transformers — Effective Parameter Sharing with Layer-wise LoRA: https://arxiv.org/pdf/2410.20672
293
+
294
+ ---
295
+
296
+ ## Citation
297
+
298
+ If you use OpenMythos in your research or build on this work, please cite:
299
+
300
+ ```bibtex
301
+ @software{gomez2026openmythos,
302
+ author = {Kye Gomez},
303
+ title = {OpenMythos: A Theoretical Reconstruction of the Claude Mythos Architecture},
304
+ year = {2026},
305
+ url = {https://github.com/kyegomez/OpenMythos},
306
+ note = {Recurrent-Depth Transformer with MoE, MLA, LTI-stable injection, and ACT halting}
307
+ }
308
+ ```
309
+
310
+ ---
311
+
312
+ ## License
313
+
314
+ MIT License — Copyright (c) 2026 Kye Gomez. See [`LICENSE`](LICENSE) for the full text.
docs/open_mythos.md ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `OpenMythos` — Class Reference
2
+
3
+ **Module:** `open_mythos.main`
4
+ **Base class:** `torch.nn.Module`
5
+
6
+ ---
7
+
8
+ ## Overview
9
+
10
+ `OpenMythos` is the top-level model class implementing the Recurrent-Depth Transformer (RDT) architecture described in [the OpenMythos hypothesis](../README.md). It assembles three functional stages — **Prelude**, **Recurrent Block**, and **Coda** — into a complete autoregressive language model.
11
+
12
+ ```
13
+ Input token IDs (B, T)
14
+ ↓
15
+ [Embedding] token index → dim-dimensional vector
16
+ ↓
17
+ [Prelude] prelude_layers × standard TransformerBlock (run once)
18
+ ↓
19
+ [Recurrent Block] one TransformerBlock looped T times
20
+ ↑___________↓ h_{t+1} = A·h_t + B·e + Transformer(h_t, e)
21
+ ↓
22
+ [Coda] coda_layers × standard TransformerBlock (run once)
23
+ ↓
24
+ [RMSNorm → LM head]
25
+ ↓
26
+ Output logits (B, T, vocab_size)
27
+ ```
28
+
29
+ Every architectural choice in `OpenMythos` can be configured through a single [`MythosConfig`](#mythosconfig) dataclass passed at construction.
30
+
31
+ ---
32
+
33
+ ## `MythosConfig`
34
+
35
+ ```python
36
+ @dataclass
37
+ class MythosConfig
38
+ ```
39
+
40
+ All hyperparameters for the model are stored in this single frozen-style dataclass. Pass an instance to `OpenMythos.__init__`.
41
+
42
+ ### Core fields
43
+
44
+ | Field | Type | Default | Description |
45
+ |---|---|---|---|
46
+ | `vocab_size` | `int` | `32000` | Token vocabulary size; sets the embedding and LM head dimension |
47
+ | `dim` | `int` | `2048` | Model hidden dimension — the width of the residual stream throughout |
48
+ | `n_heads` | `int` | `16` | Number of query attention heads |
49
+ | `n_kv_heads` | `int` | `4` | Number of key/value heads (GQA only); `n_heads // n_kv_heads` Q heads share each KV pair |
50
+ | `max_seq_len` | `int` | `4096` | Maximum sequence length; RoPE frequencies are precomputed up to this length |
51
+ | `max_loop_iters` | `int` | `16` | Default recurrent loop depth T at inference. Can be overridden per call |
52
+ | `prelude_layers` | `int` | `2` | Number of standard transformer blocks run once before the recurrent loop |
53
+ | `coda_layers` | `int` | `2` | Number of standard transformer blocks run once after the recurrent loop |
54
+
55
+ ### Attention fields
56
+
57
+ `attn_type` selects between two complete attention implementations. All other attention fields are implementation-specific.
58
+
59
+ | Field | Type | Default | Description |
60
+ |---|---|---|---|
61
+ | `attn_type` | `str` | `"mla"` | `"gqa"` for Grouped Query Attention; `"mla"` for Multi-Latent Attention |
62
+ | `kv_lora_rank` | `int` | `512` | **[MLA only]** Compressed KV latent rank stored in the cache instead of full K and V |
63
+ | `q_lora_rank` | `int` | `1536` | **[MLA only]** Compressed Q latent rank |
64
+ | `qk_rope_head_dim` | `int` | `64` | **[MLA only]** Per-head dimension receiving RoPE positional encoding |
65
+ | `qk_nope_head_dim` | `int` | `128` | **[MLA only]** Per-head dimension without positional encoding |
66
+ | `v_head_dim` | `int` | `128` | **[MLA only]** Per-head value dimension |
67
+
68
+ **GQA vs MLA:** GQA reduces KV cache by having fewer KV heads than Q heads (factor of `n_heads / n_kv_heads`). MLA achieves a much larger reduction by caching a low-rank KV latent (`kv_lora_rank`) and the RoPE keys (`n_heads × qk_rope_head_dim`), then reconstructing full K and V on the fly. At production scale MLA yields roughly 10–20× smaller KV cache than standard attention.
69
+
70
+ ### MoE FFN fields
71
+
72
+ The Mixture-of-Experts FFN is used exclusively inside the Recurrent Block. Prelude and Coda use a dense SwiGLU FFN.
73
+
74
+ | Field | Type | Default | Description |
75
+ |---|---|---|---|
76
+ | `n_experts` | `int` | `64` | Total number of routed expert FFNs |
77
+ | `n_shared_experts` | `int` | `2` | Always-active shared experts; absorb common cross-domain patterns |
78
+ | `n_experts_per_tok` | `int` | `4` | Top-K routed experts selected per token by the router |
79
+ | `expert_dim` | `int` | `512` | Hidden dimension inside each fine-grained routed expert |
80
+
81
+ Approximately `n_experts_per_tok / n_experts = 6.25%` of routed expert parameters are activated per token, plus all shared expert parameters.
82
+
83
+ ### Stability and adaptation fields
84
+
85
+ | Field | Type | Default | Description |
86
+ |---|---|---|---|
87
+ | `act_threshold` | `float` | `0.99` | ACT cumulative halting threshold; loop exits per-position once this is exceeded |
88
+ | `rope_theta` | `float` | `500000.0` | RoPE base frequency (LLaMA-3 default; higher = slower frequency decay over sequence positions) |
89
+ | `lora_rank` | `int` | `16` | Rank of the depth-wise LoRA adapter applied inside each loop iteration |
90
+
91
+ ---
92
+
93
+ ## Constructor
94
+
95
+ ```python
96
+ OpenMythos(cfg: MythosConfig)
97
+ ```
98
+
99
+ Builds all sub-modules, precomputes RoPE frequency buffers, and runs weight initialization.
100
+
101
+ **What happens internally:**
102
+
103
+ 1. `nn.Embedding(vocab_size, dim)` — token embedding table, weight-tied with the LM head.
104
+ 2. RoPE buffers — `freqs_cis` (for GQA, dim = `dim // n_heads`) and `freqs_cis_mla` (for MLA, dim = `qk_rope_head_dim`) are precomputed once and registered as non-parameter buffers. The correct buffer is selected at forward time based on `cfg.attn_type`.
105
+ 3. `prelude` — `nn.ModuleList` of `prelude_layers` `TransformerBlock` instances with dense SwiGLU FFN.
106
+ 4. `recurrent` — a single `RecurrentBlock` containing one `TransformerBlock` (with MoE FFN), `LTIInjection`, `ACTHalting`, and `LoRAAdapter`.
107
+ 5. `coda` — `nn.ModuleList` of `coda_layers` `TransformerBlock` instances with dense SwiGLU FFN.
108
+ 6. `RMSNorm(dim)` applied before the LM head.
109
+ 7. `nn.Linear(dim, vocab_size, bias=False)` LM head with weights tied to the embedding.
110
+ 8. All `nn.Linear` and `nn.Embedding` weights initialized from N(0, 0.02).
111
+
112
+ **Example:**
113
+
114
+ ```python
115
+ from open_mythos.main import OpenMythos, MythosConfig
116
+
117
+ cfg = MythosConfig(
118
+ vocab_size=32000,
119
+ dim=2048,
120
+ n_heads=16,
121
+ n_kv_heads=4,
122
+ max_loop_iters=16,
123
+ attn_type="mla",
124
+ )
125
+ model = OpenMythos(cfg)
126
+ print(f"Parameters: {sum(p.numel() for p in model.parameters()):,}")
127
+ ```
128
+
129
+ ---
130
+
131
+ ## `forward`
132
+
133
+ ```python
134
+ def forward(
135
+ self,
136
+ input_ids: torch.Tensor,
137
+ n_loops: Optional[int] = None,
138
+ kv_cache: Optional[dict] = None,
139
+ ) -> torch.Tensor
140
+ ```
141
+
142
+ Single forward pass through the full Prelude → Recurrent Block → Coda pipeline.
143
+
144
+ ### Parameters
145
+
146
+ | Parameter | Type | Description |
147
+ |---|---|---|
148
+ | `input_ids` | `Tensor (B, T)` | Batch of token index sequences. `B` = batch size, `T` = sequence length |
149
+ | `n_loops` | `int \| None` | Recurrent loop depth for this call. Defaults to `cfg.max_loop_iters`. Pass a higher value at inference to extrapolate to harder problems (depth extrapolation property). |
150
+ | `kv_cache` | `dict \| None` | If provided, keys and values are accumulated here for autoregressive decoding. Pass `{}` on the first decode step and reuse the same dict across steps. Pass `None` for training or full-context inference. |
151
+
152
+ ### Returns
153
+
154
+ `Tensor (B, T, vocab_size)` — raw (unnormalized) logits over the vocabulary for each position.
155
+
156
+ ### Behavior walkthrough
157
+
158
+ ```
159
+ 1. Embed: x = embedding(input_ids) # (B, T, dim)
160
+ 2. Select RoPE buffer:
161
+ if attn_type == "mla": use freqs_cis_mla[:T]
162
+ else: use freqs_cis[:T]
163
+ 3. Build causal mask (upper-triangular -inf):
164
+ if T > 1: mask = _causal_mask(T, device)
165
+ else: mask = None (single-token decode step)
166
+ 4. Prelude:
167
+ for i, layer in prelude:
168
+ x = layer(x, freqs_cis, mask, kv_cache, f"prelude_{i}")
169
+ 5. Freeze encoded input:
170
+ e = x # (B, T, dim)
171
+ 6. Recurrent loop:
172
+ x = recurrent(x, e, freqs_cis, mask, n_loops, kv_cache)
173
+ 7. Coda:
174
+ for i, layer in coda:
175
+ x = layer(x, freqs_cis, mask, kv_cache, f"coda_{i}")
176
+ 8. Project: logits = lm_head(norm(x)) # (B, T, vocab_size)
177
+ ```
178
+
179
+ **Step 5 (freeze `e`)** is the key architectural invariant: the encoded input `e` is captured after the Prelude and injected at *every* loop iteration unchanged. This prevents the hidden state from drifting away from the original input signal regardless of loop depth.
180
+
181
+ ### Training example
182
+
183
+ ```python
184
+ import torch
185
+ from open_mythos.main import OpenMythos, MythosConfig
186
+
187
+ model = OpenMythos(MythosConfig()).cuda()
188
+ optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
189
+
190
+ input_ids = torch.randint(0, 32000, (2, 512)).cuda()
191
+ labels = torch.randint(0, 32000, (2, 512)).cuda()
192
+
193
+ logits = model(input_ids) # (2, 512, 32000)
194
+ loss = torch.nn.functional.cross_entropy(
195
+ logits.view(-1, 32000),
196
+ labels.view(-1),
197
+ )
198
+ loss.backward()
199
+ optimizer.step()
200
+ ```
201
+
202
+ ### Depth extrapolation at inference
203
+
204
+ A looped transformer trained on `N` loops can be evaluated on `N + k` loops and often achieves higher quality on hard multi-hop problems. Pass `n_loops` at inference time:
205
+
206
+ ```python
207
+ # Trained with max_loop_iters=16 — try deeper reasoning at test time
208
+ logits_deep = model(input_ids, n_loops=32)
209
+ ```
210
+
211
+ ---
212
+
213
+ ## `generate`
214
+
215
+ ```python
216
+ @torch.no_grad()
217
+ def generate(
218
+ self,
219
+ input_ids: torch.Tensor,
220
+ max_new_tokens: int = 64,
221
+ n_loops: int = 8,
222
+ temperature: float = 1.0,
223
+ top_k: int = 50,
224
+ ) -> torch.Tensor
225
+ ```
226
+
227
+ Autoregressive token generation with KV caching. Processes the full prompt on step 0, then decodes one token at a time using the accumulated cache.
228
+
229
+ ### Parameters
230
+
231
+ | Parameter | Type | Default | Description |
232
+ |---|---|---|---|
233
+ | `input_ids` | `Tensor (B, T)` | — | Prompt token indices |
234
+ | `max_new_tokens` | `int` | `64` | Number of new tokens to generate |
235
+ | `n_loops` | `int` | `8` | Recurrent loop depth per decode step. Can be higher than the training value for harder prompts (depth extrapolation) |
236
+ | `temperature` | `float` | `1.0` | Softmax temperature applied to logits before sampling. Values < 1 make the distribution more peaked (less random); values > 1 make it flatter |
237
+ | `top_k` | `int` | `50` | Restricts sampling to the top-K most probable tokens at each step. `0` disables filtering (full vocabulary sampling) |
238
+
239
+ ### Returns
240
+
241
+ `Tensor (B, T + max_new_tokens)` — the original prompt concatenated with the generated token indices.
242
+
243
+ ### KV caching mechanism
244
+
245
+ On step 0, the full prompt `(B, T)` is passed and all keys/values for every layer are populated in `kv_cache`. On steps 1…N only the single most recent token `(B, 1)` is passed; the attention layers read back all prior K/V from the cache. This makes decode cost proportional to a single token per step rather than the full growing sequence.
246
+
247
+ Each layer caches under a deterministic string key (`"prelude_0"`, `"recurrent_loop_3"`, `"coda_1"`, etc.), so caches from different layers never collide.
248
+
249
+ ### Sampling strategy
250
+
251
+ ```
252
+ logits = forward(cur_ids, n_loops, kv_cache)[:, -1, :] / temperature
253
+
254
+ if top_k > 0:
255
+ threshold = logits.topk(top_k).values[:, -1:]
256
+ logits[logits < threshold] = -inf
257
+
258
+ probs = softmax(logits)
259
+ next_tok = multinomial(probs, num_samples=1)
260
+ ```
261
+
262
+ ### Generation example
263
+
264
+ ```python
265
+ import torch
266
+ from open_mythos.main import OpenMythos, MythosConfig
267
+
268
+ model = OpenMythos(MythosConfig()).eval()
269
+
270
+ # Tokenized prompt (use your tokenizer of choice)
271
+ prompt = torch.tensor([[1, 450, 3118, 310, 278]]) # (1, 5)
272
+
273
+ output = model.generate(
274
+ prompt,
275
+ max_new_tokens=128,
276
+ n_loops=16, # deeper reasoning
277
+ temperature=0.8,
278
+ top_k=40,
279
+ )
280
+ # output.shape == (1, 133)
281
+ ```
282
+
283
+ ---
284
+
285
+ ## Internal Components
286
+
287
+ The following sub-modules are assembled inside `OpenMythos`. They are not typically called directly but understanding them clarifies the model's behavior.
288
+
289
+ ### `RecurrentBlock`
290
+
291
+ The heart of the architecture. A single `TransformerBlock` (with MoE FFN) is run in a loop for up to `n_loops` iterations, with the following per-iteration pipeline:
292
+
293
+ ```
294
+ h_loop = loop_index_embedding(h, t, loop_dim) # inject sinusoidal loop-index signal
295
+ combined = RMSNorm(h_loop + e) # add frozen encoded input
296
+ trans_out = TransformerBlock(combined, ...) # attention + MoE FFN
297
+ trans_out = trans_out + LoRAAdapter(trans_out, t) # depth-wise LoRA delta
298
+ h = LTIInjection(h, e, trans_out) # stable update: A·h + B·e + trans_out
299
+ p = ACTHalting(h) # per-position halting probability
300
+ ```
301
+
302
+ The loop exits early for positions whose cumulative halting probability exceeds `cfg.act_threshold`. If all positions have halted, the loop exits before `n_loops`. The final output is an ACT-weighted sum of `h` across iterations.
303
+
304
+ ### `LTIInjection`
305
+
306
+ Implements the stable recurrent update rule `h_{t+1} = A·h_t + B·e + transformer_out`. The diagonal matrix `A` is parameterized as:
307
+
308
+ ```
309
+ A_continuous = Diag(-exp(log_A)) # always negative diagonal
310
+ A_discrete = exp(Δt · A_continuous) # ZOH discretization, values ∈ (0, 1)
311
+ ```
312
+
313
+ This guarantees spectral radius `ρ(A) < 1` by construction, making the looped model unconditionally stable regardless of learning rate or batch noise. See [Parcae (Prairie et al., 2026)](https://arxiv.org/abs/2604.12946) for the theoretical foundation.
314
+
315
+ ### `ACTHalting`
316
+
317
+ A single linear layer mapping `(B, T, dim) → (B, T)` followed by sigmoid. At each loop step, the scalar halting probability per position is accumulated. When the cumulative sum exceeds `cfg.act_threshold`, the ACT remainder trick assigns the remaining probability mass as the final weight and the position stops contributing. Implements Graves (2016) ACT.
318
+
319
+ ### `LoRAAdapter`
320
+
321
+ A depth-wise low-rank adapter with three components:
322
+
323
+ - `down`: shared `Linear(dim, rank)` — down-projects the transformer output
324
+ - `B`: shared parameter matrix `(rank, dim)` — up-projects back to full dimension
325
+ - `scale`: `Embedding(max_loops, rank)` — per-loop element-wise scale
326
+
327
+ The delta per iteration is `(down(x) * scale[t]) @ B`. Bridges the expressiveness gap between pure weight-tying and fully distinct per-layer weights. Based on [Relaxed Recursive Transformers (Bae et al., 2024)](https://arxiv.org/pdf/2410.20672).
328
+
329
+ ### `TransformerBlock`
330
+
331
+ Pre-norm transformer block with swappable attention and FFN:
332
+
333
+ - **Attention:** `MLAttention` (MLA) or `GQAttention` (GQA), selected by `cfg.attn_type`
334
+ - **FFN:** `MoEFFN` (when `use_moe=True`, inside `RecurrentBlock`) or dense `Expert` (Prelude, Coda)
335
+ - Pre-norm via `RMSNorm` applied to both the attention input and FFN input
336
+
337
+ ### `MLAttention`
338
+
339
+ Multi-Latent Attention ([DeepSeek-V2, 2024](https://arxiv.org/abs/2405.04434)). The cache stores only the compressed KV latent `c_kv` (rank `kv_lora_rank`) plus the RoPE-encoded keys. At each decode step, `K_nope` and `V` are cheaply reconstructed from `c_kv` via a shared up-projection, trading a fast linear multiply for dramatically smaller KV memory footprint.
340
+
341
+ Cache size per layer per token: `kv_lora_rank + n_heads × qk_rope_head_dim` vs. full GQA cache of `n_kv_heads × head_dim × 2`.
342
+
343
+ ### `GQAttention`
344
+
345
+ Grouped Query Attention ([Ainslie et al., 2023](https://arxiv.org/abs/2305.13245)). `n_kv_heads` KV pairs are shared across `n_heads // n_kv_heads` query heads each, reducing KV cache by that factor while preserving full query expressiveness.
346
+
347
+ ### `MoEFFN`
348
+
349
+ Fine-grained Mixture-of-Experts FFN ([DeepSeekMoE, Dai et al., 2024](https://arxiv.org/abs/2401.06066)):
350
+
351
+ - **Routed experts:** `n_experts` small SwiGLU FFNs. Each token's router selects the top-`n_experts_per_tok` via softmax over learned logits. A per-expert bias `router_bias` (non-gradient, updated externally) keeps load balanced.
352
+ - **Shared experts:** `n_shared_experts` always-active FFNs with width `expert_dim × n_experts_per_tok`, absorbing cross-domain patterns.
353
+
354
+ Total activated parameters per token: `(n_experts_per_tok / n_experts)` of routed capacity + all shared capacity.
355
+
356
+ ### `Expert`
357
+
358
+ Single SwiGLU feed-forward unit: `down(silu(gate(x)) * up(x))`. Used both as individual routed experts inside `MoEFFN` and as the dense FFN in Prelude/Coda blocks.
359
+
360
+ ### `RMSNorm`
361
+
362
+ Root Mean Square Layer Normalization ([Zhang & Sennrich, 2019](https://arxiv.org/abs/1910.07467)). Normalizes by `x / rms(x)` with a learned per-channel rescaling weight. No bias, no mean subtraction. Used throughout in place of standard LayerNorm.
363
+
364
+ ---
365
+
366
+ ## Utility functions
367
+
368
+ ### `precompute_rope_freqs(dim, max_len, theta)`
369
+
370
+ Precomputes complex-valued RoPE rotation matrices as a `(max_len, dim//2)` complex64 tensor. Called once in `__init__` and stored as a buffer.
371
+
372
+ ### `apply_rope(x, freqs_cis)`
373
+
374
+ Applies precomputed RoPE frequencies to a query or key tensor by treating adjacent feature pairs as complex numbers and multiplying pointwise by the positional phasor.
375
+
376
+ ### `loop_index_embedding(h, loop_t, loop_dim, theta)`
377
+
378
+ Injects a sinusoidal loop-index signal into the first `loop_dim` channels of the hidden state, analogous to RoPE but over recurrence depth rather than sequence position. Allows the shared recurrent block weights to behave differently at different loop iterations.
379
+
380
+ ---
381
+
382
+ ## Key design properties
383
+
384
+ | Property | Mechanism | Benefit |
385
+ |---|---|---|
386
+ | Depth extrapolation | Recurrent block with looped identical weights | Train on N loops, test on N+k — harder problems solved without retraining |
387
+ | Parameter efficiency | Weight sharing across all loop iterations | k-layer model achieves quality of kL-layer model; parameters ≈ k, compute ∝ L |
388
+ | Adaptive compute | ACT halting per position | Easy tokens exit early; hard tokens receive full loop depth — within the same batch |
389
+ | Stable training | LTI injection with ZOH-constrained A (ρ(A) < 1) | No residual explosion; robust to high learning rates |
390
+ | Domain breadth | MoE FFN in recurrent block | Different expert subsets can be routed to at each loop depth |
391
+ | Loop differentiation | Loop-index sinusoidal embedding | Same weights implement functionally distinct phases per iteration |
392
+ | Efficient KV memory | MLA (default) or GQA | MLA: 10–20× smaller cache vs standard attention at production scale |
393
+ | Depth-wise adaptation | LoRA adapter per loop iteration | Expressiveness beyond pure weight-tying; minimal parameter overhead |
394
+
395
+ ---
396
+
397
+ ## Full configuration reference
398
+
399
+ The default `MythosConfig()` targets a mid-scale research model. Below is a minimal configuration for quick experimentation:
400
+
401
+ ```python
402
+ from open_mythos.main import OpenMythos, MythosConfig
403
+
404
+ # Minimal config for fast iteration / unit testing
405
+ small_cfg = MythosConfig(
406
+ vocab_size=8192,
407
+ dim=256,
408
+ n_heads=4,
409
+ n_kv_heads=2,
410
+ max_seq_len=512,
411
+ max_loop_iters=4,
412
+ prelude_layers=1,
413
+ coda_layers=1,
414
+ attn_type="gqa",
415
+ n_experts=8,
416
+ n_shared_experts=1,
417
+ n_experts_per_tok=2,
418
+ expert_dim=64,
419
+ lora_rank=4,
420
+ )
421
+ model = OpenMythos(small_cfg)
422
+ ```
423
+
424
+ And a production-oriented MLA configuration matching the default hyperparameters:
425
+
426
+ ```python
427
+ # Default MLA config (matches MythosConfig() defaults)
428
+ prod_cfg = MythosConfig(
429
+ vocab_size=32000,
430
+ dim=2048,
431
+ n_heads=16,
432
+ n_kv_heads=4,
433
+ max_seq_len=4096,
434
+ max_loop_iters=16,
435
+ prelude_layers=2,
436
+ coda_layers=2,
437
+ attn_type="mla", # Multi-Latent Attention
438
+ kv_lora_rank=512,
439
+ q_lora_rank=1536,
440
+ qk_rope_head_dim=64,
441
+ qk_nope_head_dim=128,
442
+ v_head_dim=128,
443
+ n_experts=64,
444
+ n_shared_experts=2,
445
+ n_experts_per_tok=4,
446
+ expert_dim=512,
447
+ act_threshold=0.99,
448
+ rope_theta=500000.0,
449
+ lora_rank=16,
450
+ )
451
+ model = OpenMythos(prod_cfg)
452
+ ```
453
+
454
+ ---
455
+
456
+ ## References
457
+
458
+ | Component | Paper |
459
+ |---|---|
460
+ | Recurrent-Depth Transformer | [Loop, Think, & Generalize (2025)](https://arxiv.org/pdf/2604.07822) |
461
+ | LTI-stable injection (Parcae) | [Scaling Laws for Stable Looped Language Models (Prairie et al., 2026)](https://arxiv.org/abs/2604.12946) |
462
+ | Looped transformer reasoning | [Reasoning with Latent Thoughts (Saunshi et al., 2025)](https://arxiv.org/abs/2502.17416) |
463
+ | Multi-Latent Attention | [DeepSeek-V2 (2024)](https://arxiv.org/abs/2405.04434) |
464
+ | Grouped Query Attention | [Ainslie et al., 2023](https://arxiv.org/abs/2305.13245) |
465
+ | Mixture-of-Experts FFN | [DeepSeekMoE (Dai et al., 2024)](https://arxiv.org/abs/2401.06066) |
466
+ | Adaptive Computation Time | [Graves, 2016](https://arxiv.org/abs/1603.08983) |
467
+ | Depth-wise LoRA | [Relaxed Recursive Transformers (Bae et al., 2024)](https://arxiv.org/pdf/2410.20672) |
468
+ | RMSNorm | [Zhang & Sennrich, 2019](https://arxiv.org/abs/1910.07467) |
469
+ | RoPE | [Su et al., 2021](https://arxiv.org/abs/2104.09864) |
470
+ | Universal Transformer (ACT basis) | [Dehghani et al., 2018](https://arxiv.org/pdf/1807.03819) |
471
+ | Continuous latent reasoning | [COCONUT (2024)](https://arxiv.org/abs/2412.06769) |