You now know how a net learns, and what a model actually reads. The next question is what a full training loop looks like. nanoGPT was written to answer that in two short files. The README describes train.py as a roughly 300-line training loop and model.py as a roughly 300-line GPT definition, which can optionally load GPT-2 weights from OpenAI. In the current tree, train.py is 336 lines and model.py is 330 lines.
Read this repo for clarity. Do not start a new serious training run with it. An update from November 2025 at the top of the README says nanoGPT is now very old and deprecated, and points you to nanochat, which is lesson 6 of this course.
The shape of the loop
A training loop does the same five things, over and over.
flowchart LR
Batch["Take a batch of token IDs"] --> Forward["Forward pass"]
flowchart LR
Batch["Take a batch of token IDs"] --> Forward["Forward pass"]
Forward --> Loss["Compute the loss"]
flowchart LR
Batch["Take a batch of token IDs"] --> Forward["Forward pass"]
Forward --> Loss["Compute the loss"]
Loss --> Backward["Backward pass"]
Backward --> Step["Optimizer step"]
Step --> Batch
The forward pass is the GPT in model.py. Tokens become embeddings, then a stack of transformer blocks, then a linear layer that predicts the next token. The loss is usually cross-entropy against the next token in the sequence. The backward pass is autograd, now on tensors in PyTorch rather than on micrograd scalars. The optimizer, often AdamW, takes a step down the gradient. That is the loop Hao wanted you to see without a large trainer library in the way.
The sketch below is a teaching outline, not a copy of nanoGPT, and not a model you should expect to be useful. It shows the shape you should be able to recognise in train.py.
import torch
from torch import nn
device = "mps" if torch.backends.mps.is_available() else "cpu"
if torch.cuda.is_available():
device = "cuda"
# token_ids: shape (batch, context + 1), already on device
def train_step(model, optimizer, token_ids):
inputs = token_ids[:, :-1]
targets = token_ids[:, 1:]
logits = model(inputs)
loss = nn.functional.cross_entropy(
logits.reshape(-1, logits.size(-1)),
targets.reshape(-1),
)
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
return loss.item()
What to run on a laptop
The README's professional path trained GPT-2 (124M) on OpenWebText on an 8×A100 node in about four days. That is historical context, and it is not the path you should take in this repo today. The path that still makes sense on a laptop is the character-level Shakespeare example in the README.
git clone https://github.com/karpathy/nanoGPT.git
cd nanoGPT
uv venv --python 3.11
source .venv/bin/activate
uv add torch numpy transformers datasets tiktoken wandb tqdm
uv run python data/shakespeare_char/prepare.py
uv run python train.py config/train_shakespeare_char.py --compile=False
uv run python sample.py --out_dir=out-shakespeare-char --compile=False
The README describes that Shakespeare GPT as a 6-layer model with 6 heads and a context of 256 characters. On one A100 it took about three minutes. On CPU or MPS it will take longer. If torch.compile is not available on your machine, pass --compile=False, which the README also recommends as the workaround.
When you read model.py, keep two papers nearby: Attention Is All You Need and the GPT-2 paper. Lecture 7 is the spoken build: Let's build GPT. Then come back here, because the value of nanoGPT is how small the production-shaped loop can be. When you want to train a chat model with the current pipeline, use nanochat.
Key concepts
- nanoGPT's README describes a roughly 300-line training loop and a roughly 300-line GPT model. The current files are 336 and 330 lines.
- The loop is batch, forward, loss, backward, optimizer step, repeated.
- The model predicts the next token. The loss is cross-entropy on that prediction.
- A November 2025 README update marks nanoGPT deprecated and points to nanochat. Read this repo for clarity, not to start a new large training run.
- The laptop-scale path in the README is character-level Shakespeare.
Takeaways
- Open train.py and model.py and point to where each step of the loop lives.
- If you want to feel a run, use the Shakespeare character example, and disable torch.compile if your machine needs that.
- When you are ready to train a current GPT-2-level chat model, go to nanochat, not to this repo.