tiny-engine-165k: 165K-param in-context engine
Browse filesFiles changed (19)
- README.mdAdded+76
- SHA256SUMSAdded+18
- demo.pyAdded+42
- engine.pyAdded+175
- results/demo_seed1.txtAdded+9
- results/score.txtAdded+10
- results/seed1.jsonAdded+1
- results/seed2.jsonAdded+1
- results/seed3.jsonAdded+1
- results/seed4.jsonAdded+1
- results/seed5.jsonAdded+1
- results/seed6.jsonAdded+1
- score.pyAdded+13
- weights/engine_seed1.safetensorsAdded+3
- weights/engine_seed2.safetensorsAdded+3
- weights/engine_seed3.safetensorsAdded+3
- weights/engine_seed4.safetensorsAdded+3
- weights/engine_seed5.safetensorsAdded+3
- weights/engine_seed6.safetensorsAdded+3
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576---license: mitlibrary_name: pytorchtags: - tiny-model - in-context-learning - induction-heads - rotary-embeddings - research---
# tiny-engine-165k: 165,120 parameters that learn from their context
This is a very small transformer, **0.66 MB**, trained from scratch on a laptop-class CPU in about 6 minutes. Itdoes three different things using only what is in its input:
| Skill | At trained lengths | Beyond trained lengths ||---|---|---|| **Continue a repeating pattern**, including pattern lengths it never saw | 0.998–0.999 | 0.967–0.995 at **4× longer** inputs || **Look up a value** from key–value pairs given earlier | 1.000 | 0.948–0.972 at 2×, 0.825–0.883 at 4× || **Copy a string exactly** | 1.000 (up to 63 tokens) | 0.53–0.77 for 127-token strings: **the known weak spot** |
These are results across 6 independently trained seeds, against a pass bar[written before training](https://github.com/holland202/principia-artificialis/blob/exp/tiny-engine-001/experiments/tiny_engine/REGISTRATION.md).An untrained copy of the model scores about 0.01 on every test.
**Result: 2 of 3 registered criteria passed. Long-string copying failed and is reported, not hidden.**
## Try it
```bashpip install torch safetensors numpypython demo.py weights/engine_seed1.safetensors```
Output:
```1) continue a pattern of period 11 (never trained), after 300 tokens of context -> OK2) look up 40 values from 40 key-value pairs given earlier: 40/40 correct3) copy a 50-token string exactly: 50/50 tokens correct```
Seed 1 is the best of the six on long copying; the other five weights are included.
## How it is built
- **Architecture:** attention-only (no MLPs), 2 layers × 2 heads, width 128.- **Positions:** rotary (relative) positions, and no position embeddings. That is why it keeps working on longer inputs.- **Output layer:** separate (untied). Tying it to the input embedding stopped learning completely in our tests.- **Training:** a mix of three synthetic tasks over 128 content tokens; inputs of 32–128 tokens; AdamW at learning rate 1e-3, 6,000 steps.
## Honest limits
- **Not a language model:** it works on abstract tokens, not text.- **Not a new mechanism:** induction heads, and relative positions helping them generalize, are known results (e.g. arXiv 2412.11459). This is a small, open, fully tested working instance of them.- **Self-tested:** one AI designed, trained and graded it. It has not been independently reproduced.
## Files
| Path | What ||---|---|| `weights/engine_seed{1..6}.safetensors` | six independently trained models || `engine.py` | model, task generators, evaluation || `demo.py` | a quick hands-on test || `score.py` | applies the registered pass bar || `results/` | per-seed scores and the demo output |
## Provenance
AI participation: Claude (Anthropic, Opus 5.5) designed, built, trained and evaluated the model and wrote this card→ human validation: not performed → human editing/curation: direction by Chad Holland, 2026-11-16 → humanresponsibility: Chad Holland. Review level: direction only.123456789101112131415161718404f35ef3263ba31edc854045874af89c93422f7b155a04b2f4d97c71e794476 README.mdde7234b9d2e9c74ecc1de2b3f4689767a79611a8f10f8d6b27a532d05095dbde demo.pyd701a90d63782126330c0d31d51687682bf2f89492765c6b67b5ee40f01d5576 engine.pyf1993d41bb622359f1f216ce4f9e68fc796e6126029f7be0a741f1311a35d7c6 results/demo_seed1.txtd730bb1797d44fc918c85a80ed1b8a15174afb3020ed8d5925dde10be506c508 results/score.txt928b9adedf63e99ac1a694ccff803a1271e7da78ec87fba9570351b4924ac086 results/seed1.json19eef19335e90dab8aa5f9c1abcc400d7481ad6a549db3d90ab2cfa3ca50d1b2 results/seed2.json665207b56a75f09d50aa825e92222b4e533f1f30347487c4e8cada95d24ca81d results/seed3.json097f9bd0f2455a8ebdf4df6d09e80c511fbc50231c7a2b49c2a10c2c51543f84 results/seed4.json78c5a3d3293f2d48dcf34c82d7d75a8f7160ba778d7701d92dfb84bfc6da364f results/seed5.json9cea52984ae85af459546771a64a2c8a6da79dfd32c5748f74fde248d73e9bc3 results/seed6.jsona2ba58e0bcb3e068749110b0d7474794a5e316173a0cdf61ebcd01d69899489d score.py5d39dc8785bf021082de26864edf8012c5bbfd9c8f068f6efc88018f759586c3 weights/engine_seed1.safetensorsf19fdf2a24ae3040fd6056708985483a8ae4ed3780b713f9d8546dabe8dbbf83 weights/engine_seed2.safetensors085b36fa301668a88edf3e241d5310e2e86f49b205be6d0304a1edf4ad22ccae weights/engine_seed3.safetensors8e6827a6f1d26906723327cfc2c0e61cf8ebd0ed32ebb947ebb14b2e90ce7833 weights/engine_seed4.safetensors9d0c81404b735e9581a4264688f46f7cf2afb62b4a671bd1c8528e80451e8fa6 weights/engine_seed5.safetensorsfe800006a98d8fd2f71fc6c72f72170e2d72feb0e74d6e6c0c9430413626dcdd weights/engine_seed6.safetensors123456789101112131415161718192021222324252627282930313233343536373839404142"""Try the tiny in-context engine. Usage: python3 demo.py weights/engine_seed1.safetensorsShows the three skills on fresh random inputs, including inputs longer than any it trained on."""import sys
import numpy as npimport torchfrom safetensors.torch import load_file
import engine as E
def greedy(m, prefix, n): x = torch.tensor([prefix]) with torch.no_grad(): for _ in range(n): x = torch.cat([x, m(x)[:, -1:].argmax(-1)], 1) return x[0, len(prefix):].tolist()
m = E.TinyEngine()m.load_state_dict(load_file(sys.argv[1] if len(sys.argv) > 1 else "weights/engine_seed1.safetensors"))m.eval()rng = np.random.default_rng(2026)print(f"TinyEngine, {E.n_params(m):,} parameters\n")
seg = rng.integers(1, 128, size=11).tolist() # period 11 was never trained onprefix = [E.BOS] + (seg * 30)[:300] # 300 tokens: longer than any training inputout = greedy(m, prefix, 22)want = (seg * 40)[300:322]print("1) continue a pattern of period 11 (never trained), after 300 tokens of context")print(" model :", out); print(" truth :", want, "->", "OK" if out == want else "DIFF")
keys = rng.choice(np.arange(1, 64), 40, replace=False); vals = rng.choice(np.arange(64, 128), 40)ctx = [E.BOS] + [int(t) for kv in zip(keys, vals) for t in kv]hits = 0for j in range(40): hits += greedy(m, ctx + [E.QRY, int(keys[j])], 1)[0] == int(vals[j])print(f"\n2) look up 40 values from 40 key-value pairs given earlier: {hits}/40 correct")
s = rng.choice(np.arange(1, 128), 50, replace=False).tolist()out = greedy(m, [E.BOS] + s + [E.SEP], 50)print(f"\n3) copy a 50-token string exactly: {sum(a == b for a, b in zip(out, s))}/50 tokens correct")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175"""Tiny in-context engine: an attention-only transformer with rotary (relative) positions, trained from scratch on amix of in-context tasks, then tested on lengths it never saw. See REGISTRATION.md.Written by Claude (Anthropic, Opus 5.5) at Chad Holland's direction, 2026-11-16. SELF-TESTED only."""import math
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as F
N_CONTENT = 127 # content tokens 1..127BOS, SEP, QRY = 0, 128, 129VOCAB = 130CFG = dict(d_model=128, n_heads=2, n_layers=2, train_lens=(32, 64, 96, 128), batch=64, lr=1e-3, steps=6000)PERIODS_SEEN = tuple(L for L in range(4, 25) if L not in (7, 11, 15, 19, 23))PERIODS_HELD = (7, 11, 15, 19, 23)
# ---------------------------------------------------------------- tasks: (tokens, loss mask), mask marks positions whose# NEXT token is determined by the context, so the score is only over learnable predictions.def task_periodic(rng, T, periods): L = int(rng.choice(periods)) seg = rng.integers(1, N_CONTENT + 1, size=L) x = np.concatenate([[BOS], np.resize(seg, T - 1)]) m = np.zeros(T, bool) m[L:T - 1] = True # predicting x[t+1] from position t, for t+1 > L return x, m
KEYS = np.arange(1, 64) # keys and values come from disjoint halves of the vocabulary, so a key token canVALS = np.arange(64, N_CONTENT + 1) # never also appear as a value (that made the first version of this task ambiguous)
def task_recall(rng, T): """BOS k1 v1 ... kn vn, then queries 'QRY k v' about earlier pairs, filling length T.""" n = min(len(KEYS), max(2, (T - 1) * 2 // 5 // 2 * 2 // 2)) nq = (T - 1 - 2 * n) // 3 while nq < 1: n -= 1 nq = (T - 1 - 2 * n) // 3 keys = rng.choice(KEYS, size=n, replace=False) vals = rng.choice(VALS, size=n) x = [BOS] + [t for kv in zip(keys, vals) for t in kv] m = [False] * len(x) for j in rng.integers(0, n, size=nq): x += [QRY, keys[j], vals[j]] m += [False, True, False] # position of the key predicts the value pad = T - len(x) x += list(rng.integers(1, N_CONTENT + 1, size=pad)) m += [False] * pad return np.array(x), np.array(m)
def task_copy(rng, T): """BOS s SEP s: s has distinct tokens (so copying is unambiguous); length fills T.""" k = min((T - 2) // 2, N_CONTENT) s = rng.choice(np.arange(1, N_CONTENT + 1), size=k, replace=False) x = np.concatenate([[BOS], s, [SEP], s]) m = np.zeros(len(x), bool) m[k + 1:len(x) - 1] = True # from SEP onward, each next token is the copy pad = T - len(x) x = np.concatenate([x, rng.integers(1, N_CONTENT + 1, size=pad)]) m = np.concatenate([m, np.zeros(pad, bool)]) return x, m
TASKS = ("periodic", "recall", "copy")
def make_batch(rng, n, T, task=None, periods=PERIODS_SEEN): xs, ms = [], [] for _ in range(n): t = task or TASKS[int(rng.integers(len(TASKS)))] x, m = (task_periodic(rng, T, periods) if t == "periodic" else task_recall(rng, T) if t == "recall" else task_copy(rng, T)) xs.append(x); ms.append(m) return torch.tensor(np.array(xs)).long(), torch.tensor(np.array(ms))
# ---------------------------------------------------------------- modeldef rope(x, base=10000.0): """Rotary position embedding on the last dim of (b, h, t, d).""" t, d = x.shape[-2], x.shape[-1] inv = 1.0 / base ** (torch.arange(0, d, 2, dtype=torch.float32) / d) ang = torch.arange(t, dtype=torch.float32)[:, None] * inv[None] cos, sin = ang.cos(), ang.sin() x1, x2 = x[..., 0::2], x[..., 1::2] return torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], -1).flatten(-2)
class Attn(nn.Module): def __init__(self, d, h, use_rope=True): super().__init__() self.h, self.dh, self.use_rope = h, d // h, use_rope self.q, self.k, self.v, self.o = (nn.Linear(d, d, bias=False) for _ in range(4))
def forward(self, x): b, t, d = x.shape sh = lambda z: z.view(b, t, self.h, self.dh).transpose(1, 2) q, k = sh(self.q(x)), sh(self.k(x)) if self.use_rope: q, k = rope(q), rope(k) y = F.scaled_dot_product_attention(q, k, sh(self.v(x)), is_causal=True) return self.o(y.transpose(1, 2).reshape(b, t, d))
class TinyEngine(nn.Module): """Token embedding (no position embedding: positions enter only through rotary attention), attention-only pre-LN blocks, separate (untied) unembedding. Tying the unembedding to the embedding stopped learning entirely in exploration (0.00 periodic accuracy after 1,500 steps at d_model 256; untied reached 1.00)."""
def __init__(self, cfg=CFG): super().__init__() d = cfg["d_model"] self.pos_kind = cfg.get("pos", "rope") self.emb = nn.Embedding(VOCAB, d) self.pos = nn.Embedding(1024, d) if self.pos_kind == "learned" else None self.lns = nn.ModuleList(nn.LayerNorm(d) for _ in range(cfg["n_layers"])) self.attn = nn.ModuleList(Attn(d, cfg["n_heads"], self.pos_kind == "rope") for _ in range(cfg["n_layers"])) self.lnf = nn.LayerNorm(d) self.head = None if cfg.get("tied", False) else nn.Linear(d, VOCAB, bias=False)
def forward(self, x): h = self.emb(x) if self.pos is not None: h = h + self.pos(torch.arange(x.shape[1])) for ln, at in zip(self.lns, self.attn): h = h + at(ln(h)) h = self.lnf(h) return self.head(h) if self.head is not None else h @ self.emb.weight.T
def n_params(m): return sum(p.numel() for p in m.parameters())
# ---------------------------------------------------------------- evaluation@torch.no_grad()def accuracy(m, task, T, seed, n=256, periods=PERIODS_SEEN): x, mask = make_batch(np.random.default_rng(seed), n, T, task, periods) pred = m(x).argmax(-1)[:, :-1] ok = (pred == x[:, 1:])[mask[:, :-1]] return float(ok.float().mean())
EVAL_LENS = (128, 256, 512) # 128 = longest trained; 256 and 512 = 2x and 4x beyond it
def evaluate(m): m.eval() r = {} for L in EVAL_LENS: n = 256 if L <= 128 else 96 r[f"periodic_heldout_L{L}"] = accuracy(m, "periodic", L, 100 + L, n, periods=PERIODS_HELD) r[f"recall_L{L}"] = accuracy(m, "recall", L, 200 + L, n) r[f"copy_L{L}"] = accuracy(m, "copy", L, 300 + L, n) r["periodic_seen_L128"] = accuracy(m, "periodic", 128, 99) m.train() return r
def train(seed, cfg=CFG, log=None): torch.manual_seed(seed) torch.use_deterministic_algorithms(True) rng = np.random.default_rng(seed) m = TinyEngine(cfg) opt = torch.optim.AdamW(m.parameters(), lr=cfg["lr"], weight_decay=0.0) for step in range(1, cfg["steps"] + 1): x, mask = make_batch(rng, cfg["batch"], int(rng.choice(cfg["train_lens"]))) logits = m(x)[:, :-1] loss = F.cross_entropy(logits[mask[:, :-1]], x[:, 1:][mask[:, :-1]]) opt.zero_grad(); loss.backward(); opt.step() if log and step % 500 == 0: log(step, float(loss.detach())) return m123456789TinyEngine, 165,120 parameters
1) continue a pattern of period 11 (never trained), after 300 tokens of context model : [82, 47, 60, 11, 48, 82, 46, 106, 109, 23, 4, 82, 47, 60, 11, 48, 82, 46, 106, 109, 23, 4] truth : [82, 47, 60, 11, 48, 82, 46, 106, 109, 23, 4, 82, 47, 60, 11, 48, 82, 46, 106, 109, 23, 4] -> OK
2) look up 40 values from 40 key-value pairs given earlier: 40/40 correct
3) copy a 50-token string exactly: 50/50 tokens correct12345678910seed periodic_heldout_L128 recall_L128 copy_L128 periodic_heldout_L256 recall_L256 copy_L256 periodic_heldout_L512 1 0.998 1.000 1.000 0.999 0.972 0.767 0.985 2 0.998 1.000 1.000 0.999 0.948 0.576 0.975 3 0.998 1.000 1.000 0.999 0.954 0.563 0.995 4 0.998 1.000 1.000 0.998 0.953 0.529 0.967 5 0.998 1.000 1.000 0.997 0.961 0.625 0.988 6 0.999 1.000 1.000 0.998 0.959 0.538 0.985Q1: HELD (6/6 seeds meet every threshold; need 5)Q2: FAILED (1/6 seeds meet every threshold; need 5)Q3: HELD (6/6 seeds meet every threshold; need 5)1{"seed": 1, "cfg": {"d_model": 128, "n_heads": 2, "n_layers": 2, "train_lens": [32, 64, 96, 128], "batch": 64, "lr": 0.001, "steps": 6000}, "params": 165120, "scores": {"periodic_heldout_L128": 0.9984326958656311, "recall_L128": 1.0, "copy_L128": 1.0, "periodic_heldout_L256": 0.9987830519676208, "recall_L256": 0.9720180034637451, "copy_L256": 0.7667322754859924, "periodic_heldout_L512": 0.985174298286438, "recall_L512": 0.8795573115348816, "copy_L512": 0.7662401795387268, "periodic_seen_L128": 0.9990339279174805}, "train_seconds": 353}1{"seed": 2, "cfg": {"d_model": 128, "n_heads": 2, "n_layers": 2, "train_lens": [32, 64, 96, 128], "batch": 64, "lr": 0.001, "steps": 6000}, "params": 165120, "scores": {"periodic_heldout_L128": 0.9983630776405334, "recall_L128": 0.9998437762260437, "copy_L128": 0.9999380111694336, "periodic_heldout_L256": 0.9990438222885132, "recall_L256": 0.9483251571655273, "copy_L256": 0.5763615369796753, "periodic_heldout_L512": 0.9746325016021729, "recall_L512": 0.868408203125, "copy_L512": 0.5822670459747314, "periodic_seen_L128": 0.9986889362335205}, "train_seconds": 344}1{"seed": 3, "cfg": {"d_model": 128, "n_heads": 2, "n_layers": 2, "train_lens": [32, 64, 96, 128], "batch": 64, "lr": 0.001, "steps": 6000}, "params": 165120, "scores": {"periodic_heldout_L128": 0.9981192350387573, "recall_L128": 0.9996874928474426, "copy_L128": 1.0, "periodic_heldout_L256": 0.9985222816467285, "recall_L256": 0.953839898109436, "copy_L256": 0.5629921555519104, "periodic_heldout_L512": 0.9947711229324341, "recall_L512": 0.8627116084098816, "copy_L512": 0.5631561875343323, "periodic_seen_L128": 0.9989304542541504}, "train_seconds": 375}1{"seed": 4, "cfg": {"d_model": 128, "n_heads": 2, "n_layers": 2, "train_lens": [32, 64, 96, 128], "batch": 64, "lr": 0.001, "steps": 6000}, "params": 165120, "scores": {"periodic_heldout_L128": 0.9981889128684998, "recall_L128": 0.9996874928474426, "copy_L128": 0.9996899962425232, "periodic_heldout_L256": 0.9980006814002991, "recall_L256": 0.9526143670082092, "copy_L256": 0.5291174650192261, "periodic_heldout_L512": 0.9666106700897217, "recall_L512": 0.8251953125, "copy_L512": 0.5330544710159302, "periodic_seen_L128": 0.9980334043502808}, "train_seconds": 360}1{"seed": 5, "cfg": {"d_model": 128, "n_heads": 2, "n_layers": 2, "train_lens": [32, 64, 96, 128], "batch": 64, "lr": 0.001, "steps": 6000}, "params": 165120, "scores": {"periodic_heldout_L128": 0.9979799389839172, "recall_L128": 1.0, "copy_L128": 0.9999380111694336, "periodic_heldout_L256": 0.997001051902771, "recall_L256": 0.961192786693573, "copy_L256": 0.6246719360351562, "periodic_heldout_L512": 0.988156259059906, "recall_L512": 0.8828938603401184, "copy_L512": 0.6314796805381775, "periodic_seen_L128": 0.9984129071235657}, "train_seconds": 349}1{"seed": 6, "cfg": {"d_model": 128, "n_heads": 2, "n_layers": 2, "train_lens": [32, 64, 96, 128], "batch": 64, "lr": 0.001, "steps": 6000}, "params": 165120, "scores": {"periodic_heldout_L128": 0.9987461566925049, "recall_L128": 1.0, "copy_L128": 1.0, "periodic_heldout_L256": 0.997783362865448, "recall_L256": 0.9585375785827637, "copy_L256": 0.538385808467865, "periodic_heldout_L512": 0.9846702814102173, "recall_L512": 0.861572265625, "copy_L512": 0.5410104990005493, "periodic_seen_L128": 0.9986889362335205}, "train_seconds": 340}12345678910111213"""Apply REGISTRATION.md's bar to the per-seed results. Usage: python3 score.py RESULTS_DIR"""import json, sysfrom pathlib import PathR = [json.loads(p.read_text()) for p in sorted(Path(sys.argv[1]).glob("seed*.json"), key=lambda p: int(p.stem[4:]))]BAR = {"Q1": [("periodic_heldout_L128", .95), ("recall_L128", .95), ("copy_L128", .95)], "Q2": [("periodic_heldout_L256", .95), ("recall_L256", .90), ("copy_L256", .70)], "Q3": [("periodic_heldout_L512", .90)]}print("seed " + " ".join(k for q in BAR.values() for k, _ in q))for r in R: print(f"{r['seed']:>4} " + " ".join(f"{r['scores'][k]:.3f}" for q in BAR.values() for k, _ in q))for q, rules in BAR.items(): ok = sum(all(r["scores"][k] >= t for k, t in rules) for r in R) print(f"{q}: {'HELD' if ok >= 5 else 'FAILED'} ({ok}/{len(R)} seeds meet every threshold; need 5)")123version https://git-lfs.github.com/spec/v1oid sha256:5d39dc8785bf021082de26864edf8012c5bbfd9c8f068f6efc88018f759586c3size 661752123version https://git-lfs.github.com/spec/v1oid sha256:f19fdf2a24ae3040fd6056708985483a8ae4ed3780b713f9d8546dabe8dbbf83size 661752123version https://git-lfs.github.com/spec/v1oid sha256:085b36fa301668a88edf3e241d5310e2e86f49b205be6d0304a1edf4ad22ccaesize 661752123version https://git-lfs.github.com/spec/v1oid sha256:8e6827a6f1d26906723327cfc2c0e61cf8ebd0ed32ebb947ebb14b2e90ce7833size 661752123version https://git-lfs.github.com/spec/v1oid sha256:9d0c81404b735e9581a4264688f46f7cf2afb62b4a671bd1c8528e80451e8fa6size 661752123version https://git-lfs.github.com/spec/v1oid sha256:fe800006a98d8fd2f71fc6c72f72170e2d72feb0e74d6e6c0c9430413626dcddsize 661752README.mdAdded+76
SHA256SUMSAdded+18
demo.pyAdded+42
engine.pyAdded+175
results/demo_seed1.txtAdded+9
results/score.txtAdded+10
results/seed1.jsonAdded+1
results/seed2.jsonAdded+1
results/seed3.jsonAdded+1
results/seed4.jsonAdded+1
results/seed5.jsonAdded+1
results/seed6.jsonAdded+1
score.pyAdded+13
weights/engine_seed1.safetensorsAdded+3
weights/engine_seed2.safetensorsAdded+3
weights/engine_seed3.safetensorsAdded+3
weights/engine_seed4.safetensorsAdded+3
weights/engine_seed5.safetensorsAdded+3
weights/engine_seed6.safetensorsAdded+3