Phase 01/Inside the transformer block/Transformer architecture
PHASE 01 · Inside the transformer block

Transformer architecture

0%
8 h6 subtopics2 lessons · 2 required
In plain English

A transformer is a stack of identical floors in a building. Text enters the ground floor as a row of numbers, one row per token. On each floor, every token first looks around at the other tokens to gather context (attention), then thinks on its own for a moment (a small feed-forward network). The result is passed up to the next floor along a central elevator shaft called the residual stream, which carries a running summary that each floor only adjusts slightly. After the top floor, the numbers for the last token are turned into a guess for the next token. The whole model is this one floor plan repeated 12 to 100 times with different learned settings on each floor.

Why it matters

Every inference optimisation you will meet later (KV cache, FlashAttention, tensor parallelism, quantisation) is a trick applied to one specific block of this architecture. If you cannot name the block and its tensor shapes, you cannot reason about the trick or read the engine's source code.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Crusoe, Databricks, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Draw the decoder-only transformer block from memory with tensor shapes.
  • Explain the role of the residual stream and pre-norm layer normalisation.
  • Derive GPT-2 small's parameter count from its config and match it exactly.
  • Identify which sub-block dominates FLOPs and which dominates memory traffic.
  • Load GPT-2 weights into nanoGPT and verify its logits match Hugging Face.

Key concepts

Decoder-only
The GPT-style variant with only masked self-attention blocks; what all modern chat LLMs use.
Residual stream
The running (T, d_model) vector per token that each block reads from and adds its output to.
Pre-norm
Applying LayerNorm (or RMSNorm) before attention and MLP rather than after; the modern default for stability.
MLP / feed-forward block
Two linear layers with a nonlinearity (GELU or SwiGLU) and a 4x hidden width; holds about two thirds of the parameters.
Forward pass
One run of the input through all blocks producing logits; inference is forward passes only.
Logits
The (T, vocab) unnormalised scores output by the LM head before softmax.
config.json
The file that fixes n_layer, n_head, d_model, vocab and context length, from which every tensor shape follows.

Subtopics

  1. 1. Embedding and unembedding

    Token ids become vectors via a lookup table; the final normalised vectors become logits via a (often tied) projection.

  2. 2. The decoder block

    Pre-norm, masked self-attention, residual add, pre-norm, MLP, residual add; GPT-2 vs Llama differences (LayerNorm vs RMSNorm, GELU vs SwiGLU, RoPE).

  3. 3. Shapes and parameter count

    Derive parameter count from d_model, n_layer, n_head and vocab; check against GPT-2 small's 124,439,808.

  4. 4. FLOPs per token

    Roughly 2*N FLOPs per token for N non-embedding parameters plus attention's 4*T*d per layer; which term wins at which T.

  5. 5. The forward pass as a program

    Reading nanoGPT's GPT.forward line by line as a sequence of tensor ops with shapes annotated.

  6. 6. Greedy decoding loop

    Take argmax of the last logit row, append, repeat; the simplest generation loop and the baseline for everything in m3.

Resources

repo
tutorial

Hands-on lessons

L1

Trace one token through GPT-2 small

CPU · your Macnotebook90 minrequired

Goal · Print the shape of every intermediate tensor for one forward pass of GPT-2 small and reproduce the parameter count from the config.

  1. 1pip install torch transformers; load gpt2 with AutoModelForCausalLM and print model.config.
  2. 2Register forward hooks on every nn.Module and log (qualified name, output shape) in order.
  3. 3Run the prompt 'The GPU is' and collect the log into a table.
  4. 4Hand-derive the expected shapes of wte, wpe, ln_1, c_attn, c_proj, c_fc, mlp.c_proj, ln_f and lm_head from config.json and compare.
  5. 5Write params(config) implementing the formula and compare with sum(p.numel() for p in model.parameters()).
  6. 6Implement a 20-step greedy decoding loop with argmax and confirm it matches model.generate(do_sample=False).
Deliverable
A notebook with the shape table, the formula and a markdown cell explaining any surprises (such as Conv1D weight layout).
Check
Your formula returns 124,439,808 exactly; every hooked shape matches your prediction; your greedy loop and generate produce identical token ids.
L2

Annotate nanoGPT and match Hugging Face logits

CPU · your Macreading-code90 minrequired

Goal · Produce a fully shape-annotated copy of nanoGPT's model.py and prove it computes the same function as the Hugging Face GPT-2.

  1. 1Clone karpathy/nanoGPT; open model.py and add a comment with the tensor shape after every line in CausalSelfAttention.forward, MLP.forward, Block.forward and GPT.forward.
  2. 2Call GPT.from_pretrained('gpt2') and load the Hugging Face gpt2 model.
  3. 3Run the same 32-token input through both and compare logits with torch.allclose(atol=1e-4).
  4. 4Count FLOPs for one forward at T=32 using 2*params_per_token plus attention terms; compare with nanoGPT's estimate_mfu formula.
  5. 5Swap the GELU in MLP for ReLU and observe the logit difference to confirm you edited the live path.
Deliverable
The annotated model.py and a script printing the max logit difference.
Check
Max absolute logit difference between nanoGPT and Hugging Face is below 1e-4 before your ReLU edit and well above it after.

Build your own

Build your own GPT-2 forward pass

PythonCPU · your Mac~7 h

A complete GPT-2-small decoder in plain PyTorch, loading the Hugging Face weights and matching its logits to 1e-4, ending with a greedy generation loop.

The real thing: github.com/karpathy/nanoGPT/blob/master/model.py ↗

How you know a stage passes

Write tests/test_gpt2.py first. Every stage registers a forward hook on the matching Hugging Face GPT2LMHeadModel module and asserts your intermediate tensor matches it (torch.allclose, atol 1e-4) on the same 32 real tokens; the parameter-count stage asserts on an integer. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01embeddings in
    Token and position embeddings load from the Hugging Face state dict and sum into the [B, T, 768] residual stream.
    test · Your embedding output matches the hook on transformer.drop input at atol 1e-5; the two tables have exactly 50257 * 768 and 1024 * 768 parameters.
  2. 02LayerNorm and the MLP
    A hand-written LayerNorm (mean, var, eps 1e-5) and the fc, GELU (tanh approximation), proj MLP work on the stage-1 output.
    test · Block-0 MLP output matches the transformer.h.0.mlp hook at atol 1e-4; replacing tanh-GELU with exact erf GELU moves the max difference above 1e-3.
  3. 03the attention sublayer
    The fused c_attn projection splits into Q, K, V, runs causal multi-head attention and projects through c_proj.
    test · Block-0 attention output matches the transformer.h.0.attn hook at atol 1e-4 on 32 tokens.
  4. 04a full block and the stack
    Pre-norm residual block x + attn(ln1(x)) then x + mlp(ln2(x)), stacked 12 times, then ln_f.
    test · Hidden state after block 11 matches the transformer.ln_f output at atol 1e-4; your model reports exactly 124,439,808 parameters when counting the tied unembedding once.
  5. 05logits and the loss
    The tied unembedding produces [B, T, 50257] logits and a cross-entropy over shifted targets.
    test · Max absolute logit difference against GPT2LMHeadModel is below 1e-4 on 32 tokens; your loss equals the Hugging Face loss within 1e-4.
  6. 06generate
    `python generate.py --prompt 'The capital of France is' --max-new 32` runs greedy decoding with a FLOP counter printed per token.
    test · Your 32 greedy tokens equal Hugging Face generate() with do_sample=False; the printed FLOPs per token are within 10 percent of 2 * 124M plus the attention term you derive.

Knowledge check

QWhich block holds most of the parameters in a standard transformer, attention or MLP?

The MLP; it has roughly 8*d_model^2 parameters per layer versus 4*d_model^2 for attention.

QWhy is the residual stream important for deep stacks?

It gives information a direct path through all layers, so each block only has to learn a small correction and the model stays trainable at depth.

QWhat does the unembedding produce?

Logits: one unnormalised score per vocabulary entry for the next token.

QFor a short prompt, which dominates FLOPs, the linear layers or QK^T?

The linear layers; attention's T^2 term only overtakes 2*N when T is on the order of d_model times a constant, thousands of tokens for GPT-2.

QName three differences between a GPT-2 block and a Llama block.

LayerNorm vs RMSNorm, learned absolute positions vs RoPE, GELU MLP vs gated SwiGLU MLP (and Llama has no biases).

Completion

  • All 6 subtopics marked done
  • All 2 required lessons done
  • All subtopics marked completed.
  • Lessons l1 and l2 checks pass.
  • Can draw the block diagram with shapes for GPT-2 small from memory.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →