""" Builds attention_lecture_demo.ipynb: the laptop demos for the Week 13 attention lectures (ATTENTION_claude_lecturePlan: Lecture A Mon 12/7, Lecture B = first half of the extra lecture). Single source: md()/code() cells below. Code starts from the d2l book's own notebooks (chapter 11); every code cell's first line says whether it is book code, changed from the book, or added for CS6140. python3 build_attention_lecture_demo.py # write the notebook (unexecuted) jupyter nbconvert --to notebook --execute --inplace attention_lecture_demo.ipynb python3 build_attention_lecture_demo.py --times # put the measured per-segment times into the intro table Leak rule (posted to students): added code uses F.scaled_dot_product_attention, nn.MultiheadAttention and the d2l package's classes for every piece HW7 Problems 2-3 ask students to write (masked softmax, scaled dot-product attention, multi-head split/merge, positional encoding, causal mask, the HW's attention decoder). The book's own Bahdanau decoder (d2l 11.4) is shown as the book wrote it. """ import json import sys from datetime import datetime import nbformat as nbf CELLS = [] NB = "attention_lecture_demo.ipynb" NSEG = 9 def md(src): CELLS.append(("md", src.strip("\n"))) def code(src): CELLS.append(("code", src.strip("\n"))) INTRO = r"""# Attention Lecture Demos (Week 13) Laptop demos for the two attention lectures, in the order of the lecture plan: **Lecture A** (Mon 12/7, segments 1–6) and **Lecture B** (first half of the extra lecture, segments 7–9). Each segment matches a block on the board and a section of the note *Attention: Queries, Keys, and Values*. The code starts from the d2l book (chapter 11); the first line of every code cell says where it comes from: * `# [Book §x.y]`: the book's code as is (or the d2l package's version of it); * `# [Changed from book §x.y]`: the book's code with one change, named on that line; * `# [Added for CS6140]`: something the book does not show. | Seg. | Lecture | Board topic (note §) | Changed / added vs. the book | Time | |---|---|---|---|---| | 1 | A | Flashback: attention is a kernel smoother (§2) | — (book code) | {t1} | | 2 | A | Scores are similarities (§3) | Added: which norm cancels in the softmax, on numbers | {t2} | | 3 | A | Scaled dot-product attention, √d (§4) | Added: the note's 2-token example with `F.scaled_dot_product_attention`; the √d saturation table | {t3} | | 4 | A | Masks (§5) | Added: the same padding mask in PyTorch's two conventions (`F.scaled_dot_product_attention`: True = may attend; `nn.MultiheadAttention`: True = blocked) | {t4} | | 5 | A | Multi-head attention (§6) | Added: `nn.MultiheadAttention`'s per-head weights and its parameter count | {t5} | | 6 | A | Attention inside the translator (§10) | Changed: HW6's Spanish→English data (book: French→English), a 1-minute training run; Added: the reverse-a-sequence task, without vs with attention | {t6} | | 7 | B | Self-attention ignores word order (§7) | Added: permutation equivariance, checked on numbers | {t7} | | 8 | B | Positional encoding (§8) | Added: the note's d = 4 table | {t8} | | 9 | B | The causal mask (§9) | Added: all-zero scores under the causal mask give the running mean; the future cannot leak back | {t9} | Times: measured on an Apple M1 Max (Apple GPU for the translator, CPU elsewhere). Segment 6 is the long one: about 1.5 minutes for the translator and 1.5 minutes for the reverse task; start it before you go back to the board. The translator in segment 6 is the **book's** Bahdanau decoder (the context enters the GRU's input); HW7 Problem 3's decoder adds the attention step after the GRU instead (note §10): same attention, different wiring. """ md(INTRO) md(r"""## Setup (run once)""") code(r'''# [Added for CS6140] device, the d2l Apple-GPU patch (as in the HW starters), the course data folder and # the HW's data module for the Spanish-English pairs import math, os, sys, time import torch from torch import nn import torch.nn.functional as F from d2l import torch as d2l import matplotlib.pyplot as plt DEVICE = (torch.device("cuda") if torch.cuda.is_available() else torch.device("mps") if torch.backends.mps.is_available() else torch.device("cpu")) if DEVICE.type == "mps": # d2l only knows CUDA: point its GPU helpers at Apple's GPU d2l.num_gpus = lambda: 1 d2l.gpu = lambda i=0: DEVICE d2l.try_gpu = lambda i=0: DEVICE DATA = next((d for d in ["../data", "../../data", "../../../data"] if os.path.isdir(d)), "../data") COMMON = next((p for p in [".", "../hw7", "../../../2.5_NN/HW7"] if os.path.exists(f"{p}/seq2seq_common.py")), None) assert COMMON, "seq2seq_common.py (it comes with the HW7 starter) not found" sys.path.insert(0, COMMON) import seq2seq_common torch.manual_seed(0) print("device:", DEVICE, "| data:", os.path.abspath(DATA))''') # --------------------------------------------------------------------------------------------------------- md(r"""## Segment 1 — Flashback: attention is a kernel smoother (note §2) · Lecture A **What to watch:** each prediction is a weighted average of the training targets, with weights from a kernel on the distance between the query and the training inputs: exactly attention, with the training inputs as keys and their targets as values. Narrow kernels follow the noise; wide ones blur.""") code(r'''# [Book §11.2] four kernels def gaussian(x): return torch.exp(-x**2 / 2) def boxcar(x): return torch.abs(x) < 1.0 def constant(x): return 1.0 + 0 * x def epanechikov(x): return torch.max(1 - torch.abs(x), torch.zeros_like(x)) fig, axes = d2l.plt.subplots(1, 4, sharey=True, figsize=(12, 3)) kernels = (gaussian, boxcar, constant, epanechikov) names = ('Gaussian', 'Boxcar', 'Constant', 'Epanechikov') x = torch.arange(-2.5, 2.5, 0.1) for kernel, name, ax in zip(kernels, names, axes): ax.plot(x.detach().numpy(), kernel(x).detach().numpy()) ax.set_xlabel(name) d2l.plt.show()''') code(r'''# [Book §11.2] training data y = 2 sin(x) + x + noise; Nadaraya-Watson = kernel weights, normalized over keys def f(x): return 2 * torch.sin(x) + x n = 40 x_train, _ = torch.sort(torch.rand(n) * 5) y_train = f(x_train) + torch.randn(n) x_val = torch.arange(0, 5, 0.1) y_val = f(x_val) def nadaraya_watson(x_train, y_train, x_val, kernel): dists = x_train.reshape((-1, 1)) - x_val.reshape((1, -1)) # Each column/row corresponds to each query/key k = kernel(dists).type(torch.float32) # Normalization over keys for each query attention_w = k / k.sum(0) y_hat = y_train@attention_w return y_hat, attention_w def plot(x_train, y_train, x_val, y_val, kernels, names, attention=False): fig, axes = d2l.plt.subplots(1, 4, sharey=True, figsize=(12, 3)) for kernel, name, ax in zip(kernels, names, axes): y_hat, attention_w = nadaraya_watson(x_train, y_train, x_val, kernel) if attention: pcm = ax.imshow(attention_w.detach().numpy(), cmap='Reds') else: ax.plot(x_val, y_hat) ax.plot(x_val, y_val, 'm--') ax.plot(x_train, y_train, 'o', alpha=0.5); ax.set_xlabel(name) if not attention: ax.legend(['y_hat', 'y']) if attention: fig.colorbar(pcm, ax=axes, shrink=0.7) plot(x_train, y_train, x_val, y_val, kernels, names)''') code(r'''# [Book §11.2] the attention weights: rows = training inputs (keys), columns = queries plot(x_train, y_train, x_val, y_val, kernels, names, attention=True)''') code(r'''# [Book §11.2] the kernel's width: narrow follows the noise, wide over-smooths sigmas = (0.1, 0.2, 0.5, 1) names = ['Sigma ' + str(sigma) for sigma in sigmas] def gaussian_with_width(sigma): return (lambda x: torch.exp(-x**2 / (2*sigma**2))) kernels = [gaussian_with_width(sigma) for sigma in sigmas] plot(x_train, y_train, x_val, y_val, kernels, names)''') # --------------------------------------------------------------------------------------------------------- md(r"""## Segment 2 — Scores are similarities (note §3) · Lecture A **What to watch:** the masked softmax gives padded keys weight 0; additive and dot-product scoring produce the same shapes. With the Gaussian kernel the query's own length cancels in the softmax, the keys' lengths do not, unless all keys have the same length.""") code(r'''# [Book §11.3] masked softmax (the d2l package's version): valid lengths 2 and 3 out of 4 keys print(d2l.masked_softmax(torch.rand(2, 2, 4), torch.tensor([2, 3])))''') code(r'''# [Book §11.3] additive (Bahdanau) and scaled dot-product attention: the d2l package's classes, same shapes queries, keys = torch.normal(0, 1, (2, 1, 20)), torch.normal(0, 1, (2, 10, 2)) values = torch.normal(0, 1, (2, 10, 4)) valid_lens = torch.tensor([2, 6]) attention = d2l.AdditiveAttention(num_hiddens=8, dropout=0.1) attention.eval() print("additive:", attention(queries, keys, values, valid_lens).shape) d2l.show_heatmaps(attention.attention_weights.reshape((1, 1, 2, 10)), xlabel='Keys', ylabel='Queries') queries = torch.normal(0, 1, (2, 1, 2)) attention = d2l.DotProductAttention(dropout=0.5) attention.eval() print("dot product:", attention(queries, keys, values, valid_lens).shape)''') code(r'''# [Added for CS6140] the note's §3 claim on numbers: softmax(-|q-k|^2/2) = softmax(q.k) when all keys have # the same length, and differs when they don't (|q|^2 is the same for every key, |k|^2 is not) q = torch.tensor([1.0, 2.0]) for name, K in [("equal-length keys", torch.tensor([[1.0, 0.0], [0.0, 1.0], [0.6, 0.8]])), ("unequal keys", torch.tensor([[1.0, 0.0], [0.0, 2.0], [0.6, 0.8]]))]: gauss = torch.softmax(-((q - K) ** 2).sum(1) / 2, 0) dot = torch.softmax(K @ q, 0) print(f"{name:18s} Gaussian {gauss.numpy().round(4)} dot product {dot.numpy().round(4)}")''') # --------------------------------------------------------------------------------------------------------- md(r"""## Segment 3 — Scaled dot-product attention and the √d (note §4) · Lecture A **What to watch:** the note's 2-token example gives weights 0.6225 / 0.3775. Scores of $d$ random products have spread $\sqrt d$: without the division the softmax piles almost all weight on one key as $d$ grows; with it, the weights stay spread out. (The scores here are drawn directly with spread $\sqrt d$, so the table is close to, not identical with, the note's, which uses real dot products.)""") code(r'''# [Added for CS6140] the note's 2-token example (d = 4, so sqrt(d) = 2), computed by PyTorch's attention Q = torch.tensor([[1.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 1.0]]) K = torch.tensor([[1.0, 1.0, 0.0, 0.0], [1.0, 0.0, 1.0, 0.0]]) V = torch.eye(2) # V = I, so the output IS the weight matrix print(F.scaled_dot_product_attention(Q[None], K[None], V[None])[0])''') code(r'''# [Added for CS6140] the sqrt(d) saturation: scores with spread sqrt(d) (what q.k of d random products has), # softmax over 10 keys, mean largest weight, with and without dividing by sqrt(d) g = torch.Generator().manual_seed(0) print(" d score std largest weight (unscaled) largest weight (scaled by sqrt d)") for d in [4, 16, 64, 256]: scores = torch.randn(20000, 10, generator=g) * math.sqrt(d) unscaled = torch.softmax(scores, -1).max(-1).values.mean() scaled = torch.softmax(scores / math.sqrt(d), -1).max(-1).values.mean() print(f"{d:3d} {scores.std():6.1f} {unscaled:.2f} {scaled:.2f}")''') # --------------------------------------------------------------------------------------------------------- md(r"""## Segment 4 — Masks (note §5) · Lecture A **What to watch:** blocked keys get weight exactly 0 because their scores become $-\infty$ *before* the softmax. PyTorch has two opposite conventions for the same mask: in `F.scaled_dot_product_attention` `True` means *may attend*; in `nn.MultiheadAttention` / `nn.Transformer` `True` means *blocked*.""") code(r'''# [Added for CS6140] one padding mask (2 sentences, 4 keys, lengths 3 and 1), in PyTorch's two conventions torch.manual_seed(0) X = torch.randn(2, 4, 8) # (batch, positions, d) keep = torch.tensor([[True, True, True, False], # (batch, keys): True = a real token [True, False, False, False]]) mha = nn.MultiheadAttention(8, num_heads=1, batch_first=True, bias=False).eval() _, w = mha(X, X, X, key_padding_mask=~keep) # nn.MultiheadAttention: True = BLOCKED, hence ~keep print("nn.MultiheadAttention weights, sentence 1 (keys 4 blocked) and 2 (keys 2-4 blocked):") print(w.detach().round(decimals=3)) Wq, Wk, Wv = mha.in_proj_weight.chunk(3) # the same projections, through F.sdpa out = F.scaled_dot_product_attention(X @ Wq.T, X @ Wk.T, X @ Wv.T, attn_mask=keep[:, None, :]) # F.sdpa: True = MAY ATTEND print("same output both ways:", torch.allclose(mha.out_proj(out), mha(X, X, X, key_padding_mask=~keep)[0], atol=1e-6))''') # --------------------------------------------------------------------------------------------------------- md(r"""## Segment 5 — Multi-head attention (note §6) · Lecture A **What to watch:** the shapes. $h$ heads split the width $d$ into $h$ pieces of $d/h$, attend in parallel (one weight matrix per head), and are merged back to $d$. The parameter count is $4(d^2+d)$, the same as one big head.""") code(r'''# [Book §11.5] the d2l package's MultiHeadAttention: queries (2, 4, 100), key-values (2, 6, 100) -> (2, 4, 100) num_hiddens, num_heads = 100, 5 attention = d2l.MultiHeadAttention(num_hiddens, num_heads, 0.5) batch_size, num_queries, num_kvpairs = 2, 4, 6 valid_lens = torch.tensor([3, 2]) X = torch.ones((batch_size, num_queries, num_hiddens)) Y = torch.ones((batch_size, num_kvpairs, num_hiddens)) d2l.check_shape(attention(X, Y, Y, valid_lens), (batch_size, num_queries, num_hiddens)) print("output:", attention(X, Y, Y, valid_lens).shape)''') code(r'''# [Added for CS6140] PyTorch's version: one weight matrix per head, and the parameter count 4(d^2 + d) d, h = 256, 4 mha = nn.MultiheadAttention(d, h, batch_first=True) X = torch.randn(2, 7, d) out, w = mha(X, X, X, average_attn_weights=False) print("output", tuple(out.shape), "| per-head weights", tuple(w.shape), "= (batch, heads, queries, keys)") print("parameters:", sum(p.numel() for p in mha.parameters()), "= 4(d^2+d) =", 4 * (d * d + d))''') # --------------------------------------------------------------------------------------------------------- md(r"""## Segment 6 — Attention inside the translator (note §10) · Lecture A **What to watch:** the book's Bahdanau decoder: at every output step the decoder's state queries all the encoder's outputs, and the context it gets back enters the GRU. One minute of training on HW6's Spanish–English data already gives sensible short translations, and the weights show a rough, soft alignment. Then the long-sequence test: reversing a random sequence, where one fixed context vector must hold the whole input.""") code(r'''# [Book §11.4] the book's Bahdanau decoder (the d2l package does not ship it) class Seq2SeqAttentionDecoder(d2l.AttentionDecoder): def __init__(self, vocab_size, embed_size, num_hiddens, num_layers, dropout=0): super().__init__() self.attention = d2l.AdditiveAttention(num_hiddens, dropout) self.embedding = nn.Embedding(vocab_size, embed_size) self.rnn = nn.GRU( embed_size + num_hiddens, num_hiddens, num_layers, dropout=dropout) self.dense = nn.LazyLinear(vocab_size) self.apply(d2l.init_seq2seq) def init_state(self, enc_outputs, enc_valid_lens): # Shape of outputs: (num_steps, batch_size, num_hiddens). # Shape of hidden_state: (num_layers, batch_size, num_hiddens) outputs, hidden_state = enc_outputs return (outputs.permute(1, 0, 2), hidden_state, enc_valid_lens) def forward(self, X, state): # Shape of enc_outputs: (batch_size, num_steps, num_hiddens). # Shape of hidden_state: (num_layers, batch_size, num_hiddens) enc_outputs, hidden_state, enc_valid_lens = state # Shape of the output X: (num_steps, batch_size, embed_size) X = self.embedding(X).permute(1, 0, 2) outputs, self._attention_weights = [], [] for x in X: # Shape of query: (batch_size, 1, num_hiddens) query = torch.unsqueeze(hidden_state[-1], dim=1) # Shape of context: (batch_size, 1, num_hiddens) context = self.attention( query, enc_outputs, enc_outputs, enc_valid_lens) # Concatenate on the feature dimension x = torch.cat((context, torch.unsqueeze(x, dim=1)), dim=-1) # Reshape x as (1, batch_size, embed_size + num_hiddens) out, hidden_state = self.rnn(x.permute(1, 0, 2), hidden_state) outputs.append(out) self._attention_weights.append(self.attention.attention_weights) # After fully connected layer transformation, shape of outputs: # (num_steps, batch_size, vocab_size) outputs = self.dense(torch.cat(outputs, dim=0)) return outputs.permute(1, 0, 2), [enc_outputs, hidden_state, enc_valid_lens] @property def attention_weights(self): return self._attention_weights''') code(r'''# [Changed from book §11.4] HW6's Spanish->English data and a 1-minute training run (book: French->English, # 30 epochs); the book's encoder, decoder and masked loss t0 = time.time() data = seq2seq_common.TatoebaEsEn(DATA, batch_size=128) print(data.describe()) embed_size, num_hiddens, num_layers, dropout = 256, 256, 2, 0.2 encoder = d2l.Seq2SeqEncoder(len(data.src_vocab), embed_size, num_hiddens, num_layers, dropout) decoder = Seq2SeqAttentionDecoder(len(data.tgt_vocab), embed_size, num_hiddens, num_layers, dropout) model = seq2seq_common.BookSeq2Seq(encoder, decoder, tgt_pad=data.tgt_vocab[''], lr=0.005) model(*(a[:2] for a in data.arrays[:3])) # one forward pass sizes the book's nn.LazyLinear hist = seq2seq_common.train_seq2seq(model, data, DEVICE, steps=TRANSLATOR_STEPS, lr=0.005, loss_fn=lambda Y_hat, Y: model.loss(Y_hat, Y)) print(f"{hist['steps']} steps in {hist['seconds']:.0f} s, validation loss {hist['val_loss'][-1]:.2f}")''') code(r'''# [Changed from book §11.4] translate with the book's predict_step (greedy), Spanish sentences def translate(model, data, sentences, save_attention=False): toks = [seq2seq_common.tokenize(s) for s in sentences] src, src_len = data.src_batch(toks) bos = torch.full((len(toks), 1), data.tgt_vocab['']) preds, att = model.predict_step((src, bos, src_len, bos), DEVICE, data.num_steps, save_attention) outs = [seq2seq_common.ids_to_tokens(p, data.tgt_vocab) for p in preds.tolist()] return toks, outs, att model.eval() spanish = ["tengo hambre .", "¿ dónde está la estación ?", "me gusta leer libros .", "mi hermano trabaja en un hospital grande ."] _, outs, _ = translate(model, data, spanish) for s, out in zip(spanish, outs): print(f"{s:45s} => {' '.join(out)}")''') code(r'''# [Changed from book §11.4] the attention weights of the last sentence: rows = English output words, # columns = Spanish input tokens (plus ) toks, outs, att = translate(model, data, [spanish[-1]], save_attention=True) w = torch.stack([step[0][0][0] for step in att]).cpu() # (output steps, source positions) n_out, n_in = len(outs[0]) + 1, len(toks[0]) + 1 fig, ax = plt.subplots(figsize=(5, 4)) ax.imshow(w[:n_out, :n_in].detach(), cmap='Reds') ax.set_xticks(range(n_in), toks[0] + [''], rotation=60) ax.set_yticks(range(n_out), outs[0] + ['']) ax.set_xlabel('Spanish (keys)'); ax.set_ylabel('English output (queries)') plt.show() model.train(); print(f"segment 6 so far: {time.time() - t0:.0f} s")''') code(r'''# [Added for CS6140] the long-sequence test: reverse a random sequence of 5-30 symbols. The same book # encoder, then the book's decoder WITHOUT attention (one fixed context, seq2seq_common.Seq2SeqDecoder = d2l # 10.7) vs the book's Bahdanau decoder above. Same sizes, same number of steps. class ReverseTask: """Random symbols 3..22 (0 , 1 , 2 ), in the translation data's batch format.""" def __init__(self, n, lmin, lmax, batch_size=128, seed=0): self.lmin, self.lmax, self.batch_size, self.num_steps = lmin, lmax, batch_size, lmax + 1 self.tgt_vocab = {'': 0, '': 1, '': 2} self.g = torch.Generator().manual_seed(seed) self.arrays, self.val_arrays = self.make(n), self.make(500) def make(self, n, L=None): T = self.num_steps src, tin, lab = (torch.zeros(n, T, dtype=torch.long) for _ in range(3)) lens = torch.randint(self.lmin, self.lmax + 1, (n,), generator=self.g) if L is None else torch.full((n,), L) for i, l in enumerate(lens.tolist()): s = torch.randint(3, 23, (l,), generator=self.g) src[i, :l], src[i, l] = s, 2 tin[i, 0], tin[i, 1:l + 1] = 1, s.flip(0) lab[i, :l], lab[i, l] = s.flip(0), 2 return src, tin, lens + 1, lab task = ReverseTask(20000, 5, 30) results = {} for name in ["no attention (book 10.7)", "Bahdanau attention (book 11.4)"]: t1 = time.time() torch.manual_seed(0) enc = d2l.Seq2SeqEncoder(23, 32, 128, 1) dec = (seq2seq_common.Seq2SeqDecoder(23, 32, 128, 1) if name.startswith("no") else Seq2SeqAttentionDecoder(23, 32, 128, 1)) m = seq2seq_common.BookSeq2Seq(enc, dec, tgt_pad=0, lr=0.005) m(*(a[:2] for a in task.arrays[:3])) # sizes the book's nn.LazyLinear seq2seq_common.train_seq2seq(m, task, torch.device("cpu"), steps=REVERSE_STEPS, lr=0.005, loss_fn=lambda Y_hat, Y, m=m: m.loss(Y_hat, Y)) m.eval() acc = {} for L in [5, 10, 15, 20, 25, 30]: src, tin, slen, lab = task.make(300, L) preds, _ = m.predict_step((src, tin[:, :1], slen, lab), torch.device("cpu"), L) acc[L] = (preds[:, :L] == lab[:, :L]).float().mean().item() results[name] = acc print(f"{name:32s} " + " ".join(f"L={L}: {a:.2f}" for L, a in acc.items()) + f" ({time.time() - t1:.0f} s)")''') code(r'''# [Added for CS6140] token accuracy by sequence length fig, ax = plt.subplots(figsize=(5, 3)) for name, acc in results.items(): ax.plot(list(acc), list(acc.values()), 'o-', label=name) ax.set_xlabel('sequence length'); ax.set_ylabel('token accuracy'); ax.set_ylim(0, 1.05); ax.legend() plt.show()''') # --------------------------------------------------------------------------------------------------------- md(r"""## Segment 7 — Self-attention ignores word order (note §7) · Lecture B **What to watch:** in self-attention the queries, keys and values all come from the same tokens. Shuffle the input tokens and the outputs come out shuffled the same way, nothing else changes: attention alone treats a sentence as a bag of tokens.""") code(r'''# [Book §11.6] self-attention: queries = keys = values = X (the d2l package's MultiHeadAttention) num_hiddens, num_heads = 100, 5 attention = d2l.MultiHeadAttention(num_hiddens, num_heads, 0.5) batch_size, num_queries, valid_lens = 2, 4, torch.tensor([3, 2]) X = torch.ones((batch_size, num_queries, num_hiddens)) d2l.check_shape(attention(X, X, X, valid_lens), (batch_size, num_queries, num_hiddens)) print("self-attention output:", attention(X, X, X, valid_lens).shape)''') code(r'''# [Added for CS6140] permutation equivariance: shuffle the 6 input tokens, the outputs shuffle the same way torch.manual_seed(0) mha = nn.MultiheadAttention(16, 2, batch_first=True).eval() X = torch.randn(1, 6, 16) perm = torch.tensor([3, 0, 5, 1, 4, 2]) out = mha(X, X, X)[0] out_shuffled = mha(X[:, perm], X[:, perm], X[:, perm])[0] print("output of shuffled input == shuffled output:", torch.allclose(out_shuffled, out[:, perm], atol=1e-6))''') # --------------------------------------------------------------------------------------------------------- md(r"""## Segment 8 — Positional encoding (note §8) · Lecture B **What to watch:** like a binary counter, low columns change fast with the position and high columns slowly; the sin/cos version is the continuous counter. Every position gets its own pattern, added to the token's embedding.""") code(r'''# [Book §11.6] binary representations of 0-7: the lowest bit alternates fastest for i in range(8): print(f'{i} in binary is {i:>03b}')''') code(r'''# [Book §11.6] the d2l package's PositionalEncoding: columns 6-9 over 60 positions, and the heatmap encoding_dim, num_steps = 32, 60 pos_encoding = d2l.PositionalEncoding(encoding_dim, 0) X = pos_encoding(torch.zeros((1, num_steps, encoding_dim))) P = pos_encoding.P[:, :X.shape[1], :] d2l.plot(torch.arange(num_steps), P[0, :, 6:10].T, xlabel='Row (position)', figsize=(6, 2.5), legend=["Col %d" % d for d in torch.arange(6, 10)]) d2l.show_heatmaps(P[0, :, :].unsqueeze(0).unsqueeze(0), xlabel='Column (encoding dimension)', ylabel='Row (position)', figsize=(3.5, 4), cmap='Blues')''') code(r'''# [Added for CS6140] the note's d = 4 table (positions 0-3), from the same package class print(d2l.PositionalEncoding(4, 0).P[0, :4].numpy().round(4))''') # --------------------------------------------------------------------------------------------------------- md(r"""## Segment 9 — The causal mask (note §9) · Lecture B **What to watch:** with all scores equal, position $t$ under the causal mask averages the values of positions $1..t$, the running mean. Changing the last token changes only the last output: no position can see the future, which is what lets a decoder train on every position at once.""") code(r'''# [Added for CS6140] all-zero scores (Q = K = 0) under PyTorch's causal mask: the output is the running mean of V V = torch.tensor([[1.0], [3.0], [5.0], [7.0]])[None] # (batch 1, 4 positions, 1 feature) Z = torch.zeros(1, 4, 1) print("running mean of 1, 3, 5, 7:", F.scaled_dot_product_attention(Z, Z, V, is_causal=True)[0, :, 0]) print("causal mask (True = may attend):\n", ~torch.isinf(nn.Transformer.generate_square_subsequent_mask(4)))''') code(r'''# [Added for CS6140] the future cannot leak back: change token 4, outputs 1-3 stay the same torch.manual_seed(0) mha = nn.MultiheadAttention(8, 2, batch_first=True).eval() X = torch.randn(1, 4, 8) X2 = X.clone(); X2[0, 3] += 10.0 mask = nn.Transformer.generate_square_subsequent_mask(4) a, b = mha(X, X, X, attn_mask=mask)[0], mha(X2, X2, X2, attn_mask=mask)[0] print("largest change per position:", (a - b).abs().amax(-1)[0].detach().numpy().round(6))''') md(r"""--- *Book code: A. Zhang, Z. C. Lipton, M. Li, A. J. Smola, Dive into Deep Learning (d2l.ai), CC BY-SA 4.0. Changes and additions for CS6140 are marked in each cell.*""") # the two training budgets (calibrated so each training cell takes about a minute on an M1 Max) SETTINGS = {"TRANSLATOR_STEPS": 600, "REVERSE_STEPS": 500} # --------------------------------------------------------------------------------------------------------- def build(): nb = nbf.v4.new_notebook() cells = [] for k, s in CELLS: for name, v in SETTINGS.items(): s = s.replace(f"steps={name}", f"steps={v}") cells.append(nbf.v4.new_markdown_cell(s) if k == "md" else nbf.v4.new_code_cell(s)) nb["cells"] = cells nb["cells"][0].source = INTRO.format(**{f"t{i}": "" for i in range(1, NSEG + 1)}) nb["metadata"]["kernelspec"] = {"name": "python3", "display_name": "Python 3", "language": "python"} nbf.write(nb, NB) print(f"wrote {NB}: {len(CELLS)} cells") def fill_times(): """Per-segment wall time from the executed notebook's cell timestamps, into the intro table.""" nb = nbf.read(NB, as_version=4) seg, times = 0, {} for c in nb.cells: if c.cell_type == "markdown" and c.source.startswith("## Segment"): seg = int(c.source.split()[2]) elif c.cell_type == "code" and seg and "execution" in c.metadata: e = c.metadata["execution"] t = (datetime.fromisoformat(e["shell.execute_reply"].replace("Z", "+00:00")) - datetime.fromisoformat(e["iopub.execute_input"].replace("Z", "+00:00"))).total_seconds() times[seg] = times.get(seg, 0) + t fmt = {f"t{i}": ((f"{times[i]:.0f} s" if times[i] >= 1 else "<1 s") if i in times else "") for i in range(1, NSEG + 1)} nb.cells[0].source = INTRO.format(**fmt) nbf.write(nb, NB) print("segment times:", json.dumps(fmt)) if __name__ == "__main__": fill_times() if "--times" in sys.argv else build()