{ "cells": [ { "cell_type": "markdown", "id": "b8ce2774", "metadata": {}, "source": [ "# PT02: Logistic regression in PyTorch\n", "\n", "Given a few measurements of a penguin, can we predict its species? In this lab we build a linear classifier, train it with gradient descent and evaluate it.\n", "\n", "You should be comfortable with PT01 up to its short check: tensor operations, `backward()` and parameter updates. Data loading, plotting and the training loop are provided. You write three functions: the forward pass (Activity 1), the loss (Activity 2) and one training step (Activity 3). With them we compare three learning rates, switch to PyTorch's standard components, train on mini-batches and evaluate the selected model on the test set. Each activity ends with a one-line check. Later cells use your functions, so complete the activities in order.\n", "\n", "Six optional sections follow: why the largest learning rate wins, a faulty training step, a mini-batch as large as the training set, the same training loop with an MLP, per-example gradients, and an MLP that stores an image. The fourth and the last are meant for after the MLP lecture. Exercises are rated from 1 to 3 stars based on expected difficulty. The solutions, with a short explanation for each exercise, are in [PT02 solutions](https://colab.research.google.com/github/sscardapane/teaching-materials/blob/main/notebooks/PT02_Logistic_regression_solutions.ipynb).\n", "\n", "> Try to solve these exercises without AI coding assistants." ] }, { "cell_type": "markdown", "id": "1aecb3bd", "metadata": {}, "source": [ "As in PT01, `jaxtyping` annotations document the shapes of function inputs and outputs, for example `Float[torch.Tensor, \"batch features\"]`. Nothing checks them at runtime, and they say nothing about intermediate shapes: those you have to work out yourself.\n", "\n", "Run the next cell to install `jaxtyping` before importing it." ] }, { "cell_type": "code", "execution_count": null, "id": "install-jaxtyping", "metadata": {}, "outputs": [], "source": [ "%pip install jaxtyping" ] }, { "cell_type": "code", "execution_count": null, "id": "f85c6a3c", "metadata": {}, "outputs": [], "source": [ "from io import BytesIO\n", "from pathlib import Path\n", "from urllib.request import urlopen\n", "import copy\n", "import hashlib\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "import torch\n", "from jaxtyping import Float, Int\n", "import torch.nn.functional as F\n", "from sklearn.model_selection import train_test_split\n", "\n", "torch.manual_seed(7)\n", "torch.set_printoptions(precision=3, sci_mode=False)\n", "print(\"PyTorch\", torch.__version__)" ] }, { "cell_type": "code", "execution_count": null, "id": "pt02-checks", "metadata": { "cellView": "form" }, "outputs": [], "source": [ "#@title Checks for the activities (run this cell; you do not need to read it)\n", "def check_linear_logits(linear_logits):\n", " X = torch.tensor([[1., 2.], [3., 4.]])\n", " W = torch.tensor([[1., 0.], [0., 1.], [-1., 1.]])\n", " b = torch.tensor([0.5, -0.5, 1.])\n", " expected = torch.tensor([[1.5, 1.5, 2.], [3.5, 3.5, 2.]])\n", " result = linear_logits(X, W, b)\n", " assert result.shape == (2, 3), f\"Expected one row of 3 logits per example, shape (2, 3), got {tuple(result.shape)}.\"\n", " assert torch.allclose(result, expected), f\"Expected\\n{expected}\\ngot\\n{result}\"\n", " print(\"linear_logits is correct.\")\n", "\n", "def check_cross_entropy(cross_entropy):\n", " # Ordinary logits, then logits so large that log(softmax(...)) overflows.\n", " cases = [(torch.tensor([[2., -1., 0.], [0., 1., -2.], [0.5, 0.5, 3.]]), torch.tensor([0, 2, 2])),\n", " (torch.tensor([[1000., 0., -1000.], [-1000., 0., 1000.]]), torch.tensor([2, 0]))]\n", " for logits, targets in cases:\n", " result = cross_entropy(logits, targets)\n", " expected = F.cross_entropy(logits, targets)\n", " assert result.shape == (), f\"The loss must be a scalar, got shape {tuple(result.shape)}.\"\n", " assert torch.isfinite(result), \"The loss is not finite for very large logits: use torch.logsumexp.\"\n", " assert torch.allclose(result, expected), (\n", " f\"For logits\\n{logits}\\nand targets {targets.tolist()}, expected {expected.item():.4f}, got {result.item():.4f}.\")\n", " print(\"cross_entropy is correct.\")\n", "\n", "def check_training_step(training_step):\n", " # Two consecutive steps on the same data: the second fails if the gradients are not cleared.\n", " generator = torch.Generator().manual_seed(0)\n", " X, y = torch.randn(16, 4, generator=generator), torch.randint(0, 3, (16,), generator=generator)\n", " model = torch.nn.Linear(4, 3)\n", " expected_model = copy.deepcopy(model)\n", " for step in (1, 2):\n", " loss = training_step(model, X, y, 0.1)\n", " expected_model.zero_grad()\n", " expected_loss = F.cross_entropy(expected_model(X), y)\n", " expected_loss.backward()\n", " with torch.no_grad():\n", " for parameter in expected_model.parameters():\n", " parameter -= 0.1 * parameter.grad\n", " assert isinstance(loss, float), \"Return loss.item(), a Python number, not a tensor.\"\n", " assert abs(loss - expected_loss.item()) < 1e-5, (\n", " f\"Step {step}: return the loss computed before the update ({expected_loss.item():.4f}), got {loss:.4f}.\")\n", " for (name, parameter), expected in zip(model.named_parameters(), expected_model.parameters()):\n", " hint = \" Did you clear the gradients before backward()?\" if step == 2 else \"\"\n", " assert torch.allclose(parameter, expected, atol=1e-6), f\"Step {step}: wrong {name} after the update.{hint}\"\n", " print(\"training_step is correct.\")" ] }, { "cell_type": "markdown", "id": "7d931980", "metadata": {}, "source": [ "## 1. The data\n", "\n", "We use the [Palmer Penguins dataset](https://allisonhorst.github.io/palmerpenguins/): four measurements (bill length, bill depth, flipper length and body mass) for penguins of three species, Adelie, Chinstrap and Gentoo. Each row is one penguin. We drop the two rows with missing measurements. The next cell reads the copy in `data/` if it exists, and downloads it otherwise." ] }, { "cell_type": "code", "execution_count": null, "id": "406b2044", "metadata": {}, "outputs": [], "source": [ "DATA_URL = \"https://raw.githubusercontent.com/allisonhorst/palmerpenguins/main/inst/extdata/penguins.csv\"\n", "DATA_SHA256 = \"f204db2c753b0937caac3cb35258562c14f073e4bbc76be24b4c51ce22767a93\"\n", "data_path = Path(\"data/penguins.csv\")\n", "data_bytes = data_path.read_bytes() if data_path.exists() else urlopen(DATA_URL, timeout=30).read()\n", "assert hashlib.sha256(data_bytes).hexdigest() == DATA_SHA256, \"Dataset changed; use the supplied data/penguins.csv.\"\n", "\n", "features = [\"bill_length_mm\", \"bill_depth_mm\", \"flipper_length_mm\", \"body_mass_g\"]\n", "classes = [\"Adelie\", \"Chinstrap\", \"Gentoo\"]\n", "penguins = pd.read_csv(BytesIO(data_bytes)).dropna(subset=features + [\"species\"])\n", "X = torch.tensor(penguins[features].to_numpy(), dtype=torch.float32)\n", "y = torch.tensor(pd.Categorical(penguins.species, categories=classes).codes.copy(), dtype=torch.long)\n", "assert X.shape == (342, 4) and y.shape == (342,)\n", "penguins[features + [\"species\"]].head()" ] }, { "cell_type": "markdown", "id": "d2120553", "metadata": {}, "source": [ "We split the data into a training set (60%), a validation set (about 20%) and a test set (the remaining 20%). The split is *stratified*: each set has roughly the same class proportions.\n", "\n", "The features have very different scales (body mass is in grams, the others in millimeters), so we standardize them. The mean and standard deviation come from the training set only, and are then applied to all three sets. This way the validation and test examples do not influence anything we compute during training." ] }, { "cell_type": "code", "execution_count": null, "id": "52c82ff6", "metadata": {}, "outputs": [], "source": [ "indices = np.arange(len(y))\n", "train_idx, rest_idx = train_test_split(indices, test_size=0.4, stratify=y.numpy(), random_state=7)\n", "val_idx, test_idx = train_test_split(rest_idx, test_size=0.5, stratify=y[rest_idx].numpy(), random_state=7)\n", "\n", "Xtrain_raw, ytrain = X[train_idx], y[train_idx]\n", "Xval_raw, yval = X[val_idx], y[val_idx]\n", "Xtest_raw, ytest = X[test_idx], y[test_idx]\n", "mean = Xtrain_raw.mean(dim=0)\n", "scale = Xtrain_raw.std(dim=0, correction=0).clamp_min(1e-8)\n", "Xtrain = (Xtrain_raw - mean) / scale\n", "Xval = (Xval_raw - mean) / scale\n", "Xtest = (Xtest_raw - mean) / scale\n", "\n", "print(\"Examples:\", len(ytrain), \"training;\", len(yval), \"validation;\", len(ytest), \"test\")\n", "print(\"Training means:\", Xtrain.mean(dim=0))\n", "torch.testing.assert_close(Xtrain.mean(dim=0), torch.zeros(4), atol=2e-6, rtol=0)" ] }, { "cell_type": "code", "execution_count": null, "id": "1dd6a01a", "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots(figsize=(6, 4))\n", "for c, name in enumerate(classes):\n", " points = Xtrain_raw[ytrain == c]\n", " ax.scatter(points[:, 0], points[:, 1], label=name, marker=[\"o\", \"^\", \"s\"][c], s=24, alpha=0.8)\n", "ax.set(xlabel=\"Bill length (mm)\", ylabel=\"Bill depth (mm)\")\n", "ax.legend()\n", "fig.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "831759cc", "metadata": {}, "source": [ "## 2. The model\n", "\n", "Recall the batched linear model from PT01,\n", "\n", "$$Z=XW^\\top+b,$$\n", "\n", "with $X\\sim(B,D)$, $W\\sim(C,D)$, $b\\sim(C,)$ and $Z\\sim(B,C)$. Here $D=4$ features and $C=3$ classes. The outputs are logits; we apply a softmax only when we need probabilities.\n", "\n", "### Activity 1: a batched forward pass ★\n", "\n", "Implement `linear_logits` with tensor operations and run the check. How is the bias added to each example? The model class that uses your function comes after the check." ] }, { "cell_type": "code", "execution_count": null, "id": "81f5c4d5", "metadata": { "tags": [ "exercise" ] }, "outputs": [], "source": [ "def linear_logits(X: Float[torch.Tensor, \"batch features\"], W: Float[torch.Tensor, \"classes features\"], b: Float[torch.Tensor, \"classes\"]) -> Float[torch.Tensor, \"batch classes\"]:\n", " # TODO: compute the logits of the whole batch.\n", " raise NotImplementedError(\"Activity 1: write linear_logits\")" ] }, { "cell_type": "code", "execution_count": null, "id": "c36491ad", "metadata": {}, "outputs": [], "source": [ "check_linear_logits(linear_logits)" ] }, { "cell_type": "markdown", "id": "d7739e41", "metadata": {}, "source": [ "A `torch.nn.Module` keeps track of the parameters of a model. Wrapping a tensor in `nn.Parameter` registers it as a parameter and sets `requires_grad=True`. We initialize everything to zero. This is fine for a linear classifier, but it would not work for the hidden layers of an MLP, as Optional D shows." ] }, { "cell_type": "code", "execution_count": null, "id": "d5c222da", "metadata": {}, "outputs": [], "source": [ "class LogisticRegression(torch.nn.Module):\n", " def __init__(self, input_dim, output_dim):\n", " super().__init__()\n", " self.weight = torch.nn.Parameter(torch.zeros(output_dim, input_dim))\n", " self.bias = torch.nn.Parameter(torch.zeros(output_dim))\n", "\n", " def forward(self, X: Float[torch.Tensor, \"batch features\"]) -> Float[torch.Tensor, \"batch classes\"]:\n", " return linear_logits(X, self.weight, self.bias)\n", "\n", "model = LogisticRegression(Xtrain.shape[1], len(classes))\n", "assert model(Xtrain[:5]).shape == (5, 3)\n", "print(\"Parameter tensors:\", len(list(model.parameters())))\n", "print(\"Trainable scalar parameters:\", sum(p.numel() for p in model.parameters()))" ] }, { "cell_type": "markdown", "id": "1c11f1a8", "metadata": {}, "source": [ "## 3. Loss and accuracy\n", "\n", "For a vector of logits $z$ and correct class $y$, the cross-entropy is\n", "\n", "$$\\ell(z,y)=\\log\\sum_c\\exp(z_c)-z_y.$$\n", "\n", "### Activity 2: the loss ★★\n", "\n", "Implement `cross_entropy` from this formula, averaged over the examples in the batch. Use `torch.logsumexp` for the first term, and select the logit of the correct class from each row. Do not call `F.cross_entropy`: the check uses it to test your result, including on very large logits, where computing `log(softmax(...))` directly gives infinite values.\n", "\n", "Before writing code, work out the shapes of the first term, of the selected logits and of the final loss.\n", "\n", "Hint: see NumPy's [Indexing on ndarrays](https://numpy.org/doc/stable/user/basics.indexing.html), especially [integer array indexing](https://numpy.org/doc/stable/user/basics.indexing.html#integer-array-indexing), for selecting one element from each row. The same indexing pattern works with PyTorch tensors." ] }, { "cell_type": "code", "execution_count": null, "id": "97278cda", "metadata": { "tags": [ "exercise" ] }, "outputs": [], "source": [ "def cross_entropy(logits: Float[torch.Tensor, \"batch classes\"], targets: Int[torch.Tensor, \"batch\"]) -> Float[torch.Tensor, \"\"]:\n", " # TODO: compute the mean cross-entropy over the batch.\n", " raise NotImplementedError(\"Activity 2: write cross_entropy\")" ] }, { "cell_type": "code", "execution_count": null, "id": "cd35619f", "metadata": {}, "outputs": [], "source": [ "check_cross_entropy(cross_entropy)" ] }, { "cell_type": "markdown", "id": "2f844225-intro", "metadata": {}, "source": [ "The accuracy function is provided. The next cell computes the loss and the accuracy of the model at initialization." ] }, { "cell_type": "code", "execution_count": null, "id": "fefd076e", "metadata": {}, "outputs": [], "source": [ "def accuracy(logits: Float[torch.Tensor, \"batch classes\"], targets: Int[torch.Tensor, \"batch\"]) -> Float[torch.Tensor, \"\"]:\n", " return (logits.argmax(dim=1) == targets).float().mean()\n", "\n", "logits = model(Xtrain)\n", "print(\"Initial loss:\", cross_entropy(logits, ytrain).item())\n", "print(\"Initial accuracy:\", accuracy(logits, ytrain).item())" ] }, { "cell_type": "markdown", "id": "2f844225", "metadata": {}, "source": [ "At initialization all logits are zero, so the predicted probabilities are uniform and the loss is $\\log 3 \\approx 1.0986$. The accuracy is not one third, though: `argmax` breaks ties by picking the first class (Adelie), so the initial accuracy is the fraction of Adelie penguins in the training set." ] }, { "cell_type": "markdown", "id": "7486e2cb", "metadata": {}, "source": [ "## 4. One training step\n", "\n", "One step of gradient descent has four parts, in this order:\n", "\n", "1. clear the gradients left by the previous step (set the `.grad` of each parameter to `None`);\n", "2. compute the loss on the data;\n", "3. call `backward()`;\n", "4. subtract the learning rate times its gradient from each parameter.\n", "\n", "Only the update runs inside `torch.no_grad()`. You saw all four parts in PT01; here you put them together." ] }, { "cell_type": "markdown", "id": "1024b65a", "metadata": {}, "source": [ "### Activity 3: train the classifier ★\n", "\n", "Write `training_step`. It makes one step on the data it receives, changes the model in place and returns the loss computed **before** the update, as a Python number. Loop over `model.parameters()`, so that the same code updates the weight and the bias. The data are arguments rather than global variables, so later we can call the same function on mini-batches.\n", "\n", "The check runs two consecutive steps; the second one fails if the gradients of the first step were not cleared. Then run the training loop and look at the training and validation curves together. Leave the test set alone until the end." ] }, { "cell_type": "code", "execution_count": null, "id": "05b55ab1", "metadata": { "tags": [ "exercise" ] }, "outputs": [], "source": [ "def training_step(model: torch.nn.Module, X: Float[torch.Tensor, \"batch features\"], y: Int[torch.Tensor, \"batch\"], lr: float) -> float:\n", " # TODO: clear the gradients, compute the loss, call backward() and update the parameters.\n", " raise NotImplementedError(\"Activity 3: write training_step\")" ] }, { "cell_type": "code", "execution_count": null, "id": "e0e04805", "metadata": {}, "outputs": [], "source": [ "check_training_step(training_step)" ] }, { "cell_type": "code", "execution_count": null, "id": "39a0ae97", "metadata": {}, "outputs": [], "source": [ "@torch.no_grad()\n", "def evaluate(model, X, y):\n", " model.eval()\n", " logits = model(X)\n", " return cross_entropy(logits, y).item(), accuracy(logits, y).item()\n", "\n", "def fit(model, Xtrain, ytrain, Xval, yval, lr=0.1, epochs=200):\n", " history = {name: [] for name in [\"train_loss\", \"val_loss\", \"train_accuracy\", \"val_accuracy\"]}\n", " for _ in range(epochs):\n", " model.train()\n", " training_step(model, Xtrain, ytrain, lr)\n", " # Both curves measure the model after the same update.\n", " train_loss, train_acc = evaluate(model, Xtrain, ytrain)\n", " val_loss, val_acc = evaluate(model, Xval, yval)\n", " for key, value in zip(history, [train_loss, val_loss, train_acc, val_acc]):\n", " history[key].append(value)\n", " return history\n", "\n", "model = LogisticRegression(4, 3)\n", "history = fit(model, Xtrain, ytrain, Xval, yval)\n", "fig, axes = plt.subplots(1, 2, figsize=(10, 3.5))\n", "epochs = range(1, len(history[\"train_loss\"]) + 1)\n", "for split, style in [(\"train\", \"-\"), (\"val\", \"--\")]:\n", " axes[0].plot(epochs, history[f\"{split}_loss\"], style, label=split)\n", " axes[1].plot(epochs, history[f\"{split}_accuracy\"], style, label=split)\n", "axes[0].set(xlabel=\"Epoch\", ylabel=\"Cross-entropy\")\n", "axes[1].set(xlabel=\"Epoch\", ylabel=\"Accuracy\", ylim=(0, 1.03))\n", "for ax in axes:\n", " ax.legend()\n", "fig.tight_layout()\n", "plt.show()\n", "print(\"Final validation loss and accuracy:\", evaluate(model, Xval, yval))" ] }, { "cell_type": "markdown", "id": "12fac64f", "metadata": {}, "source": [ "Each update uses the whole training set, so here one update is one epoch (one pass through the data). With mini-batches, an epoch contains several updates.\n", "\n", "The loss can go down while the accuracy stays flat: the probability of the correct class can grow without changing which class has the largest logit. Can you find such an interval in your curves?" ] }, { "cell_type": "markdown", "id": "85779245", "metadata": {}, "source": [ "### Comparing learning rates\n", "\n", "Every run starts from the same parameters and makes 200 full-batch updates; only the learning rate changes. Before running the cell, predict how the curves for `0.001`, `0.1` and `10.0` will differ. Does accuracy tell the same story as the loss?\n", "\n", "We keep the run with the lowest final validation loss. The test set plays no part in this choice." ] }, { "cell_type": "code", "execution_count": null, "id": "1b6a87cd", "metadata": {}, "outputs": [], "source": [ "learning_rates = [0.001, 0.1, 10.0]\n", "initial_model = LogisticRegression(4, 3)\n", "lr_models, lr_histories = {}, {}\n", "fig, axes = plt.subplots(1, 2, figsize=(10, 3.5))\n", "for rate, style in zip(learning_rates, [\"-\", \"--\", \":\"]):\n", " candidate = copy.deepcopy(initial_model)\n", " trace = fit(candidate, Xtrain, ytrain, Xval, yval, lr=rate, epochs=200)\n", " lr_models[rate], lr_histories[rate] = candidate, trace\n", " for ax, split in zip(axes, [\"train\", \"val\"]):\n", " ax.plot(range(1, 201), trace[f\"{split}_loss\"], style, label=f\"lr={rate:g}\")\n", " print(f\"lr={rate:g}: validation loss={trace['val_loss'][-1]:.4f}, accuracy={trace['val_accuracy'][-1]:.3f}\")\n", "for ax, title in zip(axes, [\"Training\", \"Validation\"]):\n", " ax.set(xlabel=\"Update\", ylabel=\"Cross-entropy\", title=title, yscale=\"log\")\n", " ax.legend()\n", "fig.tight_layout()\n", "plt.show()\n", "selected_lr = min(learning_rates, key=lambda rate: lr_histories[rate][\"val_loss\"][-1])\n", "model = lr_models[selected_lr]\n", "print(\"Selected learning rate:\", selected_lr)" ] }, { "cell_type": "markdown", "id": "lr-discussion", "metadata": {}, "source": [ "On this dataset the largest rate wins clearly. Do not read this as a general rule: Optional A asks why it happens here." ] }, { "cell_type": "markdown", "id": "2f5e9f1c", "metadata": {}, "source": [ "## 5. Using the standard components\n", "\n", "In practice we do not write these pieces ourselves: `nn.Linear` holds the weight and bias, `F.cross_entropy` computes the loss, and an optimizer such as `torch.optim.SGD` performs the update. They should compute exactly what our code computes.\n", "\n", "To check it, we copy the parameters of our model into the standard one and compare a single update. If the two models started from different random parameters, we could not tell implementation differences apart from initialization differences." ] }, { "cell_type": "code", "execution_count": null, "id": "8eeaca90", "metadata": {}, "outputs": [], "source": [ "manual = LogisticRegression(4, 3)\n", "standard = torch.nn.Linear(4, 3)\n", "with torch.no_grad():\n", " standard.weight.copy_(manual.weight)\n", " standard.bias.copy_(manual.bias)\n", "optimizer = torch.optim.SGD(standard.parameters(), lr=0.1)\n", "\n", "manual_loss = training_step(manual, Xtrain, ytrain, 0.1)\n", "optimizer.zero_grad(set_to_none=True)\n", "standard_loss = F.cross_entropy(standard(Xtrain), ytrain)\n", "standard_loss.backward()\n", "optimizer.step()\n", "\n", "torch.testing.assert_close(standard.weight, manual.weight)\n", "torch.testing.assert_close(standard.bias, manual.bias)\n", "torch.testing.assert_close(standard(Xval), manual(Xval))\n", "print(\"Manual and standard updates agree.\")" ] }, { "cell_type": "markdown", "id": "e3fe54e6", "metadata": {}, "source": [ "## 6. From full batches to mini-batches\n", "\n", "A `TensorDataset` pairs each row of features with its label. A `DataLoader` splits the dataset into batches and, with `shuffle=True`, uses a new order in every epoch.\n", "\n", "Before running: with 205 training examples and batches of 32, how many updates are there in one epoch? How large is the last batch?\n", "\n", "We train a new model from the same initial parameters with `lr=0.1` and compare it with the full-batch run at the same rate. After the same number of epochs, both models have seen the data equally often, but the mini-batch model has made many more updates." ] }, { "cell_type": "code", "execution_count": null, "id": "5c6bfb7d", "metadata": {}, "outputs": [], "source": [ "from torch.utils.data import TensorDataset, DataLoader\n", "\n", "train_loader = DataLoader(TensorDataset(Xtrain, ytrain), batch_size=32,\n", " shuffle=True, drop_last=False,\n", " generator=torch.Generator().manual_seed(7))\n", "mini_model = copy.deepcopy(initial_model)\n", "mini_history = {\"train_loss\": [], \"val_loss\": []}\n", "mini_updates = 0\n", "batch_sizes = []\n", "for epoch in range(30):\n", " mini_model.train()\n", " for batch_X, batch_y in train_loader:\n", " training_step(mini_model, batch_X, batch_y, lr=0.1)\n", " mini_updates += 1\n", " if epoch == 0:\n", " batch_sizes.append(len(batch_y))\n", " # Evaluate the current model on each complete split. Do not average\n", " # unweighted batch losses: the final batch contains fewer examples.\n", " mini_history[\"train_loss\"].append(evaluate(mini_model, Xtrain, ytrain)[0])\n", " mini_history[\"val_loss\"].append(evaluate(mini_model, Xval, yval)[0])\n", "print(\"Batch sizes in one epoch:\", batch_sizes)\n", "print(\"Epochs: 30; updates:\", mini_updates)\n", "fig, ax = plt.subplots(figsize=(6, 4))\n", "ax.plot(range(1, 31), mini_history[\"val_loss\"], label=\"Mini-batch, 32 examples\")\n", "ax.plot(range(1, 31), lr_histories[0.1][\"val_loss\"][:30], \"--\", label=\"Full batch\")\n", "ax.set(xlabel=\"Epoch\", ylabel=\"Validation cross-entropy\")\n", "ax.legend()\n", "fig.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "80f28f5d", "metadata": {}, "source": [ "## 7. Final evaluation\n", "\n", "We now evaluate `model`, the full-batch run selected by validation loss, on the test set. This is the first time we use the test set.\n", "\n", "For reference, we compare its accuracy with a trivial baseline that always predicts the most common class in the training set. The confusion matrix shows which species are mistaken for which. If you go back and change the model after seeing these numbers, the test set no longer gives a fair final evaluation." ] }, { "cell_type": "code", "execution_count": null, "id": "ba4bc128", "metadata": {}, "outputs": [], "source": [ "test_loss, test_accuracy = evaluate(model, Xtest, ytest)\n", "majority_class = torch.bincount(ytrain).argmax()\n", "baseline_accuracy = (ytest == majority_class).float().mean().item()\n", "print(f\"Test cross-entropy: {test_loss:.3f}\")\n", "print(f\"Test accuracy: {test_accuracy:.3f}\")\n", "print(f\"Majority-class accuracy: {baseline_accuracy:.3f}\")\n", "\n", "with torch.no_grad():\n", " predicted = model(Xtest).argmax(dim=1)\n", "confusion = torch.bincount(ytest * 3 + predicted, minlength=9).reshape(3, 3)\n", "confusion_table = pd.DataFrame(confusion.numpy(), index=classes, columns=classes)\n", "confusion_table.index.name = \"True species\"\n", "confusion_table.columns.name = \"Predicted species\"\n", "confusion_table" ] }, { "cell_type": "markdown", "id": "2d4124af", "metadata": {}, "source": [ "Pick one misclassified penguin and look at its logits or probabilities. Was the model confident? What can you conclude from a single example, and what would need more evidence?\n", "\n", "This is the end of the core of the lab." ] }, { "cell_type": "markdown", "id": "optional-intro", "metadata": {}, "source": [ "## Optional A: why does the largest rate win? ★★★\n", "\n", "The optional sections do not depend on each other, except for the last one, which builds on Optional D. Here we return to the learning-rate comparison. Write down a prediction before each step, then check it.\n", "\n", "1. Which of the three runs has the largest weight norm? Print `lr_models[rate].weight.norm()` and the training accuracy of each run.\n", "2. Copy the `lr=10` model with `copy.deepcopy` and keep training it with `fit` for 2000 more updates, recording the weight norm every 200 updates. Does the training loss reach zero? Does the norm level off?\n", "3. The norm keeps changing, but does the *direction* `W / ‖W‖` keep changing too? Compute the cosine between the directions at consecutive checkpoints.\n", "4. Train from `initial_model` with `lr=100` and `lr=1000`, and print the first ten training losses. Does anything break? In Optional D we will see what a rate of 10 does to an MLP.\n", "\n", "Do not overwrite `lr_models`: Optional E uses it." ] }, { "cell_type": "code", "execution_count": null, "id": "lr-activity-work", "metadata": {}, "outputs": [], "source": [ "# Your experiments here." ] }, { "cell_type": "markdown", "id": "3b5d1689", "metadata": {}, "source": [ "## Optional B: a different training step ★★\n", "\n", "A colleague gives you the function below. It runs, and at first its loss may even fall faster than yours. Is it the same gradient descent?\n", "\n", "Compare it with your `training_step`, starting from the same parameters and data. Design a small experiment that tells the two apart: write down what you expect, run it, then fix the function. A decreasing loss alone does not settle the question. The cell below only defines the function; the experiment is up to you." ] }, { "cell_type": "code", "execution_count": null, "id": "5c09e5ad", "metadata": {}, "outputs": [], "source": [ "def suspect_step(model: torch.nn.Module, X: Float[torch.Tensor, \"batch features\"], y: Int[torch.Tensor, \"batch\"], lr: float) -> float:\n", " loss = cross_entropy(model(X), y)\n", " loss.backward()\n", " with torch.no_grad():\n", " for parameter in model.parameters():\n", " parameter -= lr * parameter.grad\n", " return loss.item()" ] }, { "cell_type": "code", "execution_count": null, "id": "74631f24", "metadata": {}, "outputs": [], "source": [ "# Your experiment here. What do you expect, and what do you observe?" ] }, { "cell_type": "markdown", "id": "46cd33d8", "metadata": {}, "source": [ "## Optional C: a batch as large as the training set ★\n", "\n", "Why do two batches give different gradients for the same parameters? Write down your answer, then test a consequence of it. Build a `DataLoader` with `batch_size=len(ytrain)` and `shuffle=True`, and show that one epoch with it, starting from `initial_model`, gives the same parameters as one full-batch `training_step` from the same start. Does the shuffling matter here? What would change with `batch_size=len(ytrain) - 1`?" ] }, { "cell_type": "code", "execution_count": null, "id": "minibatch-activity-work", "metadata": {}, "outputs": [], "source": [ "# Your check here." ] }, { "cell_type": "markdown", "id": "mlp-intro", "metadata": {}, "source": [ "## Optional D: from logistic regression to an MLP ★★\n", "\n", "Do this section after the MLP lecture. We replace the linear model with an MLP with one hidden layer of 16 ReLU units. Nothing else changes: `fit`, `evaluate`, your `training_step` and your `cross_entropy` only need a module that maps a batch of features to a batch of logits, and they work as they are.\n", "\n", "`nn.Sequential` chains layers. Unlike our `LogisticRegression`, each `nn.Linear` starts from small random weights. We train with the same learning rate and number of updates as the linear run at `lr=0.1`, and compare the two on the validation set. The test set stays untouched: the model we evaluated in Section 7 remains our final one." ] }, { "cell_type": "code", "execution_count": null, "id": "mlp-train", "metadata": {}, "outputs": [], "source": [ "def make_mlp(width: int = 16) -> torch.nn.Module:\n", " return torch.nn.Sequential(\n", " torch.nn.Linear(4, width), torch.nn.ReLU(), torch.nn.Linear(width, len(classes))\n", " )\n", "\n", "torch.manual_seed(7)\n", "mlp = make_mlp()\n", "mlp_history = fit(mlp, Xtrain, ytrain, Xval, yval, lr=0.1, epochs=200)\n", "print(\"MLP parameters:\", sum(p.numel() for p in mlp.parameters()))\n", "print(f\"Validation loss after 200 updates: MLP {mlp_history['val_loss'][-1]:.4f}, \"\n", " f\"linear {lr_histories[0.1]['val_loss'][-1]:.4f}\")\n", "\n", "fig, ax = plt.subplots(figsize=(6, 4))\n", "ax.plot(range(1, 201), lr_histories[0.1][\"val_loss\"], label=\"Linear\")\n", "ax.plot(range(1, 201), mlp_history[\"val_loss\"], \"--\", label=\"MLP, 16 hidden units\")\n", "ax.set(xlabel=\"Update\", ylabel=\"Validation cross-entropy\", yscale=\"log\", title=\"lr=0.1\")\n", "ax.legend()\n", "fig.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "mlp-questions", "metadata": {}, "source": [ "At the same learning rate the MLP reaches a lower validation loss, but remember that the linear model at `lr=10` was already close to perfect on this data. Two experiments show where the MLP does behave differently:\n", "\n", "1. Train a new MLP with `lr=10.0`, the rate that won the comparison for the linear model. Before running, predict the training curve. What happens, and why could the linear model take such large steps?\n", "2. In Section 2 we initialized the linear model with zeros. Do the same for the MLP: after building it, set every parameter to zero inside `torch.no_grad()`, then train with `lr=0.1`. Predict the final loss. Which parameters change during training, and which stay at zero?" ] }, { "cell_type": "code", "execution_count": null, "id": "mlp-student-work", "metadata": {}, "outputs": [], "source": [ "# Try the two experiments here." ] }, { "cell_type": "markdown", "id": "per-example-intro", "metadata": {}, "source": [ "## Optional E: which examples drive the update?\n", "\n", "Autodiff is also useful to inspect a model, not only to train it. Fix the parameters and compute one gradient per training example, $g_i=\\nabla_\\theta\\ell_i$. The gradient of the mean training loss is their average, $\\bar g=\\frac{1}{N}\\sum_i g_i$, and a full-batch step moves along $-\\bar g$. The individual $g_i$ show which examples pull the parameters, and in which direction.\n", "\n", "We use a copy of the `lr=0.1` run after 200 updates, whose loss is still far enough from zero to be interesting. We use only training examples, and nothing here changes the model evaluated above.\n", "\n", "The simplest approach is a loop over the examples. `torch.autograd.grad` returns each gradient without touching the `.grad` fields. We flatten the weight and bias gradients into one vector, which gives a matrix with one row per example and one column per parameter." ] }, { "cell_type": "code", "execution_count": null, "id": "per-example-loop", "metadata": {}, "outputs": [], "source": [ "analysis_model = copy.deepcopy(lr_models[0.1]).cpu().double().eval()\n", "analysis_model.zero_grad(set_to_none=True)\n", "analysis_X, analysis_y = Xtrain.cpu().double(), ytrain.cpu().clone()\n", "analysis_parameters = tuple(analysis_model.parameters())\n", "analysis_parameter_names = tuple(dict(analysis_model.named_parameters()))\n", "\n", "def gradients_in_a_loop(\n", " Xbatch: Float[torch.Tensor, \"batch features\"],\n", " ybatch: Int[torch.Tensor, \"batch\"],\n", ") -> Float[torch.Tensor, \"batch parameters\"]:\n", " rows = []\n", " for sample, label in zip(Xbatch, ybatch):\n", " sample_loss = F.cross_entropy(analysis_model(sample[None, :]), label[None])\n", " derivatives = torch.autograd.grad(sample_loss, analysis_parameters)\n", " rows.append(torch.cat([value.reshape(-1) for value in derivatives]))\n", " return torch.stack(rows)\n", "\n", "per_example_loop = gradients_in_a_loop(analysis_X, analysis_y)\n", "batch_loss = F.cross_entropy(analysis_model(analysis_X), analysis_y)\n", "batch_derivatives = torch.autograd.grad(batch_loss, analysis_parameters)\n", "mean_gradient = torch.cat([value.reshape(-1) for value in batch_derivatives])\n", "torch.testing.assert_close(per_example_loop.mean(dim=0), mean_gradient)\n", "assert all(parameter.grad is None for parameter in analysis_parameters)\n", "print(\"Gradient matrix (examples, parameters):\", tuple(per_example_loop.shape))" ] }, { "cell_type": "markdown", "id": "per-example-transforms-text", "metadata": {}, "source": [ "### The same computation with function transforms\n", "\n", "`torch.func` lets us write the gradient for one example and apply it to the whole batch:\n", "\n", "- `functional_call(model, params, inputs)` runs the model with an explicit dictionary of parameters;\n", "- `grad(f)` returns a function that computes the gradient of `f` with respect to its first argument;\n", "- `vmap(f, in_dims=(None, 0, 0))` applies `f` to each example. `None` means that the argument (here, the parameters) is shared; `0` means that we map over the first axis of the argument.\n", "\n", "The result has an extra leading axis for the examples. After concatenating, it must match the loop. This works directly because our model has no dropout, batch normalization or other layers that depend on the whole batch; for such models, a one-example loss may not describe what the model computes on a batch. We do not compare timings for this small model. See [PyTorch's per-sample-gradient tutorial](https://docs.pytorch.org/tutorials/intermediate/per_sample_grads.html)." ] }, { "cell_type": "code", "execution_count": null, "id": "per-example-transforms", "metadata": {}, "outputs": [], "source": [ "from torch.func import functional_call, grad, vmap\n", "\n", "analysis_state = {name: value.detach() for name, value in analysis_model.named_parameters()}\n", "\n", "def single_example_loss(\n", " parameters: dict[str, torch.Tensor],\n", " sample: Float[torch.Tensor, \"features\"],\n", " label: Int[torch.Tensor, \"\"],\n", ") -> Float[torch.Tensor, \"\"]:\n", " sample_logits = functional_call(analysis_model, parameters, (sample.unsqueeze(0),))\n", " return F.cross_entropy(sample_logits, label.unsqueeze(0))\n", "\n", "one_gradient = grad(single_example_loss)\n", "all_gradients = vmap(one_gradient, in_dims=(None, 0, 0))\n", "gradient_tree = all_gradients(analysis_state, analysis_X, analysis_y)\n", "per_example_transformed = torch.cat([\n", " gradient_tree[name].reshape(len(analysis_y), -1) for name in analysis_parameter_names\n", "], dim=1)\n", "torch.testing.assert_close(per_example_transformed, per_example_loop)\n", "print(\"The loop and grad + vmap agree.\")" ] }, { "cell_type": "markdown", "id": "per-example-diagnostic-text", "metadata": {}, "source": [ "### Magnitude and direction\n", "\n", "Two numbers summarize each $g_i$. The norm $\\lVert g_i\\rVert$ measures how strongly this example pulls on the parameters. The cosine $g_i^\\top\\bar g/(\\lVert g_i\\rVert\\lVert\\bar g\\rVert)$ measures whether it agrees with the average. If the cosine is positive, a small enough step along $-\\bar g$ lowers this example's loss; if it is negative, the step raises it. This holds only locally, for small steps from the current parameters, and the cosine is undefined when either vector is zero.\n", "\n", "We highlight an *easy* example (correctly classified, with low loss) and a *difficult* one (the highest loss). Then we take the easy example and change **only its label**, keeping the model fixed. Before running, predict where this relabeled example will land in the two plots." ] }, { "cell_type": "code", "execution_count": null, "id": "per-example-diagnostic", "metadata": {}, "outputs": [], "source": [ "with torch.no_grad():\n", " clean_logits = analysis_model(analysis_X)\n", " clean_losses = F.cross_entropy(clean_logits, analysis_y, reduction=\"none\")\n", "correct_indices = torch.where(clean_logits.argmax(dim=1) == analysis_y)[0]\n", "ordered_correct = correct_indices[clean_losses[correct_indices].argsort()]\n", "easy_index = int(ordered_correct[len(ordered_correct) // 10])\n", "difficult_index = int(clean_losses.argmax())\n", "changed_label = (analysis_y[easy_index:easy_index + 1] + 1) % len(classes)\n", "changed_gradient = gradients_in_a_loop(analysis_X[easy_index:easy_index + 1], changed_label)[0]\n", "with torch.no_grad():\n", " changed_loss = F.cross_entropy(clean_logits[easy_index:easy_index + 1], changed_label)\n", "\n", "def gradient_alignment(\n", " vectors: Float[torch.Tensor, \"batch parameters\"],\n", " direction: Float[torch.Tensor, \"parameters\"],\n", ") -> Float[torch.Tensor, \"batch\"]:\n", " denominator = vectors.norm(dim=1) * direction.norm()\n", " result = torch.full_like(denominator, float(\"nan\"))\n", " valid = denominator > 1e-12\n", " result[valid] = (vectors[valid] @ direction) / denominator[valid]\n", " return result\n", "\n", "clean_norms = per_example_loop.norm(dim=1)\n", "clean_alignment = gradient_alignment(per_example_loop, mean_gradient)\n", "comparison_gradients = torch.stack([\n", " per_example_loop[easy_index], per_example_loop[difficult_index], changed_gradient\n", "])\n", "comparison = pd.DataFrame({\n", " \"case\": [\"easy\", \"difficult\", \"easy, changed label\"],\n", " \"training row\": [easy_index, difficult_index, easy_index],\n", " \"label\": [classes[int(analysis_y[easy_index])], classes[int(analysis_y[difficult_index])],\n", " classes[int(changed_label[0])]],\n", " \"loss\": [clean_losses[easy_index].item(), clean_losses[difficult_index].item(), changed_loss.item()],\n", " \"gradient norm\": comparison_gradients.norm(dim=1).numpy(),\n", " \"cosine with clean mean\": gradient_alignment(comparison_gradients, mean_gradient).numpy(),\n", "})\n", "print(comparison.to_string(index=False, float_format=lambda value: f\"{value:.4f}\"))\n", "\n", "fig, axes = plt.subplots(1, 2, figsize=(11, 4))\n", "axes[0].scatter(clean_losses.numpy(), clean_norms.numpy(), s=18, alpha=0.35, label=\"Original labels\")\n", "axes[1].scatter(clean_norms.numpy(), clean_alignment.numpy(), s=18, alpha=0.35)\n", "for row, marker, color in zip(comparison.to_dict(\"records\"), [\"o\", \"s\", \"X\"], [\"C2\", \"C1\", \"C3\"]):\n", " axes[0].scatter(row[\"loss\"], row[\"gradient norm\"], marker=marker, color=color, s=85, label=row[\"case\"])\n", " axes[1].scatter(row[\"gradient norm\"], row[\"cosine with clean mean\"], marker=marker, color=color, s=85)\n", "axes[0].set(xlabel=\"Per-example cross-entropy\", ylabel=\"Gradient norm\")\n", "axes[1].set(xlabel=\"Gradient norm\", ylabel=\"Cosine with clean mean gradient\", ylim=(-1.05, 1.05))\n", "axes[1].axhline(0, color=\"gray\", lw=1)\n", "axes[0].legend(fontsize=8)\n", "fig.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "per-example-questions", "metadata": {}, "source": [ "Which examples dominate the mean gradient: those with a large norm, those aligned with the mean, or both? Can large gradients cancel each other out?\n", "\n", "A large gradient norm does not mean that an example is mislabeled. What else could produce one? Think about ambiguous measurements, the limits of a linear model and the current parameter values. Repeat the analysis with another run from the learning-rate comparison: do the same examples stand out?" ] }, { "cell_type": "markdown", "id": "image-exercise", "metadata": {}, "source": [ "## Optional F: store an image in an MLP ★★★\n", "\n", "Do this section after the MLP lecture. Optional D swapped the linear model for an MLP on the penguins. Here we take the same tools to a different problem: a regression with a different loss and input. We fit a function that maps a pixel position `(x, y)` to its color `(r, g, b)`, so that the network itself stores the image. The next cell generates a small target image, so no download is needed.\n", "\n", "1. Build an MLP with two ReLU hidden layers and three sigmoid outputs. Train it with the mean squared error, using only the pixels in `image_train_mask` (one pixel in four). Coordinates are in `[-1, 1]` and colors in `[0, 1]`.\n", "2. Compare two inputs: the raw coordinates, and *Fourier features*, the concatenation of `sin(2*pi*coordinates @ frequencies.T)` and `cos(...)`. Here `frequencies` is a fixed matrix of 16 two-dimensional vectors, drawn once from a normal distribution with standard deviation 1.5 and never trained.\n", "3. For each input, try hidden widths 16 and 32, with seed 7, Adam with learning rate 0.01 and 400 full-batch updates. Record the error on the training pixels and on the held-out pixels, and save the reconstructions at updates 0, 100 and 400. Fix these settings before you look at held-out results.\n", "4. Evaluate the network on a finer 64 by 64 grid. Does the larger image contain detail that the network could not have seen?\n", "\n", "The held-out pixels test interpolation inside this one image, not generalization to new images. If you tune your choices on them, keep another set of pixels for the final evaluation.\n", "\n", "If you want to go further: plot the held-out error against the number of trainable parameters (at the same width, the two inputs give different counts), and compare the float32 size of the network, including the frequency matrix, with the original image at one byte per channel. What does this comparison leave out? You can also query coordinates outside `[-1, 1]`, where the network is extrapolating.\n", "\n", "The solutions notebook contains a reference experiment. Background: [Tancik et al., Fourier Features Let Networks Learn High Frequency Functions in Low Dimensional Domains](https://bmild.github.io/fourfeat/)." ] }, { "cell_type": "code", "execution_count": null, "id": "image-data", "metadata": {}, "outputs": [], "source": [ "image_side = 32\n", "\n", "def coordinate_grid(side: int) -> Float[torch.Tensor, \"pixels 2\"]:\n", " axis = (torch.arange(side, dtype=torch.float32) + 0.5) * (2. / side) - 1.\n", " yy, xx = torch.meshgrid(axis, axis, indexing=\"ij\")\n", " return torch.stack([xx, yy], dim=-1).reshape(-1, 2)\n", "\n", "image_coordinates = coordinate_grid(image_side)\n", "image_x, image_y = image_coordinates.unbind(dim=1)\n", "# A small RGB test image with smooth variation, stripes and a circular edge.\n", "image_rgb = torch.stack([\n", " 0.5 + 0.4 * torch.sin(3 * torch.pi * image_x),\n", " 0.5 + 0.4 * torch.cos(2 * torch.pi * image_y),\n", " torch.where(image_x.square() + image_y.square() < 0.45, 0.85, 0.15),\n", "], dim=1)\n", "image_bytes = (255 * image_rgb).round().to(torch.uint8)\n", "image_rgb = image_bytes.float() / 255.\n", "pixel_rows, pixel_cols = torch.meshgrid(torch.arange(image_side), torch.arange(image_side), indexing=\"ij\")\n", "image_train_mask = ((pixel_rows % 2 == 0) & (pixel_cols % 2 == 0)).flatten()\n", "image_heldout_mask = ~image_train_mask\n", "assert image_train_mask.sum().item() == 256 and image_heldout_mask.sum().item() == 768\n", "\n", "fig, axes = plt.subplots(1, 2, figsize=(6, 3))\n", "axes[0].imshow(image_rgb.reshape(image_side, image_side, 3))\n", "axes[0].set_title(\"Target RGB image\")\n", "visible = torch.ones_like(image_rgb)\n", "visible[image_train_mask] = image_rgb[image_train_mask]\n", "axes[1].imshow(visible.reshape(image_side, image_side, 3))\n", "axes[1].set_title(\"Observed pixels (others white)\")\n", "for ax in axes:\n", " ax.axis(\"off\")\n", "fig.tight_layout()\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "id": "image-student-work", "metadata": {}, "outputs": [], "source": [ "# Define the coordinate MLP, train on the observed pixels, and compare encodings.\n", "# Keep this optional exercise independent of the penguin classifier above." ] }, { "cell_type": "markdown", "id": "pt02-references", "metadata": {}, "source": [ "## References\n", "\n", "Data: Horst, Hill and Gorman (2020), [palmerpenguins](https://allisonhorst.github.io/palmerpenguins/), CC0. Original data collected by Kristen Gorman and Palmer Station LTER; see the dataset page for the ecological study and data citations.\n", "\n", "- [CrossEntropyLoss](https://docs.pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html)\n", "- [nn.Module](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html)\n", "- [Autograd mechanics](https://docs.pytorch.org/docs/stable/notes/autograd.html)\n", "- [Per-sample gradients with torch.func](https://docs.pytorch.org/tutorials/intermediate/per_sample_grads.html)\n", "- [Fourier feature networks](https://bmild.github.io/fourfeat/)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.15" } }, "nbformat": 4, "nbformat_minor": 5 }