""" Builds rnn_lecture_demo.ipynb: the laptop demos for the two RNN lectures (RNN-A Mon 11/23, RNN-B Mon 11/30), one segment per block of RNN_claude_lecturePlan, starting from the d2l book's own code (chapters 9-10). Every code cell's first line says where it comes from: # [Book §x.y] ... the book's code as is (also in the d2l package) # [Changed from book §x.y] ... the book's code with one stated change (usually: HW6's data instead of the book's) # [Added for CS6140] ... something the book doesn't show Leak rule (the notebook is posted to students): added code never implements an HW6 TODO piece the HW's way; it uses torch.nn / the d2l package / the given HW6 helpers (lm_common.generate, seq2seq_common.book_seq2seq). Run: python3 build_rnn_lecture_demo.py (writes rnn_lecture_demo.ipynb, unexecuted) jupyter nbconvert --to notebook --execute --inplace rnn_lecture_demo.ipynb python3 build_rnn_lecture_demo.py --times (writes the measured segment times into the intro table) """ import os import sys import datetime import collections import nbformat as nbf HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(HERE, "../../../2.5_NN/code_common")) import starter_common # noqa: E402 (the data-folder code shared by the HW starters) OUT = os.path.join(HERE, "rnn_lecture_demo.ipynb") CELLS = [] def md(src): CELLS.append(nbf.v4.new_markdown_cell(src.strip("\n"))) def code(src): CELLS.append(nbf.v4.new_code_cell(src.strip("\n"))) SEGMENTS = [ # (number, lecture, title, note section) (1, "A", "Tokens → IDs → embeddings → shifted targets", "§3"), (2, "A", "Language models and perplexity", "§4"), (3, "A", "The recurrent cell, by hand and in nn.RNN", "§2.1"), (4, "A", "Training the book's RNN language model; temperature", "§4"), (5, "A", "A product of factors; gradient clipping", "§5"), (6, "A", "The encoder–decoder on Spanish → English", "§7"), (7, "A", "Teacher forcing vs generation; the consistency check", "§8"), (8, "B", "Gates: the book's GRU and LSTM", "§6"), (9, "B", "How far back do gradients reach?", "§5–6"), (10, "B", "Greedy translations and BLEU", "§9"), ] CHANGES = [ # shown in the intro ("Changed", "1, 4, 8, 9", "**TinyStories, word level** (HW6 Problem 3's data, vocabulary 5,274) instead of the " "book's *Time Machine* characters; `lm_common.TinyStories` is a `d2l.TimeMachine` subclass, so the book's " "code runs on it unchanged"), ("Changed", "4, 8", "fewer steps (1,000 per model, about a minute) and 128 hidden units instead of 32"), ("Changed", "6, 7, 10", "**Spanish → English** (HW6 Problem 4's Tatoeba data, dev-sized: 10,000 pairs) instead " "of the book's French → English; smaller model (embeddings 64, hidden 128) and 12 epochs"), ("Added", "2", "perplexity of a uniform guess, computed with the library loss"), ("Added", "3", "the note's hand-computed cell step, run in the book's `RNNScratch` and in `nn.RNN` " "(transposed weights, two biases)"), ("Added", "4", "samples at two temperatures with HW6's given `lm_common.generate` (the book's `predict` " "is greedy and joins characters)"), ("Added", "5", "the per-step factor $0.9^k$ / $1.1^k$ and `nn.utils.clip_grad_norm_` on the note's $(3,4)$"), ("Added", "7", "teacher-forced guesses next to the model's own generation; whole target = word by word"), ("Added", "9", "gradient of the last prediction w.r.t. inputs $d$ words back, for the three trained models"), ("Added", "10", "BLEU with NLTK (standard BLEU-4) next to the book's `d2l.bleu` on the note's example; " "clipping with two references"), ] def intro(times=None): rows = "\n".join( f"| {n} | {lec} | {title} | {sec} | {times.get(n, '–') if times else '–'} |" for n, lec, title, sec in SEGMENTS) chg = "\n".join(f"| {kind} | {segs} | {what} |" for kind, segs, what in CHANGES) return f"""# Recurrent networks — lecture demos (RNN-A and RNN-B) Laptop demos for the RNN note (`RNN_claude_1017.pdf`), one segment per board block of the lecture plan. The code is the **d2l book's** (chapters 9–10) wherever the book has it; the first line of every code cell says whether it is the book's code as is, the book's code with one change, or something added for CS6140. | Seg. | Lecture | Board topic | Note | Time on an M1 Max | |---|---|---|---|---| {rows} **What differs from the book** | | Segments | What | |---|---|---| {chg} For the revised architecture-first notes, run setup → Segment 3 (the hand cell needs no data) → Segments 1, 2 and 4; segment numbers stay stable for existing references. Run the setup cell first; then each segment runs on its own after the ones it says it needs (segments 4 → 5, 8, 9; segment 6 → 7, 10). Numbers vary a little from run to run. """ # ------------------------------------------------------------------------------------------------ md(intro()) code(r'''# [Book §9.6] imports, plus the device setup the HW notebooks use (d2l's GPU helpers only know CUDA) import sys, time, math, collections import torch from torch import nn from torch.nn import functional as F from d2l import torch as d2l def get_device(): if torch.cuda.is_available(): return torch.device("cuda") if torch.backends.mps.is_available(): return torch.device("mps") return torch.device("cpu") DEVICE = get_device() if DEVICE.type == "mps": # point d2l's GPU helpers at Apple's GPU d2l.num_gpus = lambda: 1 d2l.gpu = lambda i=0: DEVICE d2l.try_gpu = lambda i=0: DEVICE NUM_GPUS = 1 if DEVICE.type != "cpu" else 0 CPU = torch.device("cpu") print("device:", DEVICE) ''') code("# [Added for CS6140] HW6's shared data modules and the course data folder (as in the HW starters)\n" + starter_common.DATA_BLOCK + r''' _places = [".", "../hw6", "../../../2.5_NN/HW6_advNN"] # next to this notebook, your HW6 folder, the course tree COMMON = next((p for p in _places if os.path.exists(f"{p}/lm_common.py")), None) if COMMON is None: raise FileNotFoundError("lm_common.py / seq2seq_common.py (they come with the HW6 starter) not found in: " + ", ".join(os.path.abspath(p) for p in _places)) sys.path.insert(0, COMMON) import lm_common import seq2seq_common course_file("sentence_pairs_large.tsv") # Segment 6's Spanish-English pairs (24 MB, downloaded once) print("shared modules from", os.path.abspath(COMMON), "| data in", os.path.abspath(DATA)) ''') # ------------------------------------------------------------------------------------------------ md(r"""--- # Lecture RNN-A ## Segment 1 — Tokens → IDs → embeddings → shifted targets (note §3) **What to watch:** a story becomes a list of word IDs; the target sequence is the input shifted by one word; a few thousand words cover almost all of TinyStories, and anything else becomes ``.""") code(r'''# [Changed from book §9.2–9.3] HW6's TinyStories (word level) instead of the book's Time Machine (characters) t0 = time.time() data = lm_common.TinyStories(root=f"{DATA}/tinystories", batch_size=128, num_steps=32, min_freq=10, batches_per_epoch=50) print(data.describe()) print(f"(loaded in {time.time() - t0:.0f} s)") ''') code(r'''# [Book §9.2] tokens -> IDs with the book's Vocab; IDs -> tokens back sentence = "once upon a time , there was a little girl named lily ." tokens = sentence.split() ids = data.vocab[tokens] print(tokens) print(ids) print(data.vocab.to_tokens(ids)) print("vocabulary size:", len(data.vocab), "| most frequent:", data.vocab.token_freqs[:8]) ''') code(r'''# [Added for CS6140] whole words are fine for TinyStories, not for real text: unknown words become for text in ["the little dog was happy .", "the archaeologist examined a byzantine manuscript .", "lily sayd helo to her frend ."]: toks = lm_common.tokenize(text) print(f"{text:52s} -> {' '.join(data.vocab.to_tokens(data.vocab[toks]))}") val_unk = (data.val_ids == data.vocab.unk).float().mean().item() print(f"validation tokens that are : {val_unk:.2%} (real LLMs avoid this with subword tokens: Week 13)") ''') code(r'''# [Book §9.3] a minibatch: X and Y are the same windows, Y shifted by one word X, Y = next(iter(data.train_dataloader())) print("X:", tuple(X.shape), " Y:", tuple(Y.shape)) print("input :", " ".join(data.vocab.to_tokens(X[0, :12].tolist()))) print("target:", " ".join(data.vocab.to_tokens(Y[0, :12].tolist()))) ''') code(r'''# [Book §9.5] the book feeds one-hot vectors; one-hot times a matrix = picking a row = an embedding lookup V = len(data.vocab) E = torch.randn(V, 4) # an embedding matrix with 4-dimensional rows onehot = F.one_hot(torch.tensor([ids[1]]), V).float() # the word "upon" print("one-hot x E :", (onehot @ E).squeeze()) print("row of E for ID :", E[ids[1]]) ''') # ------------------------------------------------------------------------------------------------ md(r"""## Segment 2 — Language models and perplexity (note §4) **What to watch:** perplexity = exp(mean cross-entropy) = "the number of words the model is choosing between". A uniform guess gives exactly the vocabulary size.""") code(r'''# [Added for CS6140] a model that knows nothing: equal scores for every word -> perplexity = |V| Xv, Yv = next(iter(data.val_dataloader())) uniform_logits = torch.zeros(*Yv.shape, V) loss = F.cross_entropy(uniform_logits.reshape(-1, V), Yv.reshape(-1)) print(f"cross-entropy {loss.item():.3f} nats -> perplexity {math.exp(loss.item()):,.0f} (vocabulary {V:,})") print("the ladder in HW6 (reference run): uniform 5,274 -> word frequencies only about 303.5 -> RNN about 23.8 " "-> LSTM about 18.6 -> GRU about 17.5") ''') # ------------------------------------------------------------------------------------------------ md(r"""## Segment 3 — The recurrent cell, by hand and in `nn.RNN` (note §2.1) **What to watch:** the note's hand-computed step, $H_t=\tanh(X_tW_{xh}+H_{t-1}W_{hh}+b_h)=(0.3364,-0.0500)$, from the book's from-scratch cell and from PyTorch's `nn.RNN`, which stores the matrices *transposed* and has *two* biases.""") code(r'''# [Changed from book §9.5] the book's RNNScratch, with the note's weights put in instead of random ones cell = d2l.RNNScratch(num_inputs=2, num_hiddens=2) with torch.no_grad(): cell.W_xh.copy_(torch.tensor([[0.1, 0.2], [0.3, 0.4]])) cell.W_hh.copy_(0.5 * torch.eye(2)) cell.b_h.zero_() X_t = torch.tensor([[[1.0, 0.0]]]) # (steps=1, batch=1, inputs=2): time-major, as the book H_prev = torch.tensor([[0.5, -0.5]]) outputs, H_t = cell(X_t, (H_prev,)) # the book's cell takes the state as a 1-tuple print("RNNScratch:", H_t.detach()) ''') code(r'''# [Added for CS6140] the same step in nn.RNN: weight_ih = W_xh transposed, weight_hh = W_hh transposed rnn = nn.RNN(2, 2) with torch.no_grad(): rnn.weight_ih_l0.copy_(cell.W_xh.T) rnn.weight_hh_l0.copy_(cell.W_hh.T) rnn.bias_ih_l0.zero_() rnn.bias_hh_l0.zero_() # b_h = bias_ih + bias_hh out, h = rnn(X_t, H_prev.unsqueeze(0)) print("nn.RNN :", h.detach().squeeze(0)) print("shapes: weight_ih", tuple(rnn.weight_ih_l0.shape), "weight_hh", tuple(rnn.weight_hh_l0.shape), "| the SAME three matrices are used at every time step") ''') # ------------------------------------------------------------------------------------------------ md(r"""## Segment 4 — Training the book's RNN language model; temperature (note §4) **What to watch:** the book's concise RNN, trained for about a minute on TinyStories: perplexity falls from 5,274 to under 100 and the stories start to make local sense. Temperature trades safety for variety.""") code(r'''# [Book §9.6] the book's concise RNN and RNN language model, as is class RNN(d2l.Module): #@save """The RNN model implemented with high-level APIs.""" def __init__(self, num_inputs, num_hiddens): super().__init__() self.save_hyperparameters() self.rnn = nn.RNN(num_inputs, num_hiddens) def forward(self, inputs, H=None): return self.rnn(inputs, H) class RNNLM(d2l.RNNLMScratch): #@save """The RNN-based language model implemented with high-level APIs.""" def init_params(self): self.linear = nn.LazyLinear(self.vocab_size) def output_layer(self, hiddens): return self.linear(hiddens).swapaxes(0, 1) ''') code(r'''# [Changed from book §9.6] TinyStories, 128 hidden units, 20 epochs of 50 batches (1,000 steps) instead of 100 epochs torch.manual_seed(0) rnn_lm = RNNLM(RNN(num_inputs=V, num_hiddens=128), vocab_size=V, lr=1) trainer = d2l.Trainer(max_epochs=20, gradient_clip_val=1, num_gpus=NUM_GPUS) t0 = time.time() trainer.fit(rnn_lm, data) PPL = {"RNN": lm_common.perplexity(rnn_lm, data, DEVICE)} print(f"{time.time() - t0:.0f} s | validation perplexity {PPL['RNN']:.1f}") ''') code(r'''# [Added for CS6140] stories at two temperatures, with HW6's given sampler (softmax(scores / T), then a draw) for T in [0.5, 1.0]: print(f"T = {T}:", lm_common.generate(rnn_lm, data.vocab, "once upon a time", DEVICE, n_words=40, temperature=T), "\n") ''') # ------------------------------------------------------------------------------------------------ md(r"""## Segment 5 — A product of factors; gradient clipping (note §5) **What to watch:** the gradient reaching a word $k$ steps back is a product of $k$ per-step factors, so it shrinks or blows up geometrically. Clipping rescales a too-long gradient; it cannot bring back a vanished one.""") code(r'''# [Added for CS6140] the note's numbers: a per-step factor of 0.9 vs 1.1 for k in [10, 20, 50]: print(f"k = {k:2d}: 0.9^k = {0.9 ** k:8.4f} 1.1^k = {1.1 ** k:8.2f} 0.95^k = {0.95 ** k:.3f}") ''') code(r'''# [Added for CS6140] clipping with PyTorch's clip_grad_norm_ (what the book's gradient_clip_val does): g=(3,4) for theta in [1.0, 10.0]: p = torch.zeros(2, requires_grad=True) p.grad = torch.tensor([3.0, 4.0]) norm = nn.utils.clip_grad_norm_([p], max_norm=theta) print(f"theta = {theta:4.1f}: norm before {norm.item():.1f} -> gradient after {[round(v, 4) for v in p.grad.tolist()]}") ''') # ------------------------------------------------------------------------------------------------ md(r"""## Segment 6 — The encoder–decoder on Spanish → English (note §7) **What to watch:** two RNNs that share nothing. The encoder reads the Spanish sentence and its last hidden state becomes the *context* `c`; the decoder is an English language model that reads `c` at every step. The cell after training prints the parameters by component, so you can see which tensor belongs to which half of Figure 8 in the note. **Three things this is *not*, worth saying out loud because the picture looks like Week 10's.** The encoder does not output a distribution --- `c` is one deterministic vector, with no mean, no spread and nothing sampled. The decoder does not reconstruct its input --- it produces a *different* sequence, in a different language, of a different length. And nothing shapes the space `c` lives in: there is no KL term, no prior, and drawing a random `c` and decoding it is not a meaningful thing to do. This is a **conditional** model, not a generative model of sentences.""") code(r'''# [Changed from book §10.5] HW6's Spanish-English pairs (dev-sized: 10,000 training pairs) instead of French mt = seq2seq_common.TatoebaEsEn(root=DATA, batch_size=128, num_train=10_000) print(mt.describe()) src, tgt_in, src_len, label = next(iter(mt.train_dataloader())) print("one pair:", " ".join(mt.src_vocab.to_tokens(src[0].tolist())), "|", " ".join(mt.tgt_vocab.to_tokens(label[0].tolist()))) print("decoder input (starts with ):", " ".join(mt.tgt_vocab.to_tokens(tgt_in[0].tolist()))) ''') code(r'''# [Changed from book §10.7] the book's encoder, decoder and Seq2Seq (in seq2seq_common.book_seq2seq), smaller # (embeddings 64, hidden 128, 2 layers) and 12 epochs instead of 30; trained on the CPU (small GRUs are faster there) torch.manual_seed(0) s2s = seq2seq_common.book_seq2seq(mt, embed_size=64, num_hiddens=128, num_layers=2, dropout=0.2, lr=0.005) t0 = time.time() d2l.Trainer(max_epochs=12, gradient_clip_val=1, num_gpus=0).fit(s2s, mt) print(f"{time.time() - t0:.0f} s") enc_out, enc_state = s2s.encoder(src[:4], src_len[:4]) print("encoder outputs (steps, batch, hidden):", tuple(enc_out.shape), "| final state (layers, batch, hidden):", tuple(enc_state.shape), "| context = the last layer's final state") ''') code(r"""# [Added for CS6140] what is learned, and where: the parameters of Figure 8 in the note, by component import collections groups = collections.OrderedDict() for name, prm in s2s.named_parameters(): half = "encoder" if name.startswith("encoder") else "decoder" if "embedding" in name: part = "embedding table" elif "rnn" in name: part = "GRU weights" elif "dense" in name: part = "output layer" else: part = "other" groups.setdefault((half, part), 0) groups[(half, part)] += prm.numel() total = sum(groups.values()) print(f"{'':9s}{'component':18s}{'parameters':>12s}{'share':>8s}") for (half, part), n in groups.items(): print(f"{half:9s}{part:18s}{n:12,d}{n / total:8.0%}") print(f"{'':9s}{'TOTAL':18s}{total:12,d}") print(f"\nvocabularies: Spanish {len(mt.src_vocab):,}, English {len(mt.tgt_vocab):,}" f" -- two different tables, hence two different sizes") print("the encoder has no output layer at all: it never produces a word, only the context c")""") # ------------------------------------------------------------------------------------------------ md(r"""## Segment 7 — Teacher forcing vs generation; the consistency check (note §8) **What to watch:** in training the decoder always sees the *correct* previous words (teacher forcing); when it generates, it sees *its own* previous words, so one early mistake changes everything after it. And scoring the whole target at once gives the same scores as feeding it one word at a time.""") code(r'''# [Added for CS6140] the decoder's next-word guesses with the true previous words vs its own generation s2s.eval() sent = seq2seq_common.tokenize("¿ dónde está la estación de tren ?") ref = seq2seq_common.tokenize("where is the train station ?") s, sl = mt.src_batch([sent]) t_in = torch.tensor([mt.tgt_vocab[[""] + ref]]) with torch.no_grad(): forced = s2s(s, t_in, sl).argmax(-1)[0] # teacher forcing: one pass, true words in bos = torch.full((1, mt.num_steps), mt.tgt_vocab[""]) own, _ = s2s.predict_step([s, bos, sl, bos], CPU, mt.num_steps) # the book's generation loop print("true previous words :", " ".join([""] + ref)) print("guesses (teacher-forced):", " ".join(mt.tgt_vocab.to_tokens(forced.tolist()))) print("own generation :", " ".join(seq2seq_common.ids_to_tokens(own[0].tolist(), mt.tgt_vocab))) ''') code(r'''# [Added for CS6140] the whole target at once = one word at a time, carrying the decoder state (max difference) with torch.no_grad(): state = s2s.decoder.init_state(s2s.encoder(s, sl), sl) whole, _ = s2s.decoder(t_in, state) state = s2s.decoder.init_state(s2s.encoder(s, sl), sl) steps = [] for t in range(t_in.shape[1]): out, state = s2s.decoder(t_in[:, t:t + 1], state) steps.append(out) print("max |whole - step by step| =", (whole - torch.cat(steps, 1)).abs().max().item()) ''') # ------------------------------------------------------------------------------------------------ md(r"""--- # Lecture RNN-B (needs Segment 1's `data` and Segment 4's `rnn_lm`; Segment 10 needs Segment 6) ## Segment 8 — Gates: the book's GRU and LSTM (note §6) **What to watch:** compare the same data, steps and width. The cell changes, but so do parameter count and the book learning rate (RNN 1, gated models 4); this is not a controlled gates-only experiment.""") code(r'''# [Book §10.2, §10.1] the book's concise GRU and LSTM, as is class GRU(d2l.RNN): def __init__(self, num_inputs, num_hiddens): d2l.Module.__init__(self) self.save_hyperparameters() self.rnn = nn.GRU(num_inputs, num_hiddens) class LSTM(d2l.RNN): def __init__(self, num_inputs, num_hiddens): d2l.Module.__init__(self) self.save_hyperparameters() self.rnn = nn.LSTM(num_inputs, num_hiddens) def forward(self, inputs, H_C=None): return self.rnn(inputs, H_C) ''') code(r'''# [Changed from book §10.2] GRU on TinyStories, 128 hidden units, 1,000 steps (the book's lr = 4) torch.manual_seed(0) gru_lm = d2l.RNNLM(GRU(num_inputs=V, num_hiddens=128), vocab_size=V, lr=4) t0 = time.time() d2l.Trainer(max_epochs=20, gradient_clip_val=1, num_gpus=NUM_GPUS).fit(gru_lm, data) PPL["GRU"] = lm_common.perplexity(gru_lm, data, DEVICE) print(f"{time.time() - t0:.0f} s | validation perplexity {PPL['GRU']:.1f}") ''') code(r'''# [Changed from book §10.1] LSTM on TinyStories, 128 hidden units, 1,000 steps (the book's lr = 4) torch.manual_seed(0) lstm_lm = d2l.RNNLM(LSTM(num_inputs=V, num_hiddens=128), vocab_size=V, lr=4) t0 = time.time() d2l.Trainer(max_epochs=20, gradient_clip_val=1, num_gpus=NUM_GPUS).fit(lstm_lm, data) PPL["LSTM"] = lm_common.perplexity(lstm_lm, data, DEVICE) print(f"{time.time() - t0:.0f} s | validation perplexity {PPL['LSTM']:.1f}") ''') code(r'''# [Added for CS6140] the three side by side: perplexity, cell parameters, one story each (T = 0.5) for name, m in [("RNN", rnn_lm), ("GRU", gru_lm), ("LSTM", lstm_lm)]: n_cell = sum(p.numel() for p in m.rnn.parameters()) print(f"{name:5s} perplexity {PPL[name]:6.1f} | cell parameters {n_cell:,}") print(" ", lm_common.generate(m, data.vocab, "once upon a time", DEVICE, n_words=30, temperature=0.5)) print("(the RNN's book learning rate is 1, the gated models' 4; HW6 trains all three the same way with Adam)") ''') md(r"""### The running sentence: does any of them know who `she` is? (note §1, §5 and §6) The note's running sentence is `tom gave lily his red ball , and she kept it in her bag .` --- four pronouns, each pointing back at a *different* earlier word, the furthest ten tokens away. The note describes what the hidden state would have to hold for that to work. This cell asks whether it does. **The test has to be contrastive**, because the raw probability of `she` is dominated by how common `she` is in general, not by who is in the story. So we ask the same question twice with the character swapped, and compare: > after `lily was very happy .` …, how much more likely is `she` than `he`? > after `tom was very happy .` …, the same question. If the state carries the character's gender, that quantity should be clearly **higher** for the `lily` prompt. The difference between the two is the number to read --- it cancels the base rates out.""") code(r"""# [Added for CS6140] a contrastive probe: is the subject's gender still in the state d tokens later? FILLER = "the sun was shining . " def gender_gap(model, m_fill): out = {} for who in ("lily", "tom"): text = f"{who} was very happy . " + FILLER * m_fill + "and then" ids = torch.tensor(data.vocab[data._tokenize(text)]).unsqueeze(0).to(next(model.parameters()).device) model.eval() with torch.no_grad(): lp = torch.log_softmax(model(ids)[0, -1], -1) out[who] = lp[data.vocab["she"]].item() - lp[data.vocab["he"]].item() return out["lily"] - out["tom"], 7 + 5 * m_fill FILLS = [0, 1, 2, 4] print(f"{'model':6s}" + "".join(f"{'d=' + str(7 + 5 * k):>9}" for k in FILLS)) for name, m in [("RNN", rnn_lm), ("GRU", gru_lm), ("LSTM", lstm_lm)]: print(f"{name:6s}" + "".join(f"{gender_gap(m, k)[0]:9.2f}" for k in FILLS)) print("\nvalue = [logP(she)-logP(he) after 'lily ...'] - [the same after 'tom ...']") print("a model that tracks the character scores clearly positive; see the note below for one that does.")""") md(r"""**Separate measured tables, not relabeled results.** The revised note places the plain-RNN capacity probe in §5 and the original GRU capacity probe in §6. Both use `{lily|tom} went to the park . then`, seed 0 and the original CPU/SGD learning-rate-1 recipe. The probe above uses the **happy** prompt, so its scores are not the capacity-table scores. The stored measurements and full plain-RNN runner are in `rnn_probe_1119/`; the large runs are not silently retrained by this short lecture notebook. The old GRU park-prompt contrasts were +0.00 (128 units, 1,000 updates), +0.04 (128 units, 5,000 updates), and +3.40 (512 units, 5,000 updates). The new plain-RNN measurements are shown below from the saved JSON. These are single-seed demonstrations, not proof of a capacity limit or a general advantage from gating. The two log-odds values distinguish a shift in preference from actually switching the preferred pronoun. The 512-unit GRU's separate happy-prompt distance diagnostic declines with added filler: +3.50, +2.97, +2.27, +1.02, +0.34, +0.11 at prediction positions 7, 12, 17, 27, 37, 47 (the name is at position 1). That behavioral decline is not itself a gradient measurement. In the boy/girl and man/woman filler comparisons, both the original name and inserted character change; those do not isolate a gate's action. On `tom gave lily his red ball , and`, either `he` or `she` is a grammatical continuation. Preferring `he` over the continuation we chose does not prove inability to represent the recipient. Attention provides another way to access earlier words, rather than a guarantee that the model learns every role.""") # ------------------------------------------------------------------------------------------------ code(r'''# [Added for CS6140] show measured plain-RNN capacity runs; do not train them during lecture import json from pathlib import Path _candidates = [Path("rnn_probe_1119/plain_probe_results.json"), Path(COMMON) / "rnn_probe_1119/plain_probe_results.json"] _result = next((p for p in _candidates if p.exists()), None) if _result is None: print("Open the note's Section 5, or run from the RNN folder to load rnn_probe_1119 results.") else: measured = json.loads(_result.read_text()) print("Plain RNN; prompt:", measured["prompt"]) print("hidden updates Lily log-odds Tom log-odds contrast") for r in measured["rows"]: if (r["hidden"], r["updates"]) in [(128, 1000), (128, 5000), (512, 5000)]: print(f"{r['hidden']:6d} {r['updates']:8d} {r['lily_logodds']:+14.4f} " f"{r['tom_logodds']:+14.4f} {r['contrast']:+10.4f}") ''') md(r"""## Segment 9 — How far back do gradients reach? (note §5–6) **What to watch:** how much the last prediction's loss depends on the input word $d$ positions earlier, relative to the most recent word. The plain RNN's curve falls like a straight line on the log scale (a product of factors); the gated models fall more slowly.""") code(r'''# [Added for CS6140] gradient of the last word's loss w.r.t. the one-hot input d steps back (64 validation windows) def grad_by_distance(m, T=80, n=64): m.eval() starts = torch.randint(len(data.val_ids) - T - 1, (n,), generator=torch.Generator().manual_seed(1)) win = torch.stack([data.val_ids[s:s + T + 1] for s in starts.tolist()]).to(DEVICE) x = F.one_hot(win[:, :T].T, V).float().requires_grad_() # (T, n, V): time-major, as the book out, _ = m.rnn(x) logits = m.output_layer(out) # (n, T, V) F.cross_entropy(logits[:, -1], win[:, T]).backward() g = x.grad.norm(dim=-1).mean(dim=1).cpu() # one number per position m.train() return (g / g[-1]).flip(0) # index d = d steps back curves = {name: grad_by_distance(m) for name, m in [("RNN", rnn_lm), ("GRU", gru_lm), ("LSTM", lstm_lm)]} d2l.plot(list(range(80)), [c.tolist() for c in curves.values()], xlabel="d (words back)", ylabel="relative gradient", legend=list(curves), yscale="log", figsize=(5, 3)) for d in [10, 20, 40, 79]: print(f"d = {d:2d}: " + " ".join(f"{k} {v[d]:.1e}" for k, v in curves.items())) ''') # ------------------------------------------------------------------------------------------------ md(r"""## Segment 10 — Greedy translations and BLEU (note §9) **What to watch:** the book's greedy loop on a few sentences (a dev-sized model: expect mistakes). BLEU counts matching $n$-grams, each credited at most as often as it appears in one reference, times a brevity penalty. The standard BLEU-4 and the book's `d2l.bleu` are different formulas.""") code(r'''# [Changed from book §10.7.5] the book's predict_step on Spanish sentences (cut at ) spanish = ["tengo hambre .", "me gusta leer libros .", "¿ dónde está mi perro ?", "ella no sabe nadar .", "mañana vamos a la playa con mis amigos ."] toks = [seq2seq_common.tokenize(x) for x in spanish] s, sl = mt.src_batch(toks) bos = torch.full((len(toks), mt.num_steps), mt.tgt_vocab[""]) preds, _ = s2s.predict_step([s, bos, sl, bos], CPU, mt.num_steps) for es, p in zip(spanish, preds): print(f"{es:42s} => {' '.join(seq2seq_common.ids_to_tokens(p.tolist(), mt.tgt_vocab))}") ''') code(r'''# [Added for CS6140] the note's example: standard BLEU-4 (NLTK) vs the book's d2l.bleu from nltk.translate.bleu_score import sentence_bleu, modified_precision hyp, ref = "the cat sat on mat".split(), "the cat sat on the mat".split() print("precisions p1..p4:", [round(float(modified_precision([ref], hyp, n)), 3) for n in range(1, 5)]) print(f"BLEU-4 (standard, NLTK): {sentence_bleu([ref], hyp):.3f}") print(f"d2l.bleu (book, k=4) : {d2l.bleu(' '.join(hyp), ' '.join(ref), k=4):.3f} <- a different formula") ''') code(r'''# [Added for CS6140] clipping with two references: "the" is credited at most twice (its max in ONE reference) hyp = "the the the cat".split() refs = ["the cat is the best".split(), "a cat the dog the".split()] p1 = modified_precision(refs, hyp, 1) print(f"unigram precision {p1} -> {p1.numerator} of {p1.denominator} words matched (summing over references " f"would wrongly give 4)") print("in HW6 (reference run): BLEU about 27.9; by Spanish length 1-4 / 5-6 / 7-8 / 9-12 tokens: " "about 32.4 / 37.0 / 30.1 / 18.6") ''') # ------------------------------------------------------------------------------------------------ def build(): nb = nbf.v4.new_notebook() nb["cells"] = CELLS nb["metadata"]["kernelspec"] = {"name": "python3", "display_name": "Python 3", "language": "python"} for c in CELLS: if c.cell_type == "code": first = c.source.split("\n", 1)[0] assert first.startswith(("# [Book §", "# [Changed from book §", "# [Added for CS6140]")), first nbf.write(nb, OUT) print(f"wrote {OUT}: {len(CELLS)} cells") def segment_times(): """Seconds per segment from the executed notebook's cell timing metadata.""" nb = nbf.read(OUT, as_version=4) seg, times = 0, collections.defaultdict(float) for c in nb.cells: if c.cell_type == "markdown" and c.source.lstrip().startswith(("## Segment", "---")): for line in c.source.split("\n"): if line.startswith("## Segment"): seg = int(line.split()[2]) if c.cell_type == "code" and seg: ex = c.metadata.get("execution", {}) a, b = ex.get("iopub.execute_input"), ex.get("shell.execute_reply") if a and b: parse = lambda s: datetime.datetime.fromisoformat(s.replace("Z", "+00:00")) times[seg] += (parse(b) - parse(a)).total_seconds() return {k: (f"{v:.0f} s" if v < 90 else f"{v / 60:.1f} min") for k, v in times.items()}, nb if __name__ == "__main__": if "--times" in sys.argv: times, nb = segment_times() nb.cells[0].source = intro(times).strip("\n") nbf.write(nb, OUT) print("segment times:", times) else: build()