Lecture 6

STEERING THE DISTRIBUTION

AI-Supported Software Development — SoSe 2026
Block A — Why the mechanism failsWhat the model actually is after pre- and post-training, and the ways it fails: hallucination, CLAUDE.md compliance drift, lost-in-the-middle. Every failure named in last week's vocabulary — never called a bug. §2–8 · the diagnosis
Block B — Engineering the distributionThe deliberate controls: temperature, in-context learning, few-shot, chain-of-thought, self-consistency, role priming. Real theory, with citations. §9–16 · the controls
the deliverableFive named patterns — zero-shot · few-shot · chain-of-thought · self-consistency · role priming — each a deliberate use of a Lecture 5 mechanism.
Every prompting pattern in this lecture — zero-shot, few-shot, chain-of-thought, self-consistency, role priming — is a deliberate, named use of the mechanism we built last week.
there are no new ingredients · no folklore — a mechanism and a citation, every time
A

Why the Mechanism Fails

pre-training, in one sentenceFor every position in a colossal corpus, predict the next token; compare to the truth; back-propagate the cross-entropy loss. Repeat trillions of times.

The result, after all that compute, is a model with one operational behaviour: given a sequence, emit a probability distribution over the next token. Nothing else.

the load-bearing factThe model was never trained to be correct — only to predict the most likely continuation. Everything in Block A follows from this.
No truth or correctnessIt saw correct and incorrect text alike; nothing flags the wrong answer as wrong.→ §4 hallucination
No goals or intentIt is not "trying to help." It emits a distribution; helpful-looking text was just abundant.→ RLHF shapes, not commands
No external groundingIt cannot check an endpoint, run code, or read the docs.→ factual hallucination
No memory across chatsEach forward pass sees only its current context window.→ CLAUDE.md is context, not config
read every failure this wayEach "does not have" maps to a failure mode later in Block A. The model is a pattern-completion engine — spectacular where patterns are dense, predictably wrong where they are rare.
# Base model — end of pre-training, no post-training, no preference
prompt  "What is the capital of France?"

continuation 1  "Paris."
    # Wikipedia, textbooks, educational sites
continuation 2  "What is the capital of Germany? What is the capital of Italy?"
    # quiz sheets, trivia lists — also abundant in the corpus
no preferenceBoth continuations have non-trivial probability. The base model is not choosing "helpful" over "unhelpful" — it is sampling a distribution that contains both. SFT + RLHF is what makes the answer win.
Pre-trainingnext-token loss · the base model
→
SFTimitate ideal conversations
→
RLHFoptimise toward preferred replies
SFT — teaches the formatTrain on curated (prompt, ideal-response) conversations with the same next-token loss. The model learns what an assistant looks like. Vicuna, Alpaca, LLaMA-Instruct stop here.
RLHF — teaches the preferenceA reward model learns human rankings; the policy is optimised to score higher. The model learns which assistant reply humans prefer. PPO → DPO / RLAIF / Constitutional AI.
What post-training buys What it does not buy
Instruction following — the distribution peaks on tokens that obey Truth — it aligns to preferred forms, not to facts
A helpfulness style — confident, structured, caveated Elimination of hallucination — it gilds it, not removes it
The [system] › [user] role hierarchy (a learned bias) Reliable refusal — learned, not enforced; jailbreakable
Refusal of harmful / off-topic requests New factual knowledge — that still comes from pre-training
misconception, correctedRLHF shifts style and behaviour, not knowledge. The classical reward model scores the form of an answer — authoritative, well-structured, caveated — not its truth.
the consequenceA post-trained model hallucinates more politely, not less often. The confident gloss that rankers preferred sits on top of the same base distribution — still no ground-truth check, so a falsehood can come out as a sharp, confident peak.
the frontier has movedThe classical recipe rewards human preferences over response forms. For reasoning tasks, the reward can be replaced by something stronger: automatic verification of the answer.
DeepSeek-R1 (Guo et al., 2025)Pure RL against a correctness signal elicited complex reasoning — and the SFT stage was skipped entirely in their R1-Zero variant. A new RL algorithm, GRPO, replaced PPO. We return to this in chapter 13.
register the shiftPost-training is no longer a single canonical recipe but a fast-moving family of techniques. The principles of §3 still hold.
Hallucination is not a bug. It is the expected behaviour of next-token prediction when the context is insufficient to peak the distribution onto a correct answer.
the central diagnostic claim of Block A — §4
P(next | "the capital of France is …") Peaked
One token (Paris) captures almost all the mass.
P(next | "the Stack Exchange API endpoint is …") Flat
Many tokens share the mass — no clear winner.
Same softmax. Same forward pass. Only the prompt's specificity decides the distribution's shape — and the model always picks a token, even from the flat one.
FactualA specific fact, stated confidently, and wrong. "The Stack Exchange endpoint is /api/v2/questions/monthly." It does not exist.clusters on proper nouns, versions, APIs
StructuralCode shaped correctly, but the method / signature / import does not exist. locust get_monthly_report().caught by the runtime, not by reading
Confident-nonsenseA long, fluent, contextually-perfect explanation that is end-to-end invented. requests DEFAULT_POOL_SIZE.needs domain expertise to detect
one mechanism, three facesAll three are pattern-completion artefacts with no ground-truth check (flat OR confidently wrong). Telling them apart tells you how to engineer against each.
Category Example (Act 1) Root cause (L5) Mitigation
Factual invented API endpoint no ground-truth check on a specific fact retrieval — docs in context
Structural hallucinated function signature pattern shape ≠ actual library surface grounding — API surface, type stubs
Confident-nonsense fabricated requests internals confidently-wrong sharp peak + RLHF style verification — run it, test it, ask an expert
the move"Better prompt" is rarely enough alone — each category needs a different layer. This foreshadows the three-layer model.
Checkpoint: the diagnostic foundation
hold these 1. One objective → no truth, no goals, no grounding, no memory.   2. Post-training adds style, not knowledge.   3. Hallucination = pattern completion, no ground-truth check (flat OR confidently wrong).   4. Three categories, three mitigations: retrieval · grounding · verification.

Next: why CLAUDE.md sometimes feels like it doesn't exist.

what CLAUDE.md actually isEvery modern AI coding tool reads an instruction file from the project root before answering. Across vendors the convention converged on one name: AGENTS.md — now governed by the Linux Foundation's Agentic AI Foundation, in 60,000+ repos.
the wrinkleClaude Code does not natively read AGENTS.md — it reads CLAUDE.md. The community fix: a one-line @AGENTS.md reference inside CLAUDE.md.
why it mattersThe mechanism we are about to explain is identical across AGENTS.md, CLAUDE.md, .cursorrules, copilot-instructions — they are all just project-root text the orchestration layer injects as tokens.
1,000 tokens
turn 1 — opening
CLAUDE.md (500)
task (500)
CLAUDE.md = 50%
30,000 tokens
mid-session — a few files open
task (29,500)
CLAUDE.md = 1.67%
150,000 tokens
extended session — full repo loaded
task (149,500)
CLAUDE.md = 0.33%
Same 500-token CLAUDE.md across all three rows. Only the surrounding task tokens grow — the shrinking indigo sliver is its share of positions, not its share of attention: softmax is winner-take-most, so an important token can still win strongly from a tiny slice. But it now competes with far more newer, more local tokens.
Multi-head attention dilution Eight attention heads at a single layer. Three route to CLAUDE.md tokens; five route to local task tokens. The output is a mixture of all eight heads' values. CLAUDE.md task tokens (more recent, more local) H1 H2 H3 H4 H5 H6 H7 H8 output representation = Wₒ mixture of all 8 head values 3 heads contributed CLAUDE.md content · 5 contributed task content
Each head routes to wherever its query/key match is strongest. Only some happen to route to CLAUDE.md — 3 of 8 in this caricature. The output is the WO-weighted mix of all heads, so CLAUDE.md's effective influence is whatever weight that subset carries.
CLAUDE.md does not command the model. It influences the distribution.
influenced, not commanded — short, recent, aligned instructions influence strongly; long, distant, orthogonal ones influence weakly
KV caching Prompt caching
Scope within one response across requests
Caches each token's k, v as it's generated a stable prefix's k, v (system, AGENTS.md, history)
Opt-in? automatic, intrinsic sometimes explicit; prefix must be byte-identical
What it changes recompute cost within a generation the cost of re-running a long prefix every turn
it changes cost, not influenceA cached 50K-token AGENTS.md is cheap to keep — but every token still occupies a position and still competes for attention. Caching solves the cost of dilution, not dilution itself.
Turn 2 without cache
~30K × forward-pass cost
recompute k,v for every prefix token
AGENTS.md @ pos 500
Every prefix token gets a full forward pass, every turn.
Turn 2 with cache
~100 × forward-pass cost
cached k,v (prefix reused)
Prefix k,v is read from cache; only the new turn's tokens run a fresh forward pass.
Attention weight on AGENTS.md @ pos 500
identical in both rows
same softmax over the same key sequence
The dot lines up vertically across all three rows. The model's view of AGENTS.md hasn't moved.
Prompt caching changes the cost of running the prefix, not the attention the prefix receives — cheaper to serve, just as easy to miss.
Lost in the Middle — U-shaped retrieval accuracy Retrieval accuracy is high at the beginning (primacy), drops sharply in the middle, and rises again near the end (recency). 100% 50% 0% Beginning Middle End Position of the relevant passage Retrieval accuracy primacy advantage recency advantage ~20 pp drop
Liu et al. (2023): retrieval accuracy is high at the start (primacy) and end (recency), and drops sharply in the middle — a U-shape, not the flat line naive attention theory would predict.
front-loadThe single most important rule belongs on line 5, not line 350. Early position has primacy advantage.
longer ≠ more reliableA 100-line CLAUDE.md is more reliable line-for-line than a 600-line one. Buried rules suffer middle-of-context decay.
repeat at the endIf a rule must hold for a critical task, restate it in the user prompt — recency advantage on top of the file load.
Influence layer
Probabilistic — biases the distribution
AGENTS.md prompts few-shot CoT triggers
Catches
soft signal drift
Enforcement layer
Deterministic — refuses bad output
linters type checkers tests CI schemas
Catches
hard violations
Human layer
Semantic — judgment and review
code review architecture domain expertise
Catches
wrong-but-plausible
Three parallel safety nets. Each layer catches what the other two miss — remove any one and the gaps line up.
Layer What it does What it catches Limitation
Influence biases the distribution soft signal drift probabilistic, position-dependent, dilutable
Enforcement refuses bad output deterministically hard violations can't tell if the code does the right thing
Human semantic judgment wrong-but-plausible does not scale to every line
teaching-repo asymmetryYour Locust repo is deliberately thin on enforcement — so the influence layer carries extra weight, and you feel exactly which failures it misses. In production the balance inverts.
the pivotBlock A named the failures. Block B names the controls. Every pattern ahead is a deliberate use of an L5 mechanism to shift the distribution toward the correct continuation.

The question Block B asks: what can you do at prompt-construction time to make the distribution sharper, more peaked, more aligned with correct answers?

take a breathThis is the natural break point in a 2×90 session. We switch from "why it fails" to "how to steer it."
Checkpoint: Block A synthesis
five claims to keep 1. Pre-training = one objective, no truth.   2. Post-training = style, not knowledge.   3. Hallucination = pattern completion, no ground-truth check (flat OR confidently wrong).   4. CLAUDE.md = influence, not command.   5. Reliability = influence + enforcement + human.

If you remember nothing else from Block A, remember these. Block B builds a control on top of each one.

B

Engineering the Distribution

pi  =  eℓi/T∑jeℓj/Tp_i \;=\; \frac{e^{\ell_i / T}}{\sum_{j} e^{\ell_j / T}}

T < 1 — sharpensDivide the logits by a small number → the winner takes more. T → 0 becomes argmax.
T > 1 — flattensDivide by a large number → the long tail gains mass. More variation, less commitment.
T = 0.1 — binary correctness Sharp
Argmax dominates; effectively deterministic.
T = 1.0 — graded correctness Default
Top tokens dominate, but the seconds occasionally win.
T = 2.0 — variation desired Flat
Sampling explores the long tail; correctness traded for diversity.
Temperature turns the same logits into different distributions. The model and its parameters are unchanged — only how its softmax is shaped at sampling time.
Task type Recommended T Why
Binary correctness T = 0 one right answer; commit, repeatable, debuggable
Graded correctness T ≈ 0.3–0.7 quality dimension, small variation fine — most code generation
Variation desired T ≥ 1.0 brainstorming, naming, alternatives — diversity on purpose
the one-linerMatch the sharpness of the output to the sharpness of the task's correctness criterion. There is no universal "right temperature" — only the right T for this task.
Token Logit ℓ p (T=0.1) p (T=1.0) p (T=2.0)
glowing 1.8 ≈ 0 0.058 0.107
potion 4.2 ≈ 1.000 0.637 0.354
fire 3.1 1.7×10⁻⁵ 0.212 0.204
troll 0.9 ≈ 0 0.024 0.068
smashes 1.1 ≈ 0 0.029 0.075
(+5 more) … ≈ 0 … …
temperature re-weights the dice — it does not change which face has the most dotsThe argmax never moves: potion wins at every T. At T=0.1 it carries ~all the mass; at T=2.0 the runner-ups become real candidates.
T = 0 is deterministic, not correctGreedy decoding picks the per-step argmax. If the step-1 token is wrong — a confident wrong answer that beat the genuinely-correct second-place token — every later token is conditioned on it. The cascade compounds.
why some engineers run code-gen at T = 0.3A little stochasticity lets you, across a few samples, occasionally escape a wrong cascade. Greedy without CoT is the most cascade-vulnerable configuration — which is one reason chain-of-thought (ch 13) helps.
it cannot supply a missing answerIf the model genuinely doesn't know, lowering T makes it commit harder to the modal-but-wrong answer. The ch-4 hallucinations (flat OR confidently wrong) don't vanish at T=0 — they become more repeatable. Temperature cannot add facts, and it cannot enforce constraints.
the lever moves earlierTemperature is the easiest knob, with the smallest effect. The rest of Block B shapes the distribution at prompt-construction time — far more leverage.

pi  =  e−Ei/kTZ,Z  =  ∑je−Ej/kTp_i \;=\; \frac{e^{-E_i / kT}}{Z}, \qquad Z \;=\; \sum_j e^{-E_j / kT}

softmax-with-temperature IS the Boltzmann distributionIdentify logit ℓ_i with −E_i / k and the two expressions coincide term-for-term. The T here is physical temperature, in kelvin — a 150-year-old object from statistical mechanics.
the limits transfer for freeHot system → near-uniform (high entropy). Cold system → concentrates on the ground state (argmax). T → 0: only the lowest-energy state. T → ∞: uniform.
definitionIn-context learning (ICL) is the phenomenon by which a model, with no weight updates, changes its behaviour in response to examples placed in its prompt. Three input→output pairs in; the fourth input gets an output that follows the pattern.
strange, on its faceNo gradient descent. No fine-tuning. No training. Just a forward pass over a longer context that includes examples. ICL is emergent — it appears at scale, in models trained purely on next-token prediction.
Brown et al. (2020) — "Language Models are Few-Shot Learners"A 175B-parameter model could perform tasks it was never explicitly trained on, simply by seeing a few examples in the prompt. Few-shot performance scales sharply with model size; one-shot and zero-shot do not.
the real headlineNot "we made a bigger model" — "an unexpected new capability emerged at scale: it can learn from examples in its prompt, with no parameter updates." That capability is what every pattern in this lecture exploits.
no new algorithm — the same attention machineryThe examples are additional context tokens. The forward pass — unchanged from Lecture 5 — builds Q, K, V, computes attention, mixes values, layer by layer. At the final position, heads route back over the example tokens; the values they pull in shift the representation, which shifts the unembedding logits, which shifts the output distribution.
not "training data"The weights are unchanged. The behaviour shift is entirely a consequence of changing the conditioning context for the same fixed function. ICL is attention-based conditional pattern matching.
Olsson et al. (2022)Trained transformers contain attention heads that implement one very specific routine — and these heads are tightly correlated with the model's ability to do in-context learning.
AB ··· A → predict B
the rule, in one lineIf you saw [A][B] earlier, and now you see [A], predict [B]. Find the previous match → look at the next token → route there.
Predict it
apple → red  ·  banana → yellow  ·  cherry → ?
Call the next token before the reveal. What is the induction head about to do?
Induction head routing pattern Seven tokens. Current token "cherry" at position 7 matches the earlier "cherry" at position 5; the induction head routes attention from position 7 back to position 6 — "red". induction head routes here apple red banana yellow cherry red cherry pos 1 pos 2 pos 3 pos 4 pos 5 pos 6 pos 7 previousmatch ↑ attentiontarget current(query)
The current token cherry (pos 7) appeared at pos 5; the token right after that match is red (pos 6). The head routes from pos 7 back to pos 6 — so red's value mixes into the current representation, biasing the next token toward red. Find previous match → look at the next token → route there.
def get_user(id: int ··· def get_order(→id: int
Q: capital of France?A: Paris ··· Q: capital of Spain?→A: …
same head, any payloadCode signatures, Q→A formats, translation pairs — the induction head doesn't care what the tokens mean. It matches the shape of "what followed this before" and continues it.
Min et al. (2022)Take a classification task. Replace the demonstration labels with random labels. The expected result — accuracy collapses. The actual result: only slightly lower than correct labels, and much higher than zero-shot.
what actually transfersThe format (input on one line, output on the next), the input distribution, the label space, and the task identity — not primarily the correct answer. The demonstrations are format and task-identity cues first, answer guides second.
Zero-shot — no demonstrations Flat
Mass spread across many continuations — the top-1 may not even be a label token (positive? mixed? the?).
Query review: "The plot dragged for the first hour but the ending saved it." With no demonstrations, the distribution over the next token is flat — the model has no structural cue for the task.
Few-shot — correctly-labelled Peaked ✓
Peaked on positive — the right label for this review.
Few-shot — randomly-relabelled Peaked, but wrong
Still peaked, still on a label token — but negative. Format transferred; correctness didn't.
Demonstrations shape the peak; their content shapes which peak wins. The "wrong" peak on the right is the load-bearing observation behind Min et al.'s result.
For project-specific conventions, examples beat instructions. Format transfers; content is secondary.
the bridge to few-shot in practice — show, don't tell
Checkpoint: ICL and induction heads
four to keep 1. ICL = attention on demonstrations, no weight update.   2. Induction heads: [A][B]…[A] → [B].   3. Format > content (Min et al.).   4. This is why few-shot works — and why it works even with imperfect examples.

§11 is the theoretical anchor for everything in §12–§14. Next: turning it into engineering.

Zero-shot baseline — "just ask"
What it is task description + input; no demos, no role, no reasoning trigger
Mechanism (L5) relies on pre-training + RLHF; distribution shaped by training statistics alone
SE example normalize_email — direct instruction, general Python knowledge
Evidence cue a direct instruction; no examples, no role, no reasoning request
When it fails conventions or coverage matter → task under-specified → model fills gaps from priors → hallucination
the baselineEvery other pattern improves on this by adding context that shifts the distribution. Zero-shot is fine when the task is well-represented in training data.
Rule Detail Source
k = 2–4 examples the first 1–2 carry most of the lift; past ~8, diminishing returns §12.1
Order matters put your best example last — recency bias near the query §12.2
Format > content match input shape, output shape, delimiters Min 2022
Avoid conflicts conflicting demos → flatter distribution than no examples §12.2
Known-good only the model faithfully repeats bugs in your examples §12.4
Few-shot show k input→output pairs
What it is k = 2–4 complete input→output examples before the query
Mechanism (L5) induction heads route from query to earlier outputs (Olsson 2022)
SE example project-convention code gen — get_user_by_id (exercise Card 2)
Evidence cue 2–4 demonstration pairs; "follow this pattern"
When it fails wrong / conflicting / off-distribution examples → garbage continuation
watch the orderRecency bias: the example nearest the query carries the most weight. Forward link to L7 — codified few-shot patterns become skills.
for project-specific conventions, show — don't tellPaste 1–2 existing repo functions before asking for a new one, and the model matches naming, ORM usage, return style, and type hints in one shot. A prose description of those same conventions rarely achieves the same consistency.
whyThe induction heads route over genuine examples of the codebase's idioms. Instruction-style asks the model to reconstruct the pattern from a verbal description — many constraints, many ways to misread. Few-shot is indispensable for AI coding tools for exactly this reason.
# Stack Overflow Challenge (Act 1) — same task, three ways

zero-shot  "…query the Stack Exchange API for monthly counts…"
    → hallucinates /api/v2/questions/monthly

few-shot  + 2 real calls to api.stackexchange.com/2.3/questions
    → endpoint hallucination collapses

few-shot + CoT  + "first list the APIs you'll call, then code"
    → catches the hallucination in the plan, before code
the progressionzero-shot → few-shot → few-shot + CoT — the decision tree we formalise in §16, anchored in your own Act 1 artefacts.
Wei et al. 2022 · Kojima et al. 2022Prompt the model to show its working before the answer, and accuracy on reasoning-heavy tasks jumps 10–30 points (it doubles on some). Kojima: most of the gain needs no examples — just "Let's think step by step."
the mechanism, in one lineIntermediate reasoning tokens become attended-to context for later tokens. CoT trades fixed depth for length — the model writes notes to itself, then reads them back.
Direct generation — one forward pass
pass 1
answer
↑
Layer N
⋮
Layer 2
Layer 1
↑
prompt
depth = N
Chain-of-thought — L+1 passes; each reads the growing context
pass 1
t1
↑
N
⋮
1
↑
prompt
pass 2
t2
↑
N
⋮
1
↑
promptt1
pass 3
t3
↑
N
⋮
1
↑
promptt1t2
…
pass L+1
answer
↑
N
⋮
1
↑
promptt1t2t3…tL
effective depth = N × L
Each pass is one full N-layer forward pass emitting one token, appended to the next pass's input. By the time the answer pass runs, its input contains every prior intermediate token — each itself the output of N layers. Same architecture, same N; L-times the effective depth.
Chain-of-thought reason before answering
What it is ask for intermediate reasoning ("think step by step" / "plan, then code")
Mechanism (L5) auto-regressive loop as scratchpad; trades depth for length (Wei/Kojima 2022)
SE example "list the APIs you'll call, then write the code" — catches hallucinations
Evidence cue "think step by step", "plan first", "explain your reasoning"
When it fails simple lookups (pure overhead); cascades a wrong intermediate step
row 5 is criticalCoT is not free — it costs tokens, can cascade errors, and the visible reasoning is not necessarily faithful (§15.3). Don't treat the chain as an audit trail.
the prompt"First list the external APIs you need. Then check: does each API actually exist? Then write the implementation."
why it works — Block A meets Block B§4's API hallucination was a no-ground-truth-check problem. CoT adds intermediate tokens that force the model to name the API explicitly — where it can be checked against demonstrated patterns. The hallucination surfaces in the plan, not in the code.
Simple lookups"Capital of France?" in ten times the tokens. Pure overhead — the answer was one forward pass away.
Cascade on reasoningA wrong intermediate step conditions every step after it — first-token cascade, moved to the reasoning chain.
No knowledge to addCoT extends depth, not knowledge. It can decompose a known task; it cannot summon a fact the model lacks.
Faithfulness illusionYou can read the reasoning — but it is not necessarily faithful to the internal computation. Verify with tests, not prose.
Feng et al. 2023 · Merrill & Sabharwal 2023There are problem classes provably hard for direct generation in a fixed-depth transformer that become tractable once the model may generate intermediate reasoning tokens. CoT moves the model into a strictly more expressive regime.
why it mattersThe chain-of-thought gain is not an empirical accident. It is the model accessing more computation by spending more tokens — a circuit-complexity result we state but do not prove.
o1 · DeepSeek-R1 · extended thinkingSame attention, same FFN, same N layers, same loop — no new mechanism. They are trained to generate long internal reasoning traces before answering. The auto-regressive scratchpad is the entire story; the model just uses it aggressively.
what changes for promptingPrompt for the goal, constraints, context, tools, output format, and verification criteria — not for a visible chain-of-thought. Over-prompting "let's think step by step" on a reasoning model degrades quality.
Step What happens L5 mechanism
1. Sample N paths N CoT chains at T > 0 (≈ 0.5) non-zero temperature → diverse reasoning
2. Each reaches an answer every chain ends in a final answer auto-regressive scratchpad
3. Majority vote aggregate the N final answers distribution over answers is narrower than over paths
4. Return the mode take the most common answer variance reduction (Wang 2022)
why it worksMany reasoning routes; they often converge on the same answer. Trust where independent noisy votes agree — the first test-time-compute scaling result.
Self-consistency sample many, vote
What it is sample N CoT paths at T > 0; return the majority answer
Mechanism (L5) variance reduction; paths broad, answers concentrate (Wang 2022)
SE example hard one-off eval; pipelines where correctness > latency
Evidence cue multiple independent generations; a voting / aggregation step
When it fails the wrong answer is the mode; costly (N× inference)
production realityYou rarely implement this by hand — reasoning models internalise it. But "many paths, majority vote" is the first test-time-compute-scaling idea. When you see "extended thinking," this is the ancestor.
the formal coreIf any single path is correct with probability p > 0.5, the majority of N independent samples is correct with probability much higher than p — the law of large numbers, applied to reasoning.
consensus as a diagnostic38/40 agree → high confidence. 12/40 split → the task is ambiguous; escalate to human review. In practice this is what self-consistency is most used for — detecting when the model is hedging, not winning an extra accuracy point.
Checkpoint: prompting patterns
five claims to keep 1. Zero-shot = baseline, relies on RLHF.   2. Few-shot = induction heads; format > content.   3. CoT = auto-regressive scratchpad; depth for length.   4. Self-consistency = variance reduction over paths.   5. Every pattern has a failure mode.

Four patterns covered. One more — role priming — in the synthesis. Then the pattern library ties it together.

when the output has a grammar, don't rely on promptingJSON, a typed tool call, an enum value, a schema — the inference engine compiles the grammar to an FSM / pushdown automaton and masks the logits at every step so only grammar-valid tokens can be sampled. The model never has the option to emit an invalid character.
it enforces shape, not truthA schema-valid JSON object can still contain hallucinated values. Use prompting to explain the task; use constrained decoding + a parser to enforce the shape. This is enforcement at the sampling layer — not prompting.
What you need Why prompting alone fails Right tool
Output adheres to a schema describes, can't enforce structure constrained decoding (§15.1)
Answer grounded in current facts pre-training is frozen retrieval (RAG), tool calls, doc injection
Code correct, not just plausible fluent code can still fail on real inputs tests, static analysis, type checks, review
Action respects trust boundaries instructions are influence, not enforcement permissions, sandboxing, secrets isolation, audit
faithfulnessA chain-of-thought trace — elicited by "think step by step" or produced internally by a reasoning model — is a signal, not a guarantee. The model can generate a clean, plausible chain that justifies the answer post-hoc rather than deriving it (Lyu et al. 2023).
the ruleAsk for a plan, trace, or checklist when useful. For high-stakes verification, lean on outcome tests, schema validation, source checks, and human review — not the readable chain.
Model class Best prompting style Common mistake
Standard chat clear task, examples, output format, optional CoT trusting the visible chain as audit trail
Reasoning model goal, constraints, criteria; let it reason internally over-prompting visible CoT
Coding agent repo context, task boundaries, acceptance tests, scope treating CLAUDE.md as enforcement
Tool-using agent clear permissions, typed schemas, scoped credentials trusting unsanitised tool returns
the framingThe right prompting pattern is a function of the model class, not a universal recipe.
prompt injection — OWASP LLM01Untrusted input — in a document, a web page, a tool result — can override the application's instructions. To attention, CLAUDE.md tokens and attacker-injected tokens look the same. The model isn't "tricked"; it follows the most plausible continuation.
not all instruction failures are accidentalCLAUDE.md drift is a reliability problem. Prompt injection is a security problem. For adversarial input, assume the influence layer is defeated — safety lives in enforcement (sandboxing, validation, permissions) and human review.
Role priming set perspective & register
What it is assign a role — "Act as a senior backend engineer"
Mechanism (L5) RLHF taught persona tokens to bias attention toward a matching subspace
SE example code review (Card 3): role + rubric + structured output
Evidence cue "Act as…", "You are…", explicit role + rubric
When it fails theatre if the role changes only tone, not substance
role alone is insufficient"You are an expert" without a rubric is folklore. Pair the role with a rubric (what to check) and structured output (how to format) — they amplify it.
Pattern What you do Mechanism (L5) Key citation
Zero-shot ask directly pre-training + RLHF priors —
Temperature set T at sampling scales logits before softmax (§14.2) —
Few-shot k input→output pairs induction heads Olsson; Min 2022
Chain-of-thought reason before answering auto-regressive scratchpad Wei; Kojima 2022
Self-consistency sample N, majority vote variance reduction over paths Wang 2022
Role priming assign a persona re-weights heads toward a subspace §16.1
Pick the pattern
"Match our repo's error-handling style in a new function."
Zero-shot, few-shot, CoT, self-consistency, or role priming? Decide, then we walk the tree.
Ask, in order If yes →
Well-known, standard task? Zero-shot · T = 0.3–0.7
Project-specific style / format? Few-shot · 2–4 examples, best last
Needs intermediate reasoning? Zero-shot CoT first; escalate to few-shot CoT
Accuracy-critical, can afford N×? Self-consistency on CoT
Judgment / perspective task? Role priming + rubric + structured output
that's the whole libraryTree-of-Thoughts, ReAct, Self-Refine, Reflexion are orchestration patterns built on top of these five — Lecture 7 and Act 3.
Pattern Failure mode Mechanism of failure
Zero-shot hallucinates a plausible-but-wrong answer no ground-truth check; flat OR confidently wrong (ch 4)
Temperature T=0 first-token cascade auto-regressive conditioning (ch 10)
Few-shot imitates misleading examples induction heads route regardless of correctness
Chain-of-thought builds on a wrong intermediate step scratchpad amplifies early commits
Self-consistency consensus on a misconception aggregates the mode, not the truth
Role priming confident in the wrong register persona shifts heads to a wrong subspace
No pattern is uniformly safe.
Better prompting: frequent → occasional. Better enforcement: occasional → caught. Better human review: caught → addressed.
Field The question to ask
Name which strategy is being used?
Evidence what phrase in the prompt reveals it?
Appropriateness is this the right strategy for this task?
Anti-pattern how does this strategy fail here?
the reusable methodFour questions, applied to any prompt. The exercise applies them to 12 real-world prompts across 11 SE task categories.
Card 3 walkthrough · role priming done right
Field Card 3 — code review
Name role / persona priming + rubric + structured output
Evidence "Act as a senior backend engineer", explicit rubric, output format
Appropriate? Yes — judgment task; perspective matters; rubric covers criteria
Anti-pattern risk if the role is only tone ("be professional") with no rubric → theatre
three ingredientsrole (who) · rubric (what to check) · structured output (how to format). Remove any one and the prompt degrades.
Card 12 walkthrough · CoT overuse
Field Card 12 — over-applied CoT
Name chain-of-thought (overuse)
Evidence "think step by step" on a simple lookup ("which HTTP code = not found?")
Appropriate? No — no multi-step reasoning; CoT adds overhead, risks a cascade
Anti-pattern CoT on a task better served by zero-shot + validation
the deeper lessonMore technique ≠ better. The right answer is zero-shot; the CoT only buys tokens, latency, and cascade risk.
Supporting techniques
Rubricwhat to check — makes role priming concrete.pairs with role
Structured outputhow to format — makes any response parseable.pairs with any pattern
Context groundingpaste relevant code / docs — makes few-shot specific.pairs with few-shot
Validationtests, schemas, CI — catches what prompting misses.the enforcement layer
amplifiers, not patternsThese four are not prompting patterns — they make the five primary patterns work. The exercise cards span all four.
exercise — 12 cards, 11 SE task categories
For each prompt card, apply the four-field lens: name the strategy · cite the evidence · judge appropriateness · name the anti-pattern — then rewrite a stronger version.
25 min (pairs) · 45–60 min (extended) · output: 4–6 diagnosed cards + reflection · interactive self-study quiz + full workshop guide online
in classWork 4–6 cards in pairs, then debrief Cards 3 and 12 — the two we just walked.
C

Closing the Board

# Mystery Status after L6
1 Why can't AI count letters? Solved (L4) — tokenisation hides characters
2 Why does CLAUDE.md help in some sessions? Solved (L5+L6 §6) — injection + drift + dilution
3 Why were English prompts often better? Solved (L4+L5) — token efficiency + attention competition
4 Why was curated context better? Solved (L5) — every token competes for the heads' routing
5 Why hallucinate API endpoints? Solved (L6 §4–5) — no ground-truth check; factual
6 Why do vague prompts give nonsense? Solved (L6 §4) — under-specified; model fills gaps from priors
7 Why is CLAUDE.md compliance inconsistent? Solved (L6 §6–7) — attention competition + lost-in-middle
8 Why do tools differ on the same instructions? Partly (L6 §3) — role hierarchy; finishes in L7
9 Why does few-shot work? Solved (L6 §11) — induction heads; format > content
10 Why does "think step by step" help? Solved (L6 §13) — auto-regressive scratchpad
11 Why does sampling + voting help? Solved (L6 §14) — variance reduction over paths
Lecture 7 — the orchestration layerThe system outside the model that decides what tokens it sees, when, and in what order. It resolves mystery 8 fully — same model, different orchestration, different behaviour.
Skillscodified few-shot patterns, loaded on demand — what we started today, formalised.
MCPthe open standard for connecting models to tools and data; the security boundary lives here.
SWE-Benchhow the field measures end-to-end agent quality — and why its protocol is few-shot.
Exercises (separate slots)Temperature experiments · hallucination taxonomy · context-vs-hallucination · the Prompt Strategy Diagnosis lab (12 cards).
Reflection logThe two halves in your words · your own pattern decision tree · a CLAUDE.md audit · the most counterintuitive finding · one question for L7.
optional readingThe originals — Brown, Wei, Kojima, Min, Olsson, Wang, Liu, Ouyang, DeepSeek-R1 — are open-access; the figures alone are worth the time (§18.3).
Better prompting: frequent → occasional. Better enforcement: occasional → caught. Better human review: caught → addressed.
three layers, three guarantees — the operational takeaway of Lecture 6

Questions?

STEERING THE DISTRIBUTION

dome.muller@googlemail.com

Welcome to Act 2, week 2. Last week we opened the box: an embedding became a distribution over the next token, and every arrow had a name. Today, two questions the mechanism alone can't answer — why does it ever go wrong, and once we know why, what do we deliberately do to steer it? Block A is the diagnosis; Block B is the engineering, and in a course called AI-supported software development, Block B is the half that matters most.

Frame the two halves and make them spatial — students should SEE the diagnosis / controls split. The five pattern names go into working memory now, before the diagnostic half begins; they are what students carry out of the lecture. Block A names the failures; Block B names the controls that answer them.

This is the sentence to carry through the whole lecture. Each time we meet a pattern, we state its one-line Lecture 5 mechanism. The prompting literature is full of folklore — "say please", "tell it it's an expert", "promise it a tip". We won't do that. If a pattern survives the next model generation, it's because the mechanism it exploits survives. Folklore doesn't survive; mechanism does.

Block A opens. Six chapters describing what fails about the model and why — all of it a consequence of one fact: the model is a probability distribution over the next token, conditioned on whatever is in its context. We refuse to call any of it a bug.

This is L5 recap compressed to one slide. Emphasise: the model was NEVER trained to be correct; it was trained to predict likely continuations. Code generation, Q&A, translation, instruction-following — all emergent from "the right pattern is in the distribution given this prompt."

Point forward from each card: "no truth" → hallucination (§4); "no grounding" → factual hallucinations; "no memory" → why CLAUDE.md is context, not config; "no goals" → why RLHF is shaping, not commanding. Everything in Block A is a consequence of this single fact.

You have never used a base model. Give a base GPT-style model "What is the capital of France?" and two of the most likely continuations are "Paris." and a list of more capital-of questions — both abundant in training. The base model has no preference. Students need to see this before we explain SFT and RLHF: post-training creates the assistant preference; the architecture does not.

Post-training = SFT (teaches the format) + RLHF (teaches preferences). Neither teaches facts. Depth guard per hints: do NOT derive PPO, GRPO, or reward-model training — students need WHAT, not HOW. Same architecture as pre-training throughout; only the distribution of training contexts changed.

The conceptual hinge of Block A. Every student misconception about RLHF — "it teaches the model to be truthful" — dies on the right-hand column. Post-training shifts STYLE and BEHAVIOUR far more than KNOWLEDGE. The right column predicts §4–§7: hallucination, compliance drift, jailbreaks.

Short beat — deliver the line and let it land. The single most common student misconception about post-training. The confident style is layered on top of a base distribution with no truth check — the falsehood can be flat OR a sharp, confident peak; that combination is exactly what makes a modern hallucination dangerous.

EXTENDED. Signals that the field is moving beyond PPO but the principles of §3 hold. R1 is more directly relevant to chain-of-thought than to the general post-training story — we'll return to it in §13.7.

Let the quote sit. Then: "The next slide makes this visible." The mechanism that produces a perfect validate_email and the one that produces a non-existent endpoint are the SAME mechanism — only the shape of the conditional distribution differs.

THE teaching visual for §4. Walk the left chart: lots of "capital of France" in training → peaked, Paris near-certain. Walk the right: no specific endpoint in training → flat, many near-equal options. The model samples from whichever shape it gets; there is no ground-truth check and no "I don't know" token that wins by default — so it completes the pattern anyway. That can be a flat guess OR a confidently-wrong sharp peak; either way it is the hallucination. Mystery 1: resolved.

Anchor each card in an Act 1 example students have seen: Factual → Stack Overflow challenge; Structural → Locust exercise; Confident-nonsense → the requests example. Three categories, three different mitigations — not all hallucinations are alike.

Stress that each category needs a different response: retrieval (factual), grounding/schema (structural), verification (confident-nonsense). Foreshadow the three-layer model from §8. Mystery board: resolves invented endpoints, hallucinated signatures, and confidently-wrong explanations simultaneously.

Quick consolidation. ~30 min mark. Then: "Next — why CLAUDE.md sometimes feels like it doesn't exist."

Quick framing. Students used CLAUDE.md in Act 1 — they have experience with inconsistent compliance. This slide names the problem; the next three explain it. Everywhere we say "CLAUDE.md," mentally substitute "your tool's instruction file" — the analysis carries over unchanged.

Walk the three bars. At 1K tokens CLAUDE.md is half the context; at 150K it is 0.3%. Attention at every step is a row-wise softmax over the whole sequence — softmax is winner-take-most, so the instruction file's share of positions shrinks but a learned-important token can still win strongly; it just competes with more newer, local tokens. There is no "config priority": the instruction file is just more text. This is context-drift arithmetic, not a failure of the file or the loader.

High cognitive load — keep the visual clean. Different heads attend to different parts of context; some specialise in recent tokens, some in positional patterns. Treat as a QUALITATIVE mechanism, not a precise prediction — we cannot say which heads route to which rule in a model whose internals are not public. CLAUDE.md compliance is probabilistic because head allocation is.

Let this land. This is why compliance is inconsistent — and why the three-layer model, two slides away, insists on enforcement and human layers alongside the influence layer. The model is doing exactly what its mechanism says: most attention on the most recent, most task-relevant context.

EXTENDED. The economic argument for prompt caching + the mechanism argument for why cached instructions still influence (they're in the KV cache, attending to new tokens). Keep KV caching and prompt caching apart: KV is per-request and automatic; prompt caching is the cross-request lever that makes a big AGENTS.md cheap.

EXTENDED. Visual complement to the caching table. The red dot at pos 500 lines up vertically across all three rows: the model's view of AGENTS.md hasn't moved — caching only changes what must be recomputed.

Liu et al. 2023. The model retrieves best from the beginning and end of context; the middle is a dead zone — a 20+ pp drop. Chroma's "context rot" (2025) confirms it across 18 frontier models. Striking because attention is global — the positional preference is an empirical fact of trained models, not a prediction of the architecture.

Translate the U-shape into actionable rules: front-load, keep concise, repeat critical items. These also apply to system prompts in API usage. One caveat: rules a linter/hook can enforce belong in the enforcement layer, not the influence layer — CLAUDE.md is for conventions tooling cannot decide.

The framework that closes Block A and carries through the course. The value is not in the three layers but in how they fit: you cannot replace one with more of another. Influence alone is fragile; enforcement alone is brittle (a linter can't tell you the function does the right thing); human alone doesn't scale. Production uses all three.

This table is the analytical lens the exercise uses — students classify prompt strategies into which layer they serve. "You cannot replace one layer with more of another." Mention the teaching-repo asymmetry briefly: a missing enforcement layer is most visible when it is missing.

Transition beat. "Take a break if you need one — we're about to switch from why it fails to how to steer it." The answer is a small library of named patterns, each with a one-line mechanism and a citation.

~55 min mark. Five claims. If you remember nothing else from Block A, remember these. Block B builds controls on top of each one.

Block B opens. The positive space. Every pattern here is a deliberate use of an L5 mechanism to make the distribution sharper around correct answers. We open with the simplest control — temperature — then in-context learning, few-shot, chain-of-thought, self-consistency, role priming. Real theory, with citations.

You saw softmax in L5. Temperature adds ONE parameter applied to the logits before softmax. T < 1 sharpens (greedy end); T > 1 flattens (creative end); T → 0 is argmax. This is the first engineering control — the sampling-time knob.

Walk each chart. T=0.1: nearly deterministic — always the top token. T=1.0: the trained distribution, the default. T=2.0: almost random — good for brainstorming, terrible for correctness. The dial above shows where each T sits on the peaked↔flat scale.

Match temperature to the task. Code that must compile → low T. Generating test-case variations → higher T. Production chat default is T ≈ 0.7 — covers "want a good answer, don't need a unique one."

Don't memorise the table. Trace one row: 'potion', logit 4.2. At T=0.1 its probability ≈ 1.0; at T=2.0 it drops to 0.35 and 'fire' rises to 0.20. Same logit, different temperature, dramatically different sampling. T only re-weights; it cannot promote 'fire' to the top — only the logits can.

This is why T=0 code generation sometimes produces spectacularly wrong output with total confidence: the first wrong token locks in the wrong direction. Greedy gives the per-step argmax, not the most-probable sequence — beam search escapes some traps but is rarely used (repetitive 'beam search curse').

Temperature is necessary but insufficient. Missing context that under-specifies the task isn't supplied by any T — the model still fills gaps from learned priors. Temperature controls the shape of sampling, not the quality of the distribution. The patterns in the next chapters shape the distribution itself. (Temperature experiment available for self-study.)

EXTENDED. The name 'temperature' comes from statistical mechanics — same math, different domain. This is why the engineering regimes have such clean limits: they're the Boltzmann limits since the 1870s, applied to a discrete vocabulary.

This is the substrate of few-shot prompting. The model doesn't change — the context changes, and attention routes differently. There is no piece of the training objective that says "follow demonstrations"; ICL was one of the central findings of the GPT-3 paper.

2020, the GPT-3 paper — the moment few-shot prompting became a serious engineering tool. Small models barely benefit from in-context examples; GPT-3-scale models benefit dramatically — 10–30 points on some benchmarks. Block B's patterns work because the model you call is large enough to do ICL.

No magic. The examples are tokens; attention is over all tokens; the model's query at the new position routes to the example outputs. That's the mechanism. The next slide makes the routing literal — induction heads.

This sounds trivially simple. It is. The remarkable fact is that it is exactly the algorithm few-shot needs — and it emerges at a specific point in training (Olsson et al. trace a phase-transition "bump" in the loss curve where induction heads form). It is empirically traceable: real heads in real models.

Interaction beat. Ask the room to call the token before revealing the routing on the next slide. They should reach for "a colour" — because the pattern is fruit→colour, and the induction head routes from the second 'cherry' back to whatever followed the first one.

High cognitive load — walk slowly. Step 1: a head finds "I saw this input before." Step 2: another head copies "what came after it last time." Two heads working together = induction. This is why few-shot works: you are giving the induction heads material to match against.

EXTENDED. More examples reinforce that induction heads work across domains: function signature → return-type pattern; Q: → A: pattern. The head routes on structure, not semantics — which sets up Min et al.'s "format > content" result on the next slide.

The most counterintuitive result in the ICL literature. Random labels, still better than zero-shot. In induction-head terms: the heads still route to the position after the previous similar input; if the label there is random, the conditioning is "the format is label-shaped" without "the answer is X-shaped." Engineering consequence: invest in format, not perfect example answers.

Zero-shot on sentiment classification: the model doesn't know what format to respond in. The distribution is spread across many tokens — "positive", "negative", "the", "it". This is the baseline; the next slide adds two demonstrations and watches it sharpen.

Left: correct labels, peaked on 'positive' — expected. Right: RANDOM labels, still peaked — on a label, just not always the right one. The shape changed because the FORMAT was demonstrated, not because the correct answer was. The induction heads care about the positions of the demonstration outputs, not whether they were right.

The bridge to §12. When you paste three examples of your codebase's error-handling style, the model matches the format — naming, return patterns, type hints — because the induction heads route on structure. This is the principle that underpins all of few-shot practice.

~90 min mark. Checkpoint before the pattern chapters. §11 is the theoretical anchor for the five patterns.

The first technique card. All five share the same five-row shape — study it; it's the diagnostic lens the exercise uses. Zero-shot = "just ask." Works when the task is well-represented in training data; wrong tool when conventions or coverage matter.

Five rules. k=2–4 is the sweet spot. Order matters — best example last (recency). Format transfers more than content. Past ~8 you waste context. Few-shot fails when examples conflict or are off-distribution, and it is exactly the wrong tool when you lack known-good examples.

Same shape as zero-shot. Row 2 points back to §11 (induction heads); row 5 points forward to the §16 failure-mode table. Forward link to L7: a skill is a codified few-shot pattern loaded on demand.

The most practical takeaway from §12. In your Locust exercise, did you paste existing test functions before asking for new ones? That's few-shot — and it beats describing your conventions in prose. Forward link: L7 skills codify this.

Your Stack Overflow Challenge from Act 1. Zero-shot hallucinated the endpoint; few-shot with two correct calls fixed it; adding CoT ("list the APIs first") caught the hallucination before code generation. Each pattern is a different mechanism for shifting the distribution.

Two papers, one insight. Wei 2022: few-shot CoT. Kojima 2022: zero-shot CoT ("let's think step by step"). Both work because intermediate tokens become context for later tokens — the model effectively gets more compute per problem. The trigger phrase is itself a high-prior training pattern.

High cognitive load — walk it slowly. Direct: one pass, N layers, done. CoT: L intermediate tokens, EACH gets N layers; effective depth N×L. The scratchpad analogy: you wouldn't solve multi-step algebra in your head. This is a real expressivity result (Feng 2023; Merrill & Sabharwal 2023), not a metaphor.

Row 5 is critical. CoT is not free: it costs tokens, can cascade errors, and visible reasoning is not necessarily faithful. Exercise Card 12 is the anti-pattern — CoT overuse on a simple task.

This connects Block A to Block B. The API hallucination from §4 had no ground-truth check; CoT forces the model to name the API where induction heads can check it. The hallucination surfaces in the plan, not the code. For debugging, the dual is "trace, then conclude."

Four ways CoT hurts. (1) Don't ask it to "think step by step" about what day it is. (2) Wrong first reasoning step cascades. (3) CoT can't create knowledge. (4) The subtle one: visible reasoning isn't a faithful audit trail. Tests and review are the verification layer, not readable CoT.

EXTENDED. The theoretical depth. CoT provably increases the class of problems a fixed-depth transformer can solve. We state this but don't prove it.

EXTENDED. Forward pointer to the reasoning-model frontier. In production you'll increasingly use reasoning models that do CoT internally. Your job shifts from "prompt for reasoning" to "prompt for goals, constraints, criteria." Trained with RL against verifiable correctness, not just human preference.

Wang et al. 2022. Sample 5–10 CoT paths; take the majority. Individual paths are noisy; final answers concentrate. The wrong answer has to BE the mode to fool this. Variance reduction applied to reasoning — and the seed of the reasoning-model paradigm.

The fourth card. You rarely implement self-consistency manually — o1/R1 implement it internally. But the principle (multiple paths, majority vote) is the first test-time-compute-scaling idea. Fails when a systematic misconception is the mode.

EXTENDED. Deeper treatment of when consensus is a reliable signal. The agreement rate is not a calibrated probability — the model can be confidently wrong — but it's a useful diagnostic for deciding whether to escalate to the human layer.

Four patterns covered; one more (role priming) in the synthesis chapter. Then the pattern library ties everything together.

Structured outputs are the bridge between the influence and enforcement layers. Instead of asking for JSON, you constrain sampling to valid-JSON tokens (Outlines / Willard & Louf 2023). It guarantees shape, never content. Exercise Card 8 connects here.

Four situations where prompting is the wrong tool — all enforcement-layer problems. Exercise Cards 5, 7, 10 test this judgment: students must recognise when the answer is "don't prompt for this."

Connects §13.5 (CoT hurts) to the beyond-prompting picture. Exercise Card 12 is the anti-pattern: trusting visible CoT as if it were a proof. The enforcement and human layers are where verification lives.

EXTENDED. The right prompting pattern is a function of the model class. Reasoning models don't need CoT prompts; coding agents need goals + constraints, not step-by-step instructions.

EXTENDED. One slide on security. The model treats all tokens equally — which is why influence alone cannot provide security guarantees. The mitigation is permission design, sandboxing, output validation, secrets isolation, human review — most of it implemented in Lecture 7's orchestration layer.

The fifth and final card. Role priming is the most misused pattern — "you are an expert" without a rubric is folklore. Pair with a rubric and structured output. Exercise Card 3 demonstrates the full pattern.

Reference table — students will photograph this. Each row is one line: the mechanism column points back to L5; the citation column points to the literature. Every pattern reduces to attention, the auto-regressive loop, or sampling-time logit manipulation.

Interaction beat before the decision tree. The answer is few-shot (project-specific style/format → show examples). Let the room call it, then reveal the decision flow on the next slide.

Walk the tree top to bottom. Each branch maps to a task property. A simplification — real prompts combine patterns — but it gives a starting framework. The many named "patterns" in the literature are orchestration patterns built on these five.

The companion to the summary table. Every pattern fails in a specific, predictable way, traceable to an L5 mechanism. No pattern is uniformly safe.

The emotional beat. The prompting patterns are the influence layer — necessary but not sufficient. Enforcement (tests, CI, schemas) catches what prompting misses; human review catches what automation cannot encode. All three, together.

This is the method — four questions applied to any prompt. The exercise applies it to 12 real-world prompts. This slide is the setup; the next two are worked examples.

Card 3 is the model answer for role priming done right. Three ingredients: role, rubric, structured output. Remove any one and it degrades.

Card 12 is the anti-pattern. A simple task gets wrapped in "let's think step by step" — adding tokens, latency, and cascade risk. The right answer is zero-shot. More technique ≠ better.

Four amplifiers, not patterns. Rubric makes role priming concrete; structured output makes responses parseable; context grounding makes few-shot specific; validation catches what prompting misses. The 12 exercise cards span all four.

Point to the interactive quiz for individual self-study. In class, have pairs work 4–6 cards, then debrief 2 as a group (recommend Cards 3 and 12 — the ones we just walked). The exercises run outside the theory deck.

The closing. The mystery board from Lecture 1 onward — started before students had any of this vocabulary — almost fully resolved. Then the bridge to Lecture 7's orchestration layer.

Walk the table quickly — students have tracked these since the board was introduced. Ten solved; one (mystery 8 — orchestration) partly solved, awaiting L7. The framing of Act 2: learn the mechanism, and the surprises stop being surprising. Promise kept.

Brief. Skills are codified few-shot patterns — L7 formalises what we started today. MCP is the tool-use protocol. SWE-Bench is how the field measures end-to-end agent quality. The influence layer gets an orchestration layer.

Deliverables and next steps. The exercise is the centrepiece — do it in pairs. Temperature experiment is self-study. Reflection log due by next session. Optional reading for the curious. Exercises run outside the theory deck.

If you remember one thing from today, it's this. Prompting is the influence layer — necessary, powerful, and insufficient. The full stack — influence + enforcement + human — is how production systems work.

Thank you. Act 2 is nearly closed — the board is almost empty. Next week, Lecture 7: the system around the model, where mystery 8 comes down for good and Act 3 begins.