""" Builds cnn_lecture_demo.ipynb: the laptop demos for the Week 11 CNN lecture (CNN_claude_lecturePlan). Single source: md()/code() cells below. Code starts from the d2l book's own notebooks (chapters 7, 8, 14); every code cell's first line says whether it is book code, changed from the book, or added for CS6140. python3 build_cnn_lecture_demo.py # write the notebook (unexecuted) jupyter nbconvert --to notebook --execute --inplace cnn_lecture_demo.ipynb python3 build_cnn_lecture_demo.py --times # put the measured per-segment times into the intro table Leak rule (posted to students): added code uses torch.nn / torch.nn.functional / torchvision for every piece HW6 asks students to write (convolution loops, unfold, batch norm, residual block). """ import json import sys from datetime import datetime import nbformat as nbf CELLS = [] NB = "cnn_lecture_demo.ipynb" def md(src): CELLS.append(("md", src.strip("\n"))) def code(src): CELLS.append(("code", src.strip("\n"))) INTRO = r"""# CNN Lecture Demos (Week 11) Laptop demos for the CNN lecture, in the order of the lecture plan. Each segment matches a block on the lecture segment and a section of the note *Convolutional Networks: From Sliding Windows to ResNets*. The code starts from the d2l book (chapters 7, 8 and 14.1–14.2); the first line of every code cell says where it comes from: * `# [Book §x.y]`: the book's code as is; * `# [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. | Topic (note §) | Animations (press play) | Changed / added vs. the book | |---|---|---|---| | 1 | Cross-correlation, padding, stride (§2) | the window sliding over the note's 3×3 example; again with padding; again with stride; then a real 28×28 image | Added: edge detection as pictures; the kernel's two weights converging | | 2 | Channels, 1×1, convolution as one matrix product (§3) | two input channels summing into one output | Changed: multi-channel example through `F.conv2d`; Added: the patch matrix with `F.unfold` | | 3 | Pooling; small shifts (§4) | the pooling window jumping, with the surviving element ringed | Changed: `nn` pooling layers instead of the book's loop; Added: the 1-D window-boundary example | | 4 | LeNet then and now (§5) | — | Changed: 3 epochs (book: 10); Added: modern LeNet vs MLP on shifted images; the six learned kernels, and every stage's feature maps for one image | | 5 | Batch normalization (§6) | BN vs no BN *while they train* | Changed: `nn.BatchNorm` LeNet only, 3 epochs; Added: BN vs LayerNorm toy matrix; a learning-rate sweep | | 6 | Residual blocks (§7) | per-block gradient norms, plain vs residual, *while they train* | Added: the note's 16 → 32-channel, stride-2 shape walk | | 7 | Augmentation and transfer (§8) | — | Changed: CIFAR-10 images (book: a cat photo); Added: pretrained ResNet-18 linear probe on 500 images | The animations are ordinary matplotlib written out as an inline player — step, play and scrub with the buttons under each one. Each also saves a GIF into `images_claude/`.""" md(INTRO) md(r"""## Setup (run once)""") code(r'''# [Added for CS6140] device, the d2l Apple-GPU patch (as in the HW starters), and the course data folder import os, time import torch from torch import nn import torch.nn.functional as F import torchvision from torchvision.transforms import v2 from d2l import torch as d2l import matplotlib.pyplot as plt import numpy as np FIG = "images_claude"; os.makedirs(FIG, exist_ok=True) # figures written here are reused by the note 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") TORCH_DATA = f"{DATA}/torchvision" torch.hub.set_dir(f"{TORCH_DATA}/hub") d2l.DataModule.__init__.__defaults__ = (TORCH_DATA, 4) # d2l's datasets download into the course folder torch.manual_seed(0) print("device:", DEVICE, "| data:", os.path.abspath(DATA))''') # --------------------------------------------------------------------------------------------------------- md(r"""## Segment 1 — Cross-correlation, padding, stride (note §2) **What to watch:** the note's 3×3 example gives 19, 25, 37, 43; a learned kernel recovers the edge detector $[1,-1]$ from data alone; padding keeps the size, stride shrinks it.""") code(r'''# [Book §7.2] the note's 3x3 example: a 3x3 image, a 2x2 kernel (d2l.corr2d is the book's loop) X = torch.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]) K = torch.tensor([[0.0, 1.0], [2.0, 3.0]]) d2l.corr2d(X, K)''') md(r"""**The same computation, as a picture.** The cell above prints four numbers; this one shows where each of them came from. The window slides left to right, top to bottom; the tinted cells are the ones being read, the line under the grids is the dot product for that position, and the output fills in one cell at a time. Use the player's step buttons to walk it one position at a time.""") code(r"""import matplotlib.animation as animation from IPython.display import HTML def conv_frames(X, K, padding=0, stride=1): "Every window position of a cross-correlation, as (out_row, out_col, in_row, in_col, patch, value)." sh, sw = (stride, stride) if isinstance(stride, int) else stride Xp = F.pad(X[None, None], (padding,) * 4)[0, 0] if padding else X kh, kw = K.shape oh, ow = (Xp.shape[0] - kh) // sh + 1, (Xp.shape[1] - kw) // sw + 1 frames = [] for i in range(oh): for j in range(ow): r, c = i * sh, j * sw patch = Xp[r:r + kh, c:c + kw] frames.append((i, j, r, c, patch, float((patch * K).sum()))) return Xp, frames, (oh, ow) def draw_grid(a, M, title, shown=None, box=None, dim=None, star=None, fs=12): # A matrix of numbers as a grid of cells. shown: which cells have a value yet. # box: cells being read (tinted). dim: zero padding (grey). star: ring a cell in red. a.clear(); a.set_xticks([]); a.set_yticks([]); a.set_title(title, fontsize=11) H, W = M.shape a.set_xlim(-0.5, W - 0.5); a.set_ylim(H - 0.5, -0.5); a.set_aspect('equal') for r in range(H): for c in range(W): face = 'white' if dim is not None and dim[r, c]: face = '0.92' # zero padding if box is not None and box[r, c]: face = '#ffd9b3' # the window being read edge = 'crimson' if (star is not None and star[r, c]) else '0.6' lw = 2.5 if (star is not None and star[r, c]) else 1 a.add_patch(plt.Rectangle((c - .5, r - .5), 1, 1, facecolor=face, edgecolor=edge, lw=lw)) if shown is None or shown[r, c]: a.text(c, r, f'{M[r, c]:g}', ha='center', va='center', fontsize=fs) def animate_conv(X, K, padding=0, stride=1, gif=None, fps=1.2): Xp, frames, (oh, ow) = conv_frames(X, K, padding, stride) pad_mask = torch.zeros_like(Xp, dtype=torch.bool) if padding: # which cells are the zero border pad_mask[:] = True; pad_mask[padding:-padding, padding:-padding] = False fig, ax = plt.subplots(1, 3, figsize=(10.5, 3.2), gridspec_kw={'width_ratios': [Xp.shape[1], K.shape[1], ow]}) cap = fig.text(0.5, 0.02, '', ha='center', fontsize=12, family='monospace') def draw(t): i, j, r, c, patch, val = frames[t] box = torch.zeros_like(Xp, dtype=torch.bool); box[r:r + K.shape[0], c:c + K.shape[1]] = True draw_grid(ax[0], Xp, 'input' + (' (zero-padded)' if padding else ''), box=box, dim=pad_mask) draw_grid(ax[1], K, 'kernel') O = torch.zeros((oh, ow)); shown = torch.zeros((oh, ow), dtype=torch.bool) for k in range(t + 1): O[frames[k][0], frames[k][1]] = frames[k][5]; shown[frames[k][0], frames[k][1]] = True hl = torch.zeros((oh, ow), dtype=torch.bool); hl[i, j] = True draw_grid(ax[2], O, 'output', shown=shown, box=hl) terms = ' + '.join(f'{float(x):g}*{float(k_):g}' for x, k_ in zip(patch.flatten(), K.flatten())) cap.set_text(f'output[{i},{j}] = {terms} = {val:g}') return ax anim = animation.FuncAnimation(fig, draw, frames=len(frames), interval=1000 / fps, blit=False) html = anim.to_jshtml(fps=fps) # the inline player (step / play / scrub) if gif: anim.save(f'{FIG}/{gif}', writer='pillow', fps=fps, dpi=110) # a copy for the notes plt.close(fig) print(f'{len(frames)} window positions -> {oh}x{ow} output') return HTML(html) X = torch.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]) K = torch.tensor([[0.0, 1.0], [2.0, 3.0]]) animate_conv(X, K, gif='conv_slide.gif')""") md(r"""**Padding and stride, in the same picture.** Padding adds the grey zero border, so the window can also sit over the corners and the output comes back up to 4x4. Stride makes the window *jump* rather than step, so most positions are never visited at all --- compare the printed number of window positions in each.""") code(r"""animate_conv(X, K, padding=1, gif='conv_slide_pad.gif')""") code(r"""animate_conv(X, K, padding=1, stride=(3, 2), gif='conv_slide_stride.gif')""") md(r"""**Now the same sweep on a real image.** The toy grid shows the arithmetic; this shows what the arithmetic is *for*. A 3x3 vertical-edge kernel sweeps a 28x28 Fashion-MNIST image and the response map builds up behind it, row by row. Watch the output go bright exactly as the window crosses the boot's outline, and stay flat while it is inside a smooth region --- a convolution is a *search for one pattern, everywhere at once*, and this is that search happening.""") code(r"""def animate_conv_image(img, K, step=8, gif=None, fps=12): # Sweep K over img, revealing the response map as it goes. step: show every step-th position. H, W = img.shape; kh, kw = K.shape full = F.conv2d(img[None, None], K[None, None])[0, 0] # the finished map, revealed gradually oh, ow = full.shape pos = [(i, j) for i in range(oh) for j in range(ow)][::step] fig, ax = plt.subplots(1, 3, figsize=(10.5, 3.6)) vmax = full.abs().max() def draw(t): i, j = pos[t] for a in ax: a.clear(); a.set_xticks([]); a.set_yticks([]) ax[0].imshow(img, cmap='gray'); ax[0].set_title('input, with the window', fontsize=11) ax[0].add_patch(plt.Rectangle((j - .5, i - .5), kw, kh, fill=False, edgecolor='crimson', lw=2)) ax[1].imshow(K, cmap='bwr', vmin=-K.abs().max(), vmax=K.abs().max()) ax[1].set_title('kernel: vertical edges', fontsize=11) seen = torch.full_like(full, float('nan')) # not-yet-computed stays blank flat = t * step + 1 seen.view(-1)[:flat] = full.view(-1)[:flat] ax[2].imshow(seen, cmap='bwr', vmin=-vmax, vmax=vmax) ax[2].set_title(f'response map, {flat}/{oh * ow} positions done', fontsize=11) return ax anim = animation.FuncAnimation(fig, draw, frames=len(pos), interval=1000 / fps, blit=False) html = anim.to_jshtml(fps=fps) if gif: anim.save(f'{FIG}/{gif}', writer='pillow', fps=fps, dpi=100) plt.close(fig) return HTML(html) _img = torchvision.datasets.FashionMNIST(root=TORCH_DATA, train=False, download=True).data[0].float() / 255 Kv = torch.tensor([[1.0, 0.0, -1.0], [2.0, 0.0, -2.0], [1.0, 0.0, -1.0]]) # Sobel, vertical edges animate_conv_image(_img, Kv, step=8, gif='conv_image.gif')""") code(r'''# [Book §7.2] edge detection: a 6x8 image, black columns 2-5; the kernel [1, -1] marks the two edges X = torch.ones((6, 8)) X[:, 2:6] = 0 K = torch.tensor([[1.0, -1.0]]) Y = d2l.corr2d(X, K) print(X); print(Y) print("transposed image (horizontal edges only):", d2l.corr2d(X.t(), K).abs().sum().item())''') code(r"""# [Added for CS6140] the same tensors as pictures: the kernel fires only at the two edges, # and only on the orientation it was built for fig, ax = plt.subplots(1, 3, figsize=(11, 2.6)) ax[0].imshow(X, cmap='gray', vmin=-1, vmax=1); ax[0].set_title('input: a white/black/white band', fontsize=10) ax[1].imshow(K, cmap='bwr', vmin=-1, vmax=1); ax[1].set_title('kernel [1, -1]', fontsize=10) ax[2].imshow(Y, cmap='bwr', vmin=-1, vmax=1) # signed: red = +1, blue = -1 ax[2].set_title('output: +1 at the left edge, -1 at the right, 0 elsewhere', fontsize=10) for a in ax: a.set_xticks([]); a.set_yticks([]) plt.tight_layout(); plt.savefig(f'{FIG}/edge_detect.png', dpi=130, bbox_inches='tight'); plt.show() fig, ax = plt.subplots(1, 2, figsize=(7.4, 2.6)) ax[0].imshow(d2l.corr2d(X, K), cmap='bwr', vmin=-1, vmax=1) ax[0].set_title('vertical edges: found', fontsize=10) ax[1].imshow(d2l.corr2d(X.t(), K), cmap='bwr', vmin=-1, vmax=1) ax[1].set_title('same kernel, image transposed: nothing', fontsize=10) for a in ax: a.set_xticks([]); a.set_yticks([]) plt.tight_layout(); plt.savefig(f'{FIG}/edge_orientation.png', dpi=130, bbox_inches='tight'); plt.show()""") code(r'''# [Book §7.2] learning the kernel from (X, Y) pairs: 10 gradient steps recover about [1, -1] conv2d = nn.LazyConv2d(1, kernel_size=(1, 2), bias=False) X4, Y4 = X.reshape((1, 1, 6, 8)), Y.reshape((1, 1, 6, 7)) lr = 3e-2 for i in range(10): l = (conv2d(X4) - Y4) ** 2 conv2d.zero_grad() l.sum().backward() conv2d.weight.data[:] -= lr * conv2d.weight.grad if (i + 1) % 2 == 0: print(f"epoch {i + 1}, loss {l.sum():.3f}") print("learned kernel:", conv2d.weight.data.reshape((1, 2)))''') code(r"""# [Added for CS6140] the same 10 steps, drawn: the two weights walking to +1 and -1 conv2d = nn.LazyConv2d(1, kernel_size=(1, 2), bias=False); conv2d(X4) hist = [] for i in range(10): l = ((conv2d(X4) - Y4) ** 2).sum() conv2d.zero_grad(); l.backward(); conv2d.weight.data[:] -= 3e-2 * conv2d.weight.grad hist.append(conv2d.weight.data.reshape(2).tolist() + [l.item()]) hist = np.array(hist) fig, ax = plt.subplots(1, 2, figsize=(9, 2.8)) ax[0].plot(range(1, 11), hist[:, 0], 'o-', label='w1'); ax[0].plot(range(1, 11), hist[:, 1], 'o-', label='w2') ax[0].axhline(1, color='0.6', ls='--'); ax[0].axhline(-1, color='0.6', ls='--') ax[0].set_xlabel('gradient step'); ax[0].set_title('the two kernel weights', fontsize=10); ax[0].legend(fontsize=9) ax[1].plot(range(1, 11), hist[:, 2], 'o-', color='C3'); ax[1].set_xlabel('gradient step') ax[1].set_title('squared error', fontsize=10); ax[1].set_yscale('log') plt.tight_layout(); plt.savefig(f'{FIG}/kernel_learning.png', dpi=130, bbox_inches='tight'); plt.show() print('nobody told it to look for an edge -- [1, -1] is what fits the data')""") code(r'''# [Book §7.3] padding and stride: output shapes for an 8x8 input def comp_conv2d(conv2d, X): X = X.reshape((1, 1) + X.shape) Y = conv2d(X) return Y.reshape(Y.shape[2:]) X = torch.rand(size=(8, 8)) for kw in [dict(kernel_size=3, padding=1), dict(kernel_size=(5, 3), padding=(2, 1)), dict(kernel_size=3, padding=1, stride=2), dict(kernel_size=(3, 5), padding=(0, 1), stride=(3, 4))]: print(kw, "->", tuple(comp_conv2d(nn.LazyConv2d(1, **kw), X).shape))''') code(r'''# [Added for CS6140] the padded and strided versions of the 3x3 example (note §2 numbers) X = torch.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]).reshape(1, 1, 3, 3) K = torch.tensor([[0.0, 1.0], [2.0, 3.0]]).reshape(1, 1, 2, 2) print("padding 1:\n", F.conv2d(X, K, padding=1)[0, 0]) print("padding 1, stride (3, 2):\n", F.conv2d(X, K, padding=1, stride=(3, 2))[0, 0])''') # --------------------------------------------------------------------------------------------------------- md(r"""## Segment 2 — Channels, 1×1 convolutions, convolution as one matrix product (note §3) **What to watch:** two input channels add up (56, 72, 104, 120); a 1×1 convolution is a dense layer on the channels at every pixel; unfolding the patches turns the whole convolution into one matrix product.""") code(r'''# [Changed from book §7.4] the book's two-channel example, computed with PyTorch's F.conv2d instead of # the book's loop (weight layout (c_out, c_in, k_h, k_w)) X = torch.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]], [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]]) K = torch.tensor([[[0.0, 1.0], [2.0, 3.0]], [[1.0, 2.0], [3.0, 4.0]]]) print("2 in, 1 out:\n", F.conv2d(X[None], K[None])[0, 0]) K3 = torch.stack((K, K + 1, K + 2), 0) # 3 output channels print("2 in, 3 out: shape", tuple(F.conv2d(X[None], K3)[0].shape))''') code(r'''# [Book §7.4] a 1x1 convolution = a matrix product over the channels at each pixel X = torch.normal(0, 1, (3, 3, 3)) K = torch.normal(0, 1, (2, 3, 1, 1)) Y1 = (K.reshape(2, 3) @ X.reshape(3, 9)).reshape(2, 3, 3) Y2 = F.conv2d(X[None], K)[0] print("max difference:", (Y1 - Y2).abs().max().item())''') md(r"""**Channels, in action.** With two input channels there are two kernels, and the single output cell is the sum of *both* dot products --- the channels are added, not kept apart. Watch the two windows move in lockstep and the running total at the bottom: both halves land in one number, which is why a convolution layer with 6 output channels and 3 input channels holds 18 kernels but produces only 6 maps.""") code(r"""def animate_conv_channels(X, K, gif=None, fps=1.0): # X: (C, H, W), K: (C, kh, kw). One output = sum over channels of each channel's dot product. C, H, W = X.shape; kh, kw = K.shape[1:] oh, ow = H - kh + 1, W - kw + 1 out = sum(F.conv2d(X[c][None, None], K[c][None, None])[0, 0] for c in range(C)) pos = [(i, j) for i in range(oh) for j in range(ow)] fig, ax = plt.subplots(1, 2 * C + 1, figsize=(3.1 * C + 3.2, 3.0)) cap = fig.text(0.5, 0.01, '', ha='center', fontsize=11.5, family='monospace') def draw(t): i, j = pos[t] parts = [] for c in range(C): box = torch.zeros((H, W), dtype=torch.bool); box[i:i + kh, j:j + kw] = True draw_grid(ax[2 * c], X[c], f'input channel {c}', box=box, fs=11) draw_grid(ax[2 * c + 1], K[c], f'kernel {c}', fs=11) parts.append(float((X[c][i:i + kh, j:j + kw] * K[c]).sum())) O = torch.zeros((oh, ow)); shown = torch.zeros((oh, ow), dtype=torch.bool) for k in range(t + 1): O[pos[k][0], pos[k][1]] = out[pos[k][0], pos[k][1]]; shown[pos[k][0], pos[k][1]] = True hl = torch.zeros((oh, ow), dtype=torch.bool); hl[i, j] = True draw_grid(ax[-1], O, 'one output', shown=shown, box=hl, fs=11) cap.set_text(' + '.join(f'ch{c}: {p:g}' for c, p in enumerate(parts)) + f' = {sum(parts):g}') return ax anim = animation.FuncAnimation(fig, draw, frames=len(pos), interval=1000 / fps, blit=False) html = anim.to_jshtml(fps=fps) if gif: anim.save(f'{FIG}/{gif}', writer='pillow', fps=fps, dpi=110) plt.close(fig) return HTML(html) Xc = torch.tensor([[[0.0, 1, 2], [3, 4, 5], [6, 7, 8]], [[1.0, 2, 3], [4, 5, 6], [7, 8, 9]]]) Kc = torch.tensor([[[0.0, 1], [2, 3]], [[1.0, 2], [3, 4]]]) animate_conv_channels(Xc, Kc, gif='conv_channels.gif')""") code(r'''# [Added for CS6140] convolution as ONE matrix product: PyTorch's F.unfold lists every 2x2 patch as a # column; the 3x3 example has 4 patches, and kernel x patches = 19, 25, 37, 43 X = torch.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]).reshape(1, 1, 3, 3) K = torch.tensor([[0.0, 1.0], [2.0, 3.0]]) patches = F.unfold(X, kernel_size=2)[0] # (c*k_h*k_w, number of patches) = (4, 4) print("patch matrix (one patch per column):\n", patches) print("kernel row x patches:", K.reshape(1, -1) @ patches)''') # --------------------------------------------------------------------------------------------------------- md(r"""## Segment 3 — Pooling: shrink, and forgive small moves (note §4) **What to watch:** max and average pooling on the 3×3 example; a 1-pixel move *inside* a pooling window disappears, a move *across* a window boundary does not.""") code(r'''# [Changed from book §7.5] max and average pooling on the 3x3 example with nn.MaxPool2d / nn.AvgPool2d # (instead of the book's loop pool2d); then PyTorch's default stride = window size X = torch.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]).reshape(1, 1, 3, 3) print("max:\n", nn.MaxPool2d(2, stride=1)(X)[0, 0]) print("average:\n", nn.AvgPool2d(2, stride=1)(X)[0, 0]) X16 = torch.arange(16, dtype=torch.float32).reshape((1, 1, 4, 4)) print("nn.MaxPool2d(3) on 4x4 (stride = window by default):", nn.MaxPool2d(3)(X16)[0, 0]) print("nn.MaxPool2d(3, padding=1, stride=2):\n", nn.MaxPool2d(3, padding=1, stride=2)(X16)[0, 0])''') md(r"""**Shrinking, in action.** Pooling has no weights and nothing to learn --- it only moves a window and keeps one number per position. Watch two things: the window **jumps** by its own width (stride = size), so unlike the convolutions above the positions never overlap, and the red ring marks the element that won. Only that one number survives; everything else in the window is discarded, which is both why the map shrinks and why a small shift of the input often changes nothing.""") code(r"""def animate_pool(X, size=2, stride=None, mode='max', gif=None, fps=1.2): stride = stride or size H, W = X.shape oh, ow = (H - size) // stride + 1, (W - size) // stride + 1 pos = [(i, j) for i in range(oh) for j in range(ow)] fig, ax = plt.subplots(1, 2, figsize=(7.6, 3.4), gridspec_kw={'width_ratios': [W, ow]}) cap = fig.text(0.5, 0.02, '', ha='center', fontsize=11.5, family='monospace') def draw(t): i, j = pos[t]; r, c = i * stride, j * stride patch = X[r:r + size, c:c + size] box = torch.zeros((H, W), dtype=torch.bool); box[r:r + size, c:c + size] = True star = torch.zeros((H, W), dtype=torch.bool) if mode == 'max': # ring the element that survives m = (patch == patch.max()).nonzero()[0] star[r + m[0], c + m[1]] = True draw_grid(ax[0], X, f'input ({mode} pool {size}x{size}, stride {stride})', box=box, star=star) O = torch.zeros((oh, ow)); shown = torch.zeros((oh, ow), dtype=torch.bool) for k in range(t + 1): p = X[pos[k][0] * stride:pos[k][0] * stride + size, pos[k][1] * stride:pos[k][1] * stride + size] O[pos[k]] = p.max() if mode == 'max' else p.mean(); shown[pos[k]] = True hl = torch.zeros((oh, ow), dtype=torch.bool); hl[i, j] = True draw_grid(ax[1], O, 'output', shown=shown, box=hl) kept = patch.max() if mode == 'max' else patch.mean() cap.set_text(f'window {[round(float(v), 1) for v in patch.flatten()]} -> keeps {float(kept):g}') return ax anim = animation.FuncAnimation(fig, draw, frames=len(pos), interval=1000 / fps, blit=False) html = anim.to_jshtml(fps=fps) if gif: anim.save(f'{FIG}/{gif}', writer='pillow', fps=fps, dpi=110) plt.close(fig) print(f'{H}x{W} -> {oh}x{ow}: {H * W - oh * ow} of {H * W} numbers thrown away') return HTML(html) Xp4 = torch.tensor([[1.0, 3, 2, 4], [5, 6, 1, 2], [7, 2, 9, 1], [0, 8, 3, 4]]) animate_pool(Xp4, size=2, mode='max', gif='pool_slide.gif')""") code(r'''# [Added for CS6140] the note's 1-D example: an edge response at position 2, 3, 4, max-pooled (window 2, stride 2) for pos in [2, 3, 4]: r = torch.zeros(1, 1, 8) r[0, 0, pos] = 1 print(f"edge at {pos}: response {r[0, 0].int().tolist()} max-pooled {F.max_pool1d(r, 2)[0, 0].int().tolist()}")''') # --------------------------------------------------------------------------------------------------------- md(r"""## Segment 4 — LeNet, then and now (note §5) **What to watch:** LeNet's layer shapes and 61,706 parameters; the 1998 version (sigmoid, average pooling) learns slowly; with ReLU and max pooling it learns fast and holds up much better than an MLP when the images move by a couple of pixels.""") code(r'''# [Book §7.6] LeNet-5 (d2l.LeNet: sigmoid + average pooling) and its layer shapes model = d2l.LeNet() model.layer_summary((1, 1, 28, 28)) print("parameters:", sum(p.numel() for p in model.parameters()))''') code(r'''# [Changed from book §7.6] train the 1998 LeNet: 3 epochs instead of 10 data = d2l.FashionMNIST(batch_size=128) trainer = d2l.Trainer(max_epochs=3, num_gpus=1) model = d2l.LeNet(lr=0.1) model.apply_init([next(iter(data.get_dataloader(True)))[0]], d2l.init_cnn) t0 = time.time(); trainer.fit(model, data); print(f"{time.time() - t0:.0f} s")''') code(r'''# [Added for CS6140] modern LeNet (ReLU + max pooling) vs an MLP, both trained 2 epochs with Adam, then tested # on images shifted right by 0-4 pixels (HW6 P1(C)'s experiment, small) def load(train): ds = torchvision.datasets.FashionMNIST(root=TORCH_DATA, train=train, download=True) return ds.data.float().div(255).unsqueeze(1), ds.targets Xtr, ytr = load(True); Xte, yte = load(False) mlp = nn.Sequential(nn.Flatten(), nn.Linear(784, 256), nn.ReLU(), nn.Linear(256, 10)) lenet = d2l.LeNet().net # the book's LeNet, modernized: sigmoid -> ReLU, average -> max pooling for i, m in enumerate(lenet): if isinstance(m, nn.Sigmoid): lenet[i] = nn.ReLU() elif isinstance(m, nn.AvgPool2d): lenet[i] = nn.MaxPool2d(kernel_size=2, stride=2) lenet(torch.zeros(1, 1, 28, 28)) # materialize the lazy layers def fit(net, epochs=2): net.to(DEVICE) opt = torch.optim.Adam(net.parameters(), lr=1e-3) for _ in range(epochs): perm = torch.randperm(len(Xtr)) for i in range(0, len(Xtr), 128): idx = perm[i:i + 128] loss = F.cross_entropy(net(Xtr[idx].to(DEVICE)), ytr[idx].to(DEVICE)) opt.zero_grad(); loss.backward(); opt.step() return net.eval() def shifted(X, s): # move right by s pixels, fill with background (0) return X if s == 0 else F.pad(X, (s, 0))[..., :, :-s] @torch.no_grad() def acc(net, X): return (net(X.to(DEVICE)).argmax(1).cpu() == yte).float().mean().item() t0 = time.time() fit(mlp); fit(lenet) print(f"trained in {time.time() - t0:.0f} s | parameters: MLP {sum(p.numel() for p in mlp.parameters()):,}, " f"LeNet {sum(p.numel() for p in lenet.parameters()):,}") print("shift (px): " + " ".join(f"{s:5d}" for s in range(5))) for name, net in [("MLP", mlp), ("LeNet", lenet)]: print(f"{name:12s} " + " ".join(f"{acc(net, shifted(Xte, s)):.3f}" for s in range(5)))''') md(r"""**What the network actually computed.** Every number above is an accuracy; none of it shows what the layers *do*. The next two cells open the trained LeNet up on a single test image: first the six first-layer kernels next to the six feature maps each one produced, then every stage in order. This is the same thing [CNN Explainer](https://poloclub.github.io/cnn-explainer/) shows for its own network --- here it is for the one you just trained. **What to look for --- and what not to expect.** The top row will *not* show the textbook picture of clean oriented edge detectors. Those come from much larger first layers trained far longer; after two epochs on 28x28 images these 5x5 kernels still look like structured speckle, and saying otherwise would be selling a picture the figure does not contain. What *is* legible is their **effect**: each map responds to a different aspect of the same boot --- one emphasises the sole, another the upper outline, another responds almost everywhere --- and no two are alike. Nothing instructed them to divide the work up that way. Then follow the shapes down the stack: the maps get **smaller** (pooling) and **more numerous** (channels), until 28x28 pixels have become 16 maps of 5x5 --- which is the whole design, visible in one figure. By the last conv stage a map is no longer anything you can recognise; it is a response to a pattern of patterns, which is why nobody reads deep feature maps directly.""") code(r"""# [Added for CS6140] the six learned first-layer kernels, each next to the feature map it produces img = Xte[0:1].to(DEVICE) # one test image conv1 = lenet[0] # Conv2d(1, 6, kernel_size=5, padding=2) with torch.no_grad(): maps1 = conv1(img)[0].cpu() # 6 x 28 x 28 W1 = conv1.weight.detach().cpu()[:, 0] # 6 x 5 x 5 fig, ax = plt.subplots(2, 7, figsize=(13, 4.8), gridspec_kw={'height_ratios': [1, 1.25], 'hspace': 0.35}) ax[0, 0].imshow(img[0, 0].cpu(), cmap='gray'); ax[0, 0].set_title('input', fontsize=10) ax[1, 0].axis('off') for k in range(6): ax[0, k + 1].imshow(W1[k], cmap='bwr', vmin=-W1.abs().max(), vmax=W1.abs().max()) ax[0, k + 1].set_title(f'kernel {k}', fontsize=9) ax[1, k + 1].imshow(maps1[k], cmap='viridis') ax[1, k + 1].set_title(f'-> map {k}', fontsize=9) for a in ax.ravel(): a.set_xticks([]); a.set_yticks([]) fig.suptitle('Top: the 5x5 kernels the network learned. Bottom: where each one fires on this image.', fontsize=11) plt.tight_layout(); plt.savefig(f'{FIG}/lenet_kernels.png', dpi=130, bbox_inches='tight'); plt.show()""") code(r"""# [Added for CS6140] every stage of the trained LeNet on the same image, via forward hooks acts, handles = [], [] for m in lenet: if isinstance(m, (nn.Conv2d, nn.MaxPool2d, nn.AvgPool2d)): handles.append(m.register_forward_hook( lambda mod, inp, out, _m=m: acts.append((type(_m).__name__, out.detach()[0].cpu())))) with torch.no_grad(): logits = lenet(img) for h in handles: h.remove() # hooks off again n_rows = len(acts) + 1 show = min(8, max(a[1].shape[0] for a in acts)) # at most 8 channels per row fig, ax = plt.subplots(n_rows, show, figsize=(1.35 * show, 1.5 * n_rows)) ax[0, 0].imshow(img[0, 0].cpu(), cmap='gray') ax[0, 0].set_ylabel(f'input\n1 x 28 x 28', fontsize=8.5, rotation=0, ha='right', va='center') for c in range(show): ax[0, c].set_xticks([]); ax[0, c].set_yticks([]) for c in range(1, show): ax[0, c].axis('off') for r, (name, A) in enumerate(acts, start=1): ax[r, 0].set_ylabel(f'{name}\n{tuple(A.shape)}', fontsize=8.5, rotation=0, ha='right', va='center') for c in range(show): ax[r, c].set_xticks([]); ax[r, c].set_yticks([]) if c < A.shape[0]: ax[r, c].imshow(A[c], cmap='viridis') else: ax[r, c].axis('off') fig.suptitle(f'One image through the trained LeNet (first {show} channels of each stage). ' f'Predicted class: {logits.argmax(1).item()}, true: {yte[0].item()}', fontsize=11) plt.tight_layout(); plt.savefig(f'{FIG}/lenet_stages.png', dpi=130, bbox_inches='tight'); plt.show() print('shapes down the stack:', ' -> '.join(str(tuple(A.shape)) for _, A in acts))""") # --------------------------------------------------------------------------------------------------------- md(r"""## Segment 5 — Batch normalization (note §6) **What to watch:** with batch norm the same sigmoid LeNet learns much faster (compare the first epoch with Segment 4). The toy matrix: batch norm makes every *column* the same, layer norm every *row*.""") code(r'''# [Changed from book §8.5] the book's BNLeNet (PyTorch's nn.LazyBatchNorm layers), 3 epochs instead of 10 class BNLeNet(d2l.Classifier): def __init__(self, lr=0.1, num_classes=10): super().__init__() self.save_hyperparameters() self.net = nn.Sequential( nn.LazyConv2d(6, kernel_size=5), nn.LazyBatchNorm2d(), nn.Sigmoid(), nn.AvgPool2d(kernel_size=2, stride=2), nn.LazyConv2d(16, kernel_size=5), nn.LazyBatchNorm2d(), nn.Sigmoid(), nn.AvgPool2d(kernel_size=2, stride=2), nn.Flatten(), nn.LazyLinear(120), nn.LazyBatchNorm1d(), nn.Sigmoid(), nn.LazyLinear(84), nn.LazyBatchNorm1d(), nn.Sigmoid(), nn.LazyLinear(num_classes)) trainer = d2l.Trainer(max_epochs=3, num_gpus=1) model = BNLeNet(lr=0.1) model.apply_init([next(iter(data.get_dataloader(True)))[0]], d2l.init_cnn) t0 = time.time(); trainer.fit(model, data); print(f"{time.time() - t0:.0f} s")''') code(r'''# [Added for CS6140] the note's toy matrix: BatchNorm normalizes each column (over the batch), LayerNorm each # row (over the features); and what one training step does to the running statistics x = torch.tensor([[1., 2., 3., 4., 5.], [10., 20., 30., 40., 50.], [7., 14., 21., 28., 35.]]) bn, ln = nn.BatchNorm1d(5), nn.LayerNorm(5) torch.set_printoptions(precision=3, sci_mode=False) print("BatchNorm (train mode):\n", bn(x).detach()) print("LayerNorm:\n", ln(x).detach()) print("running_mean after one step:", bn.running_mean) print("running_var[0] after one step:", bn.running_var[0].item(), "(0.9 * 1 + 0.1 * unbiased variance 21)")''') # --------------------------------------------------------------------------------------------------------- md(r"""**BatchNorm vs. no BatchNorm, while it trains.** Two identical networks, one with BN after each convolution and one without, trained on the same batches. Every 10 steps we freeze both and look at **what the next layer actually receives** --- the input to the second ReLU, which is the raw conv output in one net and the normalized one in the other. Press play. **What to look for.** Both start as a narrow spike, because neither has learned anything yet. Then they diverge, and not in width --- in *shape*. The plain net's histogram stays a **tall spike at zero with thin tails**: about a third of its values sit at $\approx 0$ at the start and are still sitting there at the end, so that share of the layer never starts carrying information. The BN net's **spreads out and fills the range**, and its near-zero share falls from roughly a third to under a tenth. Watch the printed fraction of near-zero values, which is the number the picture is really about; the standard deviations actually understate the gap, because the plain net's spread is carried by a few rare large values rather than by its bulk. This is a case where the histogram says more than the summary statistic does. **Two things this figure does *not* say.** BN does not pin its output to $\mathcal N(0,1)$: it standardizes using batch statistics and then applies a **learned** scale and shift ($\gamma$, $\beta$), so the network still chooses the final scale --- here it ends wider than the plain net, not narrower. What BN removes is not the scale, but the scale's *dependence on the layers underneath*. And BN is not unconditionally better: the learning-rate table below includes a setting where this BN network collapses to chance while the plain one is still training.""") code(r"""def make_cnn(bn): L = [nn.Conv2d(1, 16, 3, padding=1)] if bn: L.append(nn.BatchNorm2d(16)) L += [nn.ReLU(), nn.Conv2d(16, 16, 3, padding=1)] if bn: L.append(nn.BatchNorm2d(16)) tap = len(L) - 1 # watch what the NEXT layer gets: after BN where there is one L += [nn.ReLU(), nn.MaxPool2d(2), nn.Flatten(), nn.Linear(16 * 14 * 14, 10)] return nn.Sequential(*L), tap def run_bn(bn, steps=300, lr=0.05, B=128, every=None, seed=0): torch.manual_seed(seed); net, tap = make_cnn(bn); net.to(DEVICE) opt = torch.optim.SGD(net.parameters(), lr=lr) probe = Xtr[:256].to(DEVICE) torch.manual_seed(seed) # identical batches for both nets losses, snaps = [], [] for t in range(steps): i = torch.randint(0, len(Xtr), (B,)) loss = F.cross_entropy(net(Xtr[i].to(DEVICE)), ytr[i].to(DEVICE)) opt.zero_grad(); loss.backward(); opt.step(); losses.append(loss.item()) if every and (t % every == 0 or t == steps - 1): net.eval() with torch.no_grad(): h = nn.Sequential(*list(net)[:tap + 1])(probe) snaps.append((t, h.flatten().cpu().numpy())); net.train() return np.array(losses), snaps loss_no, snap_no = run_bn(False, every=10) loss_bn, snap_bn = run_bn(True, every=10) dead = lambda v: (np.abs(v) < 0.05).mean() # how much of the layer sits at ~0 print(f"at lr = 0.05 -- final loss: no BN {loss_no[-20:].mean():.3f}, with BN {loss_bn[-20:].mean():.3f}") print(f"{'':14s}{'std 0 -> end':>18s}{'near-zero 0 -> end':>24s}") for k, sn in (('no BN', snap_no), ('with BN', snap_bn)): print(f"{k:14s}{sn[0][1].std():8.2f} ->{sn[-1][1].std():6.2f}" f"{dead(sn[0][1]):18.0%} ->{dead(sn[-1][1]):6.0%}")""") code(r"""# How much does the learning rate matter, with and without BN? (the actual claim, measured) print(f"{'lr':>6} {'no BN':>9} {'with BN':>9}") for lr in (0.02, 0.05, 0.1, 0.25): a = run_bn(False, steps=300, lr=lr)[0][-20:].mean() b = run_bn(True, steps=300, lr=lr)[0][-20:].mean() print(f"{lr:6} {a:9.3f} {b:9.3f}" + (' <- BN collapsed to chance' if b > 2.2 else '')) print("\nln(10) = 2.303 is the loss of random guessing on 10 classes.") print("BN's column is nearly flat; the plain net's depends strongly on getting the rate right.") print("That -- one fewer thing to tune -- is the practical benefit here, not a magic speedup.") print("\nOptimizer: plain SGD. HW6 P1(D) runs the same comparison with AdamW at lr 1e-3 vs 3e-2") print("(the note's '30x larger learning rate'), where BN holds up at the larger rate. Adam rescales") print("each gradient by its own running size, so the two tables are not on the same scale.")""") code(r"""fig, ax = plt.subplots(1, 3, figsize=(13, 3.6)) allv = np.concatenate([s[1] for s in snap_no] + [s[1] for s in snap_bn]) lim = np.percentile(np.abs(allv), 99.5) bins = np.linspace(-lim, lim, 60) S = {'no BN': (snap_no, loss_no, 'C0'), 'with BN': (snap_bn, loss_bn, 'C2')} sm = {k: np.convolve(v[1], np.ones(10) / 10, 'valid') for k, v in S.items()} def draw(t): for a, (k, (snaps, _, col)) in zip(ax[:2], S.items()): step, vals = snaps[t] a.clear(); a.hist(vals, bins=bins, color=col) a.set_title(f'{k}: input to the next layer, step {step}\n(std = {vals.std():.2f})', fontsize=10) a.set_xlim(-lim, lim); a.set_yticks([]) ax[2].clear() for k, (_, _, col) in S.items(): ax[2].plot(sm[k], color=col, alpha=.25) n = min(snap_no[t][0], len(sm[k])) ax[2].plot(range(n), sm[k][:n], color=col, lw=2, label=k) ax[2].set_title('training loss (lr = 0.05)', fontsize=10); ax[2].set_xlabel('step'); ax[2].legend(fontsize=9) return ax anim = animation.FuncAnimation(fig, draw, frames=len(snap_no), interval=400, blit=False) html = anim.to_jshtml(fps=2.5); anim.save(f'{FIG}/bn_training.gif', writer='pillow', fps=2.5, dpi=100) plt.close(fig); HTML(html)""") md(r"""## Segment 6 — Going deeper: residual blocks (note §7) **What to watch:** the block keeps the shape, or halves the size and changes the channels when the shortcut gets a 1×1 convolution.""") code(r'''# [Book §8.6] the book's residual block (d2l.Residual): same shape, then halved size + new channels via 1x1 blk = d2l.Residual(3) X = torch.randn(4, 3, 6, 6) print(blk(X).shape) blk = d2l.Residual(6, use_1x1conv=True, strides=2) print(blk(X).shape)''') code(r'''# [Added for CS6140] the note's shape walk: 16 -> 32 channels, stride 2, on 32x32 feature maps blk = d2l.Residual(32, use_1x1conv=True, strides=2) X = torch.randn(8, 16, 32, 32) print("main path conv1:", tuple(blk.conv1(X).shape), "| shortcut 1x1:", tuple(blk.conv3(X).shape), "| block output:", tuple(blk(X).shape))''') # --------------------------------------------------------------------------------------------------------- md(r"""**Skip connections vs. none, while it trains.** A deliberately deep, deliberately plain stack --- 20 convolution layers, no normalization --- against the same stack with one skip connection added around every pair. Every snapshot we record the **gradient norm reaching each layer**, which is the quantity the chain rule multiplies down the stack. Press play and watch the bars. **What to look for.** The y-axis is logarithmic, and it needs to be: in the plain stack the gradient reaching the *first* block is around $10^{-12}$ while the last block gets about $10^{-3}$ --- a factor of roughly a **billion** across twenty layers. The early layers are receiving nothing, so they never move, and the loss sits at 2.303 = $\ln 10$, which is exactly the loss of guessing at random. With skips the same profile spans a factor of about 5, and the loss actually comes down. The mechanism is just the chain rule. A plain block contributes a Jacobian factor to the product; twenty of them multiply, and if the typical factor is below 1 the product collapses. A residual block computes $x + f(x)$, so its derivative is $1 + f'(x)$ --- the $1$ is a path along which the gradient arrives **undiminished**, no matter how many blocks sit above it. The bars are that $1$, made visible. *Honest scale note:* this is 150 steps on a deliberately handicapped network (20 layers, no normalization, no careful initialization), chosen so the effect is unmistakable. The residual net here is learning, but slowly --- the point of the figure is the gradient profile, not the final accuracy. *And note this is **not** optional Problem 7's experiment.* Problem 7 asks you to keep batch norm in **both** networks, which keeps the gradients healthy on both sides and so isolates what the shortcuts do on their own --- the **degradation** problem, where the deeper plain network trains worse even though nothing is vanishing. This cell removes normalization precisely so that something *does* vanish, because that is the easier effect to see first. Expect Problem 7's gap to be real but far smaller than the billion-fold spread above; if it is, you have done it right. CNN\_ADVANCED \S"Plain vs Residual Networks at Depth" sets it out.""") code(r"""def deep_stack(residual, depth=20, ch=8): # A plain chain of 3x3 convs, or the same chain with x + f(x) around every pair. class Block(nn.Module): def __init__(self): super().__init__() self.f = nn.Sequential(nn.Conv2d(ch, ch, 3, padding=1), nn.ReLU(), nn.Conv2d(ch, ch, 3, padding=1)) def forward(self, x): return F.relu(x + self.f(x)) if residual else F.relu(self.f(x)) return nn.Sequential(nn.Conv2d(1, ch, 3, padding=1), nn.ReLU(), *[Block() for _ in range(depth // 2)], nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(ch, 10)) def grad_profile(steps=150, every=10, lr=0.05, B=128, seed=0): torch.manual_seed(seed); nets = {'plain': deep_stack(False), 'residual': deep_stack(True)} opts = {k: torch.optim.SGD(n.parameters(), lr=lr) for k, n in nets.items()} for n in nets.values(): n.to(DEVICE) snaps, losses = [], {k: [] for k in nets} for t in range(steps): idx = torch.randint(0, len(Xtr), (B,)) xb, yb = Xtr[idx].to(DEVICE), ytr[idx].to(DEVICE) shot = {} for k, n in nets.items(): loss = F.cross_entropy(n(xb), yb) opts[k].zero_grad(); loss.backward() # one number per block: the norm of the gradient on its first conv's weights shot[k] = [b.f[0].weight.grad.norm().item() for b in n if isinstance(b, type(list(n)[2]))] opts[k].step(); losses[k].append(loss.item()) if t % every == 0 or t == steps - 1: snaps.append((t, shot)) return snaps, losses rsnaps, rlosses = grad_profile() for k, v in rlosses.items(): g = rsnaps[0][1][k] print(f"{k:9s}: loss {np.mean(v[:10]):.3f} -> {np.mean(v[-10:]):.3f} | " f"gradient at block 1 = {g[0]:.2e}, at the last block = {g[-1]:.2e}, ratio {g[-1] / max(g[0], 1e-12):.0f}x")""") code(r"""nb_blocks = len(rsnaps[0][1]['plain']) fig, ax = plt.subplots(1, 2, figsize=(12, 3.6)) gmax = max(max(s[1][k]) for s in rsnaps for k in s[1]) def draw(t): step, shot = rsnaps[t] ax[0].clear() w = 0.4 ax[0].bar(np.arange(nb_blocks) - w / 2, shot['plain'], w, label='plain', color='C0') ax[0].bar(np.arange(nb_blocks) + w / 2, shot['residual'], w, label='residual', color='C2') ax[0].set_yscale('log'); ax[0].set_ylim(1e-9, gmax * 3) ax[0].set_xlabel('block (1 = closest to the input)'); ax[0].set_ylabel('gradient norm') ax[0].set_title(f'gradient reaching each block, step {step}', fontsize=10); ax[0].legend(fontsize=9) ax[1].clear() for k, c in (('plain', 'C0'), ('residual', 'C2')): sm = np.convolve(rlosses[k], np.ones(10) / 10, 'valid') ax[1].plot(sm, color=c, alpha=.25) ax[1].plot(range(min(step, len(sm))), sm[:min(step, len(sm))], color=c, lw=2, label=k) ax[1].set_title('training loss', fontsize=10); ax[1].set_xlabel('step'); ax[1].legend(fontsize=9) return ax anim = animation.FuncAnimation(fig, draw, frames=len(rsnaps), interval=400, blit=False) html = anim.to_jshtml(fps=2.5); anim.save(f'{FIG}/residual_training.gif', writer='pillow', fps=2.5, dpi=100) plt.close(fig); HTML(html)""") md(r"""## Segment 7 — Little data: augmentation and transfer (note §8) **What to watch:** augmented copies of the same CIFAR-10 image (training data only); a pretrained ResNet-18 with only a new last layer, trained on 500 images, against the same network with random weights.""") code(r'''# [Changed from book §14.1] random crops (4-pixel padding) and horizontal flips, on CIFAR-10 images instead of # the book's cat photo cifar = torchvision.datasets.CIFAR10(root=TORCH_DATA, train=True, download=True) aug = v2.Compose([v2.RandomCrop(32, padding=4), v2.RandomHorizontalFlip()]) fig, axes = plt.subplots(3, 6, figsize=(9, 4.6)) for r, k in enumerate([0, 7, 29]): img = v2.functional.to_image(cifar.data[k]) for c in range(6): axes[r, c].imshow((img if c == 0 else aug(img)).permute(1, 2, 0)) axes[r, c].set_title("original" if c == 0 else "augmented", fontsize=8) axes[r, c].axis("off") plt.tight_layout(); plt.show()''') code(r'''# [Changed from book §14.2] transfer, as a linear probe: frozen ImageNet ResNet-18 features + a new last layer, # 50 CIFAR-10 images per class (book: fine-tuning on a hot-dog dataset); random weights for comparison def subset(train, per_class): ds = torchvision.datasets.CIFAR10(root=TORCH_DATA, train=train, download=True) y = torch.tensor(ds.targets) idx = torch.cat([torch.nonzero(y == c)[:per_class, 0] for c in range(10)]) X = torch.tensor(ds.data[idx.numpy()]).permute(0, 3, 1, 2).float().div(255) return X, y[idx] Xs, ys = subset(True, 50) Xt, yt = subset(False, 100) norm = v2.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) # ImageNet statistics @torch.no_grad() def features(net, X): net.eval().to(DEVICE) out = [net(norm(F.interpolate(X[i:i + 100], size=128, mode="bilinear")).to(DEVICE)).cpu() for i in range(0, len(X), 100)] return torch.cat(out) t0 = time.time() for name, weights in [("pretrained", torchvision.models.ResNet18_Weights.DEFAULT), ("random weights", None)]: net = torchvision.models.resnet18(weights=weights) net.fc = nn.Identity() # the 512 features before the last layer Ftr, Fte = features(net, Xs), features(net, Xt) head = nn.Linear(512, 10) opt = torch.optim.Adam(head.parameters(), lr=1e-3) for _ in range(300): loss = F.cross_entropy(head(Ftr), ys) opt.zero_grad(); loss.backward(); opt.step() print(f"{name:15s} linear probe, 500 training images: test accuracy " f"{(head(Fte).argmax(1) == yt).float().mean():.3f}") print(f"{time.time() - t0:.0f} s")''') 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.*""") # --------------------------------------------------------------------------------------------------------- def build(): nb = nbf.v4.new_notebook() nb["cells"] = [nbf.v4.new_markdown_cell(s) if k == "md" else nbf.v4.new_code_cell(s) for k, s in CELLS] nb["cells"][0].source = INTRO.format(**{f"t{i}": "" for i in range(1, 8)}) 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, 8)} 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()