nanoGPT model architecture and attention

The model takes a sequence of token IDs and scores possible next tokens. Follow one sequence through embeddings, causal attention, and the output layer.

Read the original model.py

Choose the model's sizes

Seven numbers describe the whole network. block_size is how many tokens fit in one sequence. vocab_size is how many distinct ids exist. n_layer, n_head, and n_embd are depth, heads, and width. dropout and bias are the two training switches. The defaults are a small GPT-2: context 1024, vocabulary padded from 50257 up to 50304, twelve layers, twelve heads, width 768.

Let each token look only left

Causal attention is a lookup that can only see the past. Each token is projected into query, key, and value together, three times the width, then split across heads. Scores are a dot product, scaled down by the square root of the head width so softmax does not saturate, and future positions are masked with negative infinity, or handed to Flash Attention with is_causal. The weighted values are mixed and projected back. A token never reads a later token. That is the entire constraint.

Widen the vector, then squash it

After attention has mixed information across time, each token is still just a vector. This layer expands that vector to four times the width, applies GELU, which lets positive values through and shrinks negative ones, then projects back and drops out. Positions do not talk to each other here. Attention already did that.

Normalize, with an optional shift

LayerNorm here is a per-token rescaling of the last dimension. A learned weight stretches each channel. A learned bias, if bias is on, shifts it. Epsilon is 1e-5 so a token whose channels are almost constant does not divide by zero. The point is to hand attention and the feed-forward layer a vector with a predictable scale.

Add each sublayer back onto the stream

A block does not replace its input. It adds a change. The stream is normalized and attended, and that result is added back. It is normalized again and passed through the wide layer, and that result is added back too. Those additions are the residual connections. The original token vector stays on the skip path while each sublayer contributes a delta.

Stack embeddings, blocks, and a tied word head

This is the module train.py constructs. Token ids and position ids each pick a row from a learned table, those rows are added, and the sum runs through every block, then a final norm. The output head is a linear map from width to vocabulary, and its weight is the same object as the token table. Matrices start near 0.02, and the residual projections are shrunk further as the stack gets deeper, so the residual path does not explode. The parameter count is just the sum of the tensors, printed in millions.

Turn ids into scores, and a loss if targets arrived

forward has two jobs and they share the same trunk. Embeddings plus the stack produce a vector per position. If targets were passed in, those vectors become logits for every position and cross-entropy compares them with the next id. That is the training loss. If there are no targets, only the last position is mapped to logits, because the next sample only needs a distribution at the end of the context.

Shrink a pretrained context

GPT-2 was trained with a context of 1024. If you want a shorter block_size, the position table and the causal mask are larger than you need. This method cuts both down to the new length. It does not retrain anything. It just throws away positions the smaller model will never use.

Copy OpenAI GPT-2 weights in

from_pretrained builds a fresh GPT of the right size, downloads the matching OpenAI weights, and copies tensors across by hand. Some layers are transposed because OpenAI stored them in a different orientation. The token table and the output head share weights here, so one copied tensor fills both roles. Dropout is forced off for a model you are only loading, not training from scratch. After this, the module holds GPT-2's numbers under nanoGPT's names.

Decay matrices, not shifts

Weight decay is a pull toward zero on parameters that are matrices. The layer-norm weights, the biases, and the other one-dimensional vectors are grouped separately and decayed with zero. That split is what configure_optimizers returns. It is easy to miss because it is not part of the forward pass, but it changes which numbers the optimizer is willing to shrink.

Estimate how hard the GPU is working

estimate_mfu is a back-of-the-envelope utilization. It counts the multiplies in the attention and the feed-forward for one token, doubles them for the backward pass, scales by tokens per second, and divides by the GPU's promised FLOPs. The number is a ratio, not a timer. It tells you whether the step is in the neighborhood of the hardware's peak.

Sample the next id, then feed it back

generate is a loop. The context is cropped to block_size, the model scores the last position, those scores are divided by temperature, and optionally only the top-k ids are allowed to win. A multinomial draw picks one id, it is appended, and the loop repeats. Every new id is fed back in. Attention is recomputed from scratch each time. This is the function sample.py calls when it wants text.

Check your understanding

  • What does block_size limit?
  • Where do logits get compared to the next id?

Next chapter · One training step

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