Course Wrap-up

Session 9 - Recap of the core ideas

Lambert Fatoux

Course wrap-up

Session 9

From tokens to a defensible system: the eight sessions in one hour

The course in one map

Today: one part per session, the few ideas to keep, and a self-test at the end.

Part 1: The transformer

Session 1 - a model reads tokens and predicts the next one

The big picture: one loop

Decoder-only: each token sees only the tokens before it. Training scores all positions in parallel; generation repeats this loop one token at a time. The weights hold the knowledge, the context window is the working memory.

Tokens are the currency

The tokenizer fixes the sequence length before the model runs, and you pay per token: about 4 characters per token in English, 6.6× more tokens for Russian on an English-centric tokenizer.

Attention: soft routing between tokens

\[\text{Attention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V\]

  • Query asks, key advertises, value contributes; the output is a weighted average of values
  • Scores form a \(T \times T\) matrix, so cost grows with the square of the context length
  • Multi-head: several attention patterns in parallel, \(d_k = d_{model} / n_{heads}\)
  • Attention alone is order-blind: add positional information (RoPE rotates \(Q\) and \(K\) today)

The causal mask

Future scores are set to \(-\infty\) before the softmax, so their weights are exactly 0. Without it, training leaks the answer and generation produces garbage.

The block, the families, the cache

  • Block: \(x = x + \text{Attention}(\text{Norm}(x))\), then \(x = x + \text{FFN}(\text{Norm}(x))\); each layer adds to the residual stream
  • Three families: encoder (bidirectional, BERT), decoder (generation, GPT), encoder-decoder (translation); the mask is the difference. Decoder-only won for chat
  • KV-cache: past keys and values never change, so store them; Llama 3.1 8B needs 128 KB per token, so a 128k context costs 16 GB, as much as the weights
  • Architecture becomes cost: more tokens, more attention compute and more cache memory

Part 2: Pretraining and scaling laws

Session 2 - how a model is trained and what compute buys

Pretraining: predict the next token

\[L = -\frac{1}{T}\sum_{t} \log P(x_t \mid x_{<t}) \qquad \text{perplexity} = e^{L}\]

  • Self-supervision: the text is its own label, so data is limited only by how much text exists
  • Targets are the inputs shifted by one; one pass trains \(B \times T\) predictions
  • Random init gives a loss of about \(\ln V\) (GPT-2: 10.8); a good small model reaches about 2.85
  • Perplexity is the effective number of equally likely tokens; compare it only with the same tokenizer and eval text
  • Data quality beats volume: dedup, filtering and licensing matter more than raw size

Byte-Pair Encoding

Start from bytes, repeatedly merge the most frequent adjacent pair, stop at the target vocabulary size \(V\). The tokenizer is frozen before training.

The compute rule: C ≈ 6ND

Training FLOPs ≈ 6 × parameters × tokens (2 forward + 4 backward per parameter per token); serving costs about \(2N\) FLOPs per generated token.

Chinchilla, and why products over-train

  • Chinchilla: for a fixed budget, scale \(N\) and \(D\) together, about 20 tokens per parameter; 1e21 FLOPs gives 2.9B parameters and 58B tokens
  • Chinchilla 70B on 1.4T tokens beat Gopher 280B on 300B tokens at the same compute, and is 4× cheaper to serve
  • Inference-optimal: a product pays \(2N\) per served token forever, so it trains a smaller model far past 20 tokens per parameter (Llama 3 8B saw 15T tokens)
  • Chinchilla minimises the training bill, not the total bill.

Part 3: Post-training

Session 3 - from a text completer to an assistant

The post-training pipeline

SFT imitates demonstrations, then a reward model and RL optimise preferences; DPO collapses the second part into one step.

SFT: learn to answer, not to ask

Same cross-entropy as pretraining, scored on answer tokens only (prompt labels set to -100), including the end-of-turn token. SFT teaches format and style, not reliable new facts; safety trained this way is shallow.

Preferences: reward model and the KL leash

  • Bradley-Terry: \(P(y_w \succ y_l) = \sigma(r_w - r_l)\); the reward model is a classifier trained on chosen/rejected pairs (65-75% accuracy)
  • RLHF objective: \(\max\ \mathbb{E}[r] - \beta\,\text{KL}(\pi_\theta \,\|\, \pi_{ref})\); the KL term keeps the model close to the SFT model
  • PPO needs four models in memory (policy, reference, reward, value) and is fragile

The reward model is a proxy: push it too far and true quality drops (Goodhart’s law).

RLHF vs DPO

DPO turns the KL-regularised optimum into a classification loss on log-probability ratios: no reward model, no sampling, loss \(= \ln 2\) at step 0. It is stable and simple, but offline. RL with verifiable rewards (maths, code) and GRPO go beyond it.

LoRA: train a tiny update

Freeze \(W_0\), learn \(\Delta W = BA\) with rank \(r\) (8 to 64). Rank 8 on a 4096 × 4096 matrix adds 65,536 parameters. LoRA learns less and forgets less than full fine-tuning.

Part 4: Advanced prompting

Session 4 - reliable, structured, safe outputs

Anatomy of a production prompt

Stable text first so it can be cached; long documents first and the question last; untrusted data inside tags. Prompts are code: judge them on a held-out set.

Constrained decoding

The server masks tokens that would break the schema before sampling, so the output is valid by construction: schema adherence goes from under 40% to 100%. Valid is not correct.

Reasoning, sampling and cost

  • Chain-of-thought is now built into reasoning models; thinking tokens are billed as output and add latency
  • Self-consistency: sample \(k\) answers, keep the majority vote; \(k\) times the cost, and the agreement rate is a free confidence signal
  • Sampling: temperature about 0 for classification and extraction, 0.7 to 1 for writing
  • Cost per call = input × price in + output × price out; output costs about 5× input

Prompt injection and the lethal trifecta

Instructions and data share one token stream, so injection can only be reduced and measured (attack success rate). Layers: separate, constrain, validate, limit the blast radius. Untrusted input + sensitive data + external actions together can leak data: remove one leg.

Part 5: Production-grade RAG

Session 5 - ground answers in your own documents

The pipeline

Offline: parse, chunk (300 to 800 tokens, 10 to 20% overlap), embed, index. Online: query, retrieve, rerank, generate. Update the index, not the weights.

Hybrid search with reciprocal rank fusion

BM25 wins on rare words (codes, acronyms), dense embeddings win on meaning. Fuse by rank: score = Σ 1 / (60 + rank), so score scales never need to match.

Reranking: the precision step

A bi-encoder encodes query and chunk separately (fast, coarse); a cross-encoder reads them together (precise, slow) and only sees the shortlist. Often the largest single quality gain.

Answer, cite, or abstain

  • Answer only from numbered sources, cite every sentence, say “Not found” otherwise; code validates the citations
  • Sources are data, not instructions
  • Lost in the middle: put the best chunks at the edges; 5 good chunks beat 20 mediocre ones
  • Evaluate retrieval first: Recall@k = questions whose gold chunk is in the top \(k\) / all questions
  • Faithfulness = supported claims / all claims; faithful is not correct.
  • Aggregation questions (“how many…”) need a tool, not search

Failure triage: find the broken stage

Part 6: Agents and tools

Session 6 - let the model act

An agent is an LLM in a loop

The model writes a thought and a structured tool call; your code runs it and appends the observation; repeat until final_answer. Tool errors go back as observations, they never crash the run.

Workflows first, autonomy last

Pick the lowest rung that solves the task, and climb only when an evaluation shows a gain.

Errors compound, so always stop

Per-step reliability \(p\) over \(n\) steps gives \(p^n\): 0.95 over 20 steps is about 36%. Five stop conditions: goal reached, step limit, budget, repeated call, needs a human. Always report why it stopped.

Agents need real permissions

  • Least privilege: sandbox, read-only by default, scoped short-lived credentials, audit logs
  • Human approval for send, pay, delete and deploy
  • A freeze written in a prompt is not a permission system.
  • Privacy: a cloud agent sends everything it reads, including every tool result, to the provider; sensitive data goes to a self-hosted open-weight model
  • Measure the agent: success rate, iterations, hallucinated tool calls, cost and latency, over repeated runs
  • MCP is the open standard to plug tools into any host

Part 7: Diffusion and multimodal

Session 7 - generate and read images

Diffusion in one picture

Forward: add Gaussian noise step by step (\(T = 1000\)). Training: predict the added noise, \(\|\epsilon - \epsilon_\theta(x_t, t, c)\|^2\). Reverse: start from noise and denoise. Latent diffusion runs this on a VAE-compressed image, 8× smaller per side.

Classifier-free guidance

CFG pushes away from “any image” and towards “this prompt”. Past a sweet spot, too much guidance burns the image.

How a vision LLM reads an image

The image is cut into patches, embedded by a vision encoder, projected, and spliced into the token sequence: the LLM never sees pixels. The loss is still next-token prediction. Cost grows with the number of patches.

Measuring images, and the risks

  • CLIP score: prompt match, but blind to realism, and CLIP judges CLIP-based models
  • FID: realism and variety of a set, needs thousands of images
  • Human A/B: slow and costly; report all three together
  • Provenance: C2PA metadata travels with the file, a watermark (SynthID) lives in the content; detection gives a probability, not proof
  • Treat images as untrusted input: models obey text written inside them

Part 8: Evaluation

Session 8 - from “the demo looks great” to “we can defend this”

The evaluation pyramid

Cheap deterministic checks run always, costly ones (LLM judge, human) run rarely: climb one level only when the cheaper one cannot answer.

Retrieval metrics and LLM judges

  • Recall@k: did we find it? MRR: how early is the first hit? nDCG: are relevant documents ranked early?
  • LLM-as-judge: temperature 0, a reference answer, a structured verdict, “do not reward length or style”
  • Biases: position, verbosity, self-enhancement, authority, gaming; run both orders, use another model family, check agreement with about 30 human labels
  • Public benchmarks saturate and leak into training data: build a private golden set

Is the difference real?

  • Resample the questions (paired bootstrap) to get a 95% confidence interval on B minus A; if it contains 0, the gain is not proven
  • With 50 questions one question is 2 points, so a 3-point gain is noise
  • Agents: reliability compounds, \(\text{pass}^k = p^k\); 90% per run gives 43% over 8 runs
  • Report confidence intervals, cost and latency together; keep only variants on the Pareto front

Capable models cheat, and reasoning is not an audit

  • Reward hacking: models special-case tests, edit them, or find the answer key; a higher score is not a better assistant (Goodhart again)
  • Defences: lock test files, review diffs, sandbox, read trajectories, keep held-out sets private
  • Chain-of-thought is not an explanation: with a planted hint, the reasoning admitted it only 25% of the time (Claude 3.7 Sonnet) and 39% (DeepSeek R1)
  • Guardrails in layers: input, retrieval access control, model, output, action, monitoring; keep one check outside the AI platform and measure false positives

One request, end to end

Each stage is something you learned to build, and each stage needs its own metric.

The course in 10 patterns

1
Tokens are the currency
S1, S2
2
Prompt first, fine-tune last
S3, S4
3
Structure and validate outputs
S4
4
Untrusted input is data, not instructions
S4, S5, S6, S7
5
Retrieve, rerank, cite
S5
6
Recall before faithfulness
S5, S8
7
Workflows before agents
S6
8
Least privilege, human approval
S6, S8
9
Held-out golden sets with cost and latency
all sessions
10
Guardrails in depth, monitored
S8

Self-test (1/2)

  1. S1: why does the causal mask set future scores to \(-\infty\) rather than 0?
  2. S2: what is the Chinchilla-optimal configuration for a budget of 1e21 FLOPs?
  3. S3: what is the DPO loss at step 0?
  4. S4: constrained decoding guarantees valid JSON; what does it not guarantee?

✅ Answers

  1. \(e^{-\infty} = 0\) gives exactly zero weight; a 0 score would still receive weight
  2. About 2.9B parameters on 58B tokens (\(D \approx 20N\))
  3. \(\ln 2 = 0.693\)
  4. That the content is correct: add business rules and measure accuracy

Self-test (2/2)

  1. S5: an answer has a faithfulness of 1.0 but is wrong; how?
  2. S6: an agent succeeds 95% of the time per step; what is its success rate over 20 steps?
  3. S7: what does classifier-free guidance do, and what happens when it is too high?
  4. S8: system B beats A by 3 points on 50 questions; is it better?

✅ Answers

  1. It is faithful to the wrong chunk: check Recall@k first
  2. \(0.95^{20} \approx 36\%\)
  3. It pushes towards the prompt and away from “any image”; too high burns and over-saturates the image
  4. Not proven: one question is 2 points; compute a bootstrap confidence interval

Key takeaways

  • A model is a next-token predictor; the tokenizer, the context and the cache set the bill
  • Pretraining gives knowledge, post-training gives behaviour; prompt first, RAG for facts, fine-tune last
  • Production means structure, grounding, tools and permissions, in that order of risk
  • Nothing ships without a golden set, confidence intervals, cost and latency
  • Models cheat and reasoning text is not an audit: layer your guardrails