# Weeks 11–12 (CNN, RNN/seq2seq) — Notes Catalog & Writing 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 below has been written yet. This file records
what the source material contains, what HW6 needs, and how the notes should be built.
**Scope:** `7_adv_NN/notes/` (the Tier-1 lectures, `CNN/`, `RNN/`, `introduction_to_deep_learning.pdf`),
the Weeks 11–12 items in `2.5_NN/`, the Smola/d2l decks in `7_adv_NN/non_public/smola_d2l_book/`, and the d2l
book, chapters 7–10 and 14.1–14.2.
**Contract:**
- The HW6 draft `2.5_NN/HW6_advNN/HW6_26F.html`, together with its *Prerequisites* and *Lecture notes* lines.
- The plan of record `claude_renovation_0826_code/HW5_6_7_NN_PLAN.md`. Its §8 overrides the rest of that file.

**Target:** 4 consolidated notes: 2 basic notes that carry HW6's required problems, and 2 optional advanced notes.

> Weeks 11–12 have no consolidated notes yet. Students currently get four annotated slide PDFs and the d2l
> book. HW6 already names the planned notes: "CNN note (Week 11; planned)" for P1–P2, and
> "RNN note (Week 12; planned)" for P3–P4.

---

## 1. Decisions

"Settled" means the plan of record or the instructor already decided it. **Proposed** items need the instructor's OK.

| # | Decision | Status | Consequence |
|---|---|---|---|
| 1 | **Two basic notes plus two advanced notes**: `CNN` (HW6 P1, P2, P6), `RNN` (HW6 P3, P4, P5), `CNN_ADVANCED` (P7), `RNN_ADVANCED` (P8–P10) | proposed | The RNN note covers both the language model and seq2seq. This keeps HW6's "RNN note" lines for P3 *and* P4 valid with no HW edit. The cost is length (≈20–22 pp, at the top of the house range). The split alternative is in §8 Q2. |
| 2 | **Notation follows the d2l book and the instructor's board**, not the Smola slides | proposed | Row vectors, time-major batches, $H_t=\phi(X_tW_{xh}+H_{t-1}W_{hh}+b_h)$. The board (`Lecture_AdvNN_A` p6) already writes exactly this. The slides use column vectors and feed $x_{t-1}$ into $h_t$. One bridge box per note (§4). |
| 3 | Data: **TinyStories word-level** for P3 and **Tatoeba Spanish→English** (≤ 12 tokens) for P4, through `d2l.TimeMachine` / `d2l.MTFraEng` subclasses | settled (plan §8) | The book is character-level (Time Machine) and French→English. The note supplies the word-level walkthrough and the Spanish data. |
| 4 | **"Modern LLMs tokenize into subwords, not words"** is stated in the RNN note, as *why word-level is fine for TinyStories*, with numbers | settled (plan §8.5) | It is a box in RNN §2 that feeds the P3(B) side question. The BPE algorithm itself belongs to the Week 13 note (HW7 P1). |
| 5 | **Simple, conceptual theory.** The starter does the plumbing (weight copies, masks, tolerances, loops) | settled (plan §8.3, §8.6) | Each HW-map entry names the *one effect to see*, never an ablation. |
| 6 | **Lecture order for HW6's three slots**: Thu 11/19 CNN · Mon 11/23 RNN-A · Mon 11/30 RNN-B | proposed | Thanksgiving takes Thu 11/26, and HW6 is due Tue 12/1. RNN-A must give students enough to *start* P3 and P4. RNN-B covers the gates and BLEU. See §6 and §8 Q1. |
| 7 | **Every figure is redrawn**, in TikZ or by a build script | proposed | No images are lifted from the STAT 157 decks: their title slides say "© 2018 Amazon Web Services … All rights reserved". d2l figures are CC BY-SA 4.0. They may be reused with credit, but share-alike then applies to the adapted figure, so redrawing is cleaner. §5.5 has details. |
| 8 | **BLEU = standard corpus BLEU-4** (multi-reference, clipped n-grams, corpus brevity penalty), as computed by the starter and the pilots | proposed | `d2l.bleu` is a *different* sentence-level formula. On the same toy pair it gives 0.694 where standard BLEU gives 0.579. The `d2l.Seq2Seq` package baseline is scored with the starter's BLEU. |
| 9 | **The handwritten lectures stay linked**, and the instructor's handwritten residual-block page (`CNN/cnn_resudual_block.jpg`) is promoted to Tier 1 | proposed | Primary material is never retired. |
| 10 | **Every number in a note is printed by its build script** (as in Weeks 9–10) | proposed | The numbers in §5 were verified on 2026-10-17 with the d2l env's torch (scratchpad `wk1112_numbers.py`). |

---

## 2. House style the new notes must match

This is the current convention: Weeks 7–10 after the 10/16 restructuring passes in `WEEKS_7_8_NOTES_PLAN.md` §8.4.

- **Naming and location:** `CNN/CNN_claude_MMDD`, `CNN/CNN_ADVANCED_claude_MMDD`, `RNN/RNN_claude_MMDD` and
  `RNN/RNN_ADVANCED_claude_MMDD` (`.tex`/`.pdf`), all under `7_adv_NN/notes/`.
  - The existing `CNN/` and `RNN/` folders already hold the reading material, so the notes sit next to it.
  - Each folder gets `images_claude/` and a `build_{cnn,rnn}_figs.py` that regenerates every figure and prints every number.
- **Preamble:**
  - `extarticle` 12pt, `margin=0.5in`, `\normalsize` set to 13/16pt, TikZ.
  - Environments `remark`, `keypoint` (boxed), `pseudo` (algorithm box) and `example`, copied from
    `NN_BASICS_claude_0929.tex`.
- **Title:** `<Topic>: <subtitle>` + `\large Lecture Notes Consolidated with Claude AI --- CS6140 Machine Learning`.
- **Opening blurb:** prerequisites only. Basic notes name HW5 / NN_BASICS. The RNN note also names the CNN note.
- **Structure:**
  - **Big picture first:** an overview figure before any math, and a module diagram before the math of its section.
  - **Arc:** motivating opener → narrated derivations → **worked numeric example usable as a unit test** →
    algorithm box → **one "HW6 Map" section at the end** (problem by problem, plus common bugs) → a forward-pointer section.
  - **No scattered "supports HW6-x" tags.** An inline HW reference stays only where it resolves a specific difficulty.
- **Length:** about 8–10 top-level sections. Basic ≈ 14–20 pp (≈ 350–620 `.tex` lines). Advanced ≈ 10–14 pp.
- **Lecture plans** are separate, unlinked PDFs (`*_claude_lecturePlan.tex`). Each has a 100-min table with the columns
  *Time / On the board / Worked example*. They cross-reference the note through `xr-hyper` + `\externaldocument`, so compile
  the note first. Format as `VAE_claude_lecturePlan.tex`.
- **Syllabus:**
  - Consolidated notes and handwritten `Lecture_…` PDFs go in the lecture column; everything else goes in the last column.
  - Advanced notes are annotated just "(optional)".
  - Material is unlinked only after it has been read and fully absorbed.
- **Students:** many saw gradient descent for the first time in this course, and the NN topics get 2–3 lectures each.
  - Intuition first; every equation gets a sentence of meaning.
  - Starter written-answer cells carry *How to think about it* hints. The note supplies the intuition those hints point at.

---

## 3. Catalog

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

**`Lecture_AdvNN_A_072325.pdf`, "Adv NN intro" (8 pp, fully handwritten)**
- **Content, page by page:**
  - p1: a **timeline**: CNN ≈1995 (images), RNN ≈2009 (sequences), attention 2014, Transformer 2017, large-scale GPT 2022.
  - p2–4: the conv formula $H_{ij}=u+\sum_{a,b}W_{ab}X_{i+a,j+b}$ (a = row shift, b = column shift), with a stick figure
    in two positions. The **19/25/37/43** example with every product written out. Padding = zero rows/columns;
    stride = the window's jump; pooling = average/max over neighbours.
  - p5: deep CNN, VGG.
  - p6: the RNN $H_t=\phi(X_tW_{xh}+H_{t-1}W_{hh}+b_h)$, folded and unfolded, with "**don't deal well with long-term
    dependencies!**" and "BPTT updates both $W_{xh}$ (regular) and $W_{hh}$ (recurrent)".
  - p7: LSTM/GRU ("GRU = simplification of LSTM"), deep and bidirectional RNNs, beam search, encoder → hidden state → decoder.
  - p8: attention preview.
- **Stale:** "not in HW" on p2 and "simple TRN in HW6" on p8 are last year's design.
- **Verdict:** absorb the timeline (CNN §1 roadmap), the board formula (both notes' bridge box) and the RNN page (RNN §4). Keep linked.

**`Lecture_CNN_072525.pdf`, "Convolution NNets" (51 pp, STAT 157 deck 11 + handwriting)**
- **The handwritten additions** are the part to keep:
  - **p2, the "key ideas for NN-for-images ⇒ CNN" page:** recognize a pattern ⇒ compute on the frame ⇒ *frame ×
    kernel window K*; *Frame₁×K ≈ Frame₂×K*; padding & stride; pooling as simplification (avg of [[1,2],[3,6]] = 3,
    max = 6); channels (R,G,B in → d detectors out); a multilayer net trained by backprop.
  - **"Two Principles" retitled "Two Issues"** (translation invariance, locality), with "V doesn't depend on [i,j]".
  - **"2-D convolution" crossed out → "cross-correlation"**; "K = V = W".
  - The padding purpose, written by hand: "compute $h_{ij}$ at i=1 or i=D; image size standardization".
  - Stride: "step size, default 1".
  - The 2-channel example annotated "ch1: Red pixel values, K for Red; ch2: Blue…; different kernels".
  - The handwritten general formula **$H[i,j,d]=\sum_a\sum_b\sum_c W_{abcd}X_{i+a,j+b,c}$** (d = output channel,
    c = input channel, a,b = window indices, i,j = pixel).
  - A **hand-made AVG-pooling slide** worked as 2, 3, 5, 6.
  - "Pooling = EASY layer"; "max pooling: **better for ML**"; "average pooling **≈ blurry**".
  - The MLP recap: "weights updated by BACKPROP; f(net) sigmoid/ReLU/tanh".
- **Plain d2l slides:** the parameter blow-up (36M px → 3.6B), Waldo, edge/sharpen/blur kernels, the Rob Fergus filters,
  the 1-D/3-D variants, complexity (≈1 GFLOP per layer; CPU 18 h vs GPU 14 min), LeNet, MNIST, LeNet 5 at AT&T,
  "expensive if we have many outputs", and the summary.
- **Not in the deck:** batch normalization, ResNet, augmentation, transfer learning. This term's CNN lecture has to add
  all four.
- **Verdict:** absorb. The p2 page becomes CNN §1's skeleton; the worked numbers become unit tests. Keep linked.

**`Lecture_RNN_A_073025.pdf`, "RNN, LSTM, GRU" (89 pp, STAT 157 decks 17 and 19 + handwriting)**
- **p1:** "**actually not RNN. Rather why RNN needed / why other ideas don't work?**" This is the framing for RNN §1.
  The calendar box ("Fri 8/1 demo HW6 pb1,2; Wed 8/6 pb3,4") is stale.
- **Motivation slides:** "time sequence" written on the Golden Globe ratings plot; on the USGS map, "**weather prediction:
  good in short term, terrible in long term ↔ long sequence of events**"; "stock market AVG / time" on the FTSE plot,
  plus a hand-drawn covid-2020 extension.
- **Chain-rule slide:** "t = time/sequence iterator", "$x_T$ given previous $x_1…x_{T-1}$", "Bayes in order",
  "full back, all the way to t = 1".
- **Autoregressive model:** "model $p(x_t)$ as regression 'f' of previous steps; current / past".
- **Plan A, Markov:** "**limited memory, e.g. last 4 steps (not further)**", with $\tau=4$ written out:
  $f(x_{t-4},…,x_{t-1})$.
- **Plan B, the latent variable:** "**$h_t$ = hidden state at step t = context at time t**"; "context dependence" (h→x)
  vs "data/sequence dependence" (x→x).
- **Language Models divider:** "text/language → sequence; predict the continuation; **translation text-seq-English →
  text-seq-Spanish: HW6**".
- **RNN slide:**
  - "sequence $o_t=g(h_t)$, $h_t=f(h_{t-1},x_{t-1})$ seq-input";
  - "**3 weight matrices $W_{hx},W_{hh},W_{ho}$ (indep. of step t)**";
  - "**not deep, 1 layer**";
  - the recurrent arrows drawn in red.
- **Output-decoding slide:** "Decoder" written by the output vectors and "Encoder" by the one-hot rows. This use of the
  words is not the seq2seq one (see §8 Q6).
- **Clipping:** "very large ⇒ compounding, diff too low or too high"; "**upper bound, ‖g‖ ≤ θ, don't want grad too big**".
- **Perplexity:** "**= exp(Entropy)**"; "**comparable with var. lengths**"; "log(∏…)".
- **Gradient recursion:** "infeasible computation"; "blocks before step i"; "truncate the rest of history".
- **Truncated BPTT:**
  - "**limit the ∏ of gradients (to be still useful)**";
  - don't truncate → "not possible in practice";
  - fixed intervals → "**works!**";
  - variable length → "not much benefit".
- **GRU divider (lecture 8/1):** "HW6: RNN implement for machine translation; **GRU & LSTM using 'gates' to manage
  sequence**; encoder-decoder sequence-2-sequence; GRU **simpler, faster** than LSTM".
- **GRU slides:**
  - "parts of seq not immediately relevant"; "pay ~~attention~~ → respect / manage parts of sequence";
  - **reset gate: "how much of prev $H_{t-1}$ to remember"**; **update gate: "how much duplicate $H_{t-1}$"**;
  - "$W_{hr}\ne W_{hz}$"; "computation matrix $H_{t-1}\times W$, W to be learned"; "σ = sigmoid/logistic";
  - the candidate state's tanh: "diff activation ≠ σ";
  - the candidate: "*we actually compute a probab. distribution over all candidates*" (**inaccurate**, §8 Q5);
  - $H_t$: "**retain prev $H_{t-1}$**" + "**new calculation**".
- **LSTM slides:**
  - "**how to manage sequence (steps close 'short term', steps far 'long term')**";
  - "using gates; implement '**memory cell**'";
  - "all calculations similar to GRU gates, each has its own W matrix";
  - circled ×/+ labelled "**forget / update**", "prev mem → current mem";
  - "⊙ = element-wise product, **Hadamard**".
- **Plain d2l slides:** dependent random variables, the Netflix/Koren plots, the stateful-systems rhinos, HMM/Kalman,
  n-gram smoothing ("hack"), text preprocessing, **tokenization (character / word / BPE "Goldilocks zone")**, minibatch
  partitioning (random vs sequential), the embedding matrix ("THE TIME" one-hot figure), the BPTT gradient algebra,
  the linear-RNN toy $(W_{hh}^\top)^{T-t}$, and `s.detach()`.
- **Verdict:** absorb. This is the most heavily annotated of the four PDFs. Keep linked.

**`Lecture_RNN_B_080125.pdf`, "Encoder-decoder, seq2seq" (13 pp, STAT 157 deck 22 + handwriting)**
- "**machine translation: sequence-text English ↔ sequence-text Spanish**".
- Rethinking the RNN as an encoder: "input seq, **1 token = 1 step**"; "var-length seq ⇒ hidden"; decoder "**1 token at a
  time: hidden + past output ⇒ output**".
- The architecture drawn with "**H**" for the state and "RNN-Encoder"/"RNN-Decoder"; `init_state` annotated "prev state".
- "**Need processing of translation seq: truncation, tokenization, padding, vocabulary — HW6: done as given**".
- "Different lengths = different steps".
- The seq2seq figure: "**<bos> begin-of-sentence, <eos> end-of-sentence → stop**", "out1, out2, out3" fed back,
  "**1 step = 1 token**", "1 RNN, 2 RNN-Decoder"; on the encoder/decoder details slide, "RNN ... RNN diff." (two different RNNs).
- Training: "**teacher forcing**", "**shift by one**".
- **Stops before** prediction, beam search and BLEU.
- **Verdict:** absorb (RNN §7–8). Keep linked. The BLEU and decoding material must come from the book.

**`CNN/cnn_resudual_block.jpg`, a handwritten residual-block page (1 p, promoted to Tier 1)**
- The block: X → CONV1 → BNORM1 → RELU1 → CONV2 → BN2 → **⊕ skip** → RELU → POOL.
- The bullets:
  - "Allow grad backprop to '**go around**' (via skip) to before-RESBLOCK";
  - "easier to train";
  - "**H(x) = x + R(x)**, residual";
  - "**if identity H(x)≈x is useful, R(x) can be almost 0**";
  - "solve the 'vanishing grad' problem";
  - "**POOL layer has to be (if there) AFTER the ⊕ addition, that is outside the RESBLOCK**".
- **Verdict:** absorb verbatim into CNN §7 and redraw it as the section's module diagram. Optionally link it in Week 11.

### 3.2 Tier 2 — course-adapted, mostly the instructor's own ChatGPT sessions (absorb the useful parts, don't link)

| File | Len | What | Verdict |
|---|---|---|---|
| `CNN/resBlock_BN_LN_chgpt.pdf` | 52 pp | The instructor's session building "BNLeNet + residual" on CIFAR. This is where HW6 P2(A) originates. It contains **the instructor's own questions**: *why does a resblock have 2 convs and not 3–4? why separate first/second BN if the code is the same? why Flatten? why does BN help?* | Absorb the questions as remarks and common bugs (CNN §6–7). Don't link. |
| `CNN/resBlock_BN_LN_chgpt2.pdf` | 16 pp | "Residual blocks & normalization layers — lecture notes": the residual block, BN train/eval, LN, axes of reduction. Includes a **BN-vs-LN toy matrix** $x=$ [[1..5],[10..50],[7..35]]. | Absorb the toy (verified in §5.1, a lovely unit test). Retire after the note exists. |
| `CNN/batch_normalization_diagram.png` | 1 img | An AI-generated BN flow chart with typos ("Mini-batsch", "Computete", "parar­neters", $\sigma_\beta$). It does not show the reduction axes. | Don't use. Redraw a correct axes figure (§5.5). |
| `RNN/RNN_seq_metrics.pdf` | 15 pp | ChatGPT on "the ppl reported by d2l" (= exp of the mean CE) and on sequence metrics (BLEU, ROUGE, token/sequence accuracy, edit distance). Its "LSTM PPL 30–60 on small data" is generic. | Absorb the ppl explanation. Don't link. |
| `RNN/GRU_in_RNN_chatgpt.pdf` | 4 pp | GRU explained with a 1-D toy. **It uses Cho's convention $h_t=(1-z)h_{t-1}+z\tilde h$, the opposite of d2l/PyTorch** (§4). | Don't link. Flagged in the notation bridge. |
| `RNN/rnn_vs_transformers.pdf` | 1 p | A ChatGPT comparison table (parallelism, O(T²), streaming O(1)/token, KV cache…) | Re-create, after verifying it, as the RNN §10 forward table (short) and the RNN_ADV §9 table (full). |

### 3.3 Tier 3 — keep as links (last column)

**Week 11:**
- colah, "Understanding Convolutions" (19 pp): conv as "probability of where the ball lands" and image filters. The best
  intuitive reader for CNN §1–2.
- colah, "Conv Nets: A Modular Perspective" (19 pp): weight sharing as reused modules.
- `2.5_NN/VanishingGradientProblem.pdf` (TDS, 14 pp): sigmoid′ ≤ ¼; ReLU/residual/BN as fixes. A cross-link for CNN §5/§7.
- The d2l chapters on CNNs, modern CNNs, image augmentation and fine-tuning. These currently sit in the lecture column and
  should move to the last column under the link rule.

**Week 12:**
- colah, "Understanding LSTM Networks" (19 pp): the standard LSTM reader.
- Karpathy, "The Unreasonable Effectiveness of RNNs" (36 pp): character-RNN samples. It answers last term's "nobody
  believed RNNs can do anything" complaint, and it shows a character-level model, as a contrast to our word level.
- `RNN/lecture_10_ruohan.pdf` (Stanford CS231n 2022, 120 pp): vanilla RNN, image captioning, and the **LSTM
  "uninterrupted gradient flow" figure**. The best third-party source for RNN §5–6.
- `RNN/cs3750_rnn_lstm_slides.pdf` (Pitt, 71 pp): a clean BPTT and LSTM-gradient derivation. Link from RNN_ADVANCED.
- `RNN/1308.0850v5.pdf` (Graves 2013, "Generating Sequences with RNNs"): link only from RNN_ADV further reading.
- The d2l chapters "RNN" and "RNN-modern" (move them to the last column).

**Retire once the notes exist** (thin or redundant third-party pages):
- `An Introduction to RNN for Beginners`
- `Tutorial on RNN | LSTM`
- `What is RNN` (Analytics Vidhya)
- the Choubey Medium post
- the Brilliant wiki
- the joshvarty "VisualizingRNNs" page
- `RNNs by Example in Python` (Keras)
- `introduction_to_deep_learning.pdf` (55 pp of slides borrowed from CS231n: RNN types, CNN, attention, a PyTorch intro;
  redundant with CS231n)

`2.5_NN/dropout_hinton.pdf` and the activation table are Week 9 material and not needed here.

### 3.4 Source-only material (non_public, never linked)

**Smola/d2l STAT 157 decks** in `non_public/smola_d2l_book/`:

| Deck | Pages | Relation to Tier 1 / use |
|---|---|---|
| `11-Convolution` | 56 | the unannotated original of `Lecture_CNN` |
| `12-LeNet` | 42 | LeNet → AlexNet → VGG → NiN; for the CNN_ADV lineage |
| `13-Inception` | 41 | GoogLeNet, **BatchNorm ("one normalization per channel")**, **ResNet**, DenseNet; for CNN §6–7 and CNN_ADV |
| `15-Finetune` | 33 | fine-tuning, augmentation, style transfer; for CNN §8 |
| `18-Sequence_Models` | 50 | the unannotated original of `Lecture_RNN_A` |
| `19-RNN` | 44 | the unannotated original of `Lecture_RNN_A` |
| `20-Advanced-RNN` | 39 | deep and bidirectional RNNs, dropout in RNNs, residual RNNs, applications; for RNN_ADV |
| `23-Encoder-decoder` | 19 | the original of `Lecture_RNN_B`; the deck **continues past the annotated 13 pages into beam search** ("candidates") |
| `22-Embedding` | — | belongs to the Week 13–14 fork |

**d2l book** (`book_d2l_smola.pdf`, 1,151 pp), the primary reference:
- **ch. 7:** 7.1 from dense layers to convolutions · 7.2 · 7.3 padding/stride · 7.4 channels · 7.5 pooling · 7.6 LeNet.
- **ch. 8:** 8.1 AlexNet · 8.2 VGG · 8.3 NiN · 8.4 GoogLeNet · **8.5 BatchNorm** · **8.6 ResNet** · 8.7 DenseNet · 8.8 RegNet.
- **ch. 9:** 9.1–9.7, from sequences to BPTT.
- **ch. 10:** 10.1 LSTM · 10.2 GRU · 10.3 deep RNNs · 10.4 bidirectional · 10.5 MT data · 10.6 the encoder–decoder ·
  **10.7 seq2seq** · 10.8 beam search.
- **ch. 14:** **14.1 augmentation** · **14.2 fine-tuning**.

### 3.5 Syllabus (`html/schedulen_mod.html`, rows `week11` 11/19–11/26 and `week12` 11/26–12/3)

| Row | Link | Verdict |
|---|---|---|
| wk11 lecture | videos "AdvNN", "CNN" (2025 recordings) | keep |
| wk11 lecture | `Lecture_AdvNN_A_072325.pdf` · `Lecture_CNN_072525.pdf` | keep (Tier 1); the new `CNN_claude` goes above them |
| wk11 lecture | d2l "basic CNN", "Modern CNN" | **move to the last column** (link rule) |
| wk11 last col. | *(empty)* | add `CNN_ADVANCED (optional)`, the d2l links, colah ×2, augmentation/fine-tuning (d2l 14.1–14.2) |
| wk12 lecture | videos "RNN", "Seq2Seq" | keep |
| wk12 lecture | `Lecture_RNN_A_073025.pdf` · `Lecture_RNN_B_080125.pdf` | keep (Tier 1); the new `RNN_claude` goes above them |
| wk12 lecture | d2l "RNN", "RNN-Modern" | **move to the last column** |
| wk12 last col. | *(empty)* | add `RNN_ADVANCED (optional)`, the d2l links, colah LSTM, Karpathy, CS231n Lecture 10 |

The HW6 page's References block already links the three annotated lectures as "until then" stand-ins. Update it once the
notes exist (§7.3).

---

## 4. Notation standard

The data layer already agrees across the course, the book and the instructor's board. The conflicts come from the Smola
slides, PyTorch's storage layout, and two third-party GRU conventions.

| Role | Symbol (adopt) | Source of truth | Conflicts to flag |
|---|---|---|---|
| minibatch | $n$ rows; **row vectors**; a layer is $XW+b$ | NN_BASICS ("stack a minibatch of $n$ examples as the rows"); d2l | Course-wide $i$ = datapoint index: in the CNN note **$i,j$ are pixel positions**, so say so once |
| image tensor | $X$, $c\times n_h\times n_w$; batch $(n,c,n_h,n_w)$ | d2l 7.3; PyTorch NCHW | Don't write $H$ for height (clash with the hidden state) |
| conv kernel, output | $K$ ($k_h\times k_w$), $Y=X\star K+b$ | d2l 7.2 code (`corr2d(X,K)`); the board's "K = V = W" | The book's derivation uses $V$; the board writes $W_{ab}$ and $H_{ij}$. HW7 uses $K$ for *keys*: a different note, remark only |
| general conv | $Y_{i,j,d}=b_d+\sum_{a}\sum_{b}\sum_c K_{a,b,c,d}X_{i+a,j+b,c}$ | the board's handwritten formula = d2l (7.1.7) | **PyTorch stores the weight as $(c_o,c_i,k_h,k_w)$**, the reverse of $(a,b,c,d)$. State it with the weight copy |
| padding, stride | $p_h,p_w$ (total), $s_h,s_w$; out $=\lfloor(n_h-k_h+p_h+s_h)/s_h\rfloor$ | d2l 7.3 | PyTorch's `padding=1` means 1 *per side* ($p_h=2$). PyTorch pooling defaults to stride = window, the d2l from-scratch `pool2d` to stride 1 (**a common bug**) |
| batch norm | $\hat\mu_B,\hat\sigma_B^2$ (biased), $\gamma,\beta,\epsilon$; per channel over $n\cdot n_h\cdot n_w$ values | d2l 8.5 | $\beta$ also names momentum/Adam's coefficients (NN_BASICS). **PyTorch `momentum=0.1` weights the *new* batch** (the optimizer convention is the reverse), and **`running_var` uses the unbiased variance** |
| sequence | $t=1..T$; source $T$, target $T'$ | d2l 9–10 | — |
| RNN cell | $H_t=\phi(X_tW_{xh}+H_{t-1}W_{hh}+b_h)$; $O_t=H_tW_{hq}+b_q$; $X_t\in\mathbb R^{n\times d}$, $H_t\in\mathbb R^{n\times h}$ | d2l 9.4; the **board** (AdvNN_A p6) | **Smola slides:** column vectors $h_t=\phi(W_{hh}h_{t-1}+W_{hx}x_{t-1}+b_h)$, so $W_{hx}=W_{xh}^\top$, *and* the input index is $t-1$ (latent-variable view). The output matrix is $W_{ho}$ (slides) vs $W_{hq}$ (book). **PyTorch:** `weight_ih_l0` $=W_{xh}^\top$ ($h\times d$), two biases `b_ih + b_hh` |
| batch layout | **time-major** $(T,n,\cdot)$ | d2l; `nn.RNN` default | The pilots were `batch_first`. The starter and notes must state one layout per tensor |
| vocabulary | $\mathcal V$, $\lvert\mathcal V\rvert=5{,}274$; specials `<unk> <pad> <bos> <eos>` | d2l `Vocab`; pilot | Plain $V$ is avoided (the attention values in HW7) |
| embedding | $E\in\mathbb R^{\lvert\mathcal V\rvert\times d}$; lookup = one-hot row × $E$ | Smola "THE TIME" slide; `nn.Embedding` | The Smola slide calls it $W$ and the output map $W'$ |
| GRU | $R_t,Z_t$; $\tilde H_t=\tanh(X_tW_{xh}+(R_t\odot H_{t-1})W_{hh}+b_h)$; $H_t=Z_t\odot H_{t-1}+(1-Z_t)\odot\tilde H_t$ | d2l 10.2 | **Cho 2014 and `GRU_in_RNN_chatgpt` swap $z\leftrightarrow1-z$.** **PyTorch puts the reset gate after the product**, $R_t\odot(H_{t-1}W_{hh}+b_{hn})$: on the same weights, nn.GRU gives (0.0982, 0.3582) and the d2l form gives (0.1455, 0.3195). Only matters for from-scratch GRU checks (optional) |
| LSTM | $I_t,F_t,O_t$, $\tilde C_t$, $C_t=F_t\odot C_{t-1}+I_t\odot\tilde C_t$, $H_t=O_t\odot\tanh C_t$ | d2l 10.1 = PyTorch | The book itself reuses $O_t$ for the RNN outputs *and* the output gate. The note says "logits $O_t$" outside §6. PyTorch chunks are ordered (i, f, g, o) |
| perplexity | $\exp\big(-\tfrac1T\sum_t\log p(x_t\mid x_{<t})\big)$, in nats | d2l 9.3; board "= exp(Entropy)" | — |
| BLEU | corpus BLEU-4, $\times100$ | pilots / starter | `d2l.bleu` uses weights $p_n^{1/2^n}$ and a per-sentence BP |

**Bridge box** (one in each basic note):
- **CNN note:** board $W_{ab}\equiv$ book $V_{a,b}\equiv$ note $K_{a,b}$ · board $H_{ij}\equiv$ note $Y_{ij}$ ·
  board $u\equiv b$.
- **RNN note:** slides $h_t=\phi(W_{hh}h_{t-1}+W_{hx}x_{t-1})$ ≡ note $H_t=\phi(X_tW_{xh}+H_{t-1}W_{hh})$. The
  matrices are transposed, and the slides index the input one step earlier: same model, different bookkeeping.

---

## 5. The four notes

### 5.1 `CNN/CNN_claude_MMDD` — "Convolutional Networks: From Sliding Windows to ResNets"

**Basic · carries HW6 P1 (A–D), P2 (A–C), P6 · ≈18–20 pp · 10 sections.**
Prerequisites: HW5 / NN_BASICS (MLP, softmax-CE, the training loop, §"Initialization and Vanishing Gradients").

1. **Why images need a new layer.**
   - *Content:*
     - Overview figure first: LeNet with shapes.
     - The parameter blow-up: Fashion-MNIST's MLP has 203,530 weights (NN_BASICS), LeNet 61,706.
     - Rethink a dense layer as $h_{ij}=\sum v_{ijab}x_{i+a,j+b}$, then the **"Two Issues"** (translation invariance: $V$
       must not depend on $[i,j]$; locality: $|a|,|b|\le\Delta$).
     - The board's "frame × kernel window" and the stick figure in two frames.
     - A roadmap box with the instructor's timeline (1995 → 2022 = Weeks 11–14).
   - *Sources:* CNN p2–9; AdvNN_A p1–2; d2l 7.1. *Carries:* P1(B)'s table and the framing of P6.
2. **Cross-correlation, padding, stride.**
   - *Content:*
     - $Y=X\star K+b$.
     - **"cross-correlation, not convolution"** (the board's correction) and why the flip is irrelevant for a learned kernel.
     - Hand-made kernels (edge $[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]]$, blur) vs learned ones (Fergus filters).
     - The output-size formula. Why pad (the instructor's two reasons) and why stride (224², 5×5 kernels: 44 layers without it).
   - *Sources:* CNN p10–25; d2l 7.2–7.3. *Carries:* P1(A).
3. **Channels, and convolution as one matrix product.**
   - *Content:*
     - Multi-in: $Y=\sum_c X_c\star K_c$. Multi-out: one pattern detector per output channel.
     - The board's 4-index formula and PyTorch's $(c_o,c_i,k_h,k_w)$.
     - 1×1 conv = a dense layer over the channels at each pixel.
     - Parameter and FLOP counts.
     - **Unfold (im2col):** every patch becomes a row; then one matrix product, figure and worked example.
       "*One* way to implement convolution" (plan §8.7). Memory cost ×$k_hk_w$.
   - *Sources:* CNN p27–36; d2l 7.4 (the book does only 1×1 as a product, so unfold is new). *Carries:* P1(A).
4. **Pooling.**
   - *Content:*
     - Max and average; "EASY layer"; "max better for ML, avg ≈ blurry"; per channel, no parameters.
     - The 1-pixel-shift example: conv output moves, the max-pool output barely does.
     - **What pooling does *not* buy**: large shifts, rotation, scale (sets up P6).
   - *Sources:* CNN p37–43; d2l 7.5. *Carries:* P1(A,C), P6.
5. **LeNet, then and now.**
   - *Content:*
     - A layer table with shapes and per-layer parameter counts. The total, 61,706, is a unit test.
     - Own layers vs `nn` layers: same output after a weight copy.
     - 1998's sigmoid + average pooling → ReLU + max pooling, and why ReLU trains faster (cross-reference NN_BASICS's
       product-of-factors argument).
     - Algorithm box: CNN forward pass.
   - *Sources:* CNN p44–51; d2l 7.6, 8.1. *Carries:* P1(B,C).
6. **Batch normalization.**
   - *Content:*
     - The problem: layer inputs change scale during training, so the learning rate must stay small.
     - Training mode: $\hat\mu,\hat\sigma^2$ **per channel over the batch *and* all positions** (axes figure), then $\gamma,\beta$.
     - Evaluation mode: running averages, and why it must differ (a single test image has no batch).
     - The PyTorch conventions box (momentum 0.1, unbiased running variance).
     - Placement: after the conv, before the ReLU. BN-LeNet at a higher learning rate.
     - The instructor's question "why can't two BN layers share one module?" (their own γ, β and running statistics).
     - **Preview of LayerNorm = the same formula over the other axis**, with the toy matrix: the forward link to HW7 P4(A).
   - *Sources:* d2l 8.5; Smola 13; `resBlock_chgpt*`. *Carries:* P1(D).
7. **Going deeper: residual blocks.**
   - *Content:*
     - The depth problem: the gradient reaching a layer is a product of per-layer factors (NN_BASICS).
     - $H(x)=x+R(x)$; **the instructor's handwritten block, redrawn**, with its five bullets ("go around", "R(x) ≈ 0 if the
       identity is useful", **"POOL after ⊕"**).
     - The 1×1 projection when the stride or channels change: a shape walk-through.
     - The small-ResNet layout table.
     - "Why 2 convs, not 3–4?" (one remark).
     - Forward link: every Transformer block (HW7 P4) is a residual block.
   - *Sources:* `cnn_resudual_block.jpg`; d2l 8.6; Smola 13; `resBlock_chgpt`. *Carries:* P2(A); pointer to optional P7.
8. **Training CNNs on little data: augmentation and transfer.**
   - *Content:*
     - Random crop + flip on the training data only; reading the train/test gap.
     - **Equivariance vs invariance** box: convolution is shift-*equivariant*, pooling gives approximate shift-*invariance*,
       augmentation teaches the rest (P6).
     - Scratch vs linear probe vs full fine-tuning (figure).
     - Why pretrained features win when labels are scarce.
     - Pretrain → fine-tune as the LLM workflow in miniature.
   - *Sources:* d2l 14.1–14.2; Smola 15. *Carries:* P2(B,C), P6.
9. **HW6 Map (P1, P2, P6) + common bugs.**
   - Flipping the kernel (`F.conv2d` does not flip).
   - The unfold layout ($c\,k_hk_w\times L$, channel-major).
   - Pooling-stride defaults.
   - BN statistics over $n$ only (forgetting positions); biased vs unbiased variance; forgetting `model.eval()`;
     a linear probe whose BN layers stay in train mode and drift.
   - Reusing one BN module twice; a skip-shape mismatch without the 1×1.
   - Augmenting the test set; feeding unnormalized CIFAR to an ImageNet-pretrained ResNet.
10. **Forward pointers.**
    - → CNN_ADVANCED.
    - → HW7: residual + LayerNorm in every Transformer block; ViT patches = unfold.

**Worked numbers.** All verified in torch, 2026-10-17. Each line is a ready unit test.

| Operation | Input | Result |
|---|---|---|
| `corr2d` | arange(9) 3×3 ⋆ [[0,1],[2,3]] | **[[19,25],[37,43]]** |
| padding 1 per side | same | **[[0,3,8,4],[9,19,25,10],[21,37,43,16],[6,7,8,0]]** |
| padding 1, stride (3,2) | same | **[[0,8],[6,8]]** (the shape formula gives ⌊6/3⌋ = 2, ⌊5/2⌋ = 2) |
| 2 input channels | arange(9) and arange(1,10); K₀ = [[0,1],[2,3]], K₁ = [[1,2],[3,4]] | **[[56,72],[104,120]]** |
| unfold | 3×3 input, 2×2 kernel | 4×4 patch matrix with rows (0,1,3,4), (1,2,4,5), (3,4,6,7), (4,5,7,8); × the kernel → **(19,25,37,43)** |
| pooling 2×2, stride 1 | arange(9) | max **[[4,5],[7,8]]**; average **[[2,3],[5,6]]**; the board's [[1,2],[3,6]]: avg 3, max 6 |
| edge detection | 6×8 image, columns 2–5 black; K = [1,−1] | each row → **(0,1,0,0,0,−1,0)**; shift the image 1 pixel and the ±1 move |
| LeNet (28×28, padding 2) | — | shapes 6×28×28 → 6×14×14 → 16×10×10 → 16×5×5 → 400 → 120 → 84 → 10; parameters **156 + 2,416 + 48,120 + 10,164 + 850 = 61,706** |
| BN vs LN | x = [[1..5],[10..50],[7..35]] | **BN:** every column becomes (−1.336, 1.069, 0.267). **LN:** every row becomes (−1.414, −0.707, 0, 0.707, 1.414). After one `nn.BatchNorm1d` training step: `running_mean` = (0.6, 1.2, …, 3.0) and **`running_var[0]` = 3.0** (= 0.9 + 0.1·21, unbiased; the biased variance would give 2.3) |

### 5.2 `CNN/CNN_ADVANCED_claude_MMDD` — "Convolutional Networks: Advanced Topics"

**Optional · covers HW6 optional P7, with depth for P6 · ≈10–12 pp.**

1. Backprop through conv and pooling.
   - The input gradient = a full correlation with the flipped kernel; the weight gradient = a correlation of the input
     with the output gradient; max-pool routes the gradient to the argmax.
   - A 1-D worked example; the unfold view, where backward = transposed products (cf. NN_ADVANCED §1).
2. Receptive fields: two 3×3 layers see as much as one 5×5 with fewer weights ($18c^2$ vs $25c^2$). Why VGG.
3. The modern-CNN lineage in one table: AlexNet, VGG blocks, NiN (1×1, global average pooling), GoogLeNet, ResNet,
   DenseNet, RegNet/ConvNeXt, and what each introduced (d2l ch. 8; Smola 12–13).
4. Normalization layers compared: BN, LN, GroupNorm, InstanceNorm on one axes figure.
   - BN's dependence on batch size.
   - Why Transformers use LN (→ HW7 P4(A)).
   - "Why BN works", told honestly (covariate shift vs a smoother loss landscape).
5. Plain vs residual at depth.
   - The degradation problem, the identity-mapping argument, the pre-activation ResNet.
   - What P7 shows: a deeper plain net trains *worse*.
6. Equivariance and invariance, stated formally: what breaks them (borders, stride), and how rotations need augmentation
   or special architectures (P6, in depth).
7. Transfer in detail.
   - What the layers learn (the Fergus filters).
   - Discriminative learning rates.
   - BN during fine-tuning.
   - Input resolution: 32² CIFAR vs 224² ImageNet.
8. From convolution to the Vision Transformer: patches as tokens (unfold again) → HW7.
9. Further reading: colah ×2; He et al. 2015/2016; Ioffe–Szegedy 2015; d2l ch. 8.

### 5.3 `RNN/RNN_claude_MMDD` — "Recurrent Networks: Language Models, Gates, and Translation"

**Basic · carries HW6 P3 (A–C), P4 (A–D), P5 · ≈20–22 pp · 10 sections (+ the HW map).**
Prerequisites: HW5 / NN_BASICS, and the CNN note (weight sharing; the product-of-factors gradient).
The opening blurb says that **gradient clipping is taught here from zero**: HW6 P3's prerequisite line credits HW5 with it,
but HW5 never mentions it (§8 Q3).

1. **Why sequences need memory.**
   - *Content:*
     - The board's own framing: "**why RNN is needed / why other ideas don't work**".
     - Data is not IID (the ratings, stock and weather examples: "good short term, terrible long term").
     - The chain rule $p(x_1..x_T)=\prod_tp(x_t\mid x_{<t})$.
     - **Plan A, Markov:** limited memory, $\tau=4$, n-grams and their smoothing "hack".
     - **Plan B, a hidden state:** "$h_t$ = context at time t".
     - Big-picture figure: an RNN language model unrolled over a TinyStories sentence.
   - *Sources:* RNN_A p1–35; d2l 9.1. *Carries:* P3 framing.
2. **From text to numbers: tokens → IDs → embeddings → next-token targets.**
   - *Content:*
     - The TinyStories word tokenizer (lowercase; words and punctuation; `<eos>` after each story).
     - `min_freq` = 10 gives $|\mathcal V|$ = 5,274, 99.6% coverage, `<unk>` = 0.6% of validation tokens.
     - The lookup = one-hot × $E$ (the Smola "THE TIME" figure, redrawn with words).
     - Targets = inputs shifted by one.
     - Windows: random windows (reset the state) vs sequential partitioning (carry it, `detach`).
     - **Box: "Whole words are fine here — real LLMs use subwords."**
       - TinyStories was *built* with a tiny vocabulary (coverage curve, §5.5).
       - On real text a word vocabulary explodes or floods with `<unk>`; characters make sequences long and force the
         network to learn spelling.
       - The slide's own ladder: character / word / **BPE as the "Goldilocks zone"**.
       - GPT-style models use BPE-family subword tokenizers → HW7 P1(A).
   - *Sources:* RNN_A p39–45, 56–57; d2l 9.2. *Carries:* the P3 opening walkthrough (decision 6 of plan §8) and the
     P3(B) side question.
3. **Language models and perplexity.**
   - *Content:*
     - Next-token cross-entropy.
     - Perplexity = exp(mean CE): "= exp(entropy)", "comparable across lengths", the effective number of choices.
     - **The perplexity ladder on the P3 split:** uniform 5,274 → unigram 303.5 → interpolated bigram ≈ 56 → RNN 23.1 →
       GRU 17.8 → LSTM 16.8 (→ GPT 13.5 in HW7).
     - Loss ↔ perplexity pairs: 3.14 ↔ 23.1, 5.715 ↔ 303.5.
   - *Sources:* RNN_A p36–38, 61; d2l 9.3; `RNN_seq_metrics`. *Carries:* P3(A) (frequency baseline), P3(B).
4. **The recurrent cell.**
   - *Content:*
     - The equations and a shape table (time-major).
     - "**3 weight matrices, independent of t**": weight sharing over time, as CNNs share over space. "Not deep: 1 layer".
     - The **hand-computed step** (unit test, below).
     - Loop over the sequence.
     - The mapping to `nn.RNN` (transposed weights, two biases).
     - Generation: greedy vs **temperature sampling** $\mathrm{softmax}(o/\tau)$ (not in the book), with a worked
       3-word example.
     - Algorithm box: forward pass + sampling.
   - *Sources:* AdvNN_A p6; RNN_A p48–58; d2l 9.4–9.6. *Carries:* P3(A,B).
5. **Training through time: BPTT, vanishing and exploding gradients, clipping.**
   - *Content:*
     - The computational graph.
     - $\partial H_T/\partial H_t$ = a product of $T-t$ per-step factors (linear toy: $(W_{hh}^\top)^{T-t}$); numbers below.
     - Clipping $g\leftarrow\min(1,\theta/\|g\|)\,g$ ("upper bound, don't want grad too big").
     - **Clipping fixes exploding, not vanishing**, so the plain RNN plateaus (the pilot: ~100 s).
     - Truncated BPTT, with the instructor's verdicts ("limit the ∏ to keep it useful"; fixed intervals "works!").
     - How to read the P3(C) plot.
   - *Sources:* RNN_A p59–75; d2l 9.7, 9.5. *Carries:* P3(A) clipping, P3(C), P5.
6. **Gates: the GRU and the LSTM.**
   - *Content:*
     - "Not all observations are equally relevant" (the cats and the mouse).
     - The GRU with the board's annotations: reset = "how much of $H_{t-1}$ to remember", update = "how much to copy
       $H_{t-1}$"; the candidate = a *proposed* new state (tanh), not a distribution.
     - The LSTM: memory cell; forget/input/output; ⊙ = Hadamard.
     - **The key mechanism:** along the cell path the per-step factor is $F_t$, and the update is *additive*.
       $0.95^{50}=0.077$, $0.99^{50}=0.61$ vs the RNN's $0.9^{50}=0.005$.
     - The conventions box (§4: PyTorch GRU reset placement; Cho's swapped $z$).
     - Parameter counts: 3× (GRU) and 4× (LSTM) an RNN of the same width, to keep the P3(B) comparison fair.
   - *Sources:* RNN_A p76–89; d2l 10.1–10.2; colah; CS231n L10. *Carries:* P3(B,C), P5; pointer to optional P8.
7. **The encoder–decoder.**
   - *Content:*
     - "Sequence-text Spanish → sequence-text English"; the lengths differ.
     - The encoder (embedding + GRU): "var-length sequence ⇒ hidden".
     - The **context vector**, fed to the decoder at every step and as its initial state.
     - **The decoder = P3's language model, conditioned on a source.**
     - Two *different* RNNs ("RNN diff.").
     - The d2l `Encoder`/`Decoder`/`EncoderDecoder` interface (`init_state`).
     - Tatoeba ≤ 12 tokens with `<bos> <eos> <pad>`; "preprocessing done as given" (the starter).
   - *Sources:* RNN_B p1–12; d2l 10.5–10.7. *Carries:* P4(A).
8. **Training: teacher forcing and padding masks.**
   - *Content:*
     - Decoder input = `<bos>` + target shifted by one ("1 step = 1 token").
     - Padding and the **one-line masked loss** (`ignore_index` = pad), on a worked 2×4 batch.
     - **The consistency check:** decoding the whole target at once and one word at a time must give the same scores,
       because the decoder at step t only sees steps < t.
     - The pilot bug this check caught (context taken from the decoder's own state; after the fix the gap is 2.7e-7).
   - *Sources:* RNN_B p13; d2l 10.7.3–10.7.4; plan §8.1. *Carries:* P4(B).
9. **Decoding and evaluation.**
   - *Content:*
     - The greedy loop: stop at `<eos>`, a length cap, and a "finished" mask for batches. Beam search as a pointer.
     - **BLEU:** clipped n-gram precisions, the brevity penalty, a worked toy; corpus vs sentence level; `d2l.bleu` differs.
     - **BLEU by source length** (pilot numbers below). The fixed-size context is *one* explanation for the drop, and HW7
       tests it.
     - Good and bad examples; the save cell (`results_hw6.json` + checkpoint).
   - *Sources:* d2l 10.7.5–10.7.6, 10.8. *Carries:* P4(C,D).
10. **HW6 Map (P3, P4, P5) + common bugs, then forward pointers.**
    - *Common bugs:*
      - Targets not shifted.
      - Batch-first vs time-major mixed up; weight copy without the transpose or with one bias.
      - The hidden state not reset or detached between windows.
      - Clipping placed before `backward` or after `step`.
      - Perplexity computed from a summed loss, or with pad counted.
      - Temperature applied after the softmax.
      - The masked loss averaging over pad.
      - The decoder reading its context from its own state.
      - Decoding that never stops at `<eos>`; BLEU scored on IDs with `<eos>`/`<pad>` left in.
      - A from-scratch GRU checked against nn.GRU with the d2l reset placement.
    - *Forward:*
      - Bottleneck → attention (HW7 P3); recurrence → self-attention (HW7 P2–P4).
      - The same LM on the same split → GPT (HW7 P5).
      - Words → BPE (HW7 P1).
      - A short verified RNN-vs-Transformer table.
      - → RNN_ADVANCED.

**Worked numbers** (verified, unit tests):

| Item | Input | Result |
|---|---|---|
| RNN cell step | $X_t$ = (1, 0), $H_{t-1}$ = (0.5, −0.5), $W_{xh}$ = [[0.1,0.2],[0.3,0.4]], $W_{hh}$ = 0.5·I, $b$ = 0 | net = (0.35, −0.05), $H_t$ = **(0.3364, −0.0500)** |
| clipping | g = (3, 4), θ = 1 | **(0.6, 0.8)**; with θ = 10 g is unchanged |
| gradient through time, factor 0.9 | 20 and 50 steps | **0.1216** and **0.00515** |
| gradient through time, factor 1.1 | 20 and 50 steps | **6.73** and **117.4** |
| LSTM cell path | $F$ = 0.95 and 0.99, 50 steps | **0.077** and **0.605** |
| perplexity ↔ loss | uniform 5,274 · unigram 303.5 · RNN 23.1 · LSTM 16.8 | loss **8.571 / 5.715 / 3.140 / 2.821** nats |
| BLEU toy | "the cat sat on mat" vs "the cat sat on the mat" | $p_{1..4}$ = 1, 0.75, 0.667, 0.5; BP = $e^{-0.2}$ = 0.819; **BLEU-4 = 0.579** (`d2l.bleu` gives 0.694) |
| GRU convention check | the same weights (seed 0) | nn.GRU **(0.0982, 0.3582)**; the d2l reset form (0.1455, 0.3195) |

### 5.4 `RNN/RNN_ADVANCED_claude_MMDD` — "Recurrent Networks: Advanced Topics"

**Optional · covers HW6 optional P8, P9, P10 · ≈12–14 pp.**

1. **The LSTM cell from scratch (P8).** The equations ↔ `nn.LSTM`'s layout (four chunks i, f, g, o, of $W_{ih}$
   ($4h\times d$)); a hand-computed step; forget-gate bias initialization.
2. **GRU conventions in full** (book vs PyTorch vs Cho), with the numbers above. What changes for exact checks.
3. **Your RNN inside the translator (P9)** and **the LSTM translator (P10)**: the state tuple $(H,C)$, and what to expect.
4. **The gradient analysis, properly.**
   - The Jacobian product; the spectral norm of $W_{hh}$ and $\tanh'\le1$.
   - The LSTM "gradient highway" (CS231n L10, cs3750), and why gates don't fully solve long range.
   - Truncated BPTT variants (Tallec–Ollivier; the board: "not much benefit").
   - Sequential vs random partitioning, and `detach`.
5. **Deep and bidirectional RNNs** (d2l 10.3–10.4; Smola 20): a bidirectional *encoder* is legal, a bidirectional LM is
   not; dropout between layers.
6. **Beam search vs greedy vs sampling** (d2l 10.8; Smola 23): a worked beam of 2; length normalization; why chat LLMs sample.
7. **Classical relatives of "Plan B".** The HMM and the Kalman filter (RNN_A p30–31; cross-reference EM_ADVANCED §HMM):
   the RNN as a deterministic latent-state model.
8. **Character vs word vs subword language models** (Karpathy's char-RNN, Graves 2013): a preview of HW7 P1.
9. **RNNs today:** streaming with O(1) memory per token; a state-space-model pointer; the full verified
   RNN-vs-Transformer table.
10. **Further reading:** colah, Karpathy, CS231n L10, cs3750, Graves 2013, d2l ch. 9–10.

### 5.5 Figures to build (TikZ unless noted; scripts in `images_claude/build_*_figs.py`)

**CNN note:**
- (1) the LeNet pipeline with shapes (§1 overview);
- (2) the sliding window with numbers, 19 highlighted;
- (3) padding and stride grids;
- (4) a multi-channel stack (R, G, B → d detectors);
- (5) unfold: the patch matrix × the kernel vector;
- (6) max vs average pooling with numbers;
- (7) shift sensitivity: the edge map and the 1-pixel shift, before and after max pooling (matplotlib);
- (8) **the BN axes figure**: an $n\times c\times n_h\times n_w$ block with the reduced axes shaded, and LN alongside;
- (9) **the instructor's residual block**, redrawn (plus a projection variant);
- (10) augmentation samples on CIFAR images (matplotlib, from the data);
- (11) scratch / linear probe / fine-tune as frozen vs trainable blocks;
- (12) parameters vs accuracy, MLP vs LeNet (matplotlib, after the build pilot).

**RNN note:**
- (1) an RNN language model unrolled over a TinyStories sentence (§1 overview);
- (2) tokens → IDs → one-hot × $E$ → vectors;
- (3) **the perplexity ladder** (matplotlib bars; GPT shown greyed as the HW7 preview);
- (4) **the TinyStories coverage curve** (cumulative token coverage vs vocabulary rank; mark 5,274 / 99.6%) (matplotlib);
- (5) the BPTT graph;
- (6) gradient size vs distance, $0.9^k$, $1.1^k$, $F^k$ (matplotlib; the real P3(C) curve once the solution exists);
- (7) clipping as projection onto a ball;
- (8) the GRU and LSTM cells;
- (9) the encoder–decoder unrolled with the context at every step;
- (10) teacher forcing vs greedy decoding, side by side;
- (11) a padded batch with its loss mask;
- (12) BLEU by source length (matplotlib, pilot numbers).

**Where a d2l figure would be better.** d2l's GRU/LSTM cell diagrams (10.1–10.2) and the seq2seq figures (10.7) are the
clearest available, and students will meet them in the book.
- *Recommendation:* redraw them in TikZ, keeping d2l's layout, and credit "after Zhang et al., *Dive into Deep Learning*,
  CC BY-SA 4.0".
- A d2l figure used *as is* needs the credit line, and the share-alike terms then attach to the adapted figure. A
  self-drawn figure carries no such terms.
- Nothing is taken from the STAT 157 slide decks (AWS, "all rights reserved").

---

## 6. Lecture plans

There is one board-first plan per basic note, in the VAE/GAN format. The RNN note gets **two** 100-min tables in one file,
because it spans two lectures.

The calendar:
- HW5 is due Tue 11/17 and HW6 runs 11/17–12/1.
- The slots are **Thu 11/19, Mon 11/23 and Mon 11/30**; Thanksgiving takes Thu 11/26.
- Students can do P1–P2 in the first week and P3–P4 in the second, so RNN-A must unlock *all* of P3(A) and P4(A–C).

**`CNN_claude_lecturePlan` — Thu 11/19:**

| Time | On the board | Worked example / demo |
|---|---|---|
| 0–10 | Roadmap timeline (1995 → 2022 = Weeks 11–14). The LeNet picture stays up all lecture. The MLP's parameter count for an image. (§1) | 203,530 vs 61,706 |
| 10–30 | "Two Issues" → a window with shared weights = cross-correlation (not convolution); padding and stride formulas. (§1–2) | 19/25/37/43 done by hand; the padded 4×4 |
| 30–45 | Channels: R, G, B → d detectors; the board's 4-index formula; 1×1 conv; unfold as one product. (§3) | 56/72/104/120; the patch matrix |
| 45–55 | Pooling: max vs average; the 1-pixel shift; LeNet's shapes. (§4–5) | Demo (3 min): the shift-sensitivity figure |
| 55–70 | Batch norm: the axes, train vs eval, running statistics; LN as "the other axis" (HW7 preview). (§6) | The toy matrix: BN columns and LN rows |
| 70–88 | The residual block (the handwritten page, redrawn on the board); the 1×1 projection; "the gradient goes around". (§7) | Shape walk-through 16→32 channels, stride 2 |
| 88–100 | Augmentation (train only) and transfer (scratch/probe/fine-tune); HW6 P1–P2 map. (§8–9) | — |

**`RNN_claude_lecturePlan`, Lecture A — Mon 11/23 (unlocks P3(A) and P4(A–C)):**

| Time | On the board | Worked example |
|---|---|---|
| 0–12 | Why other ideas don't work: not IID; the chain rule; Plan A (τ = 4) vs Plan B (hidden state = context). (§1) | Weather: good short term, terrible long term |
| 12–27 | Tokens → IDs → embeddings → shifted targets on one TinyStories sentence; why words are fine here, and why LLMs use subwords. (§2) | Coverage 99.6% at 5,274 |
| 27–37 | Perplexity; the ladder. (§3) | 5,274 → 303.5 → 23.1 |
| 37–55 | The cell; 3 matrices shared over time; generation and temperature. (§4) | The hand step (0.3364, −0.0500) |
| 55–68 | BPTT = a product of factors; exploding vs vanishing; clipping. (§5) | 0.9⁵⁰, 1.1⁵⁰; (3,4) → (0.6,0.8) |
| 68–95 | The encoder–decoder as a *conditioned* LM; teacher forcing; padding mask; the consistency check; greedy loop. (§7–8, §9 first half) | A 2×4 padded batch; "shift by one" |
| 95–100 | HW6 P3(A), P4(A–C) map | — |

**`RNN_claude_lecturePlan`, Lecture B — Mon 11/30 (P3(B,C), P4(D), P5):**

| Time | On the board | Worked example |
|---|---|---|
| 0–10 | Recap: why the RNN plateaus; the gradient-vs-distance plot. (§5) | Pilot: RNN flat after ~100 s |
| 10–40 | The GRU (reset/update in the board's words) → the LSTM (memory cell, the additive path through $F_t$). (§6) | 0.95⁵⁰ = 0.077 vs 0.9⁵⁰ = 0.005 |
| 40–50 | Reading the P3(C) plot; what clipping can't fix (P5). (§5–6) | — |
| 50–75 | BLEU from n-grams; BLEU by length and what it suggests (the bottleneck → HW7). (§9) | The toy, 0.579; 37 → 22 by length |
| 75–90 | Beam search vs greedy vs temperature, in one picture (advanced pointer). (§9) | — |
| 90–100 | HW6 Q&A; the HW7 bridge (attention, GPT on the same split). (§10) | — |

---

## 7. HW6 accounting

### 7.1 HW6 — 260 required points (P1–P6) + 4 optional problems

| # | Part | Pts | Covered by | d2l section | What the note must add beyond the book | Key effect to observe |
|---|---|---|---|---|---|---|
| 1 | (A) corr2d → channels → unfold → pooling | 15 | CNN §2–4 | 7.2–7.5 | unfold as one product (the book only does 1×1); `F.unfold` layout; exact checks vs `F.conv2d` | the hand-made and library outputs agree exactly (19/25/37/43 …) |
| | (B) own LeNet vs nn LeNet; table vs the HW5 MLP | 10 | CNN §1, §5 | 7.6 | per-layer parameter count; the comparison with HW5's 203,530-weight MLP | far fewer weights, accuracy as good or better. *No CNN pilot yet* (§8 Q9) |
| | (C) modernize: ReLU + max pooling | 10 | CNN §4–5 | 7.6 ex., 8.1 | why sigmoid stalls (cross-reference NN_BASICS) | faster training, higher accuracy (to be measured) |
| | (D) BatchNorm from scratch, train and eval | 15 | CNN §6 | 8.5 | the axes figure; the PyTorch conventions (momentum, unbiased running variance); eval mode explained; the LN preview | BN-LeNet trains at a learning rate that breaks plain LeNet (to be measured) |
| 2 | (A) residual block + small ResNet vs BN-LeNet | 20 | CNN §7 | 8.6 | the instructor's block; the 1×1 shape walk-through; pool after ⊕; separate BN modules | the deeper residual net trains and beats BN-LeNet on CIFAR-10 (to be measured) |
| | (B) augmentation (train only) | 15 | CNN §8 | 14.1 | reading the train/test gap; equivariance vs invariance | the gap shrinks, test accuracy rises (to be measured) |
| | (C) scratch vs linear probe vs fine-tune on a 5k subset | 15 | CNN §8 | 14.2 | ImageNet normalization; BN in the probe; the LLM-workflow link | pretrained wins by a wide margin with scarce labels (to be measured) |
| 3 | (A) RNN step → sequence → `nn.RNN` → clipping; frequency baseline; own vs nn | 30 | RNN §2–5 | 9.2–9.7 | **word-level TinyStories**; **the tokens → IDs → embeddings walkthrough**; shifted targets; the hand step; the nn.RNN weight mapping; the unigram baseline; speed (Python loop vs fused kernel) | unigram **303.5** → RNN **23.1**; own = nn in perplexity, nn much faster (timing pending) |
| | (B) GRU/LSTM swap; temperatures; words-vs-subwords side question | 15 | RNN §2 box, §4, §6 | 10.1–10.2 | temperature sampling; **"why word-level is fine here but LLMs use subwords"** with the coverage curve; fair parameter counts | perplexity **23.1 → 17.8 → 16.8**; RNN samples drift and repeat whole sentences, LSTM samples are far more coherent (still with contradictions) |
| | (C) provided gradient-vs-distance experiment | 15 | RNN §5–6 | 9.7, 10.1 | **how to read the experiment**; the $F_t$ path | the RNN's gradient decays geometrically with distance, the LSTM's far more slowly |
| 4 | (A) encoder (embedding + GRU) | 10 | RNN §7 | 10.5–10.7 | Spanish data module; time-major shapes; packed sequences (starter) | shape check passes |
| | (B) teacher-forced decoder + masked loss; whole-target = step-by-step check | 15 | RNN §8 | 10.7.3–10.7.4 | the one-line `ignore_index` loss; **the teacher-forced = step-by-step consistency check** and why it must hold | max difference ≈ 1e-7 (pilot 2.7e-7) |
| | (C) greedy decoding | 10 | RNN §9 | 10.7.5 (`predict_step`) | stop at `<eos>`, length cap, batch finished-mask | short everyday sentences come out right |
| | (D) BLEU overall and by length; examples; save cell | 15 | RNN §9 | 10.7.6 | corpus BLEU-4 (not `d2l.bleu`); **BLEU by length**; `results_hw6.json` + checkpoint | BLEU **30.0**; by length **37.1 / 37.8 / 31.4 / 21.8** (≤ 12 tokens); `d2l.Seq2Seq` similar |
| 5 | (THEORY) why the LSTM reaches further back; clipping vs vanishing | 25 | RNN §5–6 | 9.7, 10.1 | a simple conceptual argument: a product of factors vs an additive cell path | — |
| 6 | (THEORY) what convolution is and isn't robust to | 25 | CNN §4, §8 | 7.1, 7.5, 14.1 | equivariance vs invariance; rotation not handled | — |
| 7 | (opt) plain vs residual at 20+ layers | — | CNN_ADV §5 | 8.6 | — | the deeper plain net trains worse |
| 8 | (opt) LSTM cell from scratch | — | RNN_ADV §1 | 10.1 | nn.LSTM layout | — |
| 9 | (opt) own RNN inside the translator | — | RNN_ADV §2–3 | — | GRU conventions | — |
| 10 | (opt) LSTM translator | — | RNN_ADV §3 | — | $(H,C)$ state | — |

**Total required: 260** (P1 50, P2 50, P3 60, P4 50, P5 25, P6 25).
**Coverage:** every required part maps to a section of a basic note, and every optional part to an advanced note.

### 7.2 Forward links that HW7 needs (each flagged inside the note where it first appears)

| HW6 concept (note §) | Used in HW7 |
|---|---|
| Residual connection (CNN §7) | P4 "add & norm", every Transformer block; P5 GPT block |
| Normalization (CNN §6, BN with the LN preview and toy) | **P4(A): LayerNorm "your HW6 batch norm, over the other axis"**; P5(B) pre-norm vs post-norm |
| Next-token LM on TinyStories, the same split and vocabulary (RNN §2–4) | **P5: GPT on the identical split**; the perplexity ladder continues (13.5) |
| Encoder–decoder; context at every step (RNN §7) | P3 Bahdanau (the context becomes an attention average); P4 full Transformer; BLEU-by-length comparison P3(C) |
| Masks: padding mask in the loss (RNN §8) | P2(D) attention masks (padding + **causal**) |
| Teacher forcing = step-by-step check (RNN §8) | GPT training is teacher forcing at all positions at once under a causal mask; the same check |
| Tokens → IDs → embeddings (RNN §2) | P1 BPE + embeddings (SGNS); P5's input layer |
| **"Subwords, not words" side question (RNN §2 box)** | **P1(A) BPE from scratch (required)** + its data-specific side question |
| Temperature sampling (RNN §4) | P5(C) sampling from scratch (temperature, top-k) |
| Pretrain → fine-tune (CNN §8) | the LLM workflow narrative; HF GPT-2 in P5 |
| `results_hw6.json` + a reference checkpoint (RNN §9) | the P3/P4 baselines (plan §8.7: a reference checkpoint so HW7 is never blocked) |

### 7.3 HW-page edits this plan implies (*not made*: this fork may only write this file)

- **HW6 P3 prerequisites:** drop "gradient clipping as an idea" from the HW5 list. HW5 and NN_BASICS never mention
  clipping, and the RNN note teaches it.
- **HW6 P4 "What to see":** "because the whole source sentence must fit into one fixed-size vector (HW7 fixes this)"
  needs softening to "one explanation; HW7 tests it". At ≤ 12 tokens Bahdanau fell with length exactly like the GRU
  (plan §8.1). The ≤ 25 pilot is running.
- **Once the notes exist:**
  - Replace "(Week 11; planned)" / "(Week 12; planned)" with links on P1–P4.
  - Update the References block.
  - Add "CNN_ADVANCED / RNN_ADVANCED (optional)" to the Optional section.

---

## 8. Open questions for the instructor

1. **Calendar.** Three slots (Thu 11/19, Mon 11/23, Mon 11/30) with HW6 due Tue 12/1. Is the §6 order OK, given that
   Lecture B (gates, BLEU, P5) lands the day before the due date? The alternatives:
   - move HW6 to Thu 12/3, which leaves HW7 12 days to 12/15;
   - or spend this term's "extra lecture" here rather than on Weeks 13–14.
2. **One RNN note or two?** The recommendation is one note (≈20–22 pp), because HW6 already says "RNN note" for P3 and
   P4. The alternative splits it into `RNN_claude` (P3, P5) + `SEQ2SEQ_claude` (P4), which needs a one-word edit on HW6 P4.
3. **Gradient clipping** is credited to HW5 in HW6 P3's prerequisites, but HW5 never mentions it. OK to drop it there
   (§7.3) and teach it in RNN §5?
4. **The P4 "What to see" claim** (§7.3).
   - At ≤ 12 tokens, BLEU falls 37 → 22 for *both* the GRU and Bahdanau.
   - At ≤ 25 tokens (GRU only so far, 10 min), BLEU falls 29.9 / 33.3 / 29.7 / 18.9 / **8.8 / 6.0**.
   - Should the note present the bottleneck as a *hypothesis that HW7 tests*?
5. **The board's GRU candidate annotation** ("we compute a probability distribution over all candidates") is inaccurate:
   $\tilde H_t$ is a tanh *proposal*, not a distribution. OK to say it correctly in the note without comment?
6. **The "Encoder"/"Decoder" labels on the output-decoding slide** (RNN_A p59) attach to the embedding/output maps, not to
   seq2seq. Should the note keep "encoder/decoder" strictly for seq2seq, and say "embedding" / "output layer" there?
7. **The Smola slides' $x_{t-1}$ vs the book's $X_t$.** Adopt the book (= your board, AdvNN_A p6)?
8. **BLEU.** Use standard corpus BLEU-4 everywhere and score `d2l.Seq2Seq` with it (decision 8)?
9. **There is no CNN pilot yet.** The P1/P2 key effects in §7.1 (LeNet vs MLP accuracy, BN at a higher learning rate,
   ResNet vs BN-LeNet, the augmentation gap, transfer on 5k images) are the book's qualitative expectations, not measured
   numbers. Also undecided: whether P2(C) upsamples CIFAR to 224² for ResNet-18 (time vs accuracy). Run a CNN pilot
   before the CNN note's "what to expect" paragraphs?
10. **Figures.** Redraw everything (recommended), or import a few d2l figures (the GRU/LSTM cells) under CC BY-SA with
    credit?
11. **Syllabus.**
    - Move the d2l links to the last column (link rule)?
    - Link the handwritten residual-block page in Week 11?
    - Retire the thin third-party RNN pages (§3.3) once the notes exist?
12. **GRU speed.** The board says "GRU simpler, faster than LSTM", but the pilot's GRU looked ~4× *slower* on MPS (plan §6,
    to recheck). Until it is rechecked, the note will say nothing about speed beyond the parameter count.
13. **Demo notebooks.** Do you want `cnn_lecture_demo.ipynb` / `rnn_lecture_demo.ipynb`, as Weeks 9–10 have? Proposed
    content: the shift sensitivity, the BN/LN toy, the hand RNN step, gradient vs distance, and a greedy decode of a
    provided small model.
