Skip to content
Transformers and LLMs Foundation 9 min read

Large language models at 2,000 ft

A large language model is one function — given some tokens, output a probability for every possible next token — built from one repeated block and trained on one objective at enormous scale. This track takes that function apart: tokens, attention, the block, positions, the objective, the data, the scaling laws, decoding, and the engineering and research that push it further.

10,000 ft

The transformer (2017) is the architecture of the AI boom. Every frontier language model, most image and video generators, speech recognisers and protein-structure models are transformers or close relatives. Three properties made it win: attention lets any token read any other in one step; the whole sequence is processed in parallel, so training saturates GPUs; and its quality improves predictably with scale, so money and data could be turned into capability with confidence. This track is the core of the site. Below it sit the maths and deep learning it is built from; above it sit post-training (how a raw predictor becomes an assistant), AI systems (how it is trained and served on real hardware) and LLM application engineering (how products are built on it). If you understand every page here, you can read almost any LLM paper.

2,000 ft

An LLM, from the outside in:

  1. Tokenise: text becomes a sequence of integer ids from a vocabulary of 50K–200K subword pieces.
  2. Embed: each id becomes a vector of width \(d\) (768 in GPT-2 small, 16,384 in Llama 3 405B).
  3. Transform: \(L\) identical blocks (12 to 126) update every vector. In each, attention moves information between positions and an MLP transforms each position on its own; both add their output to a running residual stream.
  4. Predict: the final vector at each position is projected to one score per vocabulary entry; softmax turns the scores into a probability distribution over the next token.
  5. Train: adjust all parameters to raise the probability of the token that actually came next, over trillions of tokens of text — the language-modelling objective.
  6. Generate: sample a token from the distribution, append it, run again. Every chat response is this loop.

One forward pass, and the loop that turns it into text
One forward pass, and the loop that turns it into text. Text so far, Tokeniser → ids, Embedding + position, L × transformer block attention + MLP, Norm → unembed → logits, softmax → sample next token, append, repeatOne forward pass, and the loop that turns it into text. Text so far, Tokeniser → ids, Embedding + position, L × transformer block attention + MLP, Norm → unembed → logits, softmax → sample next token, append, repeat

What an LLM is

A next-token predictor. Given tokens \(t_1, \dots, t_n\), the model outputs \(p_\theta(t_{n+1} \mid t_1, \dots, t_n)\) for every token in the vocabulary. By the chain rule of probability, \(p(t_1, \dots, t_N) = \prod_i p(t_i \mid t_{<i})\), so a perfect next-token predictor is a perfect model of text. Training minimises the cross-entropy \(-\sum_i \log p_\theta(t_i \mid t_{<i})\) over a huge corpus (see the language-modelling objective and, for the theory, entropy and cross-entropy). Shannon used human next-letter prediction to estimate the entropy of English in 1951; Bengio et al. trained a neural next-word predictor in 2003 (JMLR). The transformer made the idea scale.

Why prediction produces capability. To predict the next token of a physics textbook, a legal contract or a Python file well, it helps to model the physics, the law and the program. Nothing in the objective asks for reasoning, translation or arithmetic; they emerge because they reduce prediction error on text that contains them. GPT-3 showed that a large enough predictor can perform new tasks from a few examples placed in its prompt ("in-context learning") without any weight updates (Brown et al., arXiv:2005.14165).

From predictor to assistant. A raw pre-trained model continues documents; it does not follow instructions. Post-training — supervised fine-tuning on demonstrations, then reinforcement learning from human preferences or from verifiable rewards — turns it into an assistant (Ouyang et al., InstructGPT, arXiv:2203.02155). The architecture in this track is unchanged by post-training; only the weights move.

The life cycle of a language model
The life cycle of a language model. Web, books, code (trillions of tokens), Train tokeniser, Pre-training next-token loss, Base model, Post-training SFT → RLHF / RLVR, Assistant model, Serving KV cache, batching, samplingThe life cycle of a language model. Web, books, code (trillions of tokens), Train tokeniser, Pre-training next-token loss, Base model, Post-training SFT → RLHF / RLVR, Assistant model, Serving KV cache, batching, sampling

The numbers that anchor everything

Three formulas carry most back-of-envelope reasoning about LLMs (derived on the transformer block page):

  • Parameters: \(N \approx 12\,L\,d^2\) (plus the embedding tables).
  • Training compute: \(C \approx 6ND\) FLOPs for \(N\) parameters and \(D\) training tokens.
  • Inference compute: \(\approx 2N\) FLOPs per generated token, and you must hold the weights (2 bytes each in 16-bit) plus a KV cache in memory.

Checking them against published models:

Model Parameters \(N\) Training tokens \(D\) \(6ND\) Reported
GPT-3 (2020) 175B 300B \(3.15 \times 10^{23}\) \(3.14 \times 10^{23}\) FLOPs
Chinchilla (2022) 70B 1.4T \(5.9 \times 10^{23}\) same budget as 280B Gopher
Llama 3 405B (2024) 405B 15.6T \(3.79 \times 10^{25}\) \(3.8 \times 10^{25}\) FLOPs
DeepSeek-V3 (2024) 671B total, 37B active 14.8T \(3.3 \times 10^{24}\) (active) 2.788M H800 GPU-hours

The rule of thumb lands within 1% for dense models. For a mixture-of-experts model like DeepSeek-V3, only the active parameters per token count; dividing \(3.3 \times 10^{24}\) FLOPs by 2.788 million GPU-hours gives an average of about 330 TFLOP/s per GPU actually delivered — the kind of sanity check you should be able to do in your head after this track (the full treatment is in compute maths). Chinchilla's lesson, covered in scaling laws, is that for a fixed budget GPT-3 was too big and trained on too little data; the budget is better split as roughly 20 tokens per parameter.

The map of this track

The track has three units. Unit 1 builds the architecture; unit 2 trains it and makes it talk; unit 3 makes it efficient and follows the frontier.

Units 1–2: from tokens to a trained, talking model
Units 1–2: from tokens to a trained, talking model. Tokenisation and BPE, Attention from first principles, Multi-head attention, Positional encoding, The transformer block, Language-modelling objective, Pre-training data, Scaling laws, Build a GPT from scratch, Decoding and samplingUnits 1–2: from tokens to a trained, talking model. Tokenisation and BPE, Attention from first principles, Multi-head attention, Positional encoding, The transformer block, Language-modelling objective, Pre-training data, Scaling laws, Build a GPT from scratch, Decoding and sampling
Unit 3: efficiency and the frontier
Unit 3: efficiency and the frontier. The transformer block (unit 1), Build a GPT (unit 2), KV cache, FlashAttention, MQA / GQA / MLA, Long context, Mixture of experts, Beyond transformers: SSMs, Mamba, linear attention, Reasoning models and test-time compute, linear-time alternativesUnit 3: efficiency and the frontier. The transformer block (unit 1), Build a GPT (unit 2), KV cache, FlashAttention, MQA / GQA / MLA, Long context, Mixture of experts, Beyond transformers: SSMs, Mamba, linear attention, Reasoning models and test-time compute, linear-time alternatives

How to work through this track

Study the pages in order; each assumes the ones before. Times are for studying properly — reading, running the code, answering the questions — not skimming.

  1. Unit 1, the architecture (about 6 hours). Tokenisation (50 min) → attention (75 min) → multi-head attention (60 min) → the transformer block (70 min) → positional encoding (70 min). Checkpoint: you can draw a decoder block from memory, write scaled dot-product attention in NumPy, and count GPT-2's parameters.
  2. Unit 2, training and generation (about 8 hours, half of it hands-on). The language-modelling objective → pre-training data → scaling laws → build a GPT from scratch → decoding and sampling. Checkpoint: you have trained a small GPT on your laptop and can explain why its loss curve looks the way it does. Pair it with Project: build and train a tiny GPT.
  3. Unit 3, efficiency and frontier (about 6 hours). KV cache and efficient attention → long context → mixture of experts → beyond transformers → reasoning models. Checkpoint: given a model card, you can estimate its memory footprint, decoding speed bottleneck and training cost.

If you only have one evening

Read this page, then attention up to "The maths", then watch Karpathy's Let's build GPT. You will have the right mental model; the rest of the track makes it exact.

Every page in the track

  • Tokenisation and BPE


    How text becomes integers: byte-level BPE, pre-tokenisation, and why tokenisers explain glitch tokens, bad arithmetic and multilingual cost.

  • Attention from first principles


    \(\operatorname{softmax}(QK^\top/\sqrt{d_k})V\) derived from requirements, with a worked example, the √d_k proof and the backward pass.

  • Multi-head attention


    Many low-rank heads for the price of one; QK and OV circuits; a hand-built induction head; MQA, GQA and MLA.

  • The transformer block


    Residual stream, pre-norm, RMSNorm, SwiGLU; every one of GPT-2's 124,439,808 parameters accounted for.

  • Positional encoding


    Sinusoids, relative biases, RoPE derived from one requirement, ALiBi, NoPE, and how context windows are stretched.

  • The language-modelling objective


    Next-token cross-entropy, teacher forcing, perplexity, and why prediction yields capability.

  • Pre-training data


    Where trillions of tokens come from and how they are filtered, deduplicated and mixed.

  • Scaling laws


    Kaplan to Chinchilla and beyond: how loss falls with parameters, data and compute.

  • Build a GPT from scratch


    Assemble everything into a trainable GPT and train it.

  • Decoding and sampling


    Greedy, beam, temperature, top-k, top-p: turning distributions into text.

  • KV cache, FlashAttention, MQA/GQA/MLA


    Why generation is memory-bound and how attention is made cheap.

  • Long context


    From 2K to millions of tokens: what changes, and what "using" long context means.

  • Mixture of experts


    Many MLPs and a router: more parameters without more compute per token.

  • Beyond transformers


    State-space models, Mamba and linear attention: the challengers to quadratic attention.

  • Reasoning models and test-time compute


    Models that think before answering, and scaling compute at inference time.

The five best resources for this track

For the big picture before you start, Karpathy's Intro to Large Language Models (1 hour) and Deep Dive into LLMs like ChatGPT (3.5 hours) are the best 10,000-ft tours.

Prerequisites from other tracks

You need Why Where
Dot products, cosine similarity Attention scores are dot products Vectors and the geometry of meaning
Matrix multiplication as a linear map Every projection, every head Matrices as linear maps
Tensor shapes and broadcasting Reading (B, h, T, d_h) without getting lost Tensors, shapes and broadcasting
Softmax, cross-entropy, KL The output layer and the training loss Entropy, cross-entropy and KL divergence
Numerical stability Log-sum-exp in softmax; mixed precision Floating point, stability and log-sum-exp
Backpropagation How every weight here is learned Backpropagation from scratch
Embeddings What token vectors are Embeddings and representation learning
Residual connections, normalisation Why deep transformers train Residual connections, Initialisation and normalisation
Adam, warm-up, schedules How transformers are optimised Optimisers
RNNs and seq2seq What attention replaced, and why RNNs, LSTMs and sequence-to-sequence

Where this leads