Kye Gomez commited on
Commit ·
963e112
1
Parent(s): 7d78ebe
tiny tests
Browse files- README.md +14 -1
- open_mythos/main.py +15 -4
- pyproject.toml +1 -1
- tests/bench_vs_transformer.py +480 -0
- tests/small_benchmark.py +536 -0
- variants_example.py → tests/variants_example.py +0 -0
README.md
CHANGED
|
@@ -97,8 +97,9 @@ out = model.generate(ids, max_new_tokens=8, n_loops=8)
|
|
| 97 |
print(f"[{attn_type.upper()}] Generated shape: {out.shape}")
|
| 98 |
|
| 99 |
A = model.recurrent.injection.get_A()
|
|
|
|
| 100 |
print(
|
| 101 |
-
f"[{attn_type.upper()}] Spectral radius ρ(A)
|
| 102 |
)
|
| 103 |
```
|
| 104 |
|
|
@@ -217,6 +218,17 @@ The injection of `e` at every step is what prevents the model from drifting —
|
|
| 217 |
|
| 218 |
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.
|
| 219 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
---
|
| 221 |
|
| 222 |
## Why This Explains Mythos
|
|
@@ -371,6 +383,7 @@ Theoretical analysis suggests 2-3x improvements in inference throughput. For a d
|
|
| 371 |
| Training stability | LTI-constrained injection parameters with spectral radius < 1 |
|
| 372 |
| Loop differentiation | Likely uses loop-index positional embedding (à la RoPE) per iteration |
|
| 373 |
| Halting | Adaptive Computation Time or learned convergence criterion |
|
|
|
|
| 374 |
| Scaling law | Optimal training scales looping and data together, not parameters alone |
|
| 375 |
| Reasoning vs. memory | Structurally biased toward composition; memorization requires separate treatment |
|
| 376 |
| Deployment | Continuous Depth-wise Batching enables variable compute per request |
|
|
|
|
| 97 |
print(f"[{attn_type.upper()}] Generated shape: {out.shape}")
|
| 98 |
|
| 99 |
A = model.recurrent.injection.get_A()
|
| 100 |
+
rho = torch.linalg.eigvals(A).abs().max().item()
|
| 101 |
print(
|
| 102 |
+
f"[{attn_type.upper()}] Spectral radius ρ(A) = {rho:.4f} (must be < 1)"
|
| 103 |
)
|
| 104 |
```
|
| 105 |
|
|
|
|
| 218 |
|
| 219 |
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.
|
| 220 |
|
| 221 |
+
### Attention Implementations
|
| 222 |
+
|
| 223 |
+
The attention layer is switchable via `cfg.attn_type`:
|
| 224 |
+
|
| 225 |
+
| Option | Class | Description |
|
| 226 |
+
|---|---|---|
|
| 227 |
+
| `"gqa"` | `GQAttention` | Grouped Query Attention (Ainslie et al., 2023) — fewer KV heads than Q heads (`n_kv_heads < n_heads`), reducing KV-cache memory by `n_heads / n_kv_heads`. Uses **Flash Attention 2** (Dao et al., 2023) when `flash-attn>=2.8.3` is installed: GQA is handled natively (no KV head expansion), I/O-bound-optimal, with a transparent fallback to manual scaled dot-product attention when the package is absent. |
|
| 228 |
+
| `"mla"` | `MLAttention` | Multi-Latent Attention (DeepSeek-V2) — caches a compressed KV latent (`kv_lora_rank`) rather than full K/V, with split RoPE / no-RoPE head dims for position-aware compression. |
|
| 229 |
+
|
| 230 |
+
RoPE is applied to Q and K before caching, so cached values do not need to be re-rotated on retrieval.
|
| 231 |
+
|
| 232 |
---
|
| 233 |
|
| 234 |
## Why This Explains Mythos
|
|
|
|
| 383 |
| Training stability | LTI-constrained injection parameters with spectral radius < 1 |
|
| 384 |
| Loop differentiation | Likely uses loop-index positional embedding (à la RoPE) per iteration |
|
| 385 |
| Halting | Adaptive Computation Time or learned convergence criterion |
|
| 386 |
+
| Attention | GQA (with optional Flash Attention 2) or MLA with compressed KV latent cache |
|
| 387 |
| Scaling law | Optimal training scales looping and data together, not parameters alone |
|
| 388 |
| Reasoning vs. memory | Structurally biased toward composition; memorization requires separate treatment |
|
| 389 |
| Deployment | Continuous Depth-wise Batching enables variable compute per request |
|
open_mythos/main.py
CHANGED
|
@@ -252,7 +252,9 @@ class GQAttention(nn.Module):
|
|
| 252 |
k = k.to(torch.bfloat16)
|
| 253 |
v = v.to(torch.bfloat16)
|
| 254 |
dropout_p = self.dropout_p if self.training else 0.0
|
| 255 |
-
out = flash_attn_func(
|
|
|
|
|
|
|
| 256 |
out = out.to(orig_dtype).contiguous().view(B, T, -1)
|
| 257 |
else:
|
| 258 |
# Fallback: manual scaled dot-product with explicit KV head expansion.
|
|
@@ -964,18 +966,27 @@ class OpenMythos(nn.Module):
|
|
| 964 |
nn.init.normal_(m.weight, std=0.02)
|
| 965 |
|
| 966 |
@staticmethod
|
| 967 |
-
def _causal_mask(
|
|
|
|
|
|
|
| 968 |
"""
|
| 969 |
Build an additive causal mask: 0 on and below the diagonal, -inf above.
|
| 970 |
|
| 971 |
Args:
|
| 972 |
seq_len -- sequence length
|
| 973 |
device -- target device
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 974 |
|
| 975 |
Returns:
|
| 976 |
Tensor of shape (1, 1, seq_len, seq_len) broadcastable over (B, H, T, S)
|
| 977 |
"""
|
| 978 |
-
mask = torch.full(
|
|
|
|
|
|
|
| 979 |
return torch.triu(mask, diagonal=1)
|
| 980 |
|
| 981 |
def forward(
|
|
@@ -1009,7 +1020,7 @@ class OpenMythos(nn.Module):
|
|
| 1009 |
freqs_cis = (
|
| 1010 |
self.freqs_cis_mla if self.cfg.attn_type == "mla" else self.freqs_cis
|
| 1011 |
)[start_pos : start_pos + T]
|
| 1012 |
-
mask = self._causal_mask(T, device) if T > 1 else None
|
| 1013 |
|
| 1014 |
for i, layer in enumerate(self.prelude):
|
| 1015 |
x = layer(x, freqs_cis, mask, kv_cache, cache_key=f"prelude_{i}")
|
|
|
|
| 252 |
k = k.to(torch.bfloat16)
|
| 253 |
v = v.to(torch.bfloat16)
|
| 254 |
dropout_p = self.dropout_p if self.training else 0.0
|
| 255 |
+
out = flash_attn_func(
|
| 256 |
+
q, k, v, dropout_p=dropout_p, causal=(mask is not None)
|
| 257 |
+
)
|
| 258 |
out = out.to(orig_dtype).contiguous().view(B, T, -1)
|
| 259 |
else:
|
| 260 |
# Fallback: manual scaled dot-product with explicit KV head expansion.
|
|
|
|
| 966 |
nn.init.normal_(m.weight, std=0.02)
|
| 967 |
|
| 968 |
@staticmethod
|
| 969 |
+
def _causal_mask(
|
| 970 |
+
seq_len: int, device: torch.device, dtype: torch.dtype
|
| 971 |
+
) -> torch.Tensor:
|
| 972 |
"""
|
| 973 |
Build an additive causal mask: 0 on and below the diagonal, -inf above.
|
| 974 |
|
| 975 |
Args:
|
| 976 |
seq_len -- sequence length
|
| 977 |
device -- target device
|
| 978 |
+
dtype -- tensor dtype (must match activation dtype so the additive
|
| 979 |
+
mask doesn't upcast the attention logits in the fallback
|
| 980 |
+
attention path — e.g. bf16 weights with an fp32 mask
|
| 981 |
+
promotes attn to fp32 and then breaks the fp32-vs-bf16
|
| 982 |
+
matmul against V)
|
| 983 |
|
| 984 |
Returns:
|
| 985 |
Tensor of shape (1, 1, seq_len, seq_len) broadcastable over (B, H, T, S)
|
| 986 |
"""
|
| 987 |
+
mask = torch.full(
|
| 988 |
+
(1, 1, seq_len, seq_len), float("-inf"), device=device, dtype=dtype
|
| 989 |
+
)
|
| 990 |
return torch.triu(mask, diagonal=1)
|
| 991 |
|
| 992 |
def forward(
|
|
|
|
| 1020 |
freqs_cis = (
|
| 1021 |
self.freqs_cis_mla if self.cfg.attn_type == "mla" else self.freqs_cis
|
| 1022 |
)[start_pos : start_pos + T]
|
| 1023 |
+
mask = self._causal_mask(T, device, x.dtype) if T > 1 else None
|
| 1024 |
|
| 1025 |
for i, layer in enumerate(self.prelude):
|
| 1026 |
x = layer(x, freqs_cis, mask, kv_cache, cache_key=f"prelude_{i}")
|
pyproject.toml
CHANGED
|
@@ -5,7 +5,7 @@ build-backend = "poetry.core.masonry.api"
|
|
| 5 |
|
| 6 |
[tool.poetry]
|
| 7 |
name = "open-mythos"
|
| 8 |
-
version = "0.
|
| 9 |
description = "OpenMythos — open-source theoretical reconstruction of the Claude Mythos Recurrent-Depth Transformer architecture"
|
| 10 |
license = "MIT"
|
| 11 |
authors = ["Kye Gomez <kye@swarms.world>"]
|
|
|
|
| 5 |
|
| 6 |
[tool.poetry]
|
| 7 |
name = "open-mythos"
|
| 8 |
+
version = "0.5.0"
|
| 9 |
description = "OpenMythos — open-source theoretical reconstruction of the Claude Mythos Recurrent-Depth Transformer architecture"
|
| 10 |
license = "MIT"
|
| 11 |
authors = ["Kye Gomez <kye@swarms.world>"]
|
tests/bench_vs_transformer.py
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
OpenMythos vs. vanilla GQA+MoE transformer benchmark.
|
| 3 |
+
|
| 4 |
+
Compares OpenMythos (Prelude + looped Recurrent Block + Coda with ACT halting,
|
| 5 |
+
LTI-stable injection, LoRA depth adapter) against a parameter-matched vanilla
|
| 6 |
+
transformer built from the same GQAttention + MoEFFN building blocks stacked
|
| 7 |
+
non-recurrently. The baseline reuses OpenMythos primitives so the comparison
|
| 8 |
+
isolates the recurrent-depth architecture, not the kernels.
|
| 9 |
+
|
| 10 |
+
Metrics reported:
|
| 11 |
+
- Parameter counts (total, MoE-active approximation)
|
| 12 |
+
- Prefill latency + throughput at several sequence lengths
|
| 13 |
+
- Decode (autoregressive step) latency with KV cache
|
| 14 |
+
- Peak memory (CUDA only)
|
| 15 |
+
- OpenMythos depth-scaling sweep: latency vs. n_loops
|
| 16 |
+
|
| 17 |
+
Run:
|
| 18 |
+
python benchmarks/bench_vs_transformer.py # small CPU/GPU smoke test
|
| 19 |
+
python benchmarks/bench_vs_transformer.py --size 1b --device cuda
|
| 20 |
+
python benchmarks/bench_vs_transformer.py --seq-lens 128,512,2048 --n-loops 1,4,8,16
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import argparse
|
| 26 |
+
import gc
|
| 27 |
+
import statistics
|
| 28 |
+
import time
|
| 29 |
+
from dataclasses import dataclass
|
| 30 |
+
from typing import Optional
|
| 31 |
+
|
| 32 |
+
import torch
|
| 33 |
+
import torch.nn as nn
|
| 34 |
+
|
| 35 |
+
from open_mythos import MythosConfig, OpenMythos, mythos_1b
|
| 36 |
+
from open_mythos.main import (
|
| 37 |
+
RMSNorm,
|
| 38 |
+
TransformerBlock,
|
| 39 |
+
precompute_rope_freqs,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# ---------------------------------------------------------------------------
|
| 44 |
+
# Baseline: non-looped GQA + MoE transformer
|
| 45 |
+
# ---------------------------------------------------------------------------
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class BaselineTransformer(nn.Module):
|
| 49 |
+
"""
|
| 50 |
+
Vanilla decoder-only transformer with GQA attention and MoE FFNs, stacked
|
| 51 |
+
non-recurrently. Shares TransformerBlock / GQAttention / MoEFFN kernels
|
| 52 |
+
with OpenMythos so any speed delta is attributable to the recurrent-depth
|
| 53 |
+
architecture rather than the underlying attention/FFN implementation.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
def __init__(self, cfg: MythosConfig, n_layers: int):
|
| 57 |
+
super().__init__()
|
| 58 |
+
self.cfg = cfg
|
| 59 |
+
self.n_layers = n_layers
|
| 60 |
+
self.embed = nn.Embedding(cfg.vocab_size, cfg.dim)
|
| 61 |
+
self.layers = nn.ModuleList(
|
| 62 |
+
[TransformerBlock(cfg, use_moe=True) for _ in range(n_layers)]
|
| 63 |
+
)
|
| 64 |
+
self.norm = RMSNorm(cfg.dim)
|
| 65 |
+
self.head = nn.Linear(cfg.dim, cfg.vocab_size, bias=False)
|
| 66 |
+
|
| 67 |
+
head_dim = cfg.dim // cfg.n_heads
|
| 68 |
+
self.register_buffer(
|
| 69 |
+
"freqs_cis",
|
| 70 |
+
precompute_rope_freqs(head_dim, cfg.max_seq_len, cfg.rope_theta),
|
| 71 |
+
persistent=False,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
@staticmethod
|
| 75 |
+
def _causal_mask(T: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
|
| 76 |
+
mask = torch.full((1, 1, T, T), float("-inf"), device=device, dtype=dtype)
|
| 77 |
+
return torch.triu(mask, diagonal=1)
|
| 78 |
+
|
| 79 |
+
def forward(
|
| 80 |
+
self,
|
| 81 |
+
input_ids: torch.Tensor,
|
| 82 |
+
kv_cache: Optional[dict] = None,
|
| 83 |
+
start_pos: int = 0,
|
| 84 |
+
) -> torch.Tensor:
|
| 85 |
+
T = input_ids.shape[1]
|
| 86 |
+
x = self.embed(input_ids)
|
| 87 |
+
freqs_cis = self.freqs_cis[start_pos : start_pos + T]
|
| 88 |
+
mask = self._causal_mask(T, x.device, x.dtype) if T > 1 else None
|
| 89 |
+
for i, layer in enumerate(self.layers):
|
| 90 |
+
x = layer(x, freqs_cis, mask, kv_cache, cache_key=f"layer_{i}")
|
| 91 |
+
return self.head(self.norm(x))
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ---------------------------------------------------------------------------
|
| 95 |
+
# Timing utilities
|
| 96 |
+
# ---------------------------------------------------------------------------
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _sync(device: torch.device) -> None:
|
| 100 |
+
if device.type == "cuda":
|
| 101 |
+
torch.cuda.synchronize()
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def time_fn(fn, device: torch.device, warmup: int = 2, trials: int = 5) -> float:
|
| 105 |
+
"""Returns median wall-clock seconds over `trials` after `warmup` runs."""
|
| 106 |
+
for _ in range(warmup):
|
| 107 |
+
fn()
|
| 108 |
+
_sync(device)
|
| 109 |
+
times = []
|
| 110 |
+
for _ in range(trials):
|
| 111 |
+
_sync(device)
|
| 112 |
+
t0 = time.perf_counter()
|
| 113 |
+
fn()
|
| 114 |
+
_sync(device)
|
| 115 |
+
times.append(time.perf_counter() - t0)
|
| 116 |
+
return statistics.median(times)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def peak_mem_mb(device: torch.device) -> float:
|
| 120 |
+
if device.type != "cuda":
|
| 121 |
+
return 0.0
|
| 122 |
+
return torch.cuda.max_memory_allocated() / (1024 * 1024)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def reset_mem(device: torch.device) -> None:
|
| 126 |
+
gc.collect()
|
| 127 |
+
if device.type == "cuda":
|
| 128 |
+
torch.cuda.empty_cache()
|
| 129 |
+
torch.cuda.reset_peak_memory_stats()
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# ---------------------------------------------------------------------------
|
| 133 |
+
# Parameter counting
|
| 134 |
+
# ---------------------------------------------------------------------------
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@dataclass
|
| 138 |
+
class ParamCounts:
|
| 139 |
+
total: int
|
| 140 |
+
moe_active_est: int # active per token (shared + top-k routed)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def count_params(model: nn.Module, cfg: MythosConfig) -> ParamCounts:
|
| 144 |
+
total = sum(p.numel() for p in model.parameters())
|
| 145 |
+
# Rough active-per-token count for MoE layers: shared + top-k routed fraction.
|
| 146 |
+
# For simplicity we report total and an estimated activation ratio separately.
|
| 147 |
+
active_ratio = (cfg.n_shared_experts + cfg.n_experts_per_tok) / (
|
| 148 |
+
cfg.n_shared_experts + cfg.n_experts
|
| 149 |
+
)
|
| 150 |
+
# Only FFN parameters shrink under activation; attention + embed/head are always on.
|
| 151 |
+
# This is a coarse lower bound on active params.
|
| 152 |
+
ffn_params = 0
|
| 153 |
+
other_params = 0
|
| 154 |
+
for name, p in model.named_parameters():
|
| 155 |
+
if ".ffn." in name or name.startswith("ffn.") or ".experts." in name:
|
| 156 |
+
ffn_params += p.numel()
|
| 157 |
+
else:
|
| 158 |
+
other_params += p.numel()
|
| 159 |
+
active_est = other_params + int(ffn_params * active_ratio)
|
| 160 |
+
return ParamCounts(total=total, moe_active_est=active_est)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# ---------------------------------------------------------------------------
|
| 164 |
+
# Benchmarks
|
| 165 |
+
# ---------------------------------------------------------------------------
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def bench_prefill(
|
| 169 |
+
model: nn.Module,
|
| 170 |
+
vocab_size: int,
|
| 171 |
+
batch: int,
|
| 172 |
+
seq_len: int,
|
| 173 |
+
device: torch.device,
|
| 174 |
+
n_loops: Optional[int] = None,
|
| 175 |
+
) -> tuple[float, float]:
|
| 176 |
+
"""Returns (median_seconds, tokens_per_sec)."""
|
| 177 |
+
ids = torch.randint(0, vocab_size, (batch, seq_len), device=device)
|
| 178 |
+
|
| 179 |
+
if isinstance(model, OpenMythos):
|
| 180 |
+
|
| 181 |
+
def run() -> None:
|
| 182 |
+
with torch.no_grad():
|
| 183 |
+
model(ids, n_loops=n_loops)
|
| 184 |
+
|
| 185 |
+
else:
|
| 186 |
+
|
| 187 |
+
def run() -> None:
|
| 188 |
+
with torch.no_grad():
|
| 189 |
+
model(ids)
|
| 190 |
+
|
| 191 |
+
secs = time_fn(run, device)
|
| 192 |
+
tps = (batch * seq_len) / secs
|
| 193 |
+
return secs, tps
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def bench_decode(
|
| 197 |
+
model: nn.Module,
|
| 198 |
+
vocab_size: int,
|
| 199 |
+
batch: int,
|
| 200 |
+
prompt_len: int,
|
| 201 |
+
decode_steps: int,
|
| 202 |
+
device: torch.device,
|
| 203 |
+
n_loops: Optional[int] = None,
|
| 204 |
+
) -> tuple[float, float]:
|
| 205 |
+
"""
|
| 206 |
+
Prefill a `prompt_len` prompt, then time `decode_steps` single-token decode
|
| 207 |
+
steps with KV cache. Returns (avg_seconds_per_step, decode_tokens_per_sec).
|
| 208 |
+
"""
|
| 209 |
+
prompt = torch.randint(0, vocab_size, (batch, prompt_len), device=device)
|
| 210 |
+
|
| 211 |
+
def one_run() -> None:
|
| 212 |
+
kv_cache: dict = {}
|
| 213 |
+
with torch.no_grad():
|
| 214 |
+
if isinstance(model, OpenMythos):
|
| 215 |
+
model(prompt, n_loops=n_loops, kv_cache=kv_cache, start_pos=0)
|
| 216 |
+
else:
|
| 217 |
+
model(prompt, kv_cache=kv_cache, start_pos=0)
|
| 218 |
+
for i in range(decode_steps):
|
| 219 |
+
next_tok = torch.randint(0, vocab_size, (batch, 1), device=device)
|
| 220 |
+
if isinstance(model, OpenMythos):
|
| 221 |
+
model(
|
| 222 |
+
next_tok,
|
| 223 |
+
n_loops=n_loops,
|
| 224 |
+
kv_cache=kv_cache,
|
| 225 |
+
start_pos=prompt_len + i,
|
| 226 |
+
)
|
| 227 |
+
else:
|
| 228 |
+
model(next_tok, kv_cache=kv_cache, start_pos=prompt_len + i)
|
| 229 |
+
|
| 230 |
+
secs = time_fn(one_run, device, warmup=1, trials=3)
|
| 231 |
+
per_step = secs / decode_steps
|
| 232 |
+
tps = batch * decode_steps / secs
|
| 233 |
+
return per_step, tps
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
# ---------------------------------------------------------------------------
|
| 237 |
+
# Config helpers
|
| 238 |
+
# ---------------------------------------------------------------------------
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def small_cfg() -> MythosConfig:
|
| 242 |
+
"""Tiny config for smoke tests — runs on CPU in seconds."""
|
| 243 |
+
return MythosConfig(
|
| 244 |
+
vocab_size=1024,
|
| 245 |
+
dim=256,
|
| 246 |
+
n_heads=8,
|
| 247 |
+
n_kv_heads=2,
|
| 248 |
+
max_seq_len=1024,
|
| 249 |
+
max_loop_iters=4,
|
| 250 |
+
prelude_layers=1,
|
| 251 |
+
coda_layers=1,
|
| 252 |
+
attn_type="gqa",
|
| 253 |
+
n_experts=8,
|
| 254 |
+
n_shared_experts=1,
|
| 255 |
+
n_experts_per_tok=2,
|
| 256 |
+
expert_dim=128,
|
| 257 |
+
lora_rank=4,
|
| 258 |
+
dropout=0.0,
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def get_cfg(size: str) -> MythosConfig:
|
| 263 |
+
size = size.lower()
|
| 264 |
+
if size == "small":
|
| 265 |
+
return small_cfg()
|
| 266 |
+
if size == "1b":
|
| 267 |
+
cfg = mythos_1b()
|
| 268 |
+
# GQA for apples-to-apples; MLA changes KV shape semantics.
|
| 269 |
+
cfg.attn_type = "gqa"
|
| 270 |
+
return cfg
|
| 271 |
+
raise ValueError(f"unknown size: {size!r} (use 'small' or '1b')")
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
# ---------------------------------------------------------------------------
|
| 275 |
+
# Reporting
|
| 276 |
+
# ---------------------------------------------------------------------------
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def fmt_count(n: int) -> str:
|
| 280 |
+
for unit in ("", "K", "M", "B", "T"):
|
| 281 |
+
if abs(n) < 1000:
|
| 282 |
+
return f"{n:.2f}{unit}"
|
| 283 |
+
n /= 1000
|
| 284 |
+
return f"{n:.2f}P"
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def print_header(title: str) -> None:
|
| 288 |
+
bar = "=" * 72
|
| 289 |
+
print(f"\n{bar}\n{title}\n{bar}")
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
# ---------------------------------------------------------------------------
|
| 293 |
+
# Main
|
| 294 |
+
# ---------------------------------------------------------------------------
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def parse_args() -> argparse.Namespace:
|
| 298 |
+
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
| 299 |
+
p.add_argument("--size", default="small", choices=["small", "1b"])
|
| 300 |
+
p.add_argument(
|
| 301 |
+
"--device",
|
| 302 |
+
default="cuda" if torch.cuda.is_available() else "cpu",
|
| 303 |
+
choices=["cuda", "cpu"],
|
| 304 |
+
)
|
| 305 |
+
p.add_argument(
|
| 306 |
+
"--dtype",
|
| 307 |
+
default="auto",
|
| 308 |
+
choices=["auto", "fp32", "bf16", "fp16"],
|
| 309 |
+
help="'auto' picks fp32 on CPU and bf16 on CUDA",
|
| 310 |
+
)
|
| 311 |
+
p.add_argument("--batch", type=int, default=1)
|
| 312 |
+
p.add_argument(
|
| 313 |
+
"--seq-lens",
|
| 314 |
+
default="128,512",
|
| 315 |
+
help="comma-separated prefill sequence lengths",
|
| 316 |
+
)
|
| 317 |
+
p.add_argument(
|
| 318 |
+
"--n-loops",
|
| 319 |
+
default="1,4,8",
|
| 320 |
+
help="comma-separated loop counts to sweep (OpenMythos only)",
|
| 321 |
+
)
|
| 322 |
+
p.add_argument(
|
| 323 |
+
"--decode-steps",
|
| 324 |
+
type=int,
|
| 325 |
+
default=32,
|
| 326 |
+
help="number of autoregressive decode steps after prefill",
|
| 327 |
+
)
|
| 328 |
+
p.add_argument(
|
| 329 |
+
"--decode-prompt-len",
|
| 330 |
+
type=int,
|
| 331 |
+
default=128,
|
| 332 |
+
help="prefill length before decode",
|
| 333 |
+
)
|
| 334 |
+
return p.parse_args()
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def main() -> None:
|
| 338 |
+
args = parse_args()
|
| 339 |
+
device = torch.device(args.device)
|
| 340 |
+
dtype_arg = args.dtype
|
| 341 |
+
if dtype_arg == "auto":
|
| 342 |
+
dtype_arg = "bf16" if device.type == "cuda" else "fp32"
|
| 343 |
+
dtype = {
|
| 344 |
+
"fp32": torch.float32,
|
| 345 |
+
"bf16": torch.bfloat16,
|
| 346 |
+
"fp16": torch.float16,
|
| 347 |
+
}[dtype_arg]
|
| 348 |
+
|
| 349 |
+
seq_lens = [int(s) for s in args.seq_lens.split(",") if s.strip()]
|
| 350 |
+
n_loops_sweep = [int(s) for s in args.n_loops.split(",") if s.strip()]
|
| 351 |
+
|
| 352 |
+
cfg = get_cfg(args.size)
|
| 353 |
+
print_header(f"Config: size={args.size} device={device} dtype={dtype_arg}")
|
| 354 |
+
print(
|
| 355 |
+
f" dim={cfg.dim} n_heads={cfg.n_heads} n_kv_heads={cfg.n_kv_heads} "
|
| 356 |
+
f"prelude={cfg.prelude_layers} coda={cfg.coda_layers} "
|
| 357 |
+
f"max_loop_iters={cfg.max_loop_iters}\n"
|
| 358 |
+
f" experts={cfg.n_experts} shared={cfg.n_shared_experts} "
|
| 359 |
+
f"top_k={cfg.n_experts_per_tok} expert_dim={cfg.expert_dim}"
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
# Build models. Baseline depth = prelude + 1 (one unique recurrent block) + coda
|
| 363 |
+
# to match the unique-parameter depth of OpenMythos (parameter-matched baseline).
|
| 364 |
+
baseline_n_layers = cfg.prelude_layers + 1 + cfg.coda_layers
|
| 365 |
+
|
| 366 |
+
torch.manual_seed(0)
|
| 367 |
+
mythos = OpenMythos(cfg).to(device=device, dtype=dtype).eval()
|
| 368 |
+
torch.manual_seed(0)
|
| 369 |
+
baseline = (
|
| 370 |
+
BaselineTransformer(cfg, n_layers=baseline_n_layers)
|
| 371 |
+
.to(device=device, dtype=dtype)
|
| 372 |
+
.eval()
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
m_params = count_params(mythos, cfg)
|
| 376 |
+
b_params = count_params(baseline, cfg)
|
| 377 |
+
print_header(
|
| 378 |
+
"Parameters (block-matched: baseline depth = prelude + 1 recurrent + coda)"
|
| 379 |
+
)
|
| 380 |
+
print(
|
| 381 |
+
f" OpenMythos : total={fmt_count(m_params.total):>10} "
|
| 382 |
+
f"active/tok≈{fmt_count(m_params.moe_active_est):>10}"
|
| 383 |
+
)
|
| 384 |
+
print(
|
| 385 |
+
f" Baseline : total={fmt_count(b_params.total):>10} "
|
| 386 |
+
f"active/tok≈{fmt_count(b_params.moe_active_est):>10}"
|
| 387 |
+
)
|
| 388 |
+
print(
|
| 389 |
+
f" Baseline unique layers = {baseline_n_layers} "
|
| 390 |
+
f"(Mythos total runtime depth at max_loops = "
|
| 391 |
+
f"{cfg.prelude_layers + cfg.max_loop_iters + cfg.coda_layers})"
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
# ---- Prefill ----
|
| 395 |
+
print_header("Prefill latency (batch={batch})".format(batch=args.batch))
|
| 396 |
+
header = f" {'model':<26} {'seq':>6} {'sec':>10} {'tok/s':>12} {'peak MB':>10}"
|
| 397 |
+
print(header)
|
| 398 |
+
for seq_len in seq_lens:
|
| 399 |
+
if seq_len > cfg.max_seq_len:
|
| 400 |
+
print(f" skip seq_len={seq_len} (> max_seq_len={cfg.max_seq_len})")
|
| 401 |
+
continue
|
| 402 |
+
|
| 403 |
+
reset_mem(device)
|
| 404 |
+
secs, tps = bench_prefill(baseline, cfg.vocab_size, args.batch, seq_len, device)
|
| 405 |
+
mem = peak_mem_mb(device)
|
| 406 |
+
print(
|
| 407 |
+
f" {'Baseline (stacked)':<26} {seq_len:>6} "
|
| 408 |
+
f"{secs*1000:>9.2f}ms {tps:>12,.0f} {mem:>10.1f}"
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
for nl in n_loops_sweep:
|
| 412 |
+
reset_mem(device)
|
| 413 |
+
secs, tps = bench_prefill(
|
| 414 |
+
mythos, cfg.vocab_size, args.batch, seq_len, device, n_loops=nl
|
| 415 |
+
)
|
| 416 |
+
mem = peak_mem_mb(device)
|
| 417 |
+
print(
|
| 418 |
+
f" {'OpenMythos (loops=' + str(nl) + ')':<26} {seq_len:>6} "
|
| 419 |
+
f"{secs*1000:>9.2f}ms {tps:>12,.0f} {mem:>10.1f}"
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
# ---- Decode ----
|
| 423 |
+
print_header(
|
| 424 |
+
f"Decode latency (prefill {args.decode_prompt_len} tokens + "
|
| 425 |
+
f"{args.decode_steps} decode steps, batch={args.batch})"
|
| 426 |
+
)
|
| 427 |
+
print(f" {'model':<26} {'sec/step':>12} {'decode tok/s':>14}")
|
| 428 |
+
|
| 429 |
+
reset_mem(device)
|
| 430 |
+
per_step, tps = bench_decode(
|
| 431 |
+
baseline,
|
| 432 |
+
cfg.vocab_size,
|
| 433 |
+
args.batch,
|
| 434 |
+
args.decode_prompt_len,
|
| 435 |
+
args.decode_steps,
|
| 436 |
+
device,
|
| 437 |
+
)
|
| 438 |
+
print(f" {'Baseline (stacked)':<26} {per_step*1000:>10.2f}ms {tps:>14,.1f}")
|
| 439 |
+
|
| 440 |
+
for nl in n_loops_sweep:
|
| 441 |
+
reset_mem(device)
|
| 442 |
+
per_step, tps = bench_decode(
|
| 443 |
+
mythos,
|
| 444 |
+
cfg.vocab_size,
|
| 445 |
+
args.batch,
|
| 446 |
+
args.decode_prompt_len,
|
| 447 |
+
args.decode_steps,
|
| 448 |
+
device,
|
| 449 |
+
n_loops=nl,
|
| 450 |
+
)
|
| 451 |
+
print(
|
| 452 |
+
f" {'OpenMythos (loops=' + str(nl) + ')':<26} "
|
| 453 |
+
f"{per_step*1000:>10.2f}ms {tps:>14,.1f}"
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
# ---- Depth scaling ----
|
| 457 |
+
print_header(
|
| 458 |
+
"OpenMythos depth scaling (fixed seq={}, batch={})".format(
|
| 459 |
+
seq_lens[0], args.batch
|
| 460 |
+
)
|
| 461 |
+
)
|
| 462 |
+
print(f" {'n_loops':>8} {'sec':>10} {'tok/s':>12} {'Δ vs loops=1':>14}")
|
| 463 |
+
base_secs = None
|
| 464 |
+
for nl in n_loops_sweep:
|
| 465 |
+
reset_mem(device)
|
| 466 |
+
secs, tps = bench_prefill(
|
| 467 |
+
mythos, cfg.vocab_size, args.batch, seq_lens[0], device, n_loops=nl
|
| 468 |
+
)
|
| 469 |
+
if base_secs is None:
|
| 470 |
+
base_secs = secs
|
| 471 |
+
delta = "1.00x"
|
| 472 |
+
else:
|
| 473 |
+
delta = f"{secs / base_secs:.2f}x"
|
| 474 |
+
print(f" {nl:>8} {secs*1000:>9.2f}ms {tps:>12,.0f} {delta:>14}")
|
| 475 |
+
|
| 476 |
+
print("\nDone.")
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
if __name__ == "__main__":
|
| 480 |
+
main()
|
tests/small_benchmark.py
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 5 |
+
|
| 6 |
+
Both models share the same tiny config and see the exact same batches in the
|
| 7 |
+
same order, so per-step loss + throughput are directly comparable. The baseline
|
| 8 |
+
is a dense GQA + SwiGLU stack whose unique-layer depth matches the recurrent
|
| 9 |
+
block's unique-parameter depth (prelude + 1 + coda), so parameter counts land
|
| 10 |
+
in the same ballpark.
|
| 11 |
+
|
| 12 |
+
python training/small_benchmark.py
|
| 13 |
+
python training/small_benchmark.py --steps 500 --device cuda
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import time
|
| 20 |
+
from collections import deque
|
| 21 |
+
from dataclasses import dataclass, field
|
| 22 |
+
from typing import Deque
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn as nn
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
from datasets import load_dataset
|
| 28 |
+
from torch.utils.data import DataLoader, Dataset
|
| 29 |
+
from transformers import AutoTokenizer
|
| 30 |
+
|
| 31 |
+
from open_mythos import MythosConfig, OpenMythos
|
| 32 |
+
from open_mythos.main import (
|
| 33 |
+
RMSNorm,
|
| 34 |
+
TransformerBlock,
|
| 35 |
+
precompute_rope_freqs,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# ---------------------------------------------------------------------------
|
| 40 |
+
# Baseline: dense GQA + SwiGLU transformer
|
| 41 |
+
# ---------------------------------------------------------------------------
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class BaselineTransformer(nn.Module):
|
| 45 |
+
"""Vanilla decoder-only transformer with dense SwiGLU FFNs.
|
| 46 |
+
|
| 47 |
+
Reuses OpenMythos's TransformerBlock (attention + FFN kernels are identical)
|
| 48 |
+
so any measured delta reflects the looped recurrent-depth architecture, not
|
| 49 |
+
kernel differences. Supports both attn_type="gqa" and "mla".
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def __init__(self, cfg: MythosConfig, n_layers: int):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.cfg = cfg
|
| 55 |
+
self.embed = nn.Embedding(cfg.vocab_size, cfg.dim)
|
| 56 |
+
self.layers = nn.ModuleList(
|
| 57 |
+
[TransformerBlock(cfg, use_moe=False) for _ in range(n_layers)]
|
| 58 |
+
)
|
| 59 |
+
self.norm = RMSNorm(cfg.dim)
|
| 60 |
+
self.head = nn.Linear(cfg.dim, cfg.vocab_size, bias=False)
|
| 61 |
+
self.head.weight = self.embed.weight # weight tying
|
| 62 |
+
|
| 63 |
+
# MLA applies RoPE to qk_rope_head_dim only; GQA rotates the full head_dim.
|
| 64 |
+
rope_dim = (
|
| 65 |
+
cfg.qk_rope_head_dim if cfg.attn_type == "mla" else cfg.dim // cfg.n_heads
|
| 66 |
+
)
|
| 67 |
+
self.register_buffer(
|
| 68 |
+
"freqs_cis",
|
| 69 |
+
precompute_rope_freqs(rope_dim, cfg.max_seq_len, cfg.rope_theta),
|
| 70 |
+
persistent=False,
|
| 71 |
+
)
|
| 72 |
+
self._init_weights()
|
| 73 |
+
|
| 74 |
+
def _init_weights(self) -> None:
|
| 75 |
+
for m in self.modules():
|
| 76 |
+
if isinstance(m, nn.Linear):
|
| 77 |
+
nn.init.normal_(m.weight, std=0.02)
|
| 78 |
+
elif isinstance(m, nn.Embedding):
|
| 79 |
+
nn.init.normal_(m.weight, std=0.02)
|
| 80 |
+
|
| 81 |
+
@staticmethod
|
| 82 |
+
def _causal_mask(T: int, device: torch.device) -> torch.Tensor:
|
| 83 |
+
mask = torch.full((1, 1, T, T), float("-inf"), device=device)
|
| 84 |
+
return torch.triu(mask, diagonal=1)
|
| 85 |
+
|
| 86 |
+
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
|
| 87 |
+
T = input_ids.shape[1]
|
| 88 |
+
x = self.embed(input_ids)
|
| 89 |
+
freqs_cis = self.freqs_cis[:T]
|
| 90 |
+
mask = self._causal_mask(T, x.device) if T > 1 else None
|
| 91 |
+
for i, layer in enumerate(self.layers):
|
| 92 |
+
x = layer(x, freqs_cis, mask, cache_key=f"layer_{i}")
|
| 93 |
+
return self.head(self.norm(x))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# ---------------------------------------------------------------------------
|
| 97 |
+
# Dataset: tokenize once, pack into fixed-length next-token pairs
|
| 98 |
+
# ---------------------------------------------------------------------------
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class PackedLMDataset(Dataset):
|
| 102 |
+
"""Flatten an HF text dataset into one token buffer, slice fixed-length pairs.
|
| 103 |
+
|
| 104 |
+
Accepts either map-style or streaming (`IterableDataset`) HF datasets —
|
| 105 |
+
iteration stops once `max_tokens` are collected, so large corpora like
|
| 106 |
+
TinyStories can be streamed without downloading the whole thing.
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
def __init__(
|
| 110 |
+
self,
|
| 111 |
+
hf_ds,
|
| 112 |
+
tokenizer,
|
| 113 |
+
seq_len: int,
|
| 114 |
+
max_tokens: int,
|
| 115 |
+
text_field: str = "text",
|
| 116 |
+
):
|
| 117 |
+
buf: list[int] = []
|
| 118 |
+
for sample in hf_ds:
|
| 119 |
+
text = sample[text_field]
|
| 120 |
+
if not text or not text.strip():
|
| 121 |
+
continue
|
| 122 |
+
buf.extend(tokenizer.encode(text, add_special_tokens=False))
|
| 123 |
+
if len(buf) >= max_tokens:
|
| 124 |
+
break
|
| 125 |
+
self.seq_len = seq_len
|
| 126 |
+
n_pairs = max(1, (len(buf) - 1) // seq_len)
|
| 127 |
+
buf = buf[: n_pairs * seq_len + 1]
|
| 128 |
+
self.data = torch.tensor(buf, dtype=torch.long)
|
| 129 |
+
|
| 130 |
+
def __len__(self) -> int:
|
| 131 |
+
return (len(self.data) - 1) // self.seq_len
|
| 132 |
+
|
| 133 |
+
def __getitem__(self, idx: int):
|
| 134 |
+
s = idx * self.seq_len
|
| 135 |
+
chunk = self.data[s : s + self.seq_len + 1]
|
| 136 |
+
return chunk[:-1], chunk[1:]
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
# ---------------------------------------------------------------------------
|
| 140 |
+
# Metrics
|
| 141 |
+
# ---------------------------------------------------------------------------
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@dataclass
|
| 145 |
+
class Metrics:
|
| 146 |
+
total_loss: float = 0.0
|
| 147 |
+
total_tokens: int = 0
|
| 148 |
+
total_time: float = 0.0
|
| 149 |
+
steps: int = 0
|
| 150 |
+
first_losses: list[float] = field(default_factory=list)
|
| 151 |
+
last_losses: Deque[float] = field(default_factory=lambda: deque(maxlen=10))
|
| 152 |
+
|
| 153 |
+
def update(self, loss: float, tokens: int, seconds: float) -> None:
|
| 154 |
+
self.total_loss += loss
|
| 155 |
+
self.total_tokens += tokens
|
| 156 |
+
self.total_time += seconds
|
| 157 |
+
self.steps += 1
|
| 158 |
+
if len(self.first_losses) < 10:
|
| 159 |
+
self.first_losses.append(loss)
|
| 160 |
+
self.last_losses.append(loss)
|
| 161 |
+
|
| 162 |
+
@property
|
| 163 |
+
def avg_loss(self) -> float:
|
| 164 |
+
return self.total_loss / max(1, self.steps)
|
| 165 |
+
|
| 166 |
+
@property
|
| 167 |
+
def tok_per_sec(self) -> float:
|
| 168 |
+
return self.total_tokens / max(1e-9, self.total_time)
|
| 169 |
+
|
| 170 |
+
@property
|
| 171 |
+
def initial_loss(self) -> float:
|
| 172 |
+
return sum(self.first_losses) / max(1, len(self.first_losses))
|
| 173 |
+
|
| 174 |
+
@property
|
| 175 |
+
def final_loss(self) -> float:
|
| 176 |
+
return sum(self.last_losses) / max(1, len(self.last_losses))
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# ---------------------------------------------------------------------------
|
| 180 |
+
# Training step
|
| 181 |
+
# ---------------------------------------------------------------------------
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def train_step(
|
| 185 |
+
model: nn.Module,
|
| 186 |
+
x: torch.Tensor,
|
| 187 |
+
y: torch.Tensor,
|
| 188 |
+
optimizer: torch.optim.Optimizer,
|
| 189 |
+
device: torch.device,
|
| 190 |
+
vocab_size: int,
|
| 191 |
+
) -> tuple[float, float]:
|
| 192 |
+
"""Run one optimizer step; return (loss, wall-clock seconds)."""
|
| 193 |
+
t0 = time.perf_counter()
|
| 194 |
+
model.train()
|
| 195 |
+
optimizer.zero_grad()
|
| 196 |
+
logits = model(x)
|
| 197 |
+
loss = F.cross_entropy(logits.view(-1, vocab_size), y.view(-1))
|
| 198 |
+
loss.backward()
|
| 199 |
+
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 200 |
+
optimizer.step()
|
| 201 |
+
if device.type == "cuda":
|
| 202 |
+
torch.cuda.synchronize()
|
| 203 |
+
return loss.item(), time.perf_counter() - t0
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
@torch.no_grad()
|
| 207 |
+
def evaluate(
|
| 208 |
+
model: nn.Module,
|
| 209 |
+
loader: DataLoader,
|
| 210 |
+
device: torch.device,
|
| 211 |
+
vocab_size: int,
|
| 212 |
+
max_batches: int | None = None,
|
| 213 |
+
n_loops: int | None = None,
|
| 214 |
+
) -> float:
|
| 215 |
+
"""Mean cross-entropy over (up to `max_batches`) of the loader.
|
| 216 |
+
|
| 217 |
+
`n_loops` is only forwarded to OpenMythos; for any other module the kwarg
|
| 218 |
+
is dropped, so the same function benchmarks baseline and mythos uniformly.
|
| 219 |
+
"""
|
| 220 |
+
model.eval()
|
| 221 |
+
total_loss = 0.0
|
| 222 |
+
total_tokens = 0
|
| 223 |
+
for i, (x, y) in enumerate(loader):
|
| 224 |
+
if max_batches is not None and i >= max_batches:
|
| 225 |
+
break
|
| 226 |
+
x = x.to(device, non_blocking=True)
|
| 227 |
+
y = y.to(device, non_blocking=True)
|
| 228 |
+
if isinstance(model, OpenMythos):
|
| 229 |
+
logits = model(x, n_loops=n_loops)
|
| 230 |
+
else:
|
| 231 |
+
logits = model(x)
|
| 232 |
+
# sum-reduction so we weight by token count, not batch count
|
| 233 |
+
loss = F.cross_entropy(logits.view(-1, vocab_size), y.view(-1), reduction="sum")
|
| 234 |
+
total_loss += loss.item()
|
| 235 |
+
total_tokens += y.numel()
|
| 236 |
+
return total_loss / max(1, total_tokens)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
# ---------------------------------------------------------------------------
|
| 240 |
+
# Config + utilities
|
| 241 |
+
# ---------------------------------------------------------------------------
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def build_tiny_cfg(vocab_size: int, seq_len: int) -> MythosConfig:
|
| 245 |
+
"""Tiny shared config with MLA attention — runs in reasonable time on CPU.
|
| 246 |
+
|
| 247 |
+
MLA LoRA ranks and head dims scale with `dim=128` instead of the
|
| 248 |
+
2048-dim-sized defaults (q_lora_rank=1536, qk_nope_head_dim=128, ...),
|
| 249 |
+
which would otherwise dominate the parameter count at this scale.
|
| 250 |
+
"""
|
| 251 |
+
return MythosConfig(
|
| 252 |
+
vocab_size=vocab_size,
|
| 253 |
+
dim=128,
|
| 254 |
+
n_heads=4,
|
| 255 |
+
n_kv_heads=2,
|
| 256 |
+
max_seq_len=seq_len,
|
| 257 |
+
max_loop_iters=4,
|
| 258 |
+
prelude_layers=1,
|
| 259 |
+
coda_layers=1,
|
| 260 |
+
attn_type="mla",
|
| 261 |
+
kv_lora_rank=64,
|
| 262 |
+
q_lora_rank=128,
|
| 263 |
+
qk_rope_head_dim=16,
|
| 264 |
+
qk_nope_head_dim=32,
|
| 265 |
+
v_head_dim=32,
|
| 266 |
+
n_experts=4,
|
| 267 |
+
n_shared_experts=1,
|
| 268 |
+
n_experts_per_tok=2,
|
| 269 |
+
expert_dim=128,
|
| 270 |
+
lora_rank=4,
|
| 271 |
+
rope_theta=10000.0,
|
| 272 |
+
dropout=0.0,
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def count_params(model: nn.Module) -> int:
|
| 277 |
+
return sum(p.numel() for p in model.parameters())
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def fmt_count(n: float) -> str:
|
| 281 |
+
for unit in ("", "K", "M", "B"):
|
| 282 |
+
if abs(n) < 1000:
|
| 283 |
+
return f"{n:.2f}{unit}"
|
| 284 |
+
n /= 1000
|
| 285 |
+
return f"{n:.2f}T"
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
# ---------------------------------------------------------------------------
|
| 289 |
+
# Main
|
| 290 |
+
# ---------------------------------------------------------------------------
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def parse_args() -> argparse.Namespace:
|
| 294 |
+
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
| 295 |
+
p.add_argument("--steps", type=int, default=1000)
|
| 296 |
+
p.add_argument("--batch-size", type=int, default=32)
|
| 297 |
+
p.add_argument("--seq-len", type=int, default=256)
|
| 298 |
+
p.add_argument("--lr", type=float, default=3e-4)
|
| 299 |
+
# Defaults point at TinyStories — simpler vocabulary + shorter documents
|
| 300 |
+
# lets a dim=128 model actually reach a meaningful loss in modest time.
|
| 301 |
+
p.add_argument("--dataset", default="roneneldan/TinyStories")
|
| 302 |
+
p.add_argument(
|
| 303 |
+
"--dataset-config",
|
| 304 |
+
default="",
|
| 305 |
+
help="pass '' for datasets with no config (e.g. TinyStories)",
|
| 306 |
+
)
|
| 307 |
+
p.add_argument("--train-split", default="train")
|
| 308 |
+
p.add_argument("--eval-split", default="validation")
|
| 309 |
+
p.add_argument(
|
| 310 |
+
"--train-tokens",
|
| 311 |
+
type=int,
|
| 312 |
+
default=5_000_000,
|
| 313 |
+
help="max tokens to materialize for the training buffer",
|
| 314 |
+
)
|
| 315 |
+
p.add_argument(
|
| 316 |
+
"--eval-tokens",
|
| 317 |
+
type=int,
|
| 318 |
+
default=200_000,
|
| 319 |
+
help="max tokens to materialize for the held-out eval buffer",
|
| 320 |
+
)
|
| 321 |
+
p.add_argument("--text-field", default="text")
|
| 322 |
+
p.add_argument("--tokenizer", default="gpt2")
|
| 323 |
+
p.add_argument("--log-every", type=int, default=25)
|
| 324 |
+
p.add_argument(
|
| 325 |
+
"--eval-every",
|
| 326 |
+
type=int,
|
| 327 |
+
default=200,
|
| 328 |
+
help="run held-out eval every N steps (0 disables)",
|
| 329 |
+
)
|
| 330 |
+
p.add_argument("--eval-batches", type=int, default=20)
|
| 331 |
+
p.add_argument(
|
| 332 |
+
"--depth-sweep",
|
| 333 |
+
default="1,2,4,8,16",
|
| 334 |
+
help="comma-separated n_loops values for OpenMythos depth-extrapolation eval",
|
| 335 |
+
)
|
| 336 |
+
p.add_argument("--seed", type=int, default=0)
|
| 337 |
+
p.add_argument(
|
| 338 |
+
"--device",
|
| 339 |
+
default="cuda" if torch.cuda.is_available() else "cpu",
|
| 340 |
+
)
|
| 341 |
+
return p.parse_args()
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def load_text_ds(name: str, config: str, split: str):
|
| 345 |
+
"""Streaming `load_dataset` with optional config (empty string == no config)."""
|
| 346 |
+
if config:
|
| 347 |
+
return load_dataset(name, config, split=split, streaming=True)
|
| 348 |
+
return load_dataset(name, split=split, streaming=True)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def main() -> None:
|
| 352 |
+
args = parse_args()
|
| 353 |
+
device = torch.device(args.device)
|
| 354 |
+
|
| 355 |
+
print(
|
| 356 |
+
f"[setup] device={device} batch={args.batch_size} "
|
| 357 |
+
f"seq_len={args.seq_len} steps={args.steps}"
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer)
|
| 361 |
+
# AutoTokenizer.vocab_size can be smaller than the head size for BPE
|
| 362 |
+
# tokenizers with added tokens; use len(tokenizer) to be safe.
|
| 363 |
+
vocab_size = len(tokenizer)
|
| 364 |
+
print(f"[setup] tokenizer={args.tokenizer} vocab_size={vocab_size:,}")
|
| 365 |
+
|
| 366 |
+
# ------------------------------------------------------------------
|
| 367 |
+
# Data: streamed train + held-out eval splits
|
| 368 |
+
# ------------------------------------------------------------------
|
| 369 |
+
print(f"[setup] dataset={args.dataset} config={args.dataset_config or '∅'}")
|
| 370 |
+
raw_train = load_text_ds(args.dataset, args.dataset_config, args.train_split)
|
| 371 |
+
train_ds = PackedLMDataset(
|
| 372 |
+
raw_train, tokenizer, args.seq_len, args.train_tokens, args.text_field
|
| 373 |
+
)
|
| 374 |
+
raw_eval = load_text_ds(args.dataset, args.dataset_config, args.eval_split)
|
| 375 |
+
eval_ds = PackedLMDataset(
|
| 376 |
+
raw_eval, tokenizer, args.seq_len, args.eval_tokens, args.text_field
|
| 377 |
+
)
|
| 378 |
+
print(
|
| 379 |
+
f"[setup] train tokens={train_ds.data.numel():,} pairs={len(train_ds)} | "
|
| 380 |
+
f"eval tokens={eval_ds.data.numel():,} pairs={len(eval_ds)}"
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
torch.manual_seed(args.seed)
|
| 384 |
+
train_loader = DataLoader(
|
| 385 |
+
train_ds, batch_size=args.batch_size, shuffle=True, drop_last=True
|
| 386 |
+
)
|
| 387 |
+
eval_loader = DataLoader(
|
| 388 |
+
eval_ds, batch_size=args.batch_size, shuffle=False, drop_last=False
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
# ------------------------------------------------------------------
|
| 392 |
+
# Models — same init seed so both start from the same embedding
|
| 393 |
+
# ------------------------------------------------------------------
|
| 394 |
+
cfg = build_tiny_cfg(vocab_size, args.seq_len)
|
| 395 |
+
|
| 396 |
+
torch.manual_seed(args.seed)
|
| 397 |
+
mythos = OpenMythos(cfg).to(device)
|
| 398 |
+
|
| 399 |
+
# Parameter-matched depth: prelude + one unique recurrent block + coda.
|
| 400 |
+
baseline_layers = cfg.prelude_layers + 1 + cfg.coda_layers
|
| 401 |
+
torch.manual_seed(args.seed)
|
| 402 |
+
baseline = BaselineTransformer(cfg, n_layers=baseline_layers).to(device)
|
| 403 |
+
|
| 404 |
+
n_m, n_b = count_params(mythos), count_params(baseline)
|
| 405 |
+
print(
|
| 406 |
+
f"[setup] OpenMythos params = {fmt_count(n_m)} ({n_m:,})\n"
|
| 407 |
+
f"[setup] Baseline params = {fmt_count(n_b)} ({n_b:,}) "
|
| 408 |
+
f"[{baseline_layers} layers]"
|
| 409 |
+
)
|
| 410 |
+
print(
|
| 411 |
+
f"[setup] Mythos runtime depth = prelude({cfg.prelude_layers}) + "
|
| 412 |
+
f"loops({cfg.max_loop_iters}) + coda({cfg.coda_layers}) = "
|
| 413 |
+
f"{cfg.prelude_layers + cfg.max_loop_iters + cfg.coda_layers}"
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
opt_m = torch.optim.AdamW(
|
| 417 |
+
mythos.parameters(), lr=args.lr, betas=(0.9, 0.95), weight_decay=0.1
|
| 418 |
+
)
|
| 419 |
+
opt_b = torch.optim.AdamW(
|
| 420 |
+
baseline.parameters(), lr=args.lr, betas=(0.9, 0.95), weight_decay=0.1
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
mm, bm = Metrics(), Metrics()
|
| 424 |
+
eval_history: list[tuple[int, float, float]] = [] # (step, mythos_eval, base_eval)
|
| 425 |
+
|
| 426 |
+
header = (
|
| 427 |
+
f"\n{'step':>6} | {'mythos loss':>12} | {'base loss':>10} | "
|
| 428 |
+
f"{'mythos tok/s':>13} | {'base tok/s':>11}"
|
| 429 |
+
)
|
| 430 |
+
print(header)
|
| 431 |
+
print("-" * len(header))
|
| 432 |
+
|
| 433 |
+
# ------------------------------------------------------------------
|
| 434 |
+
# Training loop with periodic held-out eval
|
| 435 |
+
# ------------------------------------------------------------------
|
| 436 |
+
data_iter = iter(train_loader)
|
| 437 |
+
t_total = time.perf_counter()
|
| 438 |
+
for step in range(1, args.steps + 1):
|
| 439 |
+
try:
|
| 440 |
+
x, y = next(data_iter)
|
| 441 |
+
except StopIteration:
|
| 442 |
+
data_iter = iter(train_loader)
|
| 443 |
+
x, y = next(data_iter)
|
| 444 |
+
x = x.to(device, non_blocking=True)
|
| 445 |
+
y = y.to(device, non_blocking=True)
|
| 446 |
+
tokens = x.numel()
|
| 447 |
+
|
| 448 |
+
loss_m, dt_m = train_step(mythos, x, y, opt_m, device, vocab_size)
|
| 449 |
+
loss_b, dt_b = train_step(baseline, x, y, opt_b, device, vocab_size)
|
| 450 |
+
|
| 451 |
+
mm.update(loss_m, tokens, dt_m)
|
| 452 |
+
bm.update(loss_b, tokens, dt_b)
|
| 453 |
+
|
| 454 |
+
if step == 1 or step % args.log_every == 0:
|
| 455 |
+
print(
|
| 456 |
+
f"{step:>6} | {loss_m:>12.4f} | {loss_b:>10.4f} | "
|
| 457 |
+
f"{tokens / dt_m:>13,.0f} | {tokens / dt_b:>11,.0f}"
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
if args.eval_every and step % args.eval_every == 0:
|
| 461 |
+
eval_m = evaluate(
|
| 462 |
+
mythos, eval_loader, device, vocab_size, args.eval_batches
|
| 463 |
+
)
|
| 464 |
+
eval_b = evaluate(
|
| 465 |
+
baseline, eval_loader, device, vocab_size, args.eval_batches
|
| 466 |
+
)
|
| 467 |
+
eval_history.append((step, eval_m, eval_b))
|
| 468 |
+
print(
|
| 469 |
+
f" [eval @ step {step}] mythos {eval_m:.4f} baseline {eval_b:.4f} "
|
| 470 |
+
f"(Δ = {eval_m - eval_b:+.4f})"
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
total_wall = time.perf_counter() - t_total
|
| 474 |
+
|
| 475 |
+
# ------------------------------------------------------------------
|
| 476 |
+
# Summary
|
| 477 |
+
# ------------------------------------------------------------------
|
| 478 |
+
bar = "=" * 70
|
| 479 |
+
print(f"\n{bar}\nSummary ({args.steps} steps, wall clock {total_wall:.1f}s)\n{bar}")
|
| 480 |
+
print(f" {'':<24} {'OpenMythos':>16} {'Baseline':>16}")
|
| 481 |
+
print(f" {'params':<24} {fmt_count(n_m):>16} {fmt_count(n_b):>16}")
|
| 482 |
+
print(
|
| 483 |
+
f" {'initial train (first 10)':<24} "
|
| 484 |
+
f"{mm.initial_loss:>16.4f} {bm.initial_loss:>16.4f}"
|
| 485 |
+
)
|
| 486 |
+
print(
|
| 487 |
+
f" {'final train (last 10)':<24} "
|
| 488 |
+
f"{mm.final_loss:>16.4f} {bm.final_loss:>16.4f}"
|
| 489 |
+
)
|
| 490 |
+
print(
|
| 491 |
+
f" {'avg train (all steps)':<24} "
|
| 492 |
+
f"{mm.avg_loss:>16.4f} {bm.avg_loss:>16.4f}"
|
| 493 |
+
)
|
| 494 |
+
print(
|
| 495 |
+
f" {'train time (sec)':<24} "
|
| 496 |
+
f"{mm.total_time:>16.2f} {bm.total_time:>16.2f}"
|
| 497 |
+
)
|
| 498 |
+
print(
|
| 499 |
+
f" {'avg tok/s':<24} " f"{mm.tok_per_sec:>16,.0f} {bm.tok_per_sec:>16,.0f}"
|
| 500 |
+
)
|
| 501 |
+
print(
|
| 502 |
+
f" {'sec/step':<24} "
|
| 503 |
+
f"{mm.total_time / max(1, mm.steps):>16.4f} "
|
| 504 |
+
f"{bm.total_time / max(1, bm.steps):>16.4f}"
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
# ------------------------------------------------------------------
|
| 508 |
+
# Depth extrapolation: OpenMythos eval loss as a function of n_loops.
|
| 509 |
+
# Trained at cfg.max_loop_iters; we run inference with a sweep to see
|
| 510 |
+
# whether additional loops keep improving (depth extrapolation) or the
|
| 511 |
+
# model collapses outside the trained regime.
|
| 512 |
+
# ------------------------------------------------------------------
|
| 513 |
+
loops_sweep = sorted({int(s) for s in args.depth_sweep.split(",") if s.strip()})
|
| 514 |
+
print(f"\n{bar}\nDepth extrapolation (held-out eval, full eval set)\n{bar}")
|
| 515 |
+
baseline_eval = evaluate(baseline, eval_loader, device, vocab_size)
|
| 516 |
+
print(f" Baseline (fixed depth) : eval loss = {baseline_eval:.4f}")
|
| 517 |
+
# First collect all sweep losses, then print with deltas vs. the trained depth.
|
| 518 |
+
sweep: list[tuple[int, float]] = []
|
| 519 |
+
for nl in loops_sweep:
|
| 520 |
+
sweep.append(
|
| 521 |
+
(nl, evaluate(mythos, eval_loader, device, vocab_size, n_loops=nl))
|
| 522 |
+
)
|
| 523 |
+
trained_loss = next((loss for nl, loss in sweep if nl == cfg.max_loop_iters), None)
|
| 524 |
+
print(f" OpenMythos (trained at n_loops={cfg.max_loop_iters}):")
|
| 525 |
+
print(f" {'n_loops':>8} {'eval loss':>10} {'Δ vs trained':>14}")
|
| 526 |
+
for nl, loss in sweep:
|
| 527 |
+
if trained_loss is None or nl == cfg.max_loop_iters:
|
| 528 |
+
delta_str = ""
|
| 529 |
+
else:
|
| 530 |
+
delta_str = f"{loss - trained_loss:+.4f}"
|
| 531 |
+
marker = " ←trained" if nl == cfg.max_loop_iters else ""
|
| 532 |
+
print(f" {nl:>8} {loss:>10.4f} {delta_str:>14}{marker}")
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
if __name__ == "__main__":
|
| 536 |
+
main()
|
variants_example.py → tests/variants_example.py
RENAMED
|
File without changes
|