How the nanoGPT training loop works

One pass through the training loop compares nanoGPT’s predictions with the actual next characters and uses the loss to update the weights.

Read the original train.py

Start from GPT-2 sized defaults

Before any loop, train.py is a pile of globals: where the weights come from, which dataset folder to read, how big a batch is, the learning-rate schedule, how often to evaluate and save, and which dtype to use on the GPU. The numbers you see are a GPT-2-scale run. They are not what the small Shakespeare lesson uses. A later file replaces them.

Use one GPU, or share the step across many

Distributed training here is optional. If the world size is 1, this is a normal single-process script. If it is more, each process owns a slice of the data and a copy of the model, and gradients are averaged. gradient_accumulation_steps lets a small micro-batch stand in for a large one: several forwards add up before AdamW steps once. The effective batch is micro-batch times accumulation times the number of processes.

Read a window of ids and the ids that follow

get_batch memory-maps train.bin or val.bin and picks random start positions. Each example is block_size ids, and the target is that same window shifted by one. The model sees x and is scored against y. Nothing in this function knows about letters. It only knows integer ids already on disk.

Take the vocabulary from the dataset, if it saved one

If meta.pkl exists, its vocab_size overrides the default. That is how a 65-character model does not accidentally build a 50,304-wide output table. If the pickle is missing, the script keeps the GPT-2-sized vocabulary it started with. This is a few lines, and they are the bridge from the prepare script to the module you just read.

Build a new model, resume, or load GPT-2

init_from has three doors. scratch constructs GPT(GPTConfig(...)) with the globals above. resume loads a checkpoint from the output directory and rebuilds the module from the args that were saved with it. A name starting with gpt2 calls the from_pretrained path inside model.py. After this branch, model is a module on the chosen device, in train mode, ready to take a loss.

Scale gradients, compile, and wrap extra GPUs

float16 training needs a GradScaler so small gradients do not underflow. bfloat16 and float32 do not. torch.compile, if enabled, replaces the module with a compiled one. If several processes are alive, DDP wraps the model so the backward pass averages gradients. The raw module is kept under a separate name because saving a checkpoint should store the unwrapped weights.

Score both splits without changing weights

estimate_loss puts the model in evaluation mode with eval(), averages the loss over many batches of each split, then switches back with train(). Dropout is off during the measurement, which is the point of evaluation mode. No optimizer step happens here. The two numbers, train and val, are what the log line and the "is this the best checkpoint" test use.

Warm the learning rate, then cosine down

get_lr is a formula of the step index. During warmup it climbs linearly from a small fraction of the peak toward the peak. After warmup it cosine-decays from the peak down to min_lr, and then it sits on that floor. The function does not change any weights. The training loop calls it and writes the number into AdamW.

Open an optional run log

If wandb is enabled, the script opens a run so later loss numbers have somewhere to go. If it is disabled, this block is a no-op. The small character config leaves it off, so you can ignore it on a first read and not miss the training step.

Set the rate, score, and save a checkpoint

The top of the loop is bookkeeping around the step. The learning rate for this iteration is written onto every parameter group. On the evaluation interval, both splits are scored and the master process may save ckpt.pt, including the model args, the weights, and the optimizer, when val loss is the best so far. The forward that produces the training loss is the same forward you read in model.py.

Accumulate gradients, clip, and step

A micro-batch is one forward and backward. If accumulation is greater than one, those gradients sum, and AdamW waits until the last micro-batch. The summed gradient is clipped so a single wild batch cannot kick the weights too far. Then the scaler steps the optimizer and the gradients are zeroed. One "iter" in the log is one of those optimizer updates, not one forward.

Time the step, then stop at the horizon

After the optimizer step, the script times how long it took and estimates tokens per second. That rate is what the earlier FLOP estimate would use. When the iteration count hits max_iters, the loop ends. On a normal small run the files in the output directory are the model you will sample from. Nothing here prints Shakespeare. It only writes weights.

Check your understanding

  • What does gradient accumulation change about batch size?
  • When does the learning rate schedule matter?

Next chapter · Text out the other side

Based on Andrej Karpathy’s nanoGPT, licensed under the MIT license.