Capstone 5: nanochat end to end
Part 5 took the GPT from Part 4 through every stage of a modern language model: making it fast, scaling it, cleaning its data, fine-tuning it to chat, aligning it, evaluating it. nanochat is Andrej Karpathy’s single, minimal repository that does all of those stages end to end: a BPE tokenizer, pretraining, supervised fine-tuning, reinforcement learning, evaluation, and a chat interface with a KV-cached inference engine. Its reference run trains a model that beats GPT-2 on the DCLM CORE benchmark in about two hours on a node of eight H100 GPUs. This capstone has three parts: read it, run it at the scale of a free GPU, and swap in one stage of your own.
1. Read it
Section titled “1. Read it”Read the repository’s README, then the files below in pipeline order, the way runs/speedrun.sh calls them. For each one, find the Glassbox module where you built the same idea, and note what nanochat does differently and why.
| nanochat file | What it does | Where you built it |
|---|---|---|
nanochat/tokenizer.py, scripts/tok_train.py |
GPT-4-style BPE (32,768 tokens) with special tokens for chat and tool use; render_conversation returns ids and a training mask |
4.1, 5.8 render_chat |
nanochat/dataset.py, nanochat/dataloader.py |
Downloads pretraining shards and streams tokenized batches across GPUs | 5.5, 5.3 |
nanochat/gpt.py |
The transformer: RoPE, RMSNorm without weights, QK norm, ReLU² MLP, grouped-query attention, sliding-window layers, logit soft-capping | 4.5, 4.6, 5.6, 5.7 |
nanochat/optim.py |
AdamW for embeddings, Muon (orthogonalised momentum) for weight matrices | 3.3 for AdamW; Muon is new |
scripts/base_train.py |
One dial, --depth, sets width (depth × 64), heads, batch size and training length for a compute-optimal run |
5.1, 5.4 |
nanochat/loss_eval.py, nanochat/core_eval.py, scripts/base_eval.py |
Bits per byte, and the CORE benchmark score | 5.12 |
scripts/chat_sft.py |
Fine-tuning on a mixture of conversations, multiple-choice and maths tasks | 5.8 |
scripts/chat_rl.py |
Policy-gradient RL on GSM8K maths problems | 5.10 |
nanochat/engine.py, scripts/chat_cli.py |
Batched generation with a KV cache, a Python tool, temperature and top-k sampling | 5.7, 4.6 |
scripts/chat_eval.py, tasks/ |
ARC, MMLU, GSM8K and HumanEval-style tasks for the chat model | 5.12 |
Two places reward a slow read. chat_rl.py explains in its docstring why it simplifies GRPO: no KL penalty, no ratio or clipping because each batch is used once, a token-level average, and advantages that subtract the mean without dividing by the standard deviation. Compare each choice with your 5.10 functions. And base_train.py shows how a single depth setting becomes a whole family of compute-optimal models, the 5.4 idea turned into code.
2. Run it on a free GPU
Section titled “2. Run it on a free GPU”The reference run needs eight 80 GB GPUs. A free Kaggle T4 has 16 GB and no bfloat16, so you will train a much smaller model, as runs/runcpu.sh does on a laptop. That script is the best template: it trains the tokenizer, pretrains a 6-layer model with a 512-token context, evaluates it, and fine-tunes it. On a Kaggle notebook with a GPU:
git clone https://github.com/karpathy/nanochat && cd nanochatpip install uv && uv sync --extra gpu && source .venv/bin/activatepython -m nanochat.dataset -n 8python -m scripts.tok_train && python -m scripts.tok_evalpython -m scripts.base_train --depth=6 --head-dim=64 --window-pattern=L --max-seq-len=512 \ --device-batch-size=32 --total-batch-size=16384 --core-metric-every=-1 --num-iterations=5000Read the README’s notes on precision first: on a T4 nanochat computes in float32 by default, and NANOCHAT_DTYPE=float16 turns on float16 with gradient scaling (the README says RL does not support it yet). If you run out of memory, lower --device-batch-size; gradient accumulation keeps the total batch the same. Kaggle sessions stop after 12 hours, so save checkpoints to the notebook’s output and resume with --resume-from-step. Then run base_eval, chat_sft and chat_eval, and talk to your model with chat_cli.
Record validation bits per byte, the CORE score and the chat evaluation results, each with its training time and FLOPs. Then make the model deeper, within your GPU budget, and plot bits per byte against compute for two or three depths: your own small scaling study, to set beside 5.4.
3. Replace one stage with your own
Section titled “3. Replace one stage with your own”Pick one, change nanochat to use your Glassbox code, and measure the difference with error bars from your 5.12 harness:
- RL. Run
chat_rl.pyafter SFT, then swap its loss for your 5.10policy_gradient_lossandgroup_normalized_advantages(clipping, standard-deviation scaling, sequence or constant normalisation) and compare GSM8K accuracy and pass@k. - LoRA. Fine-tune with your 5.11
add_lorainstead of updating every weight, and compare chat evaluation results, memory and forgetting (bits per byte on pretraining data). - Preferences. Build on-policy preference pairs from the SFT model’s own answers to GSM8K and train with your 5.9
dpo_loss. - Inference. Check
engine.py’s KV cache against your 5.7attention_step, then add your int8 weight quantization and measure speed and accuracy.
Write-up
Section titled “Write-up”Write two pages: what you trained and how long it took, the results with confidence intervals, your scaling plot, what your replacement changed, and the three things in nanochat that surprised you most. Name what you could not run and why.
Learner log: time spent and points of confusion
Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.