Tokenization, embeddings, attention, transformers, training and inference, in depth. With runnable Python and numpy right in the card.
For engineers. Some maths, explained as you go. 153 lessons.
Lessons
- Reading formulas: indices and sumsfoundationRead subscripts like $x_i$ and $W_{ij}$, Σ sums and ∏ products, and turn a formula into a loop.
- VectorsfoundationTreat a vector as a list of numbers with a length and direction; add, scale and subtract vectors.
- Dot product and cosine similarityfoundationCompute $a\cdot b$, read it as alignment times lengths, and use cosine similarity to compare vectors.
- Matrices and shapesfoundationRead a matrix as a table of rows and columns, state its shape, index rows and columns, transpose it.
- Matrix multiplicationfoundationMultiply matrix by vector and matrix by matrix, predict shapes like (T×d)(d×k) → T×k.
- A matrix as a functionfoundationSee a matrix as a linear map, XW as the same map applied to every row of X, and the identity matrix.
- Exponentials and logarithmsfoundationUse $e^x$ and $\log x$, rules like log(ab) = log a + log b, and why logs turn tiny products into sums.
- DerivativesfoundationRead a derivative as the rate of change: how much the output moves per small nudge of the input.
- The chain rulefoundationDifferentiate a composition by multiplying the rates of change along the chain.
- Partial derivatives and the gradientfoundationTake partial derivatives of a function of many inputs and collect them into the gradient vector.
- Probability and distributionsfoundationRead a discrete distribution as a probability vector that sums to 1, and compute simple probabilities.
- Random variables and expectationfoundationCompute the expected value and variance of a random variable as weighted averages.
- Conditional probabilityfoundationUse p(b|a), the chain rule p(a,b,c) = p(a)p(b|a)p(c|a,b), and Bayes' rule.
- Sampling from a distributionfoundationDraw an index from a probability vector, e.g. with cumulative sums or np.random.choice.
- Reading PythonfoundationRead short Python: lists, dicts, functions, loops, comprehensions, f-strings, imports.
- numpy arrays and shapesfoundationCreate numpy arrays, read .shape, index and slice rows, columns and ranges.
- Vectorized numpyfoundationApply operations to whole arrays, broadcast across shapes, and reduce with sum/mean/max along an axis.
- Linear algebra in numpyfoundationWrite matrix products with @, transpose with .T, and check shapes in code.
- What an LLM computes, end to endText is split into tokens: subword pieces from a fixed vocabulary of tens of thousands. Each token is looked up as a vector of numbers (its embedding), and the vectors flow through a stack of layers. At the end, each position's vector becomes a score (logit) for every vocabulary token, and the scores are turned into probabilities for the next token. The context window is the maximum number of tokens the model can look at. One pass predicts a next token at every position.
- Generating text one token at a timeTo answer a prompt, the model reads all tokens so far and outputs a probability for each possible next token. It then picks one, either the most likely or a random draw whose randomness is set by settings like temperature. That token is appended and the whole step repeats until a stop token. Every chat reply is produced this way, strictly one token at a time, so each token costs a model pass and a token, once chosen, is never revised.
- Weights, parameters and layersA neural network is a function built from layers. A layer transforms vectors by multiplying them with matrices of learned numbers and applying simple nonlinear functions. Those learned numbers are the weights, or parameters: billions of them in an LLM, and the model's size is their count. The intermediate vectors computed for a particular input are called activations. Running an input through all the layers is the forward pass. The same weights are reused for every token and every input.
- Attention in plain wordsEach token is held as a vector, and attention is the only place where those vectors exchange information. Each position forms a query (what it is looking for) and compares it with the keys (what each earlier position offers). It then takes a weighted average of those positions' values, with weights set by how well query and key match. In a language model a position may only look backwards, never at future tokens. Several attention 'heads' run side by side, each free to look for something different.
- The transformer block and the running vectorAn LLM stacks dozens of identical-shaped blocks. Each block has an attention step, which mixes information across positions, and a feed-forward step (a small MLP), which processes each token's vector on its own. Neither step replaces the token's vector. Each adds its result into a running per-token vector, the residual stream, which carries everything forward to the next block. A normalization step keeps the numbers in a stable range. After the last block the running vector is turned into next-token scores.
- What training doesThe weights start random. The model is shown real text and, at every position, predicts the next token. The loss measures how little probability it gave to the token that actually came next. A gradient tells, for every weight at once, which small nudge would lower that loss, and an optimizer applies the nudges. This repeats over batches of text, trillions of tokens in total, on many GPUs. This phase is pretraining, and its product is a base model.
- From base model to assistantA base model only continues documents in the style of its training text. Post-training turns it into an assistant in three ways. Fine-tuning on example conversations teaches the format. Optimizing toward responses that people prefer, scored by a reward, is reinforcement learning from human feedback (RLHF). Reinforcement learning (RL) on problems with checkable answers produces 'reasoning' models. In RL the model is treated as a policy that chooses tokens and is rewarded for good outcomes. A chat is stored as a single token sequence with markers for system, user and assistant turns.
- Compute, memory and scaleTraining and running LLMs is dominated by multiplying large matrices on GPUs. Work is measured in floating-point operations (FLOPs), and memory is measured in bytes: each weight is typically a 2-byte number. Big models are trained across thousands of GPUs that must constantly exchange results. Larger models trained on more data reach predictably lower loss, which is why scale matters. Serving users is a separate, ongoing cost, in which each generated token needs every weight read from memory.
- Behavior is learned, not programmedNo one writes rules into an LLM. Its knowledge and habits come from the training objective, the data and post-training, and are stored implicitly across the weights. Examples placed in a prompt can change its behavior with no weight change at all (in-context learning). Its characteristic failures, such as confident errors, flattery and odd blind spots, trace back to these same mechanisms. Interpretability research looks inside the activations, where concepts often turn out to be directions in the vector space.
- Batched tensors, broadcasting and einsumTrack shapes through reshapes, transposes, broadcasting and batched matmuls. Examples: [B, T, d] for a batch of sequences of token vectors, and [B, T, h, d_head] when each vector is split into h chunks, one per attention head. Write batched contractions such as all pairwise dot products between two sets of vectors with einsum.
- Rank and low-rank factorizationExplain why a product AB with inner dimension r has rank at most r. Compute how factoring a d×d weight matrix into d×r and r×d factors cuts parameters from d² to 2dr.
- Variance of sums and dot products of random vectorsShow that the variance of a sum of n independent terms grows like n. Conclude that the dot product of two random d-dimensional vectors with unit-variance entries has standard deviation √d.
- Near-orthogonality in high dimensionsExplain why random unit vectors in high dimension have cosine similarity around 1/√d. Explain why a d-dimensional space can hold far more than d nearly-orthogonal directions, room for many more concept directions than dimensions.
- 2D rotation matricesWrite the 2×2 matrix that rotates by angle θ. Show that rotating two vectors by angles a and b changes their dot product only through the difference a−b. This property is what later lets attention scores depend on how far apart two tokens are.
- Softmax, logits and the log-sum-exp trickTurn a logit vector into probabilities with softmax and explain why adding a constant to every logit changes nothing. Compute softmax stably by subtracting the max.
- Surprisal and entropyCompute surprisal −log p and entropy as expected surprisal, in nats or bits. Explain entropy as the irreducible uncertainty of a distribution.
- Cross-entropy and KL divergenceDerive H(p,q) = H(p) + KL(p‖q). Explain why minimizing cross-entropy against data is the same as minimizing KL, and why KL is asymmetric.
- Maximum likelihood as cross-entropy minimizationShow that maximizing the log-likelihood of a dataset equals minimizing the average cross-entropy between the empirical data distribution and the model.
- Gradients and JacobiansCompute the gradient of a scalar function of many variables and the Jacobian of a vector function. Explain the gradient as the direction of steepest increase.
- Backpropagation as reverse-mode autodiffBackpropagate gradients through a computational graph by hand using the local chain rule at each node. Explain why one backward pass costs about 2× the forward pass.
- Gradient descent and the learning rateApply the update θ ← θ − η∇𝓛. Predict what happens when η is too small or too large on a simple quadratic.
- Stochastic minibatch gradientsExplain why a minibatch gradient is an unbiased but noisy estimate of the full gradient. Show that its noise variance shrinks like 1/batch size.
- Momentum and per-parameter adaptive stepsExplain how momentum averages gradients over steps. Explain how dividing by a running RMS of gradients (RMSProp) gives each parameter its own effective step size.
- Floating point: fp32, fp16, bf16, int8Compare how exponent bits (range) and mantissa bits (precision) differ across fp32, fp16 and bf16. Explain why fp16 can underflow very small values, such as tiny gradients, to zero while bf16 rarely does.
- Counting FLOPs of matrix multipliesCompute that an (m×k)(k×n) matmul costs 2mkn FLOPs. Count the bytes it must read and write, and estimate the runtime on a GPU with a given peak FLOP rate.
- Roofline model: compute- vs memory-boundCompute arithmetic intensity (FLOPs per byte moved) and compare it with the hardware ratio of peak FLOPs to memory bandwidth. Use this to decide whether a kernel is compute-bound or memory-bound.
- Collective ops: all-reduce, all-gather, reduce-scatterDescribe what each collective produces across N devices, for example summing gradients computed on different GPUs. Explain why all-reduce = reduce-scatter + all-gather, and estimate the bytes each one sends.
- Policy gradients (REINFORCE) and baselinesFor a policy π that samples actions a and then receives a reward R, derive ∇E[R] = E[R ∇log π(a)] and turn it into a sampled update. Explain why subtracting a baseline from R reduces variance without adding bias.
- Bradley-Terry model for pairwise preferencesModel P(a preferred over b) = σ(s_a − s_b), where σ is the logistic sigmoid, and fit the scores s by maximum likelihood on comparison data, such as people choosing the better of two responses. Explain why only score differences are identifiable.
- MLPs and why nonlinearities matterShow that stacked linear layers collapse into a single linear map. Explain how an elementwise nonlinearity between them lets an MLP represent complex functions.
- Activation functions: GELU and SwiGLUCompare ReLU, GELU, and gated units (SwiGLU = (Swish(xW₁) ⊙ xW₂)W₃). Explain why SwiGLU needs three weight matrices instead of two, so its hidden layer is made about 8/3 rather than 4 times the input width to keep the same parameter count as a standard MLP.
- Initialization and activation scaleExplain why weights are initialized with variance ∝ 1/fan_in (fan_in = number of inputs to each unit), so activations neither blow up nor shrink layer by layer. Predict what happens with a bad initialization scale.
- Vanishing and exploding gradientsExplain that the gradient through a deep network is a product of per-layer Jacobians. Show why that product tends to shrink or grow exponentially with depth.
- Residual connectionsShow that y = x + f(x) has Jacobian I + ∂f/∂x. Explain how this identity path lets gradients and information pass through very deep stacks.
- LayerNorm and RMSNormCompute LayerNorm (subtract the per-token mean, divide by the std, apply a learned gain and bias) and RMSNorm (divide by the RMS, apply a gain). Explain how normalizing keeps activation scale stable.
- Language modeling as next-token predictionWrite p(x₁…x_T) = ∏ p(x_t | x_{<t}), an exact factorization by the chain rule of probability. Explain why a model of next-token conditionals is a complete generative model of text.
- Count-based n-grams and the need for generalizationBuild a bigram model by counting. Explain why counts become sparse as the context length grows, and how learned vector representations let similar contexts share statistics.
- The next-token cross-entropy objectiveWrite 𝓛 = −(1/T) Σ log p_θ(x_{t+1} | x_{≤t}) and explain it as maximum likelihood over a corpus. State the loss of a uniform guess, log V, as a reference point.
- Loss per token and perplexityConvert a loss in nats per token into perplexity exp(𝓛) and interpret it as an effective branching factor. Explain why perplexities from different tokenizers are not directly comparable.
- Prediction as compressionExplain that a model with loss 𝓛 can code text in about 𝓛 nats per token via arithmetic coding. Argue why driving 𝓛 down forces the model to capture the structure that generated the text.
- Why subword tokens: characters vs wordsCompare character, word and subword vocabularies on vocabulary size, sequence length and handling of unseen words. Explain why subwords are the practical compromise.
- Byte-pair encoding tokenizersTrain BPE by repeatedly merging the most frequent adjacent pair, and encode new text by applying the merges in order. Explain how starting from bytes guarantees any string can be encoded.
- Behavioral artifacts of tokenizationPredict tokenization-caused failures: counting letters, reversing strings, digit arithmetic, leading-space variants, and higher token cost for non-English text. Explain each from the fact that the model never sees characters directly.
- Token embeddings as a lookup tableExplain the embedding as row x_t of W_E, which equals a one-hot vector times W_E. Explain that these vectors are learned during training like any other weights.
- Geometry of learned embeddingsExplain why tokens used in similar contexts end up with similar vectors. Explain how directions such as gender or plurality can be roughly linear (king − man + woman ≈ queen).
- Unembedding: from hidden state to logitsCompute z_t = r_t W_U ∈ R^V, where r_t is the final hidden vector at position t. Each logit is then a dot product with that token's unembedding vector; apply softmax to get probabilities. Explain weight tying (W_U = W_Eᵀ) and its parameter savings.
- Why positions must exchange informationExplain that per-token processing alone cannot use context. Explain why a content-dependent weighted average over other positions is a flexible way to route information between them.
- Queries, keys and valuesExplain the roles of Q = XW_Q (what I'm looking for), K = XW_K (what I contain) and V = XW_V (what I pass on if attended to). Compute them and their dot-product match scores for a toy sequence.
- Scaled dot-product attentionCompute softmax(QKᵀ/√d_head)V with shapes T×d_head → T×T → T×d_head. Explain why dividing by √d_head keeps the softmax from saturating.
- Causal maskingAdd the mask M (−∞ above the diagonal) before the softmax so position t can only attend to positions ≤ t. Explain why this makes every position's output a valid next-token predictor.
- Multi-head attentionSplit attention into h heads of size d_head by reshaping [B, T, d] → [B, h, T, d_head], each head with its own attention pattern. Concatenate the head outputs and project with W_O, and explain why several heads can attend to different things at once.
- Injecting order: absolute position embeddingsShow that unmasked attention is permutation-equivariant, so it cannot see word order; the causal mask breaks this only weakly. Add a learned or sinusoidal position vector to each token embedding, and explain the downsides: tied to fixed positions and poor extrapolation beyond the trained length.
- Rotary position embeddings (RoPE)Rotate each 2D pair of query and key dimensions by an angle proportional to the position. Show that q·k then depends on the two positions only through their relative offset.
- QK and OV circuits of a headRewrite a head as a bilinear score W_Q W_Kᵀ that decides where to attend and a map W_V W_O that decides what gets written back into the running per-token vector. Explain why both are low-rank (rank ≤ d_head) d×d matrices.
- The position-wise feed-forward sublayerCompute the per-token MLP d → d_ff → d with a nonlinearity in the middle. Explain that it holds about 2/3 of a block's parameters and does no mixing across positions.
- MLPs as key-value memories for factsInterpret the input-weight rows as keys that detect patterns in the residual stream and the output-weight rows as values written back. Relate this to evidence that factual associations are localized in mid-layer MLPs.
- The pre-norm transformer blockWrite a block as r ← r + Attn(Norm(r)); r ← r + FFN(Norm(r)). Explain why this pre-norm form trains more stably than the original post-norm arrangement, which normalized after each residual addition, r ← Norm(r + Attn(r)), and so put the normalization on the main path itself.
- The residual stream as a shared channelExplain that every sublayer reads from and adds into one d-dimensional stream, so the final state is the embedding plus all sublayer outputs. Explain how later components can use what earlier ones wrote.
- The decoder-only transformer, end to endAssemble token ids → embeddings (+ positions) → L blocks → final norm → unembedding → logits, with shapes at each step. Explain why one forward pass yields T next-token distributions.
- The modern LLaMA-style architectureName the changes modern LLMs make to the original GPT design: RMSNorm, pre-norm, SwiGLU, RoPE, no bias terms, untied embeddings. Give the reason for each.
- Counting transformer parametersDerive about 12d² parameters per block (4d² attention + 8d² FFN), so N ≈ 12Ld², plus V·d for embeddings. Check this against a known model size.
- FLOPs per token: 2N forward, 6N trainingDerive about 2N FLOPs per token for a forward pass (ignoring the context-dependent attention term) and about 6N per token for training. Use C ≈ 6ND to estimate the cost of a training run.
- Quadratic cost of attention in context lengthShow that the score matrix costs O(T²·d_head) compute and O(T²) memory per head, adding about 4·L·T·d FLOPs per token on top of 2N. Estimate the context length at which attention FLOPs rival the parameter FLOPs.
- Mixture-of-experts layersReplace the FFN with E expert FFNs and a small learned router that sends each token to the top-k of them. Distinguish total parameters (memory) from active parameters (FLOPs per token). Explain the extra load-balancing loss added during training to keep experts evenly used.
- Shifted targets and parallel trainingBuild targets by shifting the input one token left. Explain how causal masking lets one forward pass train all T predictions in parallel, with the true prefix always fed in (teacher forcing).
- The LLM training loopWrite the loop: sample a batch of token windows, forward, cross-entropy loss, backward, optimizer step, zero gradients. Explain what each line does to the parameters.
- The Adam optimizerCompute Adam's update from the first and second moment estimates with bias correction. Explain its approximately sign-like, scale-invariant steps, and that it stores 2 extra numbers per parameter.
- AdamW and decoupled weight decayExplain why adding L2 to the loss interacts badly with Adam's rescaling, and how AdamW applies θ ← θ − ηλθ separately. Explain why norm gains and biases are usually exempt from decay.
- Learning-rate warmup and decay schedulesSketch linear warmup followed by cosine decay. Explain why warmup protects the early phase, when Adam's statistics are unreliable, and why decaying the learning rate lowers the final loss.
- Gradient clipping and loss spikesClip the global gradient norm to a threshold and explain how this bounds the size of each update. Describe loss spikes in large runs and common responses: skipping batches or rewinding to a checkpoint.
- Batch size in tokens and gradient accumulationMeasure batch size in tokens (B·T) and simulate a large batch with gradient accumulation over microbatches. Explain the critical batch size beyond which a bigger batch stops reducing the number of steps needed.
- Mixed-precision trainingExplain bf16 matmuls with fp32 master weights and fp32 accumulation, and why fp16 also needs loss scaling. Identify which operations (softmax, norms, loss) are kept in higher precision.
- GPU memory for trainingEstimate about 16 bytes per parameter for mixed-precision Adam (weights, gradients, fp32 master copy, two moments) plus activations ∝ B·T·d·L. Explain how activation checkpointing trades extra compute for less memory.
- Data parallelismReplicate the model on every GPU, give each a different shard of the batch, and all-reduce the gradients before the step. Explain why this keeps training mathematically identical to one large batch.
- Sharded data parallelism (ZeRO / FSDP)Shard optimizer states, gradients and parameters across data-parallel workers, gathering parameters just in time. Compute the resulting memory per GPU and the extra communication.
- Tensor parallelismSplit the FFN and attention matmuls column-wise then row-wise across GPUs (Megatron style), so each sublayer needs only one all-reduce in the forward pass (two per block). Explain why this frequent communication needs fast links within a node.
- Pipeline parallelismPlace consecutive layers on different GPUs and stream microbatches through them. Compute the pipeline bubble fraction and explain why more microbatches shrink it.
- Building a pretraining corpusDescribe the pipeline: web crawl → text extraction → language ID → heuristic and model-based quality filters → deduplication → domain mixture weights. Explain how each step shapes the distribution the model learns to imitate.
- Deduplication, memorization and contaminationExplain why duplicated text gets memorized verbatim and wastes compute. Explain how the questions of benchmarks (standard test sets used to score models) leaking into the training data inflate evaluation scores.
- Reading pretraining loss curvesInterpret a typical curve: a fast initial drop, then slow power-law-like decline, with training and validation loss nearly equal. Explain why near-single-epoch training rarely overfits.
- Scaling laws: loss vs parameters, data, computeState that loss falls as a power law in N, D and C toward an irreducible floor. Use a fitted law to predict a larger model's loss from small runs.
- Compute-optimal training (Chinchilla)Given C ≈ 6ND, find the split of compute between N and D that minimizes loss. Arrive at roughly 20 tokens per parameter, and size a compute-optimal model for a given FLOP budget.
- Overtraining small models for cheap inferenceExplain why serving cost per token scales with N. Explain why labs therefore train smaller models on far more than 20 tokens per parameter, accepting worse training efficiency.
- Evaluating LLMs: loss, logprob scoring, benchmarksScore a multiple-choice question either by comparing answer log-probabilities or by generating an answer. Explain what benchmarks like MMLU measure and their pitfalls: contamination, prompt format and saturation.
- Emergent abilities vs smooth improvementExplain how a capability can look like it switches on suddenly at some scale while per-token loss improves smoothly. Show how discontinuous metrics such as exact match create apparent jumps.
- Base models continue documentsExplain that a pretrained model imitates whatever kind of document the prompt looks like, rather than answering questions. Design a prompt as a document prefix to steer a base model.
- Autoregressive generation loopGenerate text by repeatedly computing logits for the last position, picking or sampling a token, appending it and running the model again. Explain why output tokens are produced strictly one at a time.
- Greedy, beam search and degenerationContrast greedy decoding, beam search and sampling. Explain why maximizing likelihood produces repetitive, bland loops in open-ended text.
- TemperatureSample from softmax(z/τ) and predict the result: τ→0 approaches greedy, τ=1 is the model's own distribution, and larger τ flattens it and raises entropy. Compute the effect on a toy logit vector.
- Top-k and nucleus (top-p) samplingTruncate the distribution to the k most likely tokens, or to the smallest set covering probability p, then renormalize. Explain how cutting the unreliable low-probability tail avoids derailing tokens.
- The KV cacheExplain why keys and values of past tokens never change under causal masking, so they can be cached instead of recomputed at every step. Compute the cache size: 2·L·h·d_head·T·bytes per sequence, a key and a value per head, layer and token.
- Prefill vs decode: compute- vs memory-boundExplain why processing the prompt (prefill) is compute-bound, while generating each new token reads every weight and the whole KV cache for little compute (memory-bound). Estimate time-to-first-token and tokens per second from the hardware specs.
- Batching, continuous batching and paged KVExplain how batching many requests amortizes weight reads during decode. Explain how continuous batching and paged KV memory raise GPU utilization in serving.
- Multi-query and grouped-query attentionShare key/value heads across groups of query heads (h_kv < h). Compute the KV-cache reduction and explain why the quality cost is small.
- Weight quantization for inferenceMap weights to int8/int4 with per-group scales and explain why this speeds up memory-bound decoding. Explain why naive quantization fails: a few activation dimensions take values far larger than the rest (outliers), and they wreck a shared scale.
- Speculative decodingLet a cheap draft model propose several tokens and have the big model verify them in one pass. Explain the accept/reject rule that keeps the output distribution exactly the big model's.
- FlashAttention: tiling and online softmaxCompute exact attention block by block in fast on-chip memory, using a running max and running sum for the softmax. Explain why it is faster despite the same FLOPs: it never writes the T×T matrix to slow memory.
- Long context: extension and its limitsExplain how RoPE scaling or interpolation extends the context window. Explain why models still use information unevenly across long contexts (for example 'lost in the middle').
- Supervised fine-tuning on demonstrationsFine-tune a base model on (prompt, ideal response) pairs, computing the loss only on response tokens. Explain why a small, high-quality set mainly teaches format and persona rather than new knowledge.
- Chat templates and special tokensShow how system, user and assistant turns are flattened into one token sequence using special role tokens. Explain why the model only ever continues that sequence and why a mismatched template degrades behavior.
- Treating the LLM as an RL policyCast generation as RL: the state is the prefix, an action is a token, the policy is π_θ, and the reward arrives at the end of the response. Write the policy-gradient update for a sampled response.
- PPO: clipped updates and a learned value baselineWrite PPO's surrogate using the probability ratio π_θ/π_old and clip it so one batch cannot push the policy too far. Explain how a learned value model, which predicts the expected reward from each prefix, supplies per-token advantages (reward minus that baseline). Explain why clipping allows several gradient steps per batch of sampled responses.
- Reward models from human comparisonsReplace an LM's unembedding with a single scalar output and train it with the Bradley-Terry loss −log σ(r(x,y_w) − r(x,y_l)) on pairs of preferred (y_w) and rejected (y_l) responses. Explain what the resulting reward does and does not capture.
- RLHF with a KL penaltyMaximize E[r(x,y)] − β·KL(π_θ ‖ π_ref) with PPO. Explain why the KL term keeps the policy near the SFT model and how β trades reward against drift.
- Reward hacking and overoptimizationExplain Goodhart's law for learned rewards (a measure that becomes a target stops being a good measure): the proxy reward keeps rising while true quality peaks and then falls as the policy drifts. Predict typical exploits such as length and confident tone.
- Direct Preference OptimizationDerive the optimal policy of the KL-regularized objective and substitute it into Bradley-Terry to get a classification loss on preference pairs. Explain what DPO gains and loses compared with RLHF.
- RL with verifiable rewards (GRPO)Train on problems with automatically checkable answers by sampling a group of responses and using each one's reward, normalized by the group mean and std, as its advantage in a PPO-style clipped update. Explain why this needs no learned value model or reward model.
- Chain of thought as extra computationExplain that each generated token gets a fixed budget of about 2N FLOPs and L sequential layers. Explain why writing intermediate steps buys more serial computation and working memory for hard problems.
- Scaling test-time compute: parallel vs sequentialCompare two ways of spending inference compute. In parallel: sample many answers, then take a majority vote or let a verifier (a checker or scoring model) pick one. Sequentially: produce longer reasoning chains. Explain why accuracy rises roughly log-linearly with thinking tokens and when each strategy wins.
- LoRA: low-rank fine-tuningFreeze W and learn the update ΔW = BA with rank r ≪ d. Compute the parameter and optimizer-memory savings, and explain why low-rank updates often suffice for fine-tuning.
- Distillation from a stronger modelTrain a smaller student on a teacher's outputs, either its full token distributions (soft targets via KL) or its sampled text. Explain why reasoning traces from a strong model transfer well to small models.
- In-context learningShow that adding a few input→output examples to the prompt changes behavior with no weight updates. Explain why this follows from next-token prediction on documents that contain repeated patterns.
- Induction headsExplain the two-head circuit that completes [A][B] … [A] → [B]. A previous-token head writes 'my predecessor was A' at B's position; an induction head at the later A searches for that marker and copies B. Relate it to the sudden drop during training in loss on tokens late in a context, which can be predicted from earlier parts of the same context.
- In-context learning as implicit task inferenceExplain ICL as inferring a latent task or format from the examples and then predicting under it. Use this to explain why the format of examples can matter more than whether their labels are correct.
- Features as directions in activation spaceExplain the linear representation hypothesis: concepts correspond to directions in the residual stream. These directions can be read out with linear probes (small linear classifiers trained on activations), and added or subtracted to steer behavior.
- Superposition and polysemantic neuronsExplain how a model packs more sparse features than it has dimensions into nearly-orthogonal directions, accepting some interference. Explain why individual neurons then respond to several unrelated things.
- Sparse autoencoders for interpretable featuresTrain a sparse autoencoder on model activations: a network that reconstructs them through a much wider hidden layer, with a penalty keeping only a few hidden units active. Its units recover interpretable feature directions. Explain how these features are inspected and used to steer the model.
- Logit lens: reading intermediate predictionsApply the final norm and W_U to the residual stream r^{(ℓ)} at intermediate layers to see how the predicted next token develops through depth. Explain the method's limits and the tuned-lens fix: a small learned linear map per layer applied before unembedding.
- Calibration of model probabilitiesDefine calibration (events assigned 70% happen 70% of the time) and explain why minimizing cross-entropy rewards calibrated next-token probabilities. Contrast this with the confidence expressed in generated text, and note that post-training often degrades calibration.
- Why models hallucinateExplain hallucination from the mechanisms: the model produces fluent, plausible continuations for facts it saw rarely or never. Explain how fine-tuning on unknown facts and grading that never rewards 'I don't know' encourage confident guessing.
- Sycophancy and other preference artifactsExplain how optimizing for human approval produces agreeing with the user, flattery, verbosity and hedging. Predict when an assistant will change a correct answer under pushback.
- Prompt injection and jailbreaksExplain prompt injection from the fact that roles are just tokens in one sequence: instructions inside retrieved documents or tool outputs can be followed like user instructions. Explain why jailbreaks work: refusal behavior is a learned shift from post-training that unusual contexts can move out of distribution.
- The reversal curse and directional knowledgeExplain why a model trained on 'A is B' often fails to answer 'who is B?'. Connect this to knowledge being learned through left-to-right next-token prediction.
- Exposure bias and compounding errorsExplain that training always conditions on true prefixes while generation conditions on the model's own outputs. Explain why an early wrong token can derail everything after it unless the model has learned to recover.
- Trace a modern LLM's forward pass with shapesGiven a prompt, trace a LLaMA-style model step by step (tokenize, embed, RoPE attention with causal mask, SwiGLU FFN, residual adds, norm, unembed, softmax) with the tensor shape at every step. Explain what each component contributes.
- Explain a pretraining run end to endDescribe how a base model is produced: data pipeline, shifted-target objective, AdamW with warmup and cosine decay, gradient clipping, mixed precision, batch size in tokens. Diagnose a loss curve, including spikes and plateaus.
- Size a model: params, FLOPs, memory, GPUsFor a given architecture and budget, compute N, training FLOPs (6ND), training memory per GPU, and a compute-optimal or deliberately overtrained N and D. Choose a sensible combination of data, tensor and pipeline parallelism, and handle MoE's active vs total parameters.
- Predict how loss and capabilities scaleUse scaling laws to predict loss improvements from more parameters, data or compute. Explain why lower loss implies broad capability gains and judge claims of emergent abilities and benchmark results critically.
- Estimate and optimize inference costEstimate KV-cache memory, time-to-first-token and decode throughput for a model on given hardware. Explain how batching, GQA, quantization, FlashAttention and speculative decoding each change those numbers.
- Predict the effect of decoding settingsPredict how temperature, top-k, top-p, greedy and beam decoding change diversity, repetition and error rates. Explain why the same model can seem creative or deterministic depending on these settings.
- Explain how a base model becomes an assistantWalk through SFT with chat templates, reward modeling, KL-regularized RLHF or DPO, and parameter-efficient variants. Explain which behaviors each stage creates and the side effects it can introduce.
- Explain reasoning models and test-time computeExplain why longer chains of thought and more samples improve accuracy on hard problems. Explain how RL with verifiable rewards trains models to produce long reasoning, and how distillation spreads this ability to smaller models.
- Explain in-context learningExplain how a frozen model adapts to examples in its prompt, both mechanistically (induction-style attention circuits) and probabilistically (inferring the task). Predict when few-shot prompting helps and what it is sensitive to.
- Explain what is known about LLM internalsDescribe how information is represented and processed inside a model: the residual stream, linear features in superposition, MLPs as fact stores, and attention circuits. Describe the tools used to probe these: logit lens and sparse autoencoders.
- Explain and predict LLM failure modesTrace hallucination, sycophancy, prompt injection, tokenization blind spots, the reversal curse, compounding errors and long-context weaknesses back to their training and architectural causes. Predict which tasks will trip a model.
Bytewise
All courses