""" Builds transformer_lecture_demo.ipynb: the laptop demos for the TRANSFORMER note's lectures (Part A = second half of the extra lecture, Part B = Thu 12/10, plus the Mon 12/14 appendix), one segment per block of TRANSFORMER_claude_lecturePlan, starting from the d2l book's own code (chapter 11.7, 11.9). 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, or in the book's text) # [Changed from book §x.y] ... the book's code with one stated change (usually: HW7'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 HW7 TODO piece the HW's way; it uses torch.nn, the d2l package, the book's own code, and Hugging Face (GPT-2 model, generate, logits warpers). Run: python3 build_transformer_lecture_demo.py (writes transformer_lecture_demo.ipynb, unexecuted) jupyter nbconvert --to notebook --execute --inplace transformer_lecture_demo.ipynb python3 build_transformer_lecture_demo.py --times (writes the measured segment times into the intro) """ 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, "transformer_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", "The big picture: the book's Transformer on Spanish → English", "§1"), (2, "A", "The wiring: three attentions and their masks", "§1"), (3, "A", "Layer norm = batch norm over the other axis", "§2"), (4, "A", "Add & Norm, the FFN, the encoder block; parameter counts", "§3–4"), (5, "B", "The decoder block: the future stays hidden", "§5"), (6, "B", "Train in parallel, generate in a loop", "§6"), (7, "B", "Delete the encoder: a tiny GPT on TinyStories", "§7"), (8, "B", "Pre-norm vs post-norm", "§8"), (9, "B", "Sampling: greedy, temperature, top-k", "§9"), (10, "12/14", "Three kinds of Transformer: attention patterns", "§10"), ] CHANGES = [ # shown in the intro ("Changed", "1, 2, 6", "**Spanish → English** (HW7's Tatoeba data, dev-sized: 10,000 pairs) instead of the book's " "French → English; `seq2seq_common.TatoebaEsEn` is a `d2l.MTFraEng` subclass, so the book's code runs on it"), ("Changed", "1, 6", "width 128 (FFN 256), 10 epochs instead of 30, so training takes about a minute"), ("Changed", "3", "the note's toy $X=[[1,2,3],[2,4,6]]$ instead of the book's 2×2 example"), ("Changed", "6", "test translations scored with **corpus BLEU-4** (as in HW6/HW7) instead of the book's " "per-sentence `d2l.bleu`"), ("Added", "2", "shapes of the three attentions' weights and their three masks, as heatmaps"), ("Added", "4", "parameter count of one block (`nn.TransformerEncoderLayer`): 3,280 at $d=16$, 789,760 at $d=256$"), ("Added", "5", "the \"change the last English word\" test with `nn.TransformerDecoderLayer` and a causal mask"), ("Added", "6", "one teacher-forced pass vs the step-by-step generation loop (time); the embedding scale " "against the positional encoding"), ("Added", "7", "GPT = decoder-only: Hugging Face's GPT-2 class, tiny (width 128, 2 blocks, context 64), " "trained about a minute on HW6/HW7's TinyStories; tied output layer; perplexity (the book has no GPT code)"), ("Added", "8", "`nn.TransformerEncoderLayer(norm_first=False / True)`: what comes out of each"), ("Added", "9", "the note's sampling table via Hugging Face's logits warpers; stories with `generate` " "(greedy, temperature 0.5 / 1.0 / 1.5, top-10)"), ("Added", "10", "attention-pattern grids for encoder-only, decoder-only and encoder–decoder models"), ] 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"""# The Transformer and GPT — lecture demos (Parts A and B, plus the 12/14 appendix) Laptop demos for the TRANSFORMER note (`TRANSFORMER_claude_1017.pdf`), one segment per board block of the lecture plan. The code is the **d2l book's** (chapter 11.7) 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. Part A = the second half of the extra lecture, Part B = Thu 12/10. | Seg. | Lecture | Board topic | Note | Time on an M1 Max | |---|---|---|---|---| {rows} **What differs from the book** | | Segments | What | |---|---|---| {chg} Needs `transformers` (HW7's setup). Run the setup cells first; segments 2, 5 and 6 need segment 1, segments 8–9 need segment 7. Numbers vary a little from run to run. The models here are tiny and trained for a minute: the HW7 numbers quoted along the way come from the full runs. """ # ------------------------------------------------------------------------------------------------ md(intro()) code(r'''# [Book §11.7] 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 import matplotlib.pyplot as plt 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] HW7's shared data modules and the course data folder (as in the HW starters)\n" + starter_common.DATA_BLOCK + r''' _places = [".", "../hw7", "../../../2.5_NN/HW7"] # next to this notebook, your HW7 folder, the course tree COMMON = next((p for p in _places if os.path.exists(f"{p}/seq2seq_common.py")), None) if COMMON is None: raise FileNotFoundError("lm_common.py / seq2seq_common.py (they come with the HW7 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") # the Spanish-English pairs (24 MB, downloaded once) print("shared modules from", os.path.abspath(COMMON), "| data in", os.path.abspath(DATA)) ''') # ------------------------------------------------------------------------------------------------ md(r"""--- # Part A (second half of the extra lecture) ## Segment 1 — The big picture: the book's Transformer on Spanish → English (note §1) **What to watch:** the parts are all familiar (embeddings, positional encoding, multi-head attention, residual + norm, an MLP per position, the output layer); the model is just their wiring. Every block keeps the shape (batch, positions, width).""") code(r'''# [Changed from book §10.5, §11.7.6] HW7'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("batch shapes: src", tuple(src.shape), "| decoder input", tuple(tgt_in.shape), "| labels", tuple(label.shape)) ''') code(r'''# [Book §11.7.5] the book's decoder block and decoder (in the book's text; the encoder is in the d2l package) class TransformerDecoderBlock(nn.Module): # The i-th block in the Transformer decoder def __init__(self, num_hiddens, ffn_num_hiddens, num_heads, dropout, i): super().__init__() self.i = i self.attention1 = d2l.MultiHeadAttention(num_hiddens, num_heads, dropout) self.addnorm1 = d2l.AddNorm(num_hiddens, dropout) self.attention2 = d2l.MultiHeadAttention(num_hiddens, num_heads, dropout) self.addnorm2 = d2l.AddNorm(num_hiddens, dropout) self.ffn = d2l.PositionWiseFFN(ffn_num_hiddens, num_hiddens) self.addnorm3 = d2l.AddNorm(num_hiddens, dropout) def forward(self, X, state): enc_outputs, enc_valid_lens = state[0], state[1] # During training all tokens of a target sentence are processed at once (state[2][i] is None); when # decoding token by token, state[2][i] holds this block's inputs for the positions decoded so far if state[2][self.i] is None: key_values = X else: key_values = torch.cat((state[2][self.i], X), dim=1) state[2][self.i] = key_values if self.training: batch_size, num_steps, _ = X.shape # (batch_size, num_steps), every row is [1, 2, ..., num_steps]: position t sees positions 1..t dec_valid_lens = torch.arange(1, num_steps + 1, device=X.device).repeat(batch_size, 1) else: dec_valid_lens = None X2 = self.attention1(X, key_values, key_values, dec_valid_lens) # masked self-attention Y = self.addnorm1(X, X2) Y2 = self.attention2(Y, enc_outputs, enc_outputs, enc_valid_lens) # cross-attention to the encoder Z = self.addnorm2(Y, Y2) return self.addnorm3(Z, self.ffn(Z)), state class TransformerDecoder(d2l.AttentionDecoder): def __init__(self, vocab_size, num_hiddens, ffn_num_hiddens, num_heads, num_blks, dropout): super().__init__() self.num_hiddens = num_hiddens self.num_blks = num_blks self.embedding = nn.Embedding(vocab_size, num_hiddens) self.pos_encoding = d2l.PositionalEncoding(num_hiddens, dropout) self.blks = nn.Sequential() for i in range(num_blks): self.blks.add_module("block" + str(i), TransformerDecoderBlock( num_hiddens, ffn_num_hiddens, num_heads, dropout, i)) self.dense = nn.LazyLinear(vocab_size) def init_state(self, enc_outputs, enc_valid_lens): return [enc_outputs, enc_valid_lens, [None] * self.num_blks] def forward(self, X, state): X = self.pos_encoding(self.embedding(X) * math.sqrt(self.num_hiddens)) self._attention_weights = [[None] * len(self.blks) for _ in range(2)] for i, blk in enumerate(self.blks): X, state = blk(X, state) self._attention_weights[0][i] = blk.attention1.attention.attention_weights # decoder self-attention self._attention_weights[1][i] = blk.attention2.attention.attention_weights # cross-attention return self.dense(X), state @property def attention_weights(self): return self._attention_weights ''') code(r'''# [Changed from book §11.7.6] the book's model, width 128 / FFN 256 (book: 256 / 64), 2 + 2 blocks, 4 heads torch.manual_seed(0) num_hiddens, num_blks, dropout, ffn_num_hiddens, num_heads = 128, 2, 0.2, 256, 4 encoder = d2l.TransformerEncoder(len(mt.src_vocab), num_hiddens, ffn_num_hiddens, num_heads, num_blks, dropout) decoder = TransformerDecoder(len(mt.tgt_vocab), num_hiddens, ffn_num_hiddens, num_heads, num_blks, dropout) model = seq2seq_common.BookSeq2Seq(encoder, decoder, tgt_pad=mt.tgt_vocab[""], lr=0.001) with torch.no_grad(): model(src[:2], tgt_in[:2], src_len[:2]) # one pass creates the lazy output layer parts = {"source embedding": encoder.embedding, "encoder blocks": encoder.blks, "target embedding": decoder.embedding, "decoder blocks": decoder.blks, "output layer": decoder.dense} for name, m in parts.items(): print(f"{name:17s} {sum(p.numel() for p in m.parameters()):>10,}") print(f"{'total':17s} {sum(p.numel() for p in model.parameters()):>10,}") ''') code(r'''# [Added for CS6140] the shape walk through the encoder: every block keeps (batch, positions, width) encoder.eval() with torch.no_grad(): X = src[:2] print("token IDs ", tuple(X.shape)) H = encoder.pos_encoding(encoder.embedding(X) * math.sqrt(num_hiddens)) print("embeddings x sqrt(d) + positions ", tuple(H.shape)) for i, blk in enumerate(encoder.blks): H = blk(H, src_len[:2]) print(f"after encoder block {i} ", tuple(H.shape)) encoder.train(); ''') # ------------------------------------------------------------------------------------------------ md(r"""## Segment 2 — The wiring: three attentions and their masks (note §1) **What to watch:** encoder self-attention (Spanish looks at Spanish, padding hidden), decoder *masked* self-attention (English looks only backwards), and cross-attention (English queries, Spanish keys and values: "the decoder asks, the encoder answers"). Before training the weights are nearly uniform; the masks already show.""") code(r'''# [Added for CS6140] the shapes of the three attentions' weights (d2l stores them as (batch x heads, queries, keys)) model.train() # training mode: the decoder uses its causal valid_lens with torch.no_grad(): model(src[:2], tgt_in[:2], src_len[:2]) enc_w = encoder.attention_weights[0] dec_self_w, cross_w = decoder.attention_weights[0][0], decoder.attention_weights[1][0] print("encoder self-attention ", tuple(enc_w.shape), " queries = keys = Spanish positions") print("decoder masked self-attn ", tuple(dec_self_w.shape), " queries = keys = English positions") print("cross-attention ", tuple(cross_w.shape), " queries = English, keys/values = Spanish") print("first sentence:", " ".join(mt.src_vocab.to_tokens(src[0, :int(src_len[0])].tolist()))) ''') code(r'''# [Added for CS6140] the three masks, seen in the (untrained) weights of head 1, first sentence n_src, n_tgt = min(int(src_len[0]) + 2, mt.num_steps), 8 fig, axes = plt.subplots(1, 3, figsize=(10, 3)) for ax, (title, w) in zip(axes, [("encoder self (padding hidden)", enc_w[0, :n_src, :n_src]), ("decoder self (causal)", dec_self_w[0, :n_tgt, :n_tgt]), ("cross (decoder asks)", cross_w[0, :n_tgt, :n_src])]): ax.imshow(w.cpu(), cmap="Reds") ax.set_title(title, fontsize=9); ax.set_xlabel("key positions", fontsize=8) ax.set_ylabel("query positions", fontsize=8) plt.tight_layout(); plt.show() ''') # ------------------------------------------------------------------------------------------------ md(r"""## Segment 3 — Layer norm = batch norm over the other axis (note §2) **What to watch:** layer norm normalizes each token (row) on its own; batch norm normalizes each feature (column) across the batch. LN removes each token's scale: both rows of the toy come out the same.""") code(r'''# [Changed from book §11.7.2] the note's toy X instead of the book's 2x2 (library layers, no learned scale/shift) X = torch.tensor([[1., 2., 3.], [2., 4., 6.]]) ln = nn.LayerNorm(3, elementwise_affine=False) bn = nn.BatchNorm1d(3, affine=False) # training mode: statistics of this batch print("layer norm (each row):\n", ln(X)) print("batch norm (each column):\n", bn(X)) ''') # ------------------------------------------------------------------------------------------------ md(r"""## Segment 4 — Add & Norm, the FFN, the encoder block; parameter counts (note §3–4) **What to watch:** Add & Norm and the FFN keep the shape; "attention communicates, the FFN computes". One block of width $d$ costs about $12d^2$ parameters: two thirds of them in the FFN.""") code(r'''# [Book §11.7.2–11.7.4] the book's FFN, Add & Norm and encoder block (d2l package) keep the shape ffn = d2l.PositionWiseFFN(4, 8) ffn.eval() print("FFN on (2, 3, 4) ->", tuple(ffn(torch.ones((2, 3, 4))).shape)) add_norm = d2l.AddNorm(4, 0.5) shape = (2, 3, 4) d2l.check_shape(add_norm(torch.ones(shape), torch.ones(shape)), shape) X = torch.ones((2, 100, 24)) valid_lens = torch.tensor([3, 2]) encoder_blk = d2l.TransformerEncoderBlock(24, 48, 8, 0.5) encoder_blk.eval() d2l.check_shape(encoder_blk(X, valid_lens), X.shape) print("encoder block on (2, 100, 24) -> (2, 100, 24): shapes check") ''') code(r'''# [Added for CS6140] parameters of one block (PyTorch's layer: attention 4(d^2+d), FFN 2*d*d_ff + d_ff + d, two LNs 4d) for d, h, d_ff in [(16, 4, 64), (256, 4, 1024)]: blk = nn.TransformerEncoderLayer(d, h, d_ff) att = sum(p.numel() for p in blk.self_attn.parameters()) ffn_p = sum(p.numel() for p in [*blk.linear1.parameters(), *blk.linear2.parameters()]) total = sum(p.numel() for p in blk.parameters()) print(f"d = {d:3d}: attention {att:,} + FFN {ffn_p:,} + layer norms {total - att - ffn_p:,} = {total:,}" f" (12 d^2 = {12 * d * d:,})") ''') # ------------------------------------------------------------------------------------------------ md(r"""--- # Part B (Thu 12/10) ## Segment 5 — The decoder block: the future stays hidden (note §5) **What to watch:** with the causal mask, changing the *last* English word changes only the last output; the earlier positions cannot see it. Without the mask every position changes.""") code(r'''# [Added for CS6140] "change the last English word" with PyTorch's decoder layer (dropout off) torch.manual_seed(0) layer = nn.TransformerDecoderLayer(d_model=16, nhead=4, dim_feedforward=32, dropout=0.0, batch_first=True).eval() memory = torch.randn(1, 5, 16) # the encoder's output for a 5-token Spanish sentence tgt = torch.randn(1, 6, 16) # 6 English positions tgt2 = tgt.clone() tgt2[0, -1] = torch.randn(16) # change only the last English word causal = nn.Transformer.generate_square_subsequent_mask(6) with torch.no_grad(): for name, mask in [("with the causal mask", causal), ("without it", None)]: diff = (layer(tgt, memory, tgt_mask=mask) - layer(tgt2, memory, tgt_mask=mask)).abs().amax(-1)[0] print(f"{name:21s} change per position: " + " ".join(f"{v:.3f}" for v in diff.tolist())) ''') # ------------------------------------------------------------------------------------------------ md(r"""## Segment 6 — Train in parallel, generate in a loop (note §6) **What to watch:** training is one pass over all target positions at once (teacher forcing + the causal mask); generation is a loop, one word per pass. A minute of training on 10,000 pairs gives rough translations; HW7's full run (100,000 pairs, more steps, a careful embedding start) reaches about 45 BLEU.""") code(r'''# [Changed from book §11.7.6] 10 epochs instead of 30, on Spanish-English t0 = time.time() trainer = d2l.Trainer(max_epochs=10, gradient_clip_val=1, num_gpus=NUM_GPUS) trainer.fit(model, mt) print(f"trained in {time.time() - t0:.0f} s") ''') code(r'''# [Added for CS6140] one teacher-forced pass vs the step-by-step loop, on the same 128 sentences model.eval() batch = [b.to(DEVICE) for b in (src, tgt_in, src_len, label)] with torch.no_grad(): t0 = time.time(); model(batch[0], batch[1], batch[2]); t_forced = time.time() - t0 t0 = time.time(); model.predict_step(batch, DEVICE, mt.num_steps); t_loop = time.time() - t0 print(f"teacher forcing, all {mt.num_steps} positions at once: {t_forced * 1000:.0f} ms | " f"generation, one position per pass: {t_loop * 1000:.0f} ms") ''') code(r'''# [Changed from book §11.7.6] 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, _ = model.predict_step([s.to(DEVICE), bos.to(DEVICE), sl.to(DEVICE), bos.to(DEVICE)], DEVICE, 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'''# [Changed from book §11.7.6] corpus BLEU-4 on 500 test sentences (all their references), as in HW6/HW7 n = 500 s, sl = mt.src_batch(mt.test_src[:n]) bos = torch.full((n, mt.num_steps), mt.tgt_vocab[""]) with torch.no_grad(): preds, _ = model.predict_step([s.to(DEVICE), bos.to(DEVICE), sl.to(DEVICE), bos.to(DEVICE)], DEVICE, mt.num_steps) hyps = [seq2seq_common.ids_to_tokens(p.tolist(), mt.tgt_vocab) for p in preds] print(f"corpus BLEU-4 after a minute: {seq2seq_common.corpus_bleu(hyps, mt.test_refs[:n]):.1f}") print("HW7 full runs (reference run): HW6 GRU about 27.9 -> attention GRU about 37.6 -> Transformer about 45") ''') code(r'''# [Added for CS6140] the embedding start: the book multiplies embeddings by sqrt(d); PyTorch starts them at N(0, 1) d = num_hiddens fresh = nn.Embedding(len(mt.src_vocab), d) pe = d2l.PositionalEncoding(d, 0).P[0, :mt.num_steps] print(f"embedding x sqrt(d): typical size {fresh.weight.std().item() * math.sqrt(d):.1f}" f" | positional encoding: values in [{pe.min().item():.0f}, {pe.max().item():.0f}]") print("at the start the word signal drowns the position signal; HW7 starts the embeddings at std 1/sqrt(d)" " (the original Transformer's choice): about 45 vs about 31 BLEU at the same budget (note §6)") ''') # ------------------------------------------------------------------------------------------------ md(r"""## Segment 7 — Delete the encoder: a tiny GPT on TinyStories (note §7) **What to watch:** what is left of the Transformer is a stack of encoder-style blocks with the causal mask: GPT. Its task is HW6 Problem 3's (next word on TinyStories), and its output layer *is* the token embedding (weight tying). The book has no GPT code; this uses Hugging Face's GPT-2 class at a tiny size.""") code(r'''# [Added for CS6140] HW6/HW7's TinyStories split and word vocabulary (5,274 words), windows of 64 words lm = lm_common.TinyStories(root=f"{DATA}/tinystories", batch_size=32, num_steps=64, min_freq=10, batches_per_epoch=50) print(lm.describe()) ''') code(r'''# [Added for CS6140] Hugging Face's GPT-2, tiny: width 128, 2 blocks, 4 heads, context 64, tied output layer import transformers from transformers import GPT2Config, GPT2LMHeadModel transformers.logging.set_verbosity_error() class HFLanguageModel(nn.Module): """Wraps GPT2LMHeadModel so that model(X) returns the logits, as lm_common.train_lm expects.""" def __init__(self, gpt): super().__init__() self.gpt = gpt def forward(self, X): return self.gpt(input_ids=X).logits torch.manual_seed(0) cfg = GPT2Config(vocab_size=len(lm.vocab), n_positions=64, n_embd=128, n_layer=2, n_head=4, n_inner=512, bos_token_id=None, eos_token_id=lm.vocab[""], pad_token_id=lm.vocab[""]) gpt = GPT2LMHeadModel(cfg) print(f"parameters: {sum(p.numel() for p in gpt.parameters()):,}") print("output layer is the token embedding (tied):", gpt.lm_head.weight is gpt.transformer.wte.weight) ''') code(r'''# [Added for CS6140] train about a minute with HW6/HW7's training loop; perplexity on the validation windows torch.manual_seed(0) lm_model = HFLanguageModel(gpt) hist = lm_common.train_lm(lm_model, lm, DEVICE, steps=2000, lr=2e-3) print(f"{hist['seconds']:.0f} s | validation perplexity {lm_common.perplexity(lm_model, lm, DEVICE):.1f} " f"(a uniform guess: {len(lm.vocab):,})") print("the HW ladder (reference runs): RNN about 23.8 -> LSTM 18.6 / GRU 17.5 -> GPT about 15.6 (HF GPT-2 14.8)") ''') # ------------------------------------------------------------------------------------------------ md(r"""## Segment 8 — Pre-norm vs post-norm (note §8) **What to watch:** post-norm ends every block with a layer norm, so its output is normalized; pre-norm puts the norm *inside* the branch and leaves the residual stream $x + f(\mathrm{LN}(x))$ untouched, which is why a pre-norm stack needs one final layer norm before the output layer.""") code(r'''# [Added for CS6140] PyTorch's encoder layer in both placements, on the same input (dropout off) torch.manual_seed(0) x = 3 * torch.randn(1, 5, 16) + 2 # a residual stream that is not normalized for norm_first in [False, True]: layer = nn.TransformerEncoderLayer(16, 4, 32, dropout=0.0, batch_first=True, norm_first=norm_first).eval() with torch.no_grad(): y = layer(x) name = "pre-norm x + f(LN(x))" if norm_first else "post-norm LN(x + f(x))" print(f"{name}: output per token mean {y.mean(-1)[0, :3].numpy().round(2)}, " f"std {y.std(-1, unbiased=False)[0, :3].numpy().round(2)}") print("in HW7 (reference run, 4 blocks): post-norm about 15.6 vs pre-norm about 15.4 perplexity: about equal;" " pre-norm's advantage shows in deep stacks") ''') # ------------------------------------------------------------------------------------------------ md(r"""## Segment 9 — Sampling: greedy, temperature, top-k (note §9) **What to watch:** temperature reshapes the distribution (low = sharper, high = flatter); top-$k$ keeps only the $k$ best words. Check *probabilities*, not text. Greedy is safe but tends to repeat; high temperature makes word salad.""") code(r'''# [Added for CS6140] the note's table for logits z = (2, 1, 0, -1), with Hugging Face's logits warpers from transformers import TemperatureLogitsWarper, TopKLogitsWarper z = torch.tensor([[2.0, 1.0, 0.0, -1.0]]) for name, warpers in [("tau = 1", [TemperatureLogitsWarper(1.0)]), ("tau = 0.5", [TemperatureLogitsWarper(0.5)]), ("tau = 2", [TemperatureLogitsWarper(2.0)]), ("top-2, tau = 1", [TemperatureLogitsWarper(1.0), TopKLogitsWarper(2)]), ("top-2, tau = 0.5", [TemperatureLogitsWarper(0.5), TopKLogitsWarper(2)])]: scores = z.clone() for w in warpers: scores = w(None, scores) print(f"{name:17s}", (scores.softmax(-1)[0]).numpy().round(4)) ''') code(r'''# [Added for CS6140] stories from the tiny GPT with Hugging Face's generate (same prompt, same seed) gpt.eval() prompt = lm.vocab[lm_common.tokenize("once upon a time , there was a little")] ids = torch.tensor([prompt], device=DEVICE) settings = [("greedy", dict(do_sample=False)), ("temperature 0.5", dict(do_sample=True, temperature=0.5, top_k=0)), ("temperature 1.0", dict(do_sample=True, temperature=1.0, top_k=0)), ("temperature 1.5", dict(do_sample=True, temperature=1.5, top_k=0)), ("top-10", dict(do_sample=True, temperature=1.0, top_k=10))] for name, kw in settings: torch.manual_seed(0) with torch.no_grad(): out = gpt.generate(ids, attention_mask=torch.ones_like(ids), max_new_tokens=40, **kw) print(f"--- {name}:\n{lm_common.detokenize(lm.vocab.to_tokens(out[0].tolist()))}") ''') # ------------------------------------------------------------------------------------------------ md(r"""--- # Appendix (Mon 12/14) ## Segment 10 — Three kinds of Transformer: attention patterns (note §10) **What to watch:** which positions may look at which. Encoder-only (BERT): everyone sees everyone. Decoder-only (GPT): only the past. Encoder–decoder (T5, translation): the source sees itself fully, the target sees its past, and every target position sees the whole source.""") code(r'''# [Added for CS6140] attention-pattern grids (white = may attend), a 6-token source and a 5-token target S, T = 6, 5 full, causal = torch.ones(S, S), torch.tril(torch.ones(T, T)) fig, axes = plt.subplots(1, 4, figsize=(11, 3)) for ax, (title, m, xl, yl) in zip(axes, [("encoder-only (BERT)", full, "keys", "queries"), ("decoder-only (GPT)", causal, "keys", "queries"), ("enc-dec: decoder self", causal, "target keys", "target queries"), ("enc-dec: cross", torch.ones(T, S), "source keys", "target queries")]): ax.imshow(m, cmap="gray", vmin=0, vmax=1) ax.set_title(title, fontsize=9); ax.set_xlabel(xl, fontsize=8); ax.set_ylabel(yl, fontsize=8) ax.set_xticks([]); ax.set_yticks([]) plt.tight_layout(); plt.show() ''') # ------------------------------------------------------------------------------------------------ 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": 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()