# Weeks 11–14 Notes Plan: CNN, RNN, Tokens, Attention, Transformer (HW6 + HW7)

**Status (2026-10-18): all 9 notes + 5 lecture plans written and compiled** (CNN 13 pp, CNN_ADV 6, RNN 13, RNN_ADV 7, TOKENS 10, TOKENS_ADV 6, ATTENTION 14, TRANSFORMER 14, TRANSFORMER_ADV 6 — below the §1 targets by choice: no padding). Linked from the syllabus (weeks 11–14) and the HW6/HW7 pages. Demo notebooks pending.

**What this plan settles**
- This is the outline of record for all nine notes, both basic and advanced.
- It is synced to the *final* HW6/HW7 pages and to the executed solution notebooks: full-run numbers from the
  2026-10-17 evening runs, after the Codex review and the dev/full rebuild.

**What it keeps from the earlier plans**
- The detailed source catalogs stay in `WEEKS_11_12_NOTES_PLAN.md` §3 and `WEEKS_13_14_NOTES_PLAN.md` §3:
  every page of the instructor's annotated lectures and what to absorb from it.
- So do the notation standards (each plan's §4) and the figure lists (§5.5 and §8).
- Where those plans' outlines, numbers or open questions differ from this file, **this file wins**. §6 lists every
  difference.

**Contracts**
- `2.5_NN/HW6_advNN/HW6_26F.html` and `2.5_NN/HW7/HW7_26F.html`.
- The solution descriptions `code_hw6/HW6_26F_solution_description.md` §3 and `code_hw7/HW7_26F_solution_description.md`
  §2–3.
- `claude_renovation_0826_code/HW5_6_7_NN_PLAN.md` §8, items 1–17.

---

## 1. The notes at a glance

**Basic notes** (required; together they carry every required HW part):

| Note | File (under `7_adv_NN/notes/`) | Carries | Lecture(s) | Target length |
|---|---|---|---|---|
| CNN | `CNN/CNN_claude_MMDD` | HW6 P1, P2, P6 | Thu 11/19 | 14–16 pp |
| RNN | `RNN/RNN_claude_MMDD` | HW6 P3, P4, P5 | Mon 11/23, Mon 11/30 | 16–18 pp |
| TOKENS | `TOKENS/TOKENS_claude_MMDD` | HW7 P1 | Thu 12/3 | 11–13 pp |
| ATTENTION | `Attention/ATTENTION_claude_MMDD` | HW7 P2, P3, P6 | Mon 12/7 + extra (first half) | 14–16 pp |
| TRANSFORMER | `TRANSFORMER/TRANSFORMER_claude_MMDD` | HW7 P4, P5, P7 | extra (second half) + Thu 12/10 | 15–17 pp |

**Advanced notes** (optional; labelled just "(optional)" on the syllabus):

| Note | File | Covers | Target length |
|---|---|---|---|
| CNN_ADVANCED | `CNN/CNN_ADVANCED_claude_MMDD` | HW6 opt. P7; depth for P6 | 8–10 pp |
| RNN_ADVANCED | `RNN/RNN_ADVANCED_claude_MMDD` | HW6 opt. P8–P11 | 9–11 pp |
| TOKENS_ADVANCED | `TOKENS/TOKENS_ADVANCED_claude_MMDD` | HW7 opt. P12; depth for P1 | 8–10 pp |
| TRANSFORMER_ADVANCED | `TRANSFORMER/TRANSFORMER_ADVANCED_claude_MMDD` | HW7 opt. P8–P11 + the dev-mode questions | 10–12 pp |

**Lecture plans** (separate, unlinked PDFs, in the VAE/GAN format):
- `CNN_claude_lecturePlan` (1 table), `RNN_claude_lecturePlan` (2 tables), `TOKENS_claude_lecturePlan` (1),
  `ATTENTION_claude_lecturePlan` (1½), `TRANSFORMER_claude_lecturePlan` (1½, plus the 12/14 appendix).

**Lengths, calibrated against the existing basic notes**
- The recent basic notes run 13–16 pp: NN_BASICS 16, VAE 13, GDA_NB 14, GAN 11. Only EM_MIXTURES reaches 20. The
  advanced notes run 8–11 pp.
- The earlier plans' 18–22 pp targets were above that pace, so they are cut here. The RNN note is the one allowed
  to run long, because it spans two lectures.
- **The cuts are by moving material, not by dropping it:** detail that no required part needs goes to the
  advanced note.

**Demo notebooks** (last, after the starters):
- One per basic note, built on the HWs' **dev configurations**, so every training cell finishes live in class
  within about 1 minute.

---

## 2. House style: what "like the previous notes" means here

Taken from NN_BASICS / NN_ADVANCED / VAE / GAN (Weeks 9–10) and EM / GDA_NB (Weeks 7–8):

- **Preamble:** `extarticle` 12pt, `margin=0.5in`, `\normalsize` 13/16pt, TikZ.
  - Environments: `remark`, `keypoint` (boxed), `pseudo` (algorithm box), `example`.
  - Copy the preamble from `NN_BASICS_claude_0929.tex`. The old `6140ml-style.tex` scribe template is not used.
- **Title:** `<Topic>: <subtitle>`, with `\large Lecture Notes Consolidated with Claude AI --- CS6140 Machine
  Learning` under it. The opening blurb lists prerequisites only.
- **Section titles say what the section shows.** For example, "The Discriminator: a Classifier You Have Already
  Built" or "Recap: One Neuron Is a Model You Already Know". Most notes **open with a recap of what students
  already know**.
- **Big picture first:**
  - An overview figure plus a **"parts: where you've seen it / NEW"** table, before any math. This is the GAN-note
    principle: assemble known parts and name only what is new.
  - Each module diagram comes before that module's math.
- **Arc of a section:**
  1. Motivation.
  2. Narrated equations, with every equation followed by one sentence of meaning.
  3. **A worked numeric example that doubles as a unit test.** Where the HW has a checkpoint, the numbers match it.
  4. The algorithm box.
- **Shapes in every boxed equation**, e.g. `(B, T, d) → (B, h, T, d/h)`.
- **HW material:**
  - One **"HW6 Map" / "HW7 Map"** section at the end: problem by problem, the one effect to see, and common bugs.
  - No scattered "supports HW-x" tags. An inline HW pointer stays only where it resolves a specific difficulty.
  - No code for `TODO_STUDENT` blanks, only equations, shapes and pseudo-code. The notes do supply the intuition
    the starters' *How to think about it* hints point at.
- **Numbers:**
  - Every number comes from a build script (`images_claude/build_*_figs.py`) or is quoted from the solution's
    results JSON. **HW results are quoted as "in the reference run" with "about"**, since GPU runs vary by ≤ 1 BLEU
    and ≤ 0.5 perplexity.
  - Claims match what the runs show. For example: the comparisons show an effect, they don't prove a cause;
    pooling reduces shift sensitivity, it doesn't remove it.
- **Figures:** redrawn by us (TikZ, or matplotlib from a build script). Instructor boards are credited as
  "after the board, Lecture 8/13 p5". Nothing is copied from the AWS STAT157 decks. d2l figures are linked, not
  embedded.
- **Notation:** the earlier plans' §4 tables (book plus the instructor's boards; row vectors; d2l symbols).
  - HW6's RNN tensors are **time-major**, and HW7 is **batch-major** with one bridge box.
  - The GRU follows **PyTorch's** convention, as the HW does.
  - BLEU = **standard corpus BLEU-4**. One remark mentions that variants exist, e.g. `d2l.bleu`.
- **Lecture plans:**
  - A "Time / On the board / Worked example" table, 100 minutes.
  - Linked to the note with `xr-hyper` + `\externaldocument` (so compile the note first). The plan's first page
    carries the main title.
  - Unlinked from the syllabus, like `VAE_claude_lecturePlan.pdf`.
- **Syllabus:**
  - New basic notes go at the top of the lecture column, above the annotated `Lecture_…` PDFs, which stay linked.
  - Advanced notes go in the last column as "(optional)". Third-party links go in the last column.

---

## 3. Calendar → lectures → HW parts

> **2026-11-01: superseded by the dated calendar in `claude_renovation_0826_code/HW5_7_progression_table.md`** (CNN Mon 11/16; RNN 11/19, 11/23; TOKENS 11/30; ATTENTION 12/3 + first half of 12/7; TRANSFORMER second half of 12/7 + extra lecture; 12/10 workshop; 12/14 optional; exam Thu 12/17). The lecture plans carry the new dates.

| Date | Lecture | Note sections | Unlocks |
|---|---|---|---|
| Thu 11/19 | CNN | CNN §1–9 | HW6 P1, P2, P6 |
| Mon 11/23 | RNN-A | RNN §1–5, §7–8 | P3(A), P4(A–B) |
| *Thu 11/26* | *no class (Thanksgiving)* | | |
| Mon 11/30 | RNN-B | RNN §6, §9–10 | P3(B–C), P4(C–D), P5 |
| Thu 12/3 | TOKENS | TOKENS §1–8 | HW7 P1 |
| Mon 12/7 | ATTENTION-A | ATTENTION §1–6, §10 | P2(A–C), P3 |
| extra (aim: week of 12/7) | ATTENTION-B + TRANSFORMER-A | ATTENTION §7–9, §11; TRANSFORMER §1–4 | P2(D), P4(A–B), P6 |
| Thu 12/10 | TRANSFORMER-B | TRANSFORMER §5–9 | P4(C–D), P5 |
| Mon 12/14 (unless it is the exam) | review + advanced tour | TRANSFORMER §10 (already readable for P7) + advanced pointers | P7; optional problems |

- **CNN gets one lecture.** That is dense: batch norm, ResNet, augmentation and transfer all have to fit. Students
  start with P1 while P2 is still a week away.
- **A fallback for CNN** if one lecture proves too dense: the RNN-A board time drops the LM history (§1) to 5
  minutes, and 10 minutes of transfer learning move there.
- If the extra lecture can't land before 12/10, TRANSFORMER §2–3 (LayerNorm, Add & Norm) become reading, and
  12/10 starts at the encoder block.

---

## 4. Note outlines (revised)

`→` marks the HW part a section carries. *Key effect* lines quote the reference full runs.

### 4.1 CNN — "Convolutional Networks: From Sliding Windows to ResNets"

*Prerequisites:* HW5 / NN_BASICS (MLP, softmax + cross-entropy, the training loop, vanishing gradients).

1. **Recap and the big picture: an MLP looking at an image.**
   - Fashion-MNIST's MLP has 203,530 weights; LeNet does the same job with 61,706.
   - LeNet overview figure with shapes.
   - The instructor's "Two Issues" (translation invariance, locality) and "frame × kernel window".
   - Timeline box (1995 → 2022 = Weeks 11–14).
   - Parts table: dense layer, ReLU, softmax-CE and backprop are known. Shared windows, pooling, batch norm and
     skips are NEW.
2. **Cross-correlation, padding, stride.**
   - "Cross-correlation, not convolution", and why the kernel flip doesn't matter when the kernel is learned.
   - The output-size formula.
   - The 19/25/37/43 example, by hand. → P1(A)
3. **Channels, and convolution as one matrix product.**
   - The 4-index formula. PyTorch's weight is $(c_o,c_i,k_h,k_w)$.
   - 1×1 convolutions.
   - **Unfold:** the patch matrix × the kernel. Worked example plus one kernel offset's slice and its shape (the
     starter now shows that slice, so the note matches it). → P1(A)
4. **Pooling.**
   - Max and average.
   - The 1-pixel shift: **pooling *reduces* sensitivity to small shifts; it doesn't remove it.** A shift across a
     window boundary changes the output (review fix).
   - What pooling does not buy: large shifts, rotation, scale. → P1(A, C), P6
5. **LeNet, then and now.**
   - Layer and parameter table (61,706).
   - Own layers vs `nn` layers after a weight copy.
   - Sigmoid + average pooling → ReLU + max pooling.
   - *Key effect:* 1998 LeNet **0.816 trails the MLP 0.881**; modernized **0.887 with 30% of the parameters**.
     On images shifted 2 px: MLP 0.536 vs LeNet 0.773. → P1(B, C)
6. **Batch normalization.**
   - Statistics per channel, over the batch *and* the positions (axes figure). Train mode vs eval mode with
     running averages.
   - PyTorch conventions box: momentum 0.1, unbiased running variance.
   - Why two BN layers can't share one module.
   - **LayerNorm preview** = the same formula over the other axis (the toy matrix).
   - *Key effect:*
     - first-epoch test accuracy 0.774 → 0.872;
     - at learning rate 3e-2, 0.853 vs **0.907**;
     - BN-LeNet beats the MLP. → P1(D)
7. **Going deeper: residual blocks.**
   - $H(x)=x+R(x)$, from the instructor's handwritten block, redrawn: "the gradient goes around", "POOL after ⊕".
   - The 1×1 projection, with a shape walk-through.
   - **The shortcut gives a direct path; it doesn't guarantee the block starts as the identity** (review fix).
   - *Key effect:* the 11-layer ResNet **0.857 vs BN-LeNet 0.684**. Honest framing: this comparison changes depth
     and shortcuts together; optional P7 separates them.
   - Forward link: every Transformer block is a residual block. → P2(A)
8. **Little data: augmentation and transfer.**
   - Augmentation on the training data only.
   - Equivariance vs invariance box.
   - Scratch vs linear probe vs fine-tuning; pretrain → fine-tune as the LLM workflow in miniature.
   - *Key effects:*
     - augmentation: train/test gap 0.138 → 0.044, test accuracy 0.857 → 0.874;
     - on 5k images: scratch 0.726, probe 0.813, fine-tune **0.881** (at 128 px). → P2(B, C), P6
9. **HW6 Map (P1, P2, P6) + common bugs.**
   - Flipping the kernel; unfold layout; pooling-stride defaults.
   - BN over the batch only; `model.eval()`; reusing one BN module; a skip whose shapes don't match.
   - Augmenting the test set; ImageNet normalization.
   - **Box "Debug small, run full":** why dev-mode checks are trustworthy while dev accuracies mean nothing.
     This is the intuition for optional P11, and the habit students need for every HW6/HW7 run.
10. **Forward:** → CNN_ADVANCED. → HW7: residual + LayerNorm in every Transformer block; ViT patches = unfold.

### 4.2 RNN — "Recurrent Networks: Language Models, Gates, and Translation"

*Prerequisites:* HW5 / NN_BASICS; the CNN note (weight sharing; a product of per-layer factors). Gradient clipping
is taught here from zero; the HW6 page no longer credits it to HW5.

1. **Why sequences need memory.**
   - The board's framing: "why other ideas don't work". Not IID; the chain rule.
   - Plan A, Markov (τ = 4, n-grams) vs Plan B, a hidden state ("$h_t$ = context at time t").
   - Overview figure: an RNN LM unrolled over a TinyStories sentence.
   - Parts table.
2. **From text to numbers: tokens → IDs → embeddings → shifted targets.**
   - Word tokenizer; `min_freq` 10 gives 5,274 words, 99.6% coverage, 0.6% `<unk>`.
   - The embedding lookup = one-hot × $E$.
   - Random windows vs carried state.
   - **Box "Whole words are fine here; real LLMs use subwords"**, with the coverage curve. → P3 walkthrough, P3(B)
     side question
3. **Language models and perplexity.**
   - Perplexity = exp(mean cross-entropy), "the effective number of choices".
   - **The ladder** (reference run): uniform 5,274 → unigram **303.5** → RNN **23.8** → LSTM **18.6** → GRU
     **17.5** (→ GPT ≈ 15.5 in HW7).
   - The interpolated-bigram rung (≈ 56) only if the build script reproduces it. → P3(A, B)
4. **The recurrent cell.**
   - Equations and a time-major shape table. "3 weight matrices, independent of t"; "not deep, 1 layer".
   - The hand step (0.3364, −0.0500), which is P3(A)'s checkpoint.
   - The mapping to `nn.RNN` (transposed weights, two biases).
   - Generation with temperature, $\mathrm{softmax}(o/\tau)$, on a 3-word example.
   - *Key effect:* own RNN ≈ `nn.RNN` (23.8 vs 23.6), **independently initialized, so similar but not identical**
     (review fix). → P3(A)
5. **Training through time: BPTT, vanishing/exploding gradients, clipping.**
   - The gradient is a product of $T-t$ per-step factors ($0.9^{50}$ = 0.005, $1.1^{50}$ = 117).
   - Clipping (3, 4) → (0.6, 0.8). **Clipping fixes exploding gradients, not vanishing ones.**
   - Truncated BPTT, with the instructor's verdicts.
   - **How to read the P3(C) plot** (reference run): relative gradient at distance 10 / 20 / 40 / 79 is RNN
     1.2e-1 / 2.7e-2 / 1.3e-3 / 2.9e-5 (a straight line on a log scale), LSTM … 3.7e-3, GRU … 2.3e-2. **The models
     are similar up to about 10 steps; the separation is at 40–79** (review fix). → P3(A, C), P5
6. **Gates: the GRU and the LSTM.**
   - The board's words for reset and update; the candidate is a tanh *proposal*, not a distribution.
   - The LSTM memory cell: the per-step factor along the cell path is $F_t$, and the update is additive
     ($0.95^{50}$ = 0.077 vs $0.9^{50}$ = 0.005).
   - Conventions box (PyTorch's GRU reset placement; Cho's swapped $z$).
   - Parameter counts: 3× / 4× an RNN of the same width.
   - *Key effect:* both gated models far below the RNN. **At this budget the GRU edges the LSTM**; the note says so
     plainly instead of promising an RNN → GRU → LSTM order.
   - Stories are read exploratorily: look for characters and scenes that carry over, and for contradictions;
     perplexity is the firm evidence. → P3(B, C), P5
7. **The encoder–decoder.**
   - Spanish → English; lengths differ.
   - Encoder (embedding + GRU, packed sequences in the starter).
   - **HW6's decoder:** a fixed context = the encoder's final state, fed at every step and as the initial state.
     **The decoder = P3's LM, conditioned on a source.**
   - The d2l `Encoder`/`Decoder` interface; Tatoeba ≤ 12 tokens; special tokens. → P4(A)
8. **Training: teacher forcing and padding masks.**
   - `<bos>` + the target shifted by one.
   - The one-line `ignore_index` masked loss on a 2×4 padded batch.
   - **The consistency check:** whole target at once = one word at a time, and why it must hold.
   - The real bug it caught (the pilot's context read from the decoder's own state) as a remark. → P4(B)
9. **Decoding and evaluation.**
   - The greedy loop: `<eos>`, a length cap, a finished mask.
   - **BLEU:** clipped n-grams (the two-reference "the the the cat" case: max, not sum), the brevity penalty, the
     toy example 0.579, corpus vs sentence level.
   - **BLEU by length** (reference run): **27.9** overall; 1–4 / 5–6 / 7–8 / 9–12 tokens: 32.4 / 37.0 / 30.1 /
     18.6.
     - Longer sentences *tend* to score worse.
     - 1–4 is below 5–6, because one wrong word breaks most 3- and 4-grams of a short sentence.
   - The book baseline is 26.3.
   - **The fixed-size context is one suspect, and HW7 tests it.** → P4(C, D)
10. **HW6 Map (P3, P4, P5) + common bugs + forward pointers.**
    - Bugs: targets not shifted; time-major vs batch-first; a weight copy without the transpose; state not
      detached; clipping in the wrong place; perplexity from a summed loss; temperature after the softmax; the
      masked loss averaging over pad; a decoder ignoring its context; no `<eos>` stop; BLEU on IDs.
    - **"HW7 needs your own HW6 full results" box:** `results_hw6.json` + `hw6_seq2seq.pt`, both from full runs.
    - Forward: bottleneck → attention (HW7 P3); recurrence → self-attention; the same LM → GPT (HW7 P5);
      words → BPE (HW7 P1). A short RNN-vs-Transformer table. → RNN_ADVANCED.

### 4.3 TOKENS — "Tokens and Word Vectors: Subwords, BPE, and word2vec"

*Prerequisites:* HW6 P3 (tokens → IDs → `nn.Embedding`) and the RNN note §2 box; HW2 logistic regression; Week 5
PCA.

1. **Recap and the big picture:** text → tokens → IDs → vectors → model (HW6 P3's pipeline with one box replaced).
   Parts table: IDs, `nn.Embedding`, logistic regression and PCA are known; merges and negative sampling are NEW.
2. **Three ways to cut text: words, characters, subwords.**
   - Picks up from the RNN note, without repeating it.
   - Real splits on five texts (reference run): with words, the Spanish sentence is 8/9 `<unk>`, the typos 3/9, the
     names 3/7.
   - BPE-5,274 leaves no unknown words (only ¿ ó á are unknown characters); GPT-2 leaves nothing unknown.
   - fastText's "friend = friends = friendship" as the bridge. → P1(A) side question
3. **Subwords in modern LLMs: the table** (GPT-2/3/4, LLaMA, BERT, T5: tokenizer, algorithm, vocabulary size;
   **sizes verified against the released configs at write time**). Message: **no modern LM reads whole words; most
   use BPE.**
4. **BPE, the algorithm.**
   - Pair counts weighted by word frequency, never across words.
   - The ordered merge list *is* the tokenizer; encoding applies the merges in learned order.
   - The tie-free toy `hug×4 hugs×2 pug×2 pun×2 bun×1 sun×1`: merges (u,g) 8, (h,ug) 6, (u,n) 4; `sung → s un g`.
   - **Ties:** the TinyStories run matches HF's first 310 merges in order and all 500 as a set. Merge 311 is a
     genuine tie (4,870 = 4,870) broken differently. "Your list may part ways at a tie; check the counts" (matches
     the notebook's verified-tie message). → P1(A)
5. **From IDs to vectors.** One-hot ("#dim = #vocab, no easy sim()"); lookup = one-hot × matrix; dot product and
   cosine.
6. **word2vec as a "fake task" network** (the 8/13 p5 board redrawn). Skip-gram; center vs context vectors; the
   softmax over 𝒱 and why it's too expensive.
7. **The tricks for computation** (8/13 p8 board).
   - **Negative sampling = HW2 logistic regression** (real neighbour 1 / noise 0); the loss.
   - Worked example: scores 2, −1, 0.5 → **1.4143** (P1(B)'s checkpoint).
   - Subsampling.
   - **Windows stay inside one story** (the pipeline is provided; one line on why). → P1(B)
8. **What the vectors learn.**
   - Neighbours (reference run): cat → meowed, kitty, fluffy; red → yellow, green, blue; tree → branches, oak, pine.
   - PCA clusters.
   - **Against gensim, with similar settings: about half of each 8-word list agrees on average** (4.5 of 8). Why
     not all: random initialization, different sampling.
   - Static vs contextual vectors → ATTENTION. → P1(C)
9. **HW7 Map (P1; opt. P12) + common bugs.**
   - BPE: counting across words; forgetting frequencies; overlapping pairs; encoding by longest match.
   - SGNS: one shared matrix; the sign of the negative term; dot vs cosine.
   - The gensim fallback file.
10. **Forward:** GloVe, CBOW, WordPiece/Unigram → TOKENS_ADVANCED; "every Transformer starts with this table" →
    ATTENTION.

### 4.4 ATTENTION — "Attention: Queries, Keys, and Values"

*Prerequisites:* matrix products and softmax (HW5); HW6 P4 (padding, the translator); kernel smoothing / soft k-NN
(LOCAL_CLASSIFIERS).

1. **Recap and the big picture: the HW6 bottleneck.**
   - BLEU falls with length (HW6 reference run 37.0 → 18.6 from 5–6 to 9–12 tokens).
   - The fix: every output step looks at every input. Overview figure.
   - Parts table: softmax, weighted averages, kernels and padding masks are known; Q/K/V, √d, heads and positions
     are NEW.
2. **Flashback: attention is a kernel smoother** (the instructor's 8/6 p5 board; Nadaraya–Watson; the database
   analogy).
3. **Scores are similarity kernels** (8/6 pp 7–8).
   - The Euclidean → dot-product derivation, stated precisely: ‖q‖² cancels exactly; ‖k‖² cancels only when the keys
     have equal norms.
   - Additive score vs dot product.
4. **Scaled dot-product attention.**
   - $\mathrm{softmax}(QK^\top/\sqrt d)V$ with shapes.
   - The 2-token example (0.6225 / 0.3775; P2(A)'s checkpoint).
   - **Why √d:**
     - the score's spread grows like √d (std 2 / 4 / 7.9 / 16 at d = 4 / 16 / 64 / 256);
     - unscaled, the largest of 10 weights goes 0.49 → 0.93;
     - **the softmax's sensitivity to its scores** (the factor every query/key gradient passes through) drops
       0.34 → 0.09;
     - scaled, the weights stay at 0.30–0.32. Wording per the review: sensitivity, not "no learning signal".
     → P2(A, B)
5. **Masking.**
   - Set blocked scores to −∞ (or −1e9) *before* the softmax; why not zero them after.
   - **One convention in the HW (True = may attend)** + the four-API conventions table.
   - Every row needs at least one valid key. → P2(A)
6. **Multi-head attention** (8/6 p12 board).
   - Project → split → attend → merge → project; the shape walk and why the transpose is not optional.
   - Parameter count $4(d^2+d)$, the same as one big head.
   - `in_proj_weight` packing (the starter copies weights). → P2(C)
7. **Self-attention and the order problem** (8/8 p2: "no recurrence → parallel").
   - Permutation equivariance (the P2(D) demo).
   - CNN / RNN / self-attention table (cost, sequential steps, path length). → P2(D)
8. **Positional encoding** (8/8 pp 7–8 boards).
   - Binary bits → sin/cos; the d = 4 table (P2(D)'s checkpoint).
   - "Position i+δ = a rotation of position i".
   - "A timestamp that the residuals carry". Learned positions and RoPE → advanced. → P2(D)
9. **The causal mask.** All-zero scores give the running mean of V; changing the last token leaves earlier outputs
   unchanged. → P2(D), reused in P5
10. **Attention inside the HW6 translator.**
    - **Rewritten to match the final HW.**
    - **HW7's decoder = HW6's decoder unchanged + one attention step on top** (Luong-style):
      - the GRU output $s_t$ is the query; keys = values = the encoder's outputs;
      - additive score $w_v^\top\tanh(W_q s_t + W_k h_s)$ for all pairs at once (by broadcasting);
      - the output reads $\tanh(W_c[s_t; c_t])$.
    - Bahdanau's original wiring (the 8/6 pp 9–11 board, d2l 11.4) feeds $c_t$ into the GRU's *input* instead, as a
      remark. **Same attention, different wiring**; ours is also exactly the Transformer's cross-attention pattern.
    - *Key effects:*
      - BLEU **27.9 → 37.6**, better in every length bucket;
      - **reverse task** (5–60 symbols): without attention, token accuracy 97% → 68% → 28% → 10% at 5 / 10 / 20 /
        60; with attention ≈ 100% up to 60.
      - Wording: *learned compression is hard at this budget*, not an absolute capacity claim. The bidirectional
        encoder in the reverse task gets one line on why.
    - **Alignments are soft** (mean largest weight ≈ 0.4): roughly diagonal at the start; some words look at their
      translation, others at the sentence end. **Report what the map shows, including diffuse rows** (review fix:
      no station→estación claim). → P3(A–C)
11. **Why several heads** (simple, conceptual):
    - one softmax gives one weighted average, so it can't put **separate** sharp peaks for different purposes;
    - heads specialize;
    - students use their own four cross-attention maps from P4. → P6
12. **HW7 Map (P2, P3, P6) + common bugs.**
    - Dividing by d instead of √d; softmax over the query axis; masking after the softmax.
    - `K.T` on a batch; `view` without a transpose; forgetting $W_o$.
    - The mask convention flipped; time-major HW6 tensors.

### 4.5 TRANSFORMER — "The Transformer and GPT: From Encoder–Decoder to Decoder-Only"

*Prerequisites:* ATTENTION; HW6 P2 (residual), P1(D) (batch norm), P3 (the language model).

1. **Big picture: the full Transformer as the thinking framework.**
   - Redraws the 8/8 p3 board: encoder ×L, decoder ×L, **three attentions colour-coded** (the cross-attention is
     P3's).
   - Parts table: only LayerNorm and the wiring are new.
2. **LayerNorm vs BatchNorm** ("norm per layer vs norm per batch"). Toy X = [[1,2,3],[2,4,6]] → both rows
   [−1.2247, 0, 1.2247]. Why LN for sequences. → P4(A)
3. **Add & Norm and the position-wise FFN** (the HW5 MLP at every position, $d_{ff}=4d$, **dropout inside**: the HW
   model now matches PyTorch's layers). → P4(A)
4. **The encoder block** (post-norm, as d2l and Vaswani). Checked against `nn.TransformerEncoderLayer`. → P4(B)
5. **The decoder block.** Masked self-attention → cross-attention (Q from the decoder, K = V = the encoder) → FFN.
   Checked against `nn.TransformerDecoderLayer`. → P4(C)
6. **Train in parallel, generate one token at a time.**
   - Teacher forcing + the causal mask = one parallel pass; decoding is a loop.
   - **Box "Initialization matters":** embeddings with std $d^{-1/2}$ (the original Transformer) vs PyTorch's
     default N(0, 1) × √d: about 45 vs about 31 BLEU at the same budget. It was found in the build; students who
     rewrite the stacks will hit it.
   - MPS nested-tensor note, one line.
   - *Key effect* (reference run):
     - own **45.4**, `nn.Transformer` **44.4** (the same architecture, dropout included), attention GRU 37.6,
       HW6 27.9;
     - better in every length bucket, with fewer parameters (14.6M vs 19.0M) and less training time. → P4(D)
7. **Decoder-only = GPT, the practical model.**
   - Delete the encoder and the cross-attention from Fig 1: what remains is P4's encoder block + the causal mask.
   - Objective = HW6 P3's next-token cross-entropy.
   - **Weight tying** (the output layer = the token embedding).
   - Parameter unit test:
     - one block at d = 256, $d_{ff}$ = 1024 is **789,760**;
     - own GPT **4,530,842** vs HF GPT-2 **4,526,080**;
     - **the gap 4,762 = our output bias (5,274) − GPT-2's final LN (512)**. This replaces the earlier plan's untied
       1.35M gap.
   - *Key effect* (reference run):
     - perplexity own post-norm **15.6**, pre-norm 15.4, HF GPT-2 **14.8**;
     - vs HW6 LSTM 18.6 and RNN 23.8, on the same split and budget.
   - Encoder–decoder vs decoder-only comparison table (practice and theory); optional P8 decoder-only translation
     43.9 ≈ the encoder–decoder model. → P5(A, B)
8. **Pre-norm vs post-norm.**
   - Pre-norm keeps the HW6 ResNet identity path untouched from input to output ($x_L = x_0 + \sum_l f_l$).
   - **About equal at 4 blocks** (15.4 vs 15.6); the reason for pre-norm is depth and large learning rates.
   - Warm-up and Xiong et al. → advanced. → P5(B) written why
9. **Sampling.**
   - Greedy / temperature / top-k (top-p in one line).
   - The table for z = (2, 1, 0, −1) (P5(C)'s checkpoint).
   - **Check probabilities, not text** (the HF logits processors).
   - Greedy is safe but repetitive; τ 1.5 gives word salad; top-k cuts the worst words.
   - A non-looping greedy sample is possible. → P5(C)
10. **Three kinds of Transformer** (the P7 reading; the HW page points here):
    - BERT encoder-only (MLM), T5/BART encoder–decoder (span corruption), GPT decoder-only (next token);
    - blocks · masks · objective · use · tokenizer;
    - "adaptations, not subsets";
    - what cross-attention gives a translator; why decoder-only won (one objective on raw text, every token a
      label, prompts as the interface, scaling). → P7
11. **HW7 Map (P4, P5, P7; opt. P8, P9) + common bugs.**
    - LN over the wrong axis; the `norm_first` mismatch; the `batch_first` default; the mask True convention.
    - Embedding scale/init; dropout left on in checks; tied vs untied heads.
    - A causal mask on the encoder; Q and K swapped in cross-attention; temperature on probabilities; top-k without
      renormalizing.

### 4.6 The advanced notes (optional)

**CNN_ADVANCED**
1. Backprop through convolution and pooling (1-D worked example; the unfold view).
2. Receptive fields (two 3×3 layers vs one 5×5) → VGG.
3. The modern-CNN lineage table (AlexNet … ConvNeXt).
4. Normalization layers compared (BN/LN/GN/IN) and why BN works, told honestly.
5. **Plain vs residual at depth** → opt. P7 (the deeper plain net trains worse).
6. Equivariance and invariance stated formally; borders and stride; rotations → P6 in depth.
7. Transfer in detail (what the layers learn; BN while fine-tuning; resolution: the measured 64 / 128 / 224 px
   probe 0.548 / 0.729 / 0.746).
8. Convolution → ViT patches.
9. Further reading.

**RNN_ADVANCED**
1. The LSTM cell from scratch (`nn.LSTM`'s i, f, g, o layout) → opt. P8.
2. GRU conventions in full.
3. Your RNN inside the translator (packed vs padded batches, stacking two layers) and the LSTM translator → opt.
   P9, P10.
4. The gradient analysis properly (Jacobian products, spectral norm, the LSTM highway, truncated-BPTT variants).
5. Deep and bidirectional RNNs (a bidirectional *encoder* is legal, as in HW7's reverse task; a bidirectional LM is
   not).
6. Beam search vs greedy vs sampling.
7. HMM / Kalman as classical "Plan B" (cross-reference EM_ADVANCED).
8. Character / word / subword LMs (Karpathy).
9. **Debug small, run full** (supports opt. P11): what a dev run must keep (every code path, real shapes, masks,
   vocabularies) and can drop (width, depth, steps, data); why dev BLEU can't show the length effect; what makes
   dev too small.
10. RNNs today (streaming, state-space pointer).
11. Further reading.

**TOKENS_ADVANCED**
1. The full-softmax skip-gram gradient ("observed minus expected").
2. CBOW.
3. Hierarchical softmax.
4. **GloVe** → opt. P12.
5. fastText.
6. WordPiece, Unigram, byte-level BPE, SentencePiece.
7. Tokenizer effects (tokens per word by language, digits, leading spaces, vocabulary size vs parameters vs
   sequence length).
8. Static vs contextual vectors; analogies with caveats.
9. Further reading.

**TRANSFORMER_ADVANCED**
1. BERT in detail.
2. T5 / BART.
3. Positions beyond sinusoids: learned, relative, **RoPE = the 8/8 p8 rotation board applied to q and k**, ALiBi.
4. Inference cost: KV cache, MQA/GQA, FlashAttention.
5. Beam search with a length penalty → opt. P10.
6. **Compute and scaling:**
   - the cost per block: $Td^2$ for projections and FFN, $T^2d$ for attention, linear in L. This **supports the HW7
     dev-mode question (ii)**;
   - the ≈ 12 L d² parameter rule, checked against §7's count;
   - power laws in one paragraph.
7. **Training stability:** post-norm needs warm-up at depth or high learning rates (Xiong et al. 2020). The modern
   block: RMSNorm, SwiGLU, RoPE, pre-norm.
8. From Bahdanau to the Transformer in five steps (last year's hybrids) → opt. P11.
9. Decoder-only translation (`es <sep> en`, loss on the target only, scoring only target positions) → opt. P8.
10. Pretrained HF models ↔ your models; GPT-2's Conv1D layout → opt. P9.
11. Further reading.

All references are resolved through LibKey at write time.

---

## 5. Coverage check (every required part → a basic-note section)

| HW6 | Note § | HW7 | Note § |
|---|---|---|---|
| P1(A) conv, unfold, pooling | CNN §2–4 | P1(A) BPE + side question | TOK §2–4 |
| P1(B) LeNet vs MLP | CNN §1, §5 | P1(B) SGNS | TOK §6–7 |
| P1(C) modernize, shifts | CNN §4–5 | P1(C) neighbours vs gensim | TOK §8 |
| P1(D) batch norm | CNN §6 | P2(A) masked softmax, SDPA | ATT §4–5 |
| P2(A) residual / ResNet | CNN §7 | P2(B) √d | ATT §4 |
| P2(B) augmentation | CNN §8 | P2(C) multi-head | ATT §6 |
| P2(C) transfer | CNN §8 | P2(D) order, PE, causal | ATT §7–9 |
| P3(A) RNN, clipping, unigram | RNN §2–5 | P3(A–C) attention decoder, alignments, reverse | ATT §10 |
| P3(B) GRU/LSTM, temperatures, subwords | RNN §2 box, §4, §6 | P4(A) LN, add & norm, FFN | TRF §2–3 |
| P3(C) gradient vs distance | RNN §5–6 | P4(B–C) blocks | TRF §4–5 |
| P4(A) encoder | RNN §7 | P4(D) train and compare | TRF §6 |
| P4(B) decoder, masked loss, check | RNN §8 | P5(A–B) GPT, tying, pre-norm | TRF §7–8 |
| P4(C–D) greedy, BLEU, save | RNN §9–10 | P5(C) sampling | TRF §9 |
| P5 theory: LSTM vs RNN, clipping | RNN §5–6 | P6 theory: heads | ATT §11 |
| P6 theory: robustness | CNN §4, §8 | P7 theory: three families | TRF §10 |

Optional parts:
- HW6 P7 → CNN_ADV §5; P8–P10 → RNN_ADV §1–3; P11 → CNN §9 box + RNN_ADV §9.
- HW7 P8 → TRF_ADV §9; P9 → §10; P10 → §5; P11 → §8; P12 → TOK_ADV §4; dev questions → TRF_ADV §6.

---

## 6. What changed relative to the two earlier plans

| Earlier plan said | Now (from the final HWs / runs) |
|---|---|
| Basic notes 18–22 pp | 14–16 pp (RNN 16–18), matching NN_BASICS/VAE/GAN; extra detail moves to the advanced notes |
| CNN "key effects to be measured" | measured (CNN §5–8 above); the 1998 LeNet *trails* the MLP; transfer at 128 px |
| Pooling gives approximate invariance | **reduces** shift sensitivity; a boundary shift can change the output |
| Perplexity ladder RNN 23.1 → GRU 17.8 → LSTM 16.8 | RNN 23.8 → **LSTM 18.6 / GRU 17.5** (GRU edges LSTM at this budget); GPT 15.5 |
| Gradient decay shown with toy factors only | the real P3(C) numbers; separation at 40–79 steps |
| HW6 BLEU 30.0; by length 37.1 / 37.8 / 31.4 / 21.8 | **27.9**; 32.4 / 37.0 / 30.1 / 18.6; "tend to"; the bottleneck as a hypothesis |
| ATTENTION §10: Bahdanau (context into the GRU input); "attention adds nothing at ≤ 12 tokens"; copy/reverse demo "if needed" | **Luong-style step on HW6's unchanged decoder**; 27.9 → 37.6 BLEU; the reverse task is part of P3(C); alignments soft |
| √d "gradients vanish" | "softmax sensitivity" 0.34 → 0.09 |
| GPT untied; gap 1,354,906 = weight tying | GPT **tied**; gap 4,762 (output bias − final LN) |
| GPT 13.5 / HF 12.8 (pilot) | 15.6 / 15.4 / HF 14.8 (HW budget) |
| Transformer 35.5 BLEU (pilot, `nn` only) | own 45.4 / `nn` 44.4; the embedding-init box |
| FFN without dropout | dropout inside the FFN (matches `nn`) |
| SGNS windows across stories | within one story; gensim "similar settings"; overlap about half |
| FAST mode | dev/full: the "debug small, run full" box (CNN §9) + RNN_ADV §9 + TRF_ADV §6 |
| HW7 pages say "Week 13 note" / "Week 14 note" | the HW pages' "Lecture notes:" lines get the real note names when the notes exist: P1 → TOKENS; P2, P3 → ATTENTION; P4, P5, P7 → TRANSFORMER |
| Open Qs (one RNN note? BLEU? clipping prereq? P3 effect? score function? figures?) | settled: one RNN note; corpus BLEU-4; HW6 no longer credits HW5 with clipping; P3 resolved; additive score; redraw everything |

---

## 7. Figures and worked numbers

- **Figure lists:** as in the earlier plans (`WEEKS_11_12` §5.5, `WEEKS_13_14` §8), with these changes:
  - **RNN Fig 6:** the real P3(C) curve, from the HW6 results.
  - **RNN Fig 12:** BLEU by length, from `results_hw6.json`.
  - **ATT Fig 8:** the *Luong-style* step on HW6's decoder, with Bahdanau's wiring as an inset.
  - **ATT, new:** reverse-task accuracy vs length, with and without attention.
  - **TRF Fig 9:** the BLEU and perplexity bars from the two results files.
- **Figures that need trained models** read the saved JSON / solution outputs. The figure scripts never train.
- **Worked numbers:** the earlier plans' unit-test tables stand. Only the GPT parameter test changes (§4.5 item 7).
  Each number that a starter checkpoint also uses is quoted identically.

## 8. Open questions for the instructor

1. **One CNN lecture** for P1–P2 (batch norm, ResNet, augmentation, transfer). OK, with the §3 fallback?
2. **The extra lecture's date** (the plan assumes the week of 12/7, before Thu 12/10).
3. **Length targets** of 14–16 pp basic and 8–12 advanced, i.e. the pace of the recent notes rather than the
   earlier plans' 18–22. OK?

## 9. Order of work

1. CNN → RNN (HW6 is first in the term), then TOKENS → ATTENTION → TRANSFORMER. For each: the build script for
   figures and numbers, the note, then its lecture plan.
2. Then the four advanced notes.
3. Compile each to 0 errors and no overfull boxes; `xr-hyper` resolves.
4. Syllabus rows for weeks 11–14; the HW pages' "Lecture notes:" lines switch from "planned" to the real links.
5. Then the starters (dev default; student copies of the shared modules), the setup page, and the demo notebooks.
