My try at building an LLM from scratch

How Hedwig learns

What I built on a MacBook Air, why a laptop wasn't enough, why rented GPUs are 26× faster, how Hedwig grew to 286.7M knobs for $2.45, and how it compares to GPT & Claude.

13.8M Mac · $097.6M A40 · $0.65286.7M 4090 · $1.7098.3% win rate
Prologue · Two films, one owl

Watch the 60-second journey first

The launch film covers the whole arc from zero knobs to 286.7M on rented GPUs for under $3. The second film, Pip and the Lost Key, was written word for word by the 286.7M brain.

🎬 Launch film · 60 s · made in code with Remotion
📖 Pip and the Lost Key · 84 s · story by 286.7M Hedwig
Step 1 · End-to-end flow

How I built my own LLM from scratch

No Hugging Face Trainer, no Lightning, no API shortcuts. Every stage is written by hand in plain PyTorch — proved on a MacBook Air first, then scaled on rented NVIDIA GPUs:

Real 4,096-vocab BPE split (69 letters → 19 word-pieces):

'Once'' upon'' a'' time'','' a'' little'' owl'' named'' H''ed''w''ig'' found'' a'' shiny'' golden'' key''.'

Hedwig v1 guessed one letter at a time (65 symbols). Building a 4,096-piece BPE tokenizer from scratch (tokenizer.py) glued common words together (3.87 letters/piece), packing ~1,000 characters of story into a 256-slot context window.

Step 2 · What a knob is

A knob is just one number

Inside Hedwig there are numbers like 0.37 or -1.2. Each one nudges a guess a little. Turn it one way and "key" gets more likely; turn it the other way and "x" does. Engineers call these numbers parameters or weights. We call them knobs.

Try it: one knob, three guesses

Drag the slider. When the knob is set right, the green bar (the right guess) is the biggest.

Step 3 · What training is

Turning millions of knobs automatically

1 · Read

Show stories

Take 32 pages × 256 word-pieces from train.bin.

2 · Guess

Predict

Guess every next word-piece using today's knobs.

3 · Check

Score it

Measure how wrong it was (cross-entropy loss).

4 · Nudge

Turn knobs

Backprop + AdamW nudge every knob slightly.

Try it: let the computer train the knob

Step 0 · knob -2.0 · wrongness 2.31

Step 4 · Mac M4 curves

What I built on the MacBook Air M4 ($0)

I started with character-level Shakespeare (4.8M knobs), upgraded one piece at a time (RoPE → RMSNorm → SwiGLU → bf16 → SDPA), and trained a 13.8M storyteller on TinyStories + 10 public-domain novels:

Part of the 13.8M Mac brainModern upgrade & what it doesKnobs
Word-piece dictionary (tok)Turns each of 4,096 BPE pieces into a 384-number thought vector1,572,864
Rotary Position (RoPE)Rotates Query/Key vectors like clock hands for relative distance (~1/3 faster convergence)0 (pure math!)
6 modern layers (Block × 6)RMSNorm + 6-head SDPA attention + gated SwiGLU MLP in 16-bit bf1610,630,656
Final norm & guesser (head)Scores all 4,096 word-pieces for the next-word prediction1,577,344
Total (tinygpt.py)13,780,864 (≈13.8M)
Step 5 · Read, answer, taste, shrink

The 3 stages of ChatGPT + 4-bit compression on Mac

After pretraining (1.795), I taught Hedwig chat manners (sft.py), preference taste (dpo.py — where it tried to cheat and got caught!), and packed 4-bit compression (quantize.py):

Reward Hacking Bug · DPO Run 1

"Lily loves Lily's key. Lily does Lily's mom's idea..."

Without a fluency anchor, pure DPO hit 89.6% win-rate by stuffing "Lily's" into every third word to game the score while breaking grammar.

Fluency Anchor Fix · DPO Run 2

0.5 × chosen NLL stopped the cheat

Adding a Llama-3-style fluency anchor forced Hedwig to prefer 👍 over 👎 while still speaking clean English. Peak win-rate jumped to 92.5% (loss 1.297).

Brain File (13.8M)PrecisionFile SizeShrinkMeasured Score
32-bit baselinefloat32 (4 bytes/knob)55.52 MB1.00×1.4530 (chat) / 1.4666 (taste)
brain_chat.pt / brain_dpo.ptbfloat16 (2 bytes/knob)27.78 MB2.00×1.4530 / 1.4666 (92.5% peak win)
brain_chat_int8.pt / brain_dpo_int8.ptint8 (-127..+127, 1 byte/knob)14.00 MB3.96×1.4531 / 1.4667 (+0.0001)
brain_chat_int4.pt / brain_dpo_int4.ptint4 (-7..+7, 2 knobs/byte!)7.87 MB7.05×1.4765 / 1.4897 (+0.023)
Step 6 · Why Mac wasn't enough & GPU speed

Why the Mac hit a wall — and why rented GPUs are 26× faster

Training work scales as FLOPs ≈ 6 × knobs × tokens. Reading the full 1.92 GB TinyStories shelf on a fanless MacBook Air M4 takes ~20 hours and heats up (throttling from 66s → 110s per 250 steps). Worse, a 14M brain with a 4k dictionary chops rare names apart. So I rehearsed cloud_train.sh --dry-run (2 steps in 92s) and rented RunPod GPUs:

Same 50 MB lesson (13.8M knobs, 3,000 steps) — live speed race

MacBook Air M4 ($0)8-core laptop GPU · fanless thermal throttle
~59 min (3,540 s)
Rented RTX A5000 ($0.10)1× data-center GPU · $0.28/hr
135 s · 26× faster!
Why data-center GPUs fly

Tensor Cores + FlashAttention + VRAM

NVIDIA GPUs pack thousands of Tensor Cores tuned for bf16 matrix math, run fused CUDA FlashAttention kernels in fast on-chip SRAM, push hundreds of GB/s across 24–48 GB VRAM, and never thermally throttle.

Why 4,096 vocab broke "Harry Potter"

Try switching dictionary size

Step 7 · How much we improved ($2.45)

13.8M vs 97.6M vs 286.7M side by side

Each model uses a different dictionary (4k vs 8k vs 16k), so raw reading scores aren't on the same scale. Reading the real outputs on the same fixed prompt (seed=42, temp=0.65) from STORY_SHOWDOWN.md shows the jump:

MetricMac Hedwig (13.8M)Cloud Hedwig (97.6M)Flagship Hedwig (286.7M)
Layout (layers × width × heads)6 × 384 × 612 × 768 × 1220 × 1024 × 16
Context / Vocabulary256 / 4,096256 / 8,192512 / 16,384
Hardware & CostMac M4 · $0.001× A40 (66m) · $0.651× 4090 (115m) · $1.70
Tokens seen (per knob)~125M (~9 / knob)~164M (~1.7 / knob)~205M (~0.7 / knob)
Stage 2 Chat SFT / Stage 3 DPO1.438 / 92.5%1.336 / 96.7%1.341 / 98.3%
4-bit size7.9 MB55.2 MB161.9 MB
Step 8 · Mac Lab experiments ($0)

Everything else tested on the MacBook Air

ExperimentScriptMeasured result
Mixture-of-Experts (8 experts, top-2)moe.py26.2M total / 11.6M active knobs per word; loss 2.461 → 1.966
Baby Hedwig (Distillation)distill.py3.4M student distilled from 13.8M teacher (6.8 MB); loss 7.602 → 2.521
Apple MLX vs PyTorchmlx_bench.py16-bit practice step 596 ms → 99 ms (6× faster); generation 635 → 832 tok/s
SSD layer streamingssd_runner.pyWeights in RAM 52.9 MB → 18.8 MB; speed 108 → 33 tok/s; identical story
iPhone Core ML exportexport_iphone.py27.7 MB Core ML brain matched PyTorch 30/30 pieces + Swift tokenizer
French Hedwiglang_hedwig.pySeparate 2.56M French brain on Dumas + Verne; val 7.776 → 3.541 in 57 s
Step 9 · Hedwig vs GPT & Claude

Same recipe, completely different GPU clusters

ChatGPT and Claude train with the same three stages (Pretraining → SFT → DPO/RLHF) and the same core Transformer blocks. What makes frontier models dramatically smarter isn't a secret algorithm — it is reading 20+ tokens per knob across 15+ trillion tokens on 10,000 to 100,000+ GPUs wired together over InfiniBand/NVLink:

ModelKnobsGPUs UsedTokens ReadTokens / KnobCost (est.)
Mac Hedwig13.8M1× MacBook Air M4~125M~9.0$0.00
Cloud Hedwig97.6M1× NVIDIA A40~164M~1.7$0.65
Flagship Hedwig286.7M1× NVIDIA RTX 4090~205M~0.7$1.70
GPT-2 Small (2019)124M32× Cloud TPU v3~10B~80~$1k–$5k
GPT-3 (2020)175B~1k–10k× V100~300B~1.7~$4.6M
Llama 3 (2024)405B16,384× H10015.6T~38.5~$50M+
Frontier (GPT-4/5 · Claude Opus)1T+ (est.)10k–100k+ H100/B20010T–20T+~20+ & RL$50M–$500M+
Step 10 · What I learnt

Five lessons written down from real numbers

1

Change one thing at a time and measure it

Twice an upgrade hurt locally: 512-BPE overfit Tiny Shakespeare after step 750 (3.007 → 3.429), and RMSNorm ran 30% slower than LayerNorm on Apple mps (419 ms vs 323 ms) because Metal didn't fuse RMSNorm yet.

2

A rising score can be a lie (Reward Hacking)

Even at 14M knobs, pure DPO gamed the score by putting "Lily's" in every third word. Pairing preference loss with an SFT fluency anchor closed the loophole cleanly.

3

Reading beats knob count (Chinchilla in action)

286.7M won on multi-part stories, yet 97.6M (~1.7 tokens/knob) fixed "I goes" → "I go" better than under-read 286.7M (~0.7 tokens/knob, stopped at $1.70).

4

Compare stories, not raw scores across vocabs

4k, 8k, and 16k tokenizers create three different quiz scales. Reading real outputs side-by-side on fixed prompts is the only fair test.

5

Rehearse locally before renting cloud GPUs

Running --dry-run on the Mac for 92 seconds caught path and resume bugs for $0, so all three RunPod runs succeeded on the first try for $2.45 total.

Built from scratch in pure PyTorch · github.com/ansarbuilds/hedwig · try it in your browser · 6-act case study