# Weeks 13–14 (Tokens, Attention, Transformers, GPT) — Notes Catalog & Rewrite Plan

> **2026-10-17 (later): the note outlines, numbers and open questions here are superseded by
> `WEEKS_11_14_NOTES_PLAN.md`** (synced to the final HW6/HW7 runs). This file remains the source catalog
> (§3), notation standard (§4) and figure list.

**Status (2026-10-17): PLAN, not executed.** No note has been written yet. Everything in §1 is a
*proposed* decision for the instructor to accept or change. The plan follows the structure of the Weeks 7–8
plan (`3_generative_models/lecture_notes/WEEKS_7_8_NOTES_PLAN.md`).
**Scope:** the three annotated lectures in `7_adv_NN/notes/`; the `Attention/`, `TRN/` and `Word2vec/`
subfolders; the distill Reader-View PDF; McCormick's word2vec tutorial; the d2l book (ch. 11, 15) and the
STAT157 decks in `7_adv_NN/non_public/smola_d2l_book/`; last year's HW7 code (`2.5_NN/HW7/`,
`2.5_NN/non_public/HW7_solution/`); and the syllabus rows `week13` and `week14`.
**Contract:** `2.5_NN/HW7/HW7_26F.html` (draft, 290 points: P1–P5 programming, P6–P7 theory, P8–P12
optional), read with `claude_renovation_0826_code/HW5_6_7_NN_PLAN.md` §8, whose decisions log overrides that
plan's earlier sections.
**Target:** 5 consolidated notes, 3 basic carrying HW7 and 2 advanced, plus one lecture plan per basic note.
They cover 4 regular lectures plus this term's extra one.

> Weeks 13–14 have no consolidated notes. The only notes-like material is the instructor's three annotated
> STAT157 decks, which were given in the summer in the order Attention (8/6) → Transformer (8/8) →
> Word2Vec (8/13, last class). That order is backwards for HW7. **Tokens and embeddings must come first**
> (HW7 P1, and the "tokens → IDs → embeddings" order rule in the NN plan §8 item 6).

---

## 1. Decisions (proposed)

| # | Decision | Consequence |
|---|---|---|
| 1 | **Three basic notes, not two**: `TOKENS` (P1), `ATTENTION` (P2, P3, P6), `TRANSFORMER` (P4, P5, P7) | P1 is a separate topic (text → pieces → vectors) with its own lecture. A merged `TOKENS_ATTENTION` would run about 28 pp, too long for one basic note. Three notes for five lectures matches the Weeks 7–8 ratio. |
| 2 | **Everything P5 needs is taught by Thu 12/10.** The Mon 12/14 lecture (the day before the 12/15 due date) carries only optional and review material | The **extra lecture goes in the week of 12/7** (see §7). If it can't, `TRANSFORMER` §7–9 (GPT, pre-norm, sampling) moves into 12/10 and the encoder–decoder block details become reading. |
| 3 | **Attention is introduced as the course's own kernel smoother**, from the instructor's "Flashback" board (Lecture 8/6 p5) | `ATTENTION` §2 cross-references `LOCAL_CLASSIFIERS` (soft k-NN, KDE) and `KERNELS`. A query looking up keys is the Week 2 weighted average with a learned similarity. This is the only conceptual step weak students must take, and they have already taken it once. |
| 4 | **The encoder–decoder Transformer is the thinking framework; GPT is the practical model** (instructor emphasis 2) | `TRANSFORMER` §1 draws the full model and lists every part with "where you've seen it". §7 *derives* GPT by deleting the encoder and cross-attention from that same figure, then compares the two models in practice and in theory (table). This is the GAN-note principle: assemble known parts and name only what is new. |
| 5 | **Subwords, not words** (instructor emphasis 1) is stated in the first section of `TOKENS`, with **the subword-in-LLMs table** | Repeated in `TRANSFORMER` §10 (the tokenizer column of the three-families table) and in HW7 P1(A)'s side question. Picks up from the Week 12 RNN note, which explains why word-level is fine for TinyStories (coordinate with the parallel Weeks 11–12 plan). |
| 6 | **Pre-norm vs post-norm is taught as the residual-path argument from HW6's ResNet**, not as a performance claim | Pilot: 4-layer GPT post-norm 13.53 vs pre-norm 13.44 perplexity, so no visible difference. The note says so plainly. P5(B) asks for a *why*, not a demonstration. |
| 7 | **Sampling (greedy, temperature, top-k) is taught in full in the basic note** | d2l has no sampling code (only greedy and beam in 10.8, and temperature as the exercise $Q\propto P^\alpha$ in 4.1). The note gives the formulas, a worked distribution, and the "check probabilities, not text" rule from NN plan §8 item 3. |
| 8 | **Batch-major everywhere in Weeks 13–14**, with one bridge box for HW6's time-major RNN tensors | Full standard in §4. The starter sets `batch_first=True` on every `nn` layer. The notes never show a time-major attention tensor. |
| 9 | **Draw our own figures** (TikZ, or a `build_*_figs.py` for plots). Redraw the instructor's boards; link d2l figures rather than embed them | d2l.ai text and figures are **CC BY-SA 4.0**. Embedding one requires a credit line, and an adapted figure would have to be share-alike. Redrawing keeps the notes' licensing simple. The few places where a d2l figure is the better picture are listed in §8 with a credit line ready, but the default is redraw. |
| 10 | **Lecture plans: yes, one per basic note**, in the GAN/VAE format (100-min table, `xr-hyper` into the note, a separate unlinked `_lecturePlan.pdf`) | `TRANSFORMER`'s plan has two pages, since it spans two lectures. |
| 11 | **Nothing in the lecture column is retired.** The three annotated decks stay linked directly under the new notes | Tier 4 (§3.4) lists only chat transcripts, duplicates and unlinked non-public copies. |

---

## 2. House style the new notes must match

As in the Weeks 7–8 plan §2, plus the conventions recorded in its §8.4:

- **Naming/location:** `TOPIC[_ADVANCED]_claude_MMDD.{tex,pdf}` under `7_adv_NN/notes/<subfolder>/`, each
  subfolder with `images_claude/` and a `build_*_figs.py`. Proposed subfolders are `TOKENS/`, `Attention/`
  (existing; reuse it) and `TRANSFORMER/`. ⚠ The Dropbox volume is case-insensitive, so a new `ATTENTION/`
  would silently merge into `Attention/`.
- **Preamble and environments:** `extarticle` 12pt, `margin=0.5in`, 13/16pt, TikZ; `remark`, `keypoint`, `pseudo`,
  `example`; `\Sig` macro (no covariance appears here, but keep the shared preamble).
- **Title:** `<Topic>: <subtitle>` + `\large Lecture Notes Consolidated with Claude AI --- CS6140 Machine Learning`.
- **Opening blurb** with prerequisites only. **No "supports HW" tags.** A **HW7 Map section at the end**.
  Inline HW references appear only where they tell the student something specific.
- **Arc:** big picture first (block diagram + "parts: where you've seen it / NEW" table) → narrated
  derivations → **worked numeric example usable as a unit test** → algorithm box → HW map + common bugs →
  forward pointer. About **10 top-level sections**.
- **Shapes in every boxed equation.** A shape line like `(B, T, d) → (B, h, T, d/h)` is the most useful
  thing a weak student can check against their tensor.
- **No solution code for `TODO_STUDENT` blanks.** The notes give equations, shapes and algorithm boxes in
  pseudo-code. The starter's own checkpoint cells are the code-level check.
- **Length:** basic ≈ 14–20 pp, advanced ≈ 8–14 pp. Advanced notes are labelled just "(optional)" in the
  syllabus.
- **References** in the advanced notes (Vaswani, Devlin, Radford, Raffel, Sennrich, Mikolov, Pennington,
  Bojanowski, Kudo, Xiong, Su, Shazeer, Ainslie, Dao, Kaplan, Holtzman) are resolved and verified through
  LibKey at write time, not from memory.

---

## 3. Catalog

### 3.1 Tier 1: the instructor's own material (absorb; **keep linked**)

#### `Lecture_WordToVec_081325.pdf`: "22. Embeddings, Word2vec, fastText, GloVe" (20 pp, annotated)

| pp | Content | Handwritten | Verdict |
|---|---|---|---|
| 1–2 | Logistics; Game of Thrones word-viz | none | skip |
| 3 | One-hot | "word ID in 300-dim vector ≡ 300 words ⇒ #dim = #vocab"; "no easy sim()" | absorb → `TOKENS` §5 |
| 4 | word2vec idea | "300 dim real numbers"; "dot prod for sim"; "probability model → multiple ways"; "loss min ≡ meaningful word vectors"; "tricks for fast computation" | absorb → §6 |
| **5** | **Full board: the word2vec network.** One-hot input of dim D = \|vocab\| for i = "machine" → dense weights → 300-dim hidden h₁…h₃₀₀ ("after training h['machine'] = embedding vector") → output dim D, o_j ≡ prob/sim(i,j) = co-occurrence, j = "learning"; labelled "NN autoencoder / similar" | the whole page | **MUST KEEP.** Redraw as TikZ, `TOKENS` Fig 4 |
| 6–7 | Skip-gram likelihood | "naive assumption of indep" (product of probabilities); "embed as center / embed as context"; "softmax (dot prod score)"; "normalization over all words" | absorb → §6 |
| **8** | **Full board: "TRICKS for computation."** Approximate the softmax by not computing the denominator and using σ(u_cᵀv_o) instead ("much easier"), meaning prob(in window); P(D=1\|w_t, w_{t+j}); negative sampling with words *not* in the window ("select some, not all"), 1−σ(u_cᵀv_n); subsampling P = max(1−√(t/f(w)), 0) | the whole page | **MUST KEEP.** This is HW7 P1(B). Absorb → §7 |
| 9–10 | Negative sampling | "simplify/approx SOFTMAX"; "max likelihood = binary logistic regression" | absorb → §7 (the HW2 link) |
| 11 | Book p. 15.1.6–15.1.8, full-softmax gradient | none | → `TOKENS_ADVANCED` §1 |
| 12–14 | CBOW | "REVERSE COND PROB"; "no naive product/indep, evaluate score on all context"; "dot product on wide window" | → `TOKENS_ADVANCED` §2 |
| 15 | t-SNE clusters picture | none | cite idea in §8 |
| **16–17** | **fastText** | "stemming/lexicographics: friend = friends = friendship = friendness…"; "embedding = Σ embed(grams)" | **Keep.** The subword idea *before* BPE. One paragraph in `TOKENS` §2 as the bridge to BPE; detail in `TOKENS_ADVANCED` §5 |
| 18–20 | GloVe | "general wordvec pretrained (large corpus), tune for your specific corpus"; x_ij "MULTICOUNT"; "download various sizes"; h(x) "monotonic, control scale and sensitivity"; "approx, easier to compute" | → `TOKENS_ADVANCED` §4 (HW7 opt. P12) |

#### `Lecture_Attention_080625.pdf`: "Encoder-Decoder, Seq2seq, Attention" (36 pp; handwriting on pp 2–12, 15)

| pp | Content | Handwritten | Verdict |
|---|---|---|---|
| 2–3 | Plan; motivation (hello world → bonjour le monde) | "Attention = a new layer in NN"; "from RNN parts ⇒ K? q? V?"; lesson outline "setup (q,k,v,α,h) → math → code (d2l)"; "Attention is ALL you need (2017)" | absorb the outline as `ATTENTION` §1's roadmap |
| 4 | Attention layer | Glossary: q queries, k keys, v values, α = sim(k,q) "kernel", d dim, H hidden, **h = #heads**; Attention(q, D={k,v}) = Σ α(q,k_i)v_i, "weighted_avg(v_i)"; "current step query / prev steps" | absorb → §2; **notation source** (§4) |
| **5** | **Full board: "Flashback."** α = similarity kernel; weighted average by similarity ("HW5" = the old numbering of the kernel-regression HW); pred(z) = Σα(z,x_i)Y_i / Σα(z,x_i) (Nadaraya–Watson); "α high ⇒ pred(z) should pay ATTENTION to x_i"; Σα = 1, α ≥ 0 ⇒ softmax of a linear score | the whole page | **MUST KEEP.** Decision 3. `ATTENTION` §2 + Fig 2 |
| 6 | Attention-layer formulas | labels | absorb |
| **7** | **Dot-product attention board.** "linear kernel" score ⟨q,k⟩; "SCALE DOT PRODUCT, scale by length"; **Euclidean derivation:** −½‖q−k‖² = qᵀk − ½‖k‖² − ½‖q‖², with the norms "irrelevant (normalization, scaling)" and qᵀk "matters" | the whole page | **MUST KEEP** → §3. ⚠ State it precisely: ‖q‖² is the same for every key, so it cancels *exactly* in the softmax. ‖k‖² varies by key, so it cancels only when the keys have equal norms (d2l 11.3 makes the same caveat). |
| **8** | **"Attention 'Pooling' as similarity computation" board.** Kernels: linear ⟨q,k⟩/√d ("important for parallel computation"), Gaussian, Gaussian with width σ, boxcar, max{0, 1−‖q−k‖}; "Masked Softmax: sequences of different lengths" | the whole page | **MUST KEEP** → §3 + Fig 3 (kernel shapes), §5 (masking) |
| 9–11 | Additive (MLP) attention; **Bahdanau board**: c_t = Σ_s α_{t,s} h_s, with t = decoder step and s = source position; k_s = v_s = h_s ("how useful is enc(x_s) at step t"); q_t = decoder state; score = vᵀ tanh(W_s h_s + W_t s_t); "at decoder step t, which encoder steps are most relevant ⇒ high α(t,s)"; "important step RNN enc-dec → Transformer" | pp 9–11 | **MUST KEEP** → `ATTENTION` §10 (HW7 P3). **Adopt the board's t/s indices** (§4) |
| **12** | **Multi-head board.** Several attentions scoring at once, H₁…H_h; "computation simplified, parallel ⇒ larger scale with GPU"; Q = XW_q ("current decoder demand"), K = XW_k ("prev enc() of x to match with q"), V = XW_v; learn W_q, W_k, W_v, W_o; MultiHead = Concat(H₁..H_h)W_o; "replace REC, CONV with attention ⇒ no REC ⇒ add positional encoding" | the whole page | **MUST KEEP** → §6 (HW7 P2(C)) and §7 (the bridge to positions) |
| 13–14 | Seq2seq with attention (d2l figures) | none | figure idea only |
| 15 | "next time: transformers" | logistics | skip |
| 16–24 | Plain d2l Transformer slides: 3 differences from seq2seq-with-attention; FFN "= two (1,1) conv"; Add & Norm, LN `mean(axis=-1)` vs BN `mean(axis=0)`; PE formula | none | covered by the 8/8 deck; the axis contrast → `TRANSFORMER` §2 |
| 25–36 | Plain BERT slides: transfer learning; BERT = encoder (Base 12/768/12/110M, Large 24/1024/16/340M); token + segment + position embeddings; MLM 15% (80/10/10); NSP 50/50; fine-tuning (classification via ⟨bos⟩, NER, QA span) | none | → `TRANSFORMER` §10 (one row) + `TRANSFORMER_ADVANCED` §1 |

#### `Lecture_SelfAttn_TRN_080825.pdf`: "Self-Attention, Transformer, BERT" (22 pp; handwriting on pp 1–8)

| pp | Content | Handwritten | Verdict |
|---|---|---|---|
| 1 | Title | "Transformer: movie concept ⇒ ? Transformer NN" | a light opener for the lecture plan |
| **2** | **Self-attention board.** "each token/step t attends each step (prev) s"; "transf seq → new seq; NOT enc-dec mech like before"; "No sequential → new SEQ mech instead of REC"; **"Run in parallel ⇒ AI CAP RACE"**; long-sequence attention drawing; "ENCODER has self attn" | yes | **MUST KEEP** → `ATTENTION` §7 (parallel vs sequential, the drawing) |
| **3** | **The Transformer figure, fully annotated.** DEC/ENC brackets, "Encoder Block ×n", "Decoder Block ×n"; the "old ATTN" (cross-attention) path from encoder output to decoder MHA highlighted in red; "self ATTN" labels on encoder MHA and decoder masked MHA; "Dec state"; FFN "for positions"; PE "keep track of seq instead of REC"; "Targets = output seq" | yes | **MUST KEEP.** This *is* decision 4's thinking framework. `TRANSFORMER` Fig 1 redraws it with the three attentions colour-coded exactly as annotated |
| 4–6 | MHA, FFN, Add & Norm | "layer normalization (after comp block)… prevent problems with computation, activations, gradients"; "×n"; PE "Once (set)"; **"norm per layer" vs "norm per batch"** | absorb → `TRANSFORMER` §2–3 |
| 7 | PE formula | "trigonometry, periodicity, separability, **analogy with binary bits**"; "global pos"; "X + P" | absorb → `ATTENTION` §8 |
| **8** | **Full board: positional encoding.** Binary table of positions 0–7 in 3 bits ("pattern by col… discrete ⇒ continuous"); sin/cos columns low/high frequency; heatmap (rows = position, cols = dimension); **"Relative positioning by δ":** ω_j = 1/10000^{2j/d} and [P_{i+δ,2j}; P_{i+δ,2j+1}] = R(δω_j)[P_{i,2j}; P_{i,2j+1}], meaning "pos at i+δ = rotation of pos at i" | the whole page | **MUST KEEP** → `ATTENTION` §8 + Fig 6. The rotation is also the cleanest on-ramp to **RoPE** (`TRANSFORMER_ADVANCED` §3) |
| 9 | Predicting: keys/values from previous steps, query at t | none | the causal idea → `ATTENTION` §9 |
| 10–11 | "Code…"; BERT title | none | skip |
| 12–22 | Plain BERT slides (transfer learning, motivation, architecture, input embeddings, MLM, NSP, fine-tuning, classification, NER, QA, "Check GluonNLP") | none | duplicates 8/6 pp 25–36 → `TRANSFORMER_ADVANCED` §1 |

### 3.2 Tier 2: course-adapted (absorb; none linked to students as-is)

| File | Len | What | Verdict |
|---|---|---|---|
| `Attention/hw7_pedagogical_notes.{md,tex,pdf}` (Nov 2025) | 5 pp | Last year's five-step path Bahdanau → MHA-in-Bahdanau → GRU + self-attn encoder → masked self-attn + GRU decoder → Transformer decoder on GRU encoder → full Transformer. Each step has equations and teaching cues: the reshape `(B,T,d)→(B,h,T,d/h)`, dropout on attention weights, "toy 4-token causal mask", KV-cache cloning for beam search | Absorb the **reshape cue** (`ATTENTION` §6) and the **4-token mask demo** (§9). The 5-step path → `TRANSFORMER_ADVANCED` §8 (backs optional P11) |
| `Attention/hw7_step1–5.png` | 5 img | Diagrams for the five steps | keep with P11 / `TRANSFORMER_ADVANCED` §8; redraw if used |
| `TRN/hw7_notes.txt` | 8 KB | A Codex Q&A on last year's `PositionalEncoding` (line refs into `hw7_sol.py`), ending with good intuition: attention treats inputs as a set, PE is a "timestamp", relative offsets show up as phase differences in Q·Kᵀ, and residuals keep the position signal alive through the stack | Absorb the intuition paragraph into `ATTENTION` §8. Don't link (chat transcript). Then Tier 4 |
| `Attention/Seq2Seq_att_chatGPT.pdf` | 28 pp | A ChatGPT 5.1 transcript contrasting d2l's RNN enc-dec, seq2seq + attention and the Transformer | Absorb only the contrast-table idea (`ATTENTION` §1 / `TRANSFORMER` §1). Don't link. Then Tier 4 |
| `Word2vec/2slides.pdf` | 2 pp | Book extracts 15.1.6–15.1.8 (skip-gram full-softmax gradient) and 15.1.13–15.1.14 (CBOW gradient) | → `TOKENS_ADVANCED` §1–2, then Tier 4 |
| Last year's HW7 code (`hw7_sol.py`, `hw7_starter.py`, 6 notebooks, `tsv_seq2seq_data.py`) | — | Classes: `MaskedSoftmax`, `AdditiveAttention`, `DotProductAttention`, `MultiHeadAttention`, Bahdanau and MHA decoders, the two hybrids, `TransformerDecoderBlock` with per-layer KV caches, `beam_search_translate` (GNMT length penalty + `_clone_state`) | A reference for the starter (not the notes). Beam search → optional P10 / `TRANSFORMER_ADVANCED` §5. **The saved outputs are the best evidence for the new design** (next row) |
| ↳ last year's notebook outputs | — | Translations show **repetition loops** ("yesterday yesterday yesterday…", "the park park park"), **`<pad>` emitted after `<eos>`** (decoding didn't stop), `<unk>` floods, and hybrid encoders producing fluent nonsense. Per-sentence BLEU was mostly 0 | Feeds the **common-bugs boxes**: stop at `<eos>`, mask pads in the loss, greedy repetition (→ sampling §9). Also justifies the Tatoeba ≤12-token data and the BLEU-by-length tables |

### 3.3 Tier 3: keep as links

- **d2l book HTML chapters** (lecture column): *NLP pretraining* (15) and *Attention and Transformers* (11).
  Proposal: link 11.1–11.6 from Week 13 and 11.7 + 11.9 from Week 14, instead of the whole chapter in Week 14.
  Also link **15.6 (subword embedding / BPE)** explicitly; HW7 already does.
- `2_GD_REG_pton_NN/Word2Vec_all_McCormick.pdf` (39 pp): **keep** in other reading. Its "fake task" /
  autoencoder framing is exactly the instructor's p5 board. `TOKENS` §6 cites it.
- `Attention and Augmented Recurrent Neural Networks __ Reader View.pdf` (distill 2016, 15 pp): **not in the
  syllabus now. Propose adding** it to Week 13 other reading as "(optional)". It has the best attention
  visualizations (alignment, attention over audio/images). It predates Transformers, so it stays optional.
- Karpathy's **nanoGPT** (already in HW7 references): propose also adding it to Week 14 other reading.
- Candidates to add (instructor's call, §9): the Hugging Face LLM-course chapter on tokenizers (BPE,
  WordPiece, Unigram compared), and the YouTube video the instructor flagged in the HW discussion
  (`GaIeu3npx04`).
- The two lecture videos (Week 13: Word2Vec, Attention; Week 14: Transformer): **keep.**

### 3.4 Tier 4: retire **after** the new notes are written and verified

None of these is linked to students today, so "retire" means "don't link, and leave it where it is":
`TRN/hw7_notes.txt` and `Seq2Seq_att_chatGPT.pdf` (chat transcripts, once absorbed) ·
`Word2vec/2slides.pdf` (book extracts) · STAT157 decks `22-Embedding.pdf` (16 pp), `23-Encoder-decoder.pdf`
(19 pp) and `24-Attention.pdf` (33 pp) in `non_public/`, which are the **unannotated originals** of the three
Tier-1 lectures · `book_d2l_smola*.pdf` (non-public copies; link the HTML).
**Keep** `hw7_pedagogical_notes` and the step images *if* optional P11 survives; otherwise retire them too.

### 3.5 Syllabus rows `week13` / `week14`: verdict per link

| Week | Column | Link | Verdict |
|---|---|---|---|
| 13 | module title | "Word Vectors, Attention" | → **"Tokens, Word Vectors, Attention"** |
| 13 | lecture | video "Word2Vec" (8/13) | keep |
| 13 | lecture | video "Attention" (8/6) | keep |
| 13 | lecture | Lecture 8/13 Word-To-Vec (annotated) | keep, under the new `TOKENS` note |
| 13 | lecture | d2l "NLP, Word Embedding" chapter | keep; add 15.6 BPE as its own line |
| 13 | lecture | Lecture 8/6 Attention (annotated) | keep, under the new `ATTENTION` note |
| 13 | lecture | (new) `TOKENS`, `ATTENTION` notes | add at the top of the column |
| 13 | other | McCormick "Simple Word-2-Vec tutorial" | keep |
| 13 | other | (new) `TOKENS_ADVANCED` "(optional)"; distill Augmented RNNs "(optional)" | add |
| 14 | module title | "Self-Attention, Transformers" | → **"Transformers, GPT"** |
| 14 | lecture | video "Transformer" (8/8) | keep |
| 14 | lecture | d2l "Attention and Transformers" chapter | keep; point it at 11.7 + 11.9 (11.1–11.6 move to Week 13) |
| 14 | lecture | Lecture 8/8 Self Attention & Transformers (annotated) | keep, under the new `TRANSFORMER` note |
| 14 | lecture | (new) `TRANSFORMER` note | add at the top |
| 14 | other | *(empty: three blank `<li>` and a stray `</li>`)* | fill: `TRANSFORMER_ADVANCED` "(optional)", nanoGPT; fix the stray `</li>` |

---

## 4. Notation standard

The rules: **batch-major tensors, d2l's attention symbols, the instructor's board where the two agree, and
rows = items**. Rows = items is the course-wide data-matrix convention (`X` is N×D with one row per
datapoint), so here `X` is T×d with one row per token.

| Role | Symbol | Source / note |
|---|---|---|
| batch size | `B` | PyTorch, HW6 |
| sequence length | `T`; `T_q`, `T_k` when queries and keys differ | **HW6's RNN time steps** (d2l `num_steps`). d2l's attention chapter uses n, m; we keep T so HW6 → HW7 reads on |
| model width | `d` (d2l `num_hiddens`, GPT `n_embd`) | board "d = dim" |
| heads, per-head width | `h`, `d_h = d/h` | board "h = #attention heads", d2l |
| token matrix | `X ∈ ℝ^{T×d}`, row `x_t` | rows = items |
| queries, keys, values | `Q ∈ ℝ^{T_q×d}`, `K ∈ ℝ^{T_k×d}`, `V ∈ ℝ^{T_k×d_v}`; rows `q_i, k_j, v_j` | d2l and board |
| projections | `W_q, W_k, W_v, W_o` (`Q = XW_q`) | board p12, verbatim |
| attention weights | `α_{ij}`, matrix `A = softmax(QKᵀ/√d)` (rows sum to 1) | board α, d2l α |
| positional encoding | `P ∈ ℝ^{T×d}`, input `X + P`; `ω_j = 1/10000^{2j/d}` | d2l, board p8 |
| RNN states (HW6) | encoder `h_s`, decoder `s_t` | **board p10** |
| Bahdanau indices | `t` = target step, `s` = source position; `c_t = Σ_s α_{ts} h_s` | **board p10.** d2l writes `t'` and `t`; the board's letters are clearer |
| vocabulary | `𝒱`, size `\|𝒱\|` | d2l 15.1. ⚠ The board writes `D = #vocab`, but course `D` = #features. Bridge box |
| word2vec vectors | `v_w` (center), `u_w` (context) | d2l 15.1. Board: "embed as center / embed as context" |
| window, negatives | window `m`; negatives per positive `n_neg` | d2l uses `K` for noise words, which collides with keys `K`; renamed |
| layer norm | `μ, σ², γ, β, ε` | same letters as HW6 batch norm, on purpose |
| FFN | `W_1 ∈ ℝ^{d×d_ff}`, `W_2 ∈ ℝ^{d_ff×d}`, `d_ff = 4d` | d2l `ffn_num_hiddens` |
| blocks | `L` blocks | board "×n" |
| logits, temperature | `z ∈ ℝ^{\|𝒱\|}`; temperature **`τ`** | ⚠ `T` is already sequence length; HF calls it `temperature` |
| top-k | `k` (used only in the sampling section) | collides with key vectors `k_j`; kept local |
| loss | cross-entropy; perplexity `= exp(mean CE)` | HW6 P3 |

**Bridge box (one per basic note, the relevant lines only):**
> board `D = #vocab` ≡ `|𝒱|` · board `H` hidden ≡ `d` · d2l `n, m` ≡ `T_q, T_k` · d2l `t', t` ≡ board `t, s` ·
> d2l noise-word `K` ≡ `n_neg` · d2l `num_hiddens` ≡ `d`, `num_heads` ≡ `h`, `num_blks` ≡ `L`.

**Tensor layout: the one real conflict.**

| Where | Layout | What the starter / note does |
|---|---|---|
| HW6 RNNs (d2l `RNNScratch`, `nn.RNN/GRU/LSTM` default) | **time-major** `(T, B, d)` | bridge box in `ATTENTION` §10: P3 permutes HW6's encoder outputs to `(B, T, d)` once (d2l's Bahdanau decoder does the same `permute(1,0,2)`) |
| d2l attention code, `F.scaled_dot_product_attention` | batch-major `(B, T, d)` / `(B, h, T, d_h)` | the notes' standard |
| `nn.MultiheadAttention`, `nn.Transformer*Layer` | **default `batch_first=False` (time-major!)** | the starter passes `batch_first=True` everywhere; the common-bugs boxes say why |

**Mask conventions** (all four appear in HW7; a table in `ATTENTION` §5):

| API | Form | `True` means |
|---|---|---|
| d2l `masked_softmax` | `valid_lens` (lengths), filled with −1e6 | — |
| `F.scaled_dot_product_attention` | bool `attn_mask` | **keep** (may attend) |
| `nn.MultiheadAttention` / `nn.Transformer*` | bool `attn_mask`, `key_padding_mask` | **block** (masked out) |
| `nn.Transformer.generate_square_subsequent_mask` | float, `−inf` above the diagonal | additive |

The starter converts between them. The note teaches *one* idea: set the blocked scores to −∞ (or a large
negative number) **before** the softmax.

---

## 5. The five notes

### 5.1 `TOKENS/TOKENS_claude_MMDD`: "Tokens and Word Vectors: Subwords, BPE, and word2vec"
**Basic · carries HW7 P1(A–C) · Lecture 1 (Thu 12/3) · ≈12–14 pp**
Prerequisites: HW6 P3 (tokens → IDs → `nn.Embedding`), HW2 logistic regression, Week 5 PCA.

1. **Big picture.** Text → tokens → IDs → vectors → model, the HW6 P3 pipeline with one box replaced. Fig 1.
   Table: *where you've seen it* (IDs, `nn.Embedding`, logistic regression, PCA) / *NEW* (subword merges,
   negative sampling).
2. **Three ways to cut text: words, characters, subwords.** Vocabulary size vs sequence length; `<unk>`;
   morphology (Spanish verbs have 40+ forms, d2l 15.6); why word-level worked for TinyStories in HW6 (5,274
   words, a children's vocabulary) and where it breaks (a Spanish sentence, a typo, a rare name, code; the
   real splits come from the starter's tokenizers at build time). fastText's "friend = friends = friendship,
   Σ embed(grams)" (8/13 p16) is the bridge to BPE. *[Sources: 8/13 p16; d2l 15.6; NN plan §8 item 5]* → **P1(A) side question**
3. **Subwords in modern LLMs: the table** (instructor emphasis 1).

   | Model | Tokenizer | Algorithm | Vocab |
   |---|---|---|---|
   | GPT-2 (2019), GPT-3 | byte-level BPE | merge most frequent pair | 50,257 |
   | RoBERTa | byte-level BPE | same | 50,265 |
   | GPT-4 / GPT-4o (`cl100k` / `o200k`) | byte-level BPE (tiktoken) | same | ≈100k / ≈200k |
   | LLaMA 1/2, Mistral 7B | SentencePiece BPE (byte fallback) | same, space = `▁` | 32,000 |
   | LLaMA 3 | byte-level BPE (tiktoken-based) | same | 128,256 |
   | BERT | WordPiece | merge by likelihood gain | 30,522 |
   | T5 | SentencePiece unigram | start large, prune | 32,100 |

   ⚠ Every vocabulary size is to be verified against the released tokenizer configs at write time.
   The one-line message: **no modern LM reads whole words; most use BPE.**
4. **BPE, the algorithm.** Count words → split into characters → count adjacent pairs (weighted by word
   frequency, never across word boundaries) → merge the most frequent → repeat. **The ordered merge list *is*
   the tokenizer.** Encoding a new word = apply the merges *in learned order* (not longest match).
   Implementation details the book skips:
   - word-boundary markers: d2l `_` suffix, Sennrich `</w>`, GPT-2 `Ġ` prefix, SentencePiece `▁`;
   - **ties and tie-breaking.** d2l's own toy corpus has a tie at merges 1, 2 and 4, so an exact match with HF
     needs a tie-free example or a stated tie-break rule;
   - overlapping pairs (`a a a`);
   - byte-level fallback = never `<unk>`;
   - special tokens.

   Algorithm box. **Worked example (unit test, tie-free, no end marker):** corpus
   `hug×4 hugs×2 pug×2 pun×2 bun×1 sun×1` (12 words). Merge 1 = (u,g), count 8 (runner-up 6). Merge 2 =
   (h,ug), 6 (runner-up 4). Merge 3 = (u,n), 4 (runner-up 2). Result: `hug | hug s | p ug | p un | b un | s un`.
   Encoding unseen words: `sung → s un g`, `bug → b ug`. Pair-count table per step in the note; verify that
   HF `tokenizers` (BPE model, `Whitespace` pre-tokenizer, `BpeTrainer`) learns the same three merges.
   *[d2l 15.6.2]* → **P1(A)**
5. **From IDs to vectors.** One-hot ("#dim = #vocab, no easy sim()", 8/13 p3). Embedding lookup = one-hot ×
   matrix (the HW6 `nn.Embedding` recap). Dot product / cosine as similarity.
6. **word2vec as a "fake task" network** (the 8/13 p5 board, Fig 4; McCormick's framing). Skip-gram:
   P(context | center); the naive independence product (p6); softmax over all of 𝒱 (p7); two vectors per word,
   `v_w` center and `u_w` context.
7. **The tricks for computation** (the 8/13 p8 board). Replace the softmax by σ(u_oᵀv_c) = "are these two in
   the same window?". **Negative sampling = HW2's logistic regression**: label 1 for the real neighbour, 0 for
   `n_neg` noise words drawn from unigram^{3/4}. Loss:
   −log σ(u_oᵀv_c) − Σ_n log σ(−u_nᵀv_c). Subsampling P(drop w) = max(1 − √(t/f(w)), 0). One-line gradient
   intuition: pull together, push apart (full gradient → advanced).
   **Worked example (unit test):** positive score 2, negative scores −1 and 0.5 → 0.1269 + 0.3133 + 0.9741 =
   **1.4143**. *[8/13 pp 8–10; d2l 15.2]* → **P1(B)**
8. **What the vectors learn.** Cosine neighbours; 2-D projection (PCA from Week 5; t-SNE picture from 8/13
   p15); analogies, with caveats. What to expect against gensim: lists overlap but are not identical (random
   init, different subsampling and negative draws). On TinyStories, neighbours are roles and topics
   (cat/dog/bird; happy/sad). Static vectors (one per word) vs contextual ones (what attention produces, a
   forward pointer). *[d2l 15.4.4, 15.7]* → **P1(C)**
9. **Forward.** GloVe, CBOW, WordPiece and unigram → `TOKENS_ADVANCED`. "Every Transformer starts with exactly
   this embedding table" → `ATTENTION`.
10. **HW7 Map** (P1 A–C; optional P12) **+ common bugs:**
    - BPE: counting pairs across word boundaries; forgetting the frequency weights; merging overlapping pairs
      twice; encoding by longest match.
    - SGNS: one matrix for both center and context; the sign of the negative term; a negative equal to the
      positive; dot vs cosine for neighbours.

### 5.2 `Attention/ATTENTION_claude_MMDD`: "Attention: Queries, Keys, and Values"
**Basic · carries HW7 P2(A–D), P3(A–C), P6 · Lecture 2 (Mon 12/7) + first half of the extra lecture · ≈16–18 pp**
Prerequisites: matrix products and softmax (HW5), padding and the seq2seq translator (HW6 P4), kernel
smoothing / soft k-NN (`LOCAL_CLASSIFIERS`).

1. **Big picture: the HW6 bottleneck.** The whole sentence is squeezed into one vector, and BLEU falls with
   length (pilot GRU: 37 on 1–4 tokens → 22 on 9–12; on the ≤25 data, 8.8 on 13–17 and 6.0 on 18–25). The fix:
   let each output step look at every input. Fig 1 (seq2seq without and with attention). Table: *where you've
   seen it* (softmax, weighted averages, kernels, padding masks) / *NEW* (Q/K/V, the √d scaling, heads,
   positions). The roadmap is the 8/6 p3 outline: setup → math → code.
2. **Flashback: attention is a kernel smoother** (the 8/6 p5 board; d2l 11.1–11.2). Nadaraya–Watson
   pred(z) = Σ α(z,x_i) y_i / Σ α(z,x_i); "α high ⇒ pay attention to x_i"; α ≥ 0, Σα = 1 ⇒ softmax of a score.
   The database analogy (query, keys, values). Fig 2 (1-D smoother with the weights drawn as bars).
   Cross-reference `LOCAL_CLASSIFIERS` §KDE.
3. **Scores are similarity kernels** (8/6 pp 7–8). The kernel list and Fig 3 (shapes). **The Euclidean →
   dot-product derivation**, stated precisely (the ‖q‖² vs ‖k‖² remark in §3.1). Additive/MLP score (Bahdanau)
   vs dot product ("important for parallel computation": a matrix product).
4. **Scaled dot-product attention.** `softmax(QKᵀ/√d)V` with shapes `(B,T_q,d)·(B,d,T_k) → (B,T_q,T_k) →
   ·(B,T_k,d_v)`. **Why √d:** qᵀk is a sum of d unit-variance products, so its variance is d. Simulated
   numbers for Fig 4, 10 keys with N(0,1) entries: mean largest weight unscaled is **0.49 / 0.73 / 0.87 /
   0.93** at d = 4 / 16 / 64 / 256; scaled it stays **≈0.30–0.32**. The softmax saturates and its gradients
   vanish. → **P2(B)**.
   **Worked 2-token example (unit test):** d = 4 (so √d = 2), Q = [[1,1,0,0],[0,0,1,1]],
   K = [[1,1,0,0],[1,0,1,0]], V = I₂ → scores/√d = [[1, .5],[0, .5]] →
   **A = [[0.6225, 0.3775],[0.3775, 0.6225]]** = output (since V = I).
5. **Masking.** Padding via `valid_lens` (HW6 P4). Set blocked scores to −∞ *before* the softmax (why not
   zero them after?). Same example with valid length 1 → A = [[1,0],[1,0]]. The mask-convention table (§4).
   Pitfall: a fully masked row → NaN. → **P2(A)**
6. **Multi-head attention** (the 8/6 p12 board). `Q = XW_q` ("current decoder demand"), `K = XW_k`, `V = XW_v`.
   Split d into h heads of d/h; attend in parallel; concatenate; `W_o`. Shape walk
   `(B,T,d) → (B,T,h,d_h) → (B,h,T,d_h) → attend → (B,T,d)`, and why the transpose is not optional (the
   pedagogical-notes cue). Parameter count `4(d²+d)`, the same as one big head, which sets up P6. Fig 5
   (dataflow with shapes). The `nn.MultiheadAttention` check: packed `in_proj_weight = [W_q;W_k;W_v]` (the
   starter copies weights). → **P2(C)**
7. **Self-attention and the order problem** (the 8/8 p2 board: "every token attends every step"; "no
   recurrence → parallel ⇒ AI cap race"; the long-sequence drawing). **Permutation equivariance:** permute the
   input rows and the output rows permute the same way, which is the P2(D) demo. CNN / RNN / self-attention
   table: cost, sequential steps, path length (d2l 11.6.2; redraw rather than copy its figure). → **P2(D)**
8. **Positional encoding** (the 8/8 pp 7–8 boards). Binary bits 0–7 → "discrete ⇒ continuous" sin/cos at
   frequencies ω_j; Fig 6 (bits table + heatmap); `X + P`.
   **Worked example (unit test), d = 4:** P₀ = [0, 1, 0, 1], P₁ = [0.8415, 0.5403, 0.0100, 1.0000],
   P₂ = [0.9093, −0.4161, 0.0200, 0.9998], P₃ = [0.1411, −0.9900, 0.0300, 0.9996].
   "Position i+δ = rotation of position i" (the board's matrix; a two-line trig check). The `hw7_notes.txt`
   intuition: a timestamp that residuals carry through the stack. Learned positions and RoPE → advanced.
   → **P2(D)**
9. **The causal mask.** Lower-triangular 4×4 (the pedagogical-notes demo; 8/8 p9).
   **Unit test:** with all-zero scores the weight rows are 1; ½,½; ⅓,⅓,⅓; ¼×4, so the output is the
   **running mean of V**. Second test: change token 4, and outputs 1–3 don't move. → **P2(D)**, and
   reused in P5.
10. **Attention inside the HW6 translator: Bahdanau** (8/6 pp 9–11 boards). `c_t = Σ_s α_{ts} h_s`;
    keys = values = encoder states; query = the decoder state; additive score `vᵀ tanh(W_s h_s + W_t s_t)` or
    the dot product from §4. Where `c_t` enters the GRU (concatenated with the embedding, as in d2l). Fig 8.
    Time-major → batch-major bridge (§4). Alignment plots: mostly diagonal for es→en, crossing on noun–adjective
    swaps (*casa blanca → white house*).
    **Key effect, stated honestly:** on ≤12-token sentences attention adds nothing (pilot GRU 30.0 vs
    Bahdanau 29.5, NN plan §8 item 1). The ≤25 pilot decides what we claim (see §9). If attention doesn't
    separate, the fallback is a provided **copy/reverse demo on 30–50 tokens**, where the no-attention GRU
    must fail. → **P3(A–C)**
11. **Why several heads** (simple and conceptual). One softmax is one weighted average, so it can't be sharp on
    two places at once. Heads specialise (position, alignment, previous token), as shown with the student's
    own maps. Same parameters, more patterns. → **P6**
12. **HW7 Map** (P2 A–D, P3 A–C, P6) **+ common bugs:** dividing by d instead of √d; softmax over the query
    axis; masking after the softmax; NaN rows; `K.T` on a batched tensor (use `transpose(-2,-1)`); splitting
    heads with `view` and no transpose; forgetting `W_o`; a flipped mask convention; PE added after dropout;
    time-major HW6 encoder outputs.

### 5.3 `TRANSFORMER/TRANSFORMER_claude_MMDD`: "The Transformer and GPT: From Encoder–Decoder to Decoder-Only"
**Basic · carries HW7 P4(A–D), P5(A–C), P7 · second half of the extra lecture + Lecture 3 (Thu 12/10) · ≈18–20 pp**
Prerequisites: `ATTENTION`; HW6 P2 (residual blocks) and P1(D) (batch norm); HW6 P3 (the language model).

1. **Big picture: the full Transformer as the thinking framework** (decision 4). Fig 1 redraws the 8/8 p3
   board: encoder ×L, decoder ×L, and **three attentions colour-coded**: encoder self-attention, decoder
   *masked* self-attention, and cross-attention (the "old ATTN" red path, which is P3's attention). Table
   "parts of a Transformer":

   | Part | Where you've seen it |
   |---|---|
   | embeddings | P1 / HW6 |
   | positional encoding, causal mask | P2(D) |
   | multi-head attention | P2(C) |
   | cross-attention | P3 |
   | residual | HW6 P2 |
   | normalization | HW6 P1(D) BN; **LN is NEW** |
   | FFN | the HW5 MLP applied per position |
   | output softmax | HW6 |

   **Only LayerNorm and the wiring are new.**
2. **LayerNorm vs BatchNorm** (8/8 p6 "norm per layer vs norm per batch"; 8/6 deck `mean(axis=-1)` vs
   `axis=0`). Formula with γ, β, ε. Why LN for sequences: variable lengths and padding, no dependence on batch
   size, the same at train and test. Fig 2 (the normalized axis drawn on a `(B,T,d)` block).
   **Worked example (unit test):** X = [[1,2,3],[2,4,6]]. LN, per row: both rows → **[−1.2247, 0, 1.2247]**
   (LN removes each token's scale). BN, per column: every column → [−1, 1]. → **P4(A)**
3. **Add & Norm and the position-wise FFN** (8/8 pp 4–5: "normalizes output… prevents problems with
   gradients"; FFN = the same MLP at every position = two 1×1 convolutions; `d_ff = 4d`). → **P4(A)**
4. **The encoder block** (MHA → add & norm → FFN → add & norm), stacked L times, bidirectional. Checked against
   `nn.TransformerEncoderLayer` (`batch_first=True`, `norm_first=False`, ReLU, dropout 0; the starter sets
   these). Fig 3 left. → **P4(B)**
5. **The decoder block.** Masked self-attention → cross-attention (Q from the decoder, K = V = the encoder
   output) → FFN, with three add & norms. Checked against `nn.TransformerDecoderLayer`. Fig 3 right.
   → **P4(C)**
6. **Training in parallel, generating one token at a time.** Teacher forcing plus the causal mask makes every
   target position one parallel computation; decoding is a loop (Fig 6). `<bos>` / `<eos>` and stopping at
   `<eos>` (last year's `<pad>`-after-`<eos>` bug). Algorithm box: greedy translation. KV cache → advanced.
   **Key effect (pilot, ≤12 tokens, about equal parameters, 5 min on MPS):** `nn.Transformer` BLEU **35.5** vs
   GRU 30.0 / Bahdanau 29.5. The gain is largest on short sentences (44.7 / 46.4 vs 37.1 / 37.8 on 1–4 / 5–6
   tokens), and it ran **1.7× more training steps in the same time** (parallel).
   **Mac gotcha:** `nn.Transformer` in eval mode with a padding mask crashes on MPS (the nested-tensor op is
   unimplemented). The starter builds it with `enable_nested_tensor=False`, and the note says why in one line.
   → **P4(D)**
7. **Decoder-only = GPT, the practical model** (decision 4). Delete the encoder and the cross-attention from
   Fig 1 (Fig 4 is the same drawing with those parts greyed out). What remains is **the encoder block + the
   causal mask**, which is P5(A) word for word. Objective = HW6 P3's next-token cross-entropy.
   **Encoder–decoder vs decoder-only**, in practice and in theory (table):
   - inputs, masks, what is trained;
   - one stack vs two;
   - every token is a training label;
   - one objective for every task, prompts instead of task-specific architectures;
   - translation as `Spanish <sep> English` (optional P8; pilot 42.0 BLEU, but it also got more steps, so say
     it cautiously).

   **Key effect (pilot, TinyStories, 5,274-word vocabulary, context 64, 5 min on MPS):** perplexity RNN
   **23.1** · LSTM **16.8** · own GPT **13.5** · HF GPT-2 **12.8**. Perplexity = exp(CE): ln 13.5 = 2.60;
   a uniform guess = 5,274.
   **Worked parameter count (unit test):** at d = 256, d_ff = 1024, L = 4, h = 4, one block is
   4(d²+d) + (2·d·d_ff + d_ff + d) + 4d = **789,760**, and 4 blocks = 3,159,040. HF GPT-2 total = 4,526,080;
   own = 5,880,986. The gap of **1,354,906 = 5,274×256 + 5,274 (untied output layer) − 512 (HF's final LN)**
   is exactly **weight tying**. This resolves NN plan §8 item 7's "4.53M vs 5.88M". → **P5(A,B)**
8. **Pre-norm vs post-norm** (decision 6). Post-norm `x ← LN(x + f(x))`: Vaswani 2017, d2l `AddNorm`, BERT,
   the `nn` default. Pre-norm `x ← x + f(LN(x))` plus a final LN before the head: GPT-2, ViT in d2l 11.8.3,
   LLaMA (with RMSNorm), `nn` with `norm_first=True`. **Why:** with pre-norm the HW6 ResNet identity path runs
   untouched from the input to the last block (`x_L = x_0 + Σ_l f_l(·)`), so gradients reach early blocks
   directly. Post-norm puts an LN on the main path in every block, and deep stacks need warm-up. Pilot: no
   difference at 4 layers (13.44 vs 13.53); the advantage shows at depth and large learning rates. Fig 5
   (side by side, residual highway highlighted). → **P5(B) written why**
9. **Sampling** (decision 7). Greedy (argmax; repetition loops, as in last year's "yesterday yesterday…");
   temperature `softmax(z/τ)` (d2l 4.1 exercise); top-k (keep the k largest, renormalize); top-p in one line.
   **Worked example (unit test),** logits z = [2, 1, 0, −1]:

   | Setting | Distribution |
   |---|---|
   | τ = 1 | [0.6439, 0.2369, 0.0871, 0.0321] |
   | τ = 0.5 | [0.8650, 0.1171, 0.0158, 0.0021] |
   | τ = 2 | [0.4551, 0.2760, 0.1674, 0.1015] |
   | top-2, τ = 1 | [0.7311, 0.2689, 0, 0] |
   | top-2, τ = 0.5 | [0.8808, 0.1192, 0, 0] |

   τ → 0 gives greedy. For top-k, temperature and truncation commute (both keep the order); for top-p they
   don't. The HF check compares *probabilities* after HF's temperature and top-k logits warpers, never sampled
   text (NN plan §8 item 3). Algorithm box: the generate loop with the context window cropped to 64. Fig 7
   (bar charts). → **P5(C)**
10. **Three kinds of Transformer** (P7; instructor emphasis 2). Table with columns blocks · masks ·
    training objective · typical use · tokenizer (from `TOKENS` §3):
    - **BERT**: encoder-only, padding mask only; MLM 15% (80/10/10) + NSP; fine-tune on the `<bos>`/[CLS] vector;
    - **T5 / BART**: encoder–decoder; span corruption with sentinels / denoising; text-to-text;
    - **GPT**: decoder-only, causal; next-token LM; prompting.

    "Adaptations, not subsets" (NN plan §8 item 7): BERT adds segment embeddings, learned positions, GELU and
    an MLM head; GPT-2 is pre-norm with learned positions and tied embeddings. Fig 8 (three attention-pattern
    grids: full; causal; full + causal + cross; d2l Fig 11.9.3's idea, redrawn).
    *What cross-attention gives a translator:* a bidirectional read of the source, kept as a fixed memory.
    *Why decoder-only won*, conceptually: one objective on raw text, every token is a label, generation is a
    universal interface, it scales. *[8/6 pp 25–36, 8/8 pp 12–22; d2l 11.9]* → **P7**
11. **HW7 Map** (P4, P5, P7; optional P8, P9) **+ common bugs:**
    - LayerNorm: normalizing over the wrong axis; no final LN in pre-norm.
    - Library mismatches: comparing pre-norm code to `nn` with `norm_first=False`; the `batch_first` default;
      the mask `True` convention; **d2l scales embeddings by √d and `nn.Transformer` has no embeddings at all**
      (they must match in the checkpoint); dropout left on in checks; a tied vs untied head.
    - Wiring: a causal mask on the encoder; Q and K swapped in cross-attention; targets not shifted by one.
    - Sampling: temperature applied to probabilities instead of logits; top-k without renormalizing.

### 5.4 `TOKENS/TOKENS_ADVANCED_claude_MMDD` (optional)
**Advanced · optional HW7 P12; depth for P1 · ≈8–10 pp**

1. Full-softmax skip-gram gradient `∂log P/∂v_c = u_o − Σ_j P(w_j|w_c) u_j`: "observed minus expected", the
   same shape as the HW2/HW5 softmax gradient *[2slides p1 = d2l 15.1.6–15.1.8; 8/13 p11]*
2. CBOW, "reverse conditional probability" *[8/13 pp 12–14; 2slides p2]*
3. Negative sampling vs hierarchical softmax *[d2l 15.2]*
4. **GloVe** *[8/13 pp 18–20]*: co-occurrence counts, weighted least squares on log counts, h(x), "pretrained,
   download sizes, tune for your corpus" → **P12**
5. **fastText** *[8/13 pp 16–17; d2l 15.6.1]*: `<wh, whe, her, ere, re>`, Σ n-gram vectors, rare/OOV words
6. Other subword algorithms: WordPiece (score = count(ab)/(count(a)·count(b))), Unigram LM (prune; T5),
   byte-level BPE (256 base symbols, GPT-2's byte↔unicode map, `Ġ`), SentencePiece (space as `▁`, no
   pre-tokenization; why that matters for Chinese/Japanese)
7. Tokenizer effects: tokens per word by language (Spanish costs more GPT-2 tokens than English), digits and
   arithmetic, leading spaces, vocabulary size vs embedding parameters vs sequence length
8. Static vs contextual embeddings; analogies and their caveats *[d2l 15.7]*
9. Further reading (LibKey-verified)

### 5.5 `TRANSFORMER/TRANSFORMER_ADVANCED_claude_MMDD` (optional)
**Advanced · optional HW7 P8–P11 · ≈12–14 pp**

1. **BERT in detail** *[8/6 pp 25–36, 8/8 pp 12–22; d2l 15.8–15.10]*: token + segment + position embeddings;
   why MLM uses 80/10/10; NSP and why RoBERTa dropped it; fine-tuning heads (classification, NER, QA span
   start/end = softmax(⟨s, v_i⟩))
2. **T5 / BART**: span corruption with sentinels; text-to-text fine-tuning *[d2l 11.9.2]*
3. **Positions beyond sinusoids:** learned absolute (BERT, GPT-2); relative; **RoPE = the instructor's 8/8 p8
   rotation board applied to q and k**, so relative position appears inside qᵀk; ALiBi; length extrapolation
4. **Inference cost:** KV cache (per-token cost O(T) instead of recomputing; last year's
   `TransformerDecoderBlock` already kept per-layer caches); **MQA / GQA** (share K, V across heads → smaller
   cache); FlashAttention (same math, memory-aware tiling); sparse and linear attention in one paragraph
5. **Decoding beyond sampling:** beam search with length penalty (last year's `beam_search_translate`, with
   state cloning per beam) → **P10**; top-p; repetition penalty
6. **Scaling:** the `≈12·L·d²` parameter rule (checked against §7's count); power-law scaling *[d2l 11.9]*;
   in-context learning
7. **A modern block** (LLaMA-style): RMSNorm, SwiGLU, RoPE, pre-norm, no biases. Table vs GPT-2 vs Vaswani
8. **From Bahdanau to the Transformer in five steps** (last year's path; `hw7_pedagogical_notes` + step
   images) → **P11**
9. **Decoder-only translation:** `es <sep> en`, loss on the target part only (the pilot's memory fix: score
   only target positions over the ≈25k shared vocabulary) → **P8**
10. **Pretrained HF models** ↔ the student's P4/P5 models; GPT-2's Conv1D weight layout (transposed `Linear`)
    → **P9**
11. Further reading (LibKey-verified)

---

## 6. HW7 accounting and book coverage

### 6.1 HW7: 290 required points, 7 required + 5 optional problems

| # | Part | Pts | Note § | d2l section | What the note must add beyond the book |
|---|---|---|---|---|---|
| 1A | BPE from scratch vs HF `tokenizers` | 10 | TOK §2–4 | 15.6.2 (toy BPE, `_` marker) | the **subword-in-LLMs table**; encode-by-merge-order; **tie-breaking** (the book's own example ties); boundary markers; byte-level; the HF equivalence; the words-vs-BPE side question on TinyStories and harder text |
| 1B | SGNS model + loss | 10 | TOK §6–7 | 15.1–15.4 (complete; d2l package has `load_data_ptb`, `skip_gram`) | the instructor boards p5/p8; **the HW2 logistic-regression link**; the loss unit test; TinyStories instead of PTB; copy rule (no d2l calls inside blanks) |
| 1C | neighbours + 2-D vs gensim | 10 | TOK §8 | 15.4.4, 15.7 | gensim expectations; PCA from Week 5 |
| 2A | masked softmax + scaled dot-product vs `F.sdpa` | 20 | ATT §2–5 | 11.1–11.3 (`masked_softmax`, `DotProductAttention` in the package) | the **kernel flashback**; the mask-convention table; NaN rows; batch-major shapes; the 2-token unit test |
| 2B | the √d experiment | 10 | ATT §4 | 11.3.2 (the variance argument, no experiment) | the saturation numbers / Fig 4 |
| 2C | MHA step by step vs `nn.MultiheadAttention` | 20 | ATT §6 | 11.5 (`MultiHeadAttention` in the package) | a check after each step; `in_proj_weight` packing; parameter count; `batch_first` |
| 2D | permutation equivariance → PE; causal mask | 20 | ATT §7–9 | 11.6 (PE, CNN/RNN/SA comparison); causal masking only implicitly in 11.7 (`dec_valid_lens`) | the equivariance demo; **the binary-bits and rotation boards**; the causal running-mean test |
| 3A | attention step in a provided GRU decoder | 20 | ATT §10 | 11.4 (Bahdanau in the *text*; **not in the d2l package**) | board t/s notation; the time-major bridge; dot vs additive score |
| 3B | alignment plots | 10 | ATT §10 | 11.4.3 (heatmap) | what diagonal / crossing means for es→en |
| 3C | BLEU by length vs HW6 | 10 | ATT §1, §10 | 10.7 (BLEU) | **the honest key effect; pending the pilot** (§9) |
| 4A | LayerNorm + add & norm + FFN | 10 | TRF §2–3 | 11.7.2 (`AddNorm`, `PositionWiseFFN`; LN vs BN in 3 lines) | LN as "HW6 BN over the other axis" + the numeric example |
| 4B | encoder block vs `nn.TransformerEncoderLayer` | 10 | TRF §4 | 11.7.4 (`TransformerEncoderBlock` in the package) | the `nn` equivalence settings; the √d embedding-scale difference |
| 4C | decoder block vs `nn.TransformerDecoderLayer` | 15 | TRF §5 | 11.7.5 (in the *text*; **not in the d2l package**) | mask conversion; cross-attention Q vs K/V |
| 4D | train own vs `nn.Transformer`, HW6, P3 | 15 | TRF §1, §6 | 11.7.6 (fra-eng) | Tatoeba es→en; the comparison table; **the MPS nested-tensor issue** |
| 5A | GPT block = encoder block + causal mask | 10 | TRF §7 | 11.9.3 (GPT *described*, no code) | **decoder-only derived from Fig 1**; the parameter-count unit test |
| 5B | train; perplexity vs RNN/LSTM and HF GPT-2; pre-norm + why | 20 | TRF §7–8 | 11.8.3 (pre-norm, for ViT only); 11.9.3 (GPT-2 "pre-normalization") | **HF GPT-2 as the library**; weight tying; the pilot table; **the pre-norm residual argument** |
| 5C | greedy / temperature / top-k vs HF probabilities | 20 | TRF §9 | **not in the book** (greedy/beam 10.8; temperature exercise 4.1) | everything: formulas, worked distribution, the HF logits-warper check |
| 6 | (THEORY) why several heads | 25 | ATT §6, §11 | 11.5 (one motivating paragraph) | the conceptual argument + the student's own maps |
| 7 | (THEORY) three kinds of Transformer | 25 | TRF §7, §10 | 11.9 (encoder-only / enc-dec / decoder-only, BERT/T5/GPT) | **the families table with objectives and tokenizers**; "adaptations, not subsets"; why decoder-only won |
| 8 | decoder-only translation | opt | TRF_ADV §9 | — | — |
| 9 | pretrained HF models | opt | TRF_ADV §10 | 15.10 (BERT pretraining) | — |
| 10 | beam search | opt | TRF_ADV §5 | 10.8 | — |
| 11 | self-attention inside an RNN (last year's hybrids) | opt | TRF_ADV §8 | — | — |
| 12 | larger corpora; GloVe | opt | TOK_ADV §4 | 15.5 | — |

Sum: P1 30 + P2 70 + P3 40 + P4 50 + P5 50 + P6 25 + P7 25 = **290** ✓.

### 6.2 What HW7 needs from earlier weeks (cross-references the notes must make)

| From | Used in | Cross-reference |
|---|---|---|
| HW2 logistic regression | P1(B) | `TOKENS` §7: SGNS *is* logistic regression on (center, context) pairs |
| Week 2–3 soft k-NN / KDE (`LOCAL_CLASSIFIERS`) | P2 | `ATTENTION` §2 (decision 3) |
| Week 5 PCA | P1(C) | `TOKENS` §8 |
| HW5 softmax / MLP | P2(A), P4(A) | the FFN is the HW5 MLP applied per position |
| HW6 P1(D) BatchNorm | P4(A) | `TRANSFORMER` §2: LN = BN over the other axis |
| HW6 P2 residual | P4, P5(B) | `TRANSFORMER` §3, §8 (the pre-norm highway) |
| HW6 P3 TinyStories LM, tokens → IDs → embedding | P1, P5 | `TOKENS` §1; `TRANSFORMER` §7 (same objective) |
| HW6 P4 seq2seq, padding, BLEU, saved results | P2(A), P3, P4(D) | `ATTENTION` §1, §5, §10 |
| Week 12 RNN note, "why word-level is fine here" | P1(A) | `TOKENS` §2 picks up from it (align with the Weeks 11–12 plan) |

---

## 7. Lectures (4 regular + 1 extra) and lecture plans

HW7 is due **Tue 12/15**. Week 13 = Thu 12/3, Mon 12/7; Week 14 = Thu 12/10, Mon 12/14.

| Lecture | Date | Board content (note §) | HW7 parts enabled |
|---|---|---|---|
| L1 | Thu 12/3 | `TOKENS` §1–8: BPE by hand on the tiny corpus; the p5 network; the p8 tricks; SGNS = logistic regression | P1 |
| L2 | Mon 12/7 | `ATTENTION` §1–6, §10: flashback → kernels → scaled dot product (2-token example by hand) → masks → MHA shapes → Bahdanau | P2(A–C), P3 |
| **Extra** | **week of 12/7** (before 12/10) | `ATTENTION` §7–9, §11 (order, PE boards, causal mask), then `TRANSFORMER` §1–3 (the big-picture figure, LN vs BN, add & norm) | P2(D), P4(A), P6 |
| L3 | Thu 12/10 | `TRANSFORMER` §4–9: encoder/decoder blocks, train vs generate, **GPT = delete parts**, pre-norm, sampling distribution by hand | P4(B–D), P5 |
| L4 | Mon 12/14 | `TRANSFORMER` §10 (three families; already readable for P7) + an advanced tour (BERT/T5, RoPE = the rotation board, KV cache, beam, scaling) + HW clinic | P7 review; optional |

**Lecture plans** (one per basic note, GAN/VAE format, a "Time | On the board | Worked example/demo" table):
- `TOKENS_claude_lecturePlan`: L1. Demo: a live BPE merge trace; gensim neighbours on TinyStories.
- `ATTENTION_claude_lecturePlan`: L2 + the extra lecture's first half. Demos: the √d saturation plot; MHA
  shape walk on a real tensor; an alignment heatmap from the reference model.
- `TRANSFORMER_claude_lecturePlan` (2 pp): the extra lecture's second half + L3, with an L4 appendix. Demos:
  `nn.TransformerEncoderLayer` vs own block (max diff); GPT stories at τ = 0.5 / 1 / 1.5; the pilot tables.

Risk: if the extra lecture can't be before 12/10, either shift `TRANSFORMER` §2–3 to reading or ask for
HW7's due date to move to after 12/14 (§9 item 1).

---

## 8. Figures

Default = our own TikZ (diagrams) or a `build_*_figs.py` (plots; numpy/matplotlib only, no training).
Figures that need a trained model come from the HW7 solution build, saved as data, so the figure scripts
stay fast. "Board" = redrawn from the instructor's annotated lecture, with a caption like "after the board,
Lecture 8/13 p5".

| Note | Fig | Content | Make it as | d2l alternative |
|---|---|---|---|---|
| TOK | 1 | text → tokens → IDs → vectors → model | TikZ | — |
| TOK | 2 | one sentence cut three ways (words / chars / BPE) with token counts | TikZ table (real splits from the starter) | — |
| TOK | 3 | BPE merge trace on `hug/pug/pun…` (pair counts per step) | TikZ table | 15.6 code output |
| TOK | 4 | **the word2vec network** (board 8/13 p5) | TikZ (board) | — |
| TOK | 5 | SGNS as logistic regression (positive 1 / noise 0) | TikZ | — |
| TOK | 6 | TinyStories neighbours, 2-D PCA | build script from solution vectors | — |
| ATT | 1 | **seq2seq bottleneck vs attention** (big picture) | TikZ | 11.4.2 |
| ATT | 2 | **kernel smoother → attention** (board 8/6 p5) | matplotlib | 11.2 plots |
| ATT | 3 | kernel shapes (board 8/6 p8) | matplotlib | 11.2.1 |
| ATT | 4 | √d saturation (the §5.2 numbers) | matplotlib | — |
| ATT | 5 | MHA dataflow with shapes | TikZ | 11.5.1 |
| ATT | 6 | **binary bits → sin/cos heatmap** (board 8/8 p8) | matplotlib + TikZ | 11.6.3 heatmap |
| ATT | 7 | padding vs causal mask grids | TikZ | — |
| ATT | 8 | Bahdanau decoder step (board 8/6 p10) | TikZ (board) | 11.4.1 |
| ATT | 9 | alignment heatmap es→en | build script from solution model | 11.4.3 |
| TRF | 1 | **the full Transformer, three attentions colour-coded** (board 8/8 p3) | TikZ (board), *the key figure* | 11.7.1 (**the one place d2l is tempting**; still redraw for the colour coding) |
| TRF | 2 | LN vs BN axis on a `(B,T,d)` block | TikZ | — |
| TRF | 3 | encoder block | decoder block | TikZ | — |
| TRF | 4 | **GPT = Fig 1 with the encoder + cross-attention greyed out** | TikZ (same source as Fig 1) | — |
| TRF | 5 | **pre-norm vs post-norm**, residual highway highlighted | TikZ | — |
| TRF | 6 | training in parallel vs the generation loop | TikZ | — |
| TRF | 7 | sampling bars at τ = 0.5 / 1 / 2 and top-2 (§5.3 numbers) | matplotlib | — |
| TRF | 8 | three families as attention-pattern grids | TikZ | 11.9.3 (right panel) |
| TRF | 9 | pilot perplexity and BLEU bars | matplotlib (from the solution build's JSON) | — |

**If a d2l figure is ever used**, the caption is: "Figure from A. Zhang, Z. C. Lipton, M. Li, A. J. Smola,
*Dive into Deep Learning*, Fig. X.Y.Z, d2l.ai, licensed CC BY-SA 4.0." Use it unmodified, and keep it out of
the basic notes.

---

## 9. Open questions

1. **Extra-lecture date.** The plan needs it in the week of 12/7 (before Thu 12/10). Otherwise P5 is taught
   on 12/14, one day before the due date. Related: when is HW7 released? If at the start of Week 13, students
   get 12 days.
2. **P3's key effect is still open.** The ≤25-token pilot is half done. GRU alone gets 22.5 BLEU overall,
   collapsing to **8.8 / 6.0** on 13–17 / 18–25-token sentences, so the room is there. The Bahdanau ≤25 run
   was still in progress when this plan was written. If attention clearly beats the GRU on long sentences,
   `ATTENTION` §10 and P3(C) say "attention pays off on long sentences". If not, P3(C) gets the provided
   **copy/reverse demo (30–50 tokens)** and the note states the honest ≤12 result. Decide when the run finishes.
3. **Three basic notes (recommended) vs two** (a merged `TOKENS_ATTENTION` of about 28 pp).
4. **Subfolder names.** Proposed `TOKENS/`, `Attention/` (existing) and `TRANSFORMER/`. The existing `TRN/` and
   `Word2vec/` keep their old files. Watch for the case-insensitive `ATTENTION`/`Attention` collision.
5. **P3's score function:** additive (board/book) or dot-product (reusing P2(A); NN plan §8 item 3)? The note
   teaches both; the HW decides which equation is boxed.
6. **Embedding √d scaling** (d2l does it, `nn.Transformer` has no embeddings). The starter's choice fixes what
   the note says. It must be identical in own and reference models for the P4 checkpoints.
7. **word2vec letters.** Keep d2l's `v` = center, `u` = context (they collide with the values `V` only
   visually), or rename?
8. **The 8/6 p7 "norms are irrelevant" line.** OK to state it precisely in the note (‖q‖ cancels exactly; ‖k‖
   only for equal-norm keys)?
9. **Syllabus additions** (§3.3, §3.5): distill Augmented RNNs, the HF tokenizer chapter, the flagged YouTube
   video, nanoGPT; the module-title changes; splitting the d2l chapter-11 link across the two weeks.
10. **Last year's hybrid notebooks and step images.** Keep them for optional P11 (linked from
    `TRANSFORMER_ADVANCED` §8) or retire them with the old HW7?
11. **Order of building.** `TOKENS` §2 and Figs 2, 6, ATT 9 and TRF 9 need the starter's tokenizers and the
    solution's trained models. Build the HW7 starter/solution first, or write the notes with placeholders and
    fill them in?
12. **Weeks 11–12 coordination.** The parallel plan names the Week 12 RNN note. `TOKENS` §2 must continue from
    its "why word-level is fine for TinyStories" section rather than repeat it.

---

## 10. Execution checklist (once approved)

1. Settle §9 items 1–3 and 5–6, then fix the folders.
2. Build or confirm the HW7 solution numbers that the notes quote (tokenizer splits, alignment model,
   perplexity/BLEU JSON).
3. Write the basic notes in lecture order (`TOKENS` → `ATTENTION` → `TRANSFORMER`), each with its
   `build_*_figs.py` and lecture plan. Check every worked example in §5 against a 10-line script before it
   goes in, and use the same numbers as the starter's checkpoint tests where they overlap.
4. Then write the two advanced notes. Resolve every reference via LibKey.
5. Compile to 0 errors / 0 overfull; `xr-hyper` resolves.
6. Syllabus pass (§3.5); HW7 "Lecture notes:" lines from "planned" to real links.
7. Only then the Tier-4 cleanup (§3.4), after re-reading each file.
