A closed world, small enough to explain an LLM ecosystem completely.
Build, train, run and understand a language model from scratch, in Python.
The model is a real GPT — the same decoder-only Transformer architecture as GPT-2/3, Llama or Claude, shrunk to ~0.8M parameters — and its entire world is Drop-Tac-Toe: Tic-Tac-Toe on a 3x3 board with Connect-Four gravity. It learns the game purely from text transcripts of moves, the way a real LLM learns language purely from text. Because the game is exactly solvable, every question about the model has a ground-truth answer: we can measure what it learned instead of guessing.
Columns are A B C (x-axis), rows 1 2 3 (y-axis, bottom to top). A move
drops a piece into a column; it lands on the lowest free cell and is written
as that cell: A1 is bottom-left, C3 top-right. Pieces never float — C3
is only legal once C1 and C2 are occupied. X moves first; three in a
row (horizontal, vertical, diagonal) wins.
The included solver proves: with perfect play the game is a draw. There are exactly 1,310 possible complete games across 694 reachable positions — a closed world, small enough to enumerate completely.
flowchart LR
D["<b>Data</b><br/>enumerate all<br/>1,310 games"] --> T["<b>Tokenize</b><br/>moves → ids"]
T --> P["<b>Pretrain</b><br/>all games →<br/>learns the rules"]
P --> F["<b>Finetune</b><br/>expert games →<br/>learns to win"]
F --> E["<b>Evaluate</b><br/>vs random +<br/>vs perfect solver"]
F --> Y["<b>Play</b><br/>against it,<br/>interactively"]
| This repo | Real LLM pipeline |
|---|---|
| Enumerate all 1,310 games | Scrape a web-scale text corpus |
| 15-token move-level vocabulary | BPE tokenizer, ~100k tokens |
| Pretrain on all games → learns the rules | Pretraining → learns grammar/facts |
| Finetune on solver-optimal games, opponent moves masked from the loss | SFT — imitate the assistant, mask the user turns |
| Temperature / top-k sampling, legality masking | Decoding strategies, guardrails |
| Legality, refereeing, win-rate metrics | Evals and benchmarks |
inspect_attention.py |
Interpretability research |
Requires uv (or any Python 3.12 — see below). Everything runs on plain CPU.
make setup # create .venv and install torch + pytest
make test # run the unit test suite
make data # enumerate every game (seconds)
make pretrain # learn the rules (minutes on CPU)
make finetune # learn to play well (~2 min CPU)
make eval # measure what it learned (seconds)
make play # play against it!Named scenarios (pretrain/finetune aliases plus the gambler variant),
and the local model zoo:
make model-base # == pretrain
make model-expert # == finetune (minimax imitation)
make model-gambler # finetune, winner-imitation variant
make model-rl-gambler # REINFORCE self-play — strongest vs random (see docs/rl-gambler.md)
make zoo # full {base,expert,gambler} x {move,char} matrix locally
make arena # pit any model against a human, random, solver, or another modelWithout uv:
python3.12 -m venv .venv
.venv/bin/pip install -r requirements.txtMeasured with python -m minillm.evaluate (see runs/eval_pretrain.json
and runs/eval.json; your numbers will match closely — training is seeded):
| Metric | after pretraining | after finetuning |
|---|---|---|
| Top-choice is a legal move (held-out) | 100.0% | 99.5% |
| Free-running legality (first try) | 99.8% | 98.8% |
| Predicts the correct result token | 99.2% | 100.0% |
| vs random player, win / draw / loss | 41.8 / 20.2 / 38.0% | 79.2 / 14.5 / 6.2% |
| vs perfect solver, win / draw / loss | 0 / 0 / 100% | 0 / 61.0 / 39.0% |
| Chooses a solver-optimal move | 70.3% | 86.5% |
The story these numbers tell is the story of modern LLMs: pretraining teaches form (the model plays 100% legally but only imitates the average game — near coin-flip vs a random opponent), finetuning teaches intent (79% wins vs random; 61% draws against the perfect solver, and a draw is the theoretical ceiling). Even the tiny legality dip after finetuning mirrors the real-world "alignment tax".
make play # you are X, model is finetuned
.venv/bin/python -m minillm.play --human O # model opens
.venv/bin/python -m minillm.play --raw --show-probs # watch it think, mistakes allowed
.venv/bin/python -m minillm.play --ckpt runs/pretrain/model.pt # play the rule-learnerIn-game: A/B/C drops a piece, p shows the model's probability
distribution, u undoes, q quits. The model never sees the board — only
the move sequence, exactly as during training.
make sample # model dreams up full games; each is replayed and verified
make attention # attention matrices per layer/head for a game prefixThe Python package keeps the short import name minillm.
minillm/
game.py the rules ("physics" of the toy world) — no ML
solver.py exact negamax solver: ground truth + data generator
tokenizer.py move-level (15 tokens) + char-level (13 tokens) vocabularies
dataset.py corpus enumeration, splits, tensors, SFT loss masking
config.py ModelConfig dataclass
model.py the GPT, from scratch, heavily commented
train.py pretrain + finetune loops (AdamW, warmup+cosine, ...)
sample.py free-running generation + transcript verification
evaluate.py behavioural metrics
play.py interactive play
inspect_attention.py print attention heads
utils.py device, seeding, checkpoint loading
tests/ the test suite: rules, solver, tokenizers, masking, causality, arena
docs/ the guided tour (start at docs/00-overview.md)
data/, runs/ generated artifacts (gitignored, reproducible)
.github/ CI, SAST, secret scan, commit lint, Pages deploy, Dependabot
requirements/ hash-pinned lockfiles for the CI toolchain
mkdocs.yml documentation site config (published to GitHub Pages)
→ Rendered site: https://yves-vogl.github.io/llm-ecosphere/
Read in order — each chapter explains one pipeline stage against this codebase, with "In a real LLM" asides connecting it to production scale:
- Overview
- The game and its exact solver
- From games to a training corpus
- Tokenization
- The Transformer, spelled out
- Training: pretraining and finetuning
- Inference: sampling and playing
- Evaluation: what did it learn?
- Exercises: make it yours
- Lab report: the character-level tokenizer — exercise 1, solved and measured (spoilers!)
- Why GPUs? The hardware under the pipeline
- Lab report: the RL gambler — exercise 10 (REINFORCE self-play), and a measured "alignment tax"
- Lab report: the temperature sweep — exercise 4: the two checkpoints respond to temperature in mirror image
- Multi-seed reruns — the char-vs-move strength claim, re-evaluated across three training seeds
- Lab report: the mirror dedup — exercise 2: pretrain on half the corpus, deduplicated across the A↔C symmetry
- Lab report: the ablations — exercise 3: depth and head count are not load-bearing; position embeddings are, exactly where order matters
- Lab report: the KV cache — exercise 5: opt-in O(T) generation, token-for-token identical to the naive loop
- Lab report: the loss curves — exercise 6: the overfitting drama a single "best val loss" number hides, plotted
- Lab report: the lookup-table baseline — exercise 7: would a hash map have done just as well? (on strength: almost — and where it provably cannot)
- Lab report: the attention-head taxonomy — exercise 8: all 16 heads catalogued; the docstring's three species exist, organized by layer
- Lab report: 4×4 Connect-3 — exercise 9: the world outgrows enumeration, the draw disappears, and eval numbers change their meaning
Use it: get a model and play it · the models in detail · change the training and watch the effect.
For teaching: learning paths + a 3-hour workshop script, and a glossary that grounds every LLM term in this repo's code.
Deep dives: why this exists · anatomy of the model · the mathematics · looking inside — the Logit Lens, the Jacobian Lens and J-space · outlook to frontier models.
Contributions welcome — see CONTRIBUTING.md. PRs go
against main, commits follow Conventional Commits and are GPG-signed.
Security findings go through SECURITY.md, not public issues.
MIT — Copyright (c) 2026 Yves Vogl.