{ "cells": [ { "cell_type": "markdown", "id": "solutions-intro", "metadata": {}, "source": [ "# PT02: Logistic regression in PyTorch: solutions\n", "\n", "The solutions to the exercises of [PT02](https://colab.research.google.com/github/sscardapane/teaching-materials/blob/main/notebooks/PT02_Logistic_regression.ipynb). Each solution comes under the heading it has in the lab, with a short explanation followed by the code. If you fall behind during the lab, copy the solution cell into your notebook in place of your version and continue from there." ] }, { "cell_type": "markdown", "id": "heading-1", "metadata": {}, "source": [ "## 2. The model" ] }, { "cell_type": "markdown", "id": "heading-2", "metadata": {}, "source": [ "### Activity 1: a batched forward pass ★" ] }, { "cell_type": "markdown", "id": "linear-logits-explanation", "metadata": {}, "source": [ "With the examples as rows, `X @ W.T` has shape `(batch, classes)`, and its row `i` is $Wx_i$. Adding `b`, of shape `(classes,)`, broadcasts it over the rows, so the same bias vector is added to every example." ] }, { "cell_type": "code", "execution_count": null, "id": "d4bcbb0d", "metadata": {}, "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", " return X @ W.T + b" ] }, { "cell_type": "markdown", "id": "heading-5", "metadata": {}, "source": [ "## 3. Loss and accuracy" ] }, { "cell_type": "markdown", "id": "heading-6", "metadata": {}, "source": [ "### Activity 2: the loss ★★" ] }, { "cell_type": "markdown", "id": "cross-entropy-explanation", "metadata": {}, "source": [ "`torch.logsumexp(logits, dim=1)` computes the first term for every example, with shape `(batch,)`; it subtracts the largest logit internally, so it does not overflow. `logits[rows, targets]`, with `rows = [0, 1, ..., B-1]`, uses integer array indexing to take from row `i` the column `targets[i]`, again with shape `(batch,)`. The mean of the difference is a scalar." ] }, { "cell_type": "code", "execution_count": null, "id": "f90a471e", "metadata": {}, "outputs": [], "source": [ "def cross_entropy(logits: Float[torch.Tensor, \"batch classes\"], targets: Int[torch.Tensor, \"batch\"]) -> Float[torch.Tensor, \"\"]:\n", " rows = torch.arange(len(targets))\n", " return (torch.logsumexp(logits, dim=1) - logits[rows, targets]).mean()" ] }, { "cell_type": "markdown", "id": "heading-9", "metadata": {}, "source": [ "## 4. One training step" ] }, { "cell_type": "markdown", "id": "heading-10", "metadata": {}, "source": [ "### Activity 3: train the classifier ★" ] }, { "cell_type": "markdown", "id": "training-step-explanation", "metadata": {}, "source": [ "The gradients are cleared first, because `backward()` adds to `.grad`. The forward pass and `backward()` run outside `torch.no_grad()`, so that autograd records the computation; only the update runs inside it. Looping over `model.parameters()` updates the weight and the bias with the same line. `loss.item()` returns the loss, computed before the update, as a Python number." ] }, { "cell_type": "code", "execution_count": null, "id": "7b7b80ce", "metadata": {}, "outputs": [], "source": [ "def training_step(model: torch.nn.Module, X: Float[torch.Tensor, \"batch features\"], y: Int[torch.Tensor, \"batch\"], lr: float) -> float:\n", " for parameter in model.parameters():\n", " parameter.grad = None\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": "markdown", "id": "heading-13", "metadata": {}, "source": [ "## Optional A: why does the largest rate win? ★★★" ] }, { "cell_type": "markdown", "id": "lr-activity-explanation", "metadata": {}, "source": [ "With these four features the three species are linearly separable on the training set: the `lr=10` run reaches 100% training accuracy. Once a linear classifier separates the data, scaling up its weights makes every correct logit larger relative to the others, so the cross-entropy keeps falling as the norm grows. The loss never reaches zero and the norm never levels off, though both change more and more slowly. The direction, instead, settles: training keeps pushing the same separator further out. A larger step travels this path faster, which is why `lr=10` wins.\n", "\n", "Rates of 100 and 1000 do not break anything either. The first update overshoots and the loss jumps, but the loss is convex in the parameters and the data are separable, so training recovers. This is a property of this problem, not of gradient descent: with an MLP, or with classes that overlap, the same rates behave very differently." ] }, { "cell_type": "code", "execution_count": null, "id": "lr-activity-reference", "metadata": {}, "outputs": [], "source": [ "for rate in learning_rates:\n", " print(f\"lr={rate:g}: weight norm {lr_models[rate].weight.norm().item():.2f}, \"\n", " f\"training accuracy {evaluate(lr_models[rate], Xtrain, ytrain)[1]:.3f}\")\n", "\n", "longer = copy.deepcopy(lr_models[10.0])\n", "norms, directions, train_losses = [], [], []\n", "for _ in range(10):\n", " trace = fit(longer, Xtrain, ytrain, Xval, yval, lr=10.0, epochs=200)\n", " norms.append(longer.weight.norm().item())\n", " directions.append((longer.weight / longer.weight.norm()).detach().flatten())\n", " train_losses.append(trace[\"train_loss\"][-1])\n", "cosines = [float(a @ b) for a, b in zip(directions, directions[1:])]\n", "print(\"Norm every 200 updates:\", [round(n, 1) for n in norms])\n", "print(\"Training loss:\", [f\"{v:.1e}\" for v in train_losses])\n", "print(\"Cosine between consecutive directions:\", [round(c, 4) for c in cosines])\n", "assert all(b > a for a, b in zip(norms, norms[1:]))\n", "assert all(b < a for a, b in zip(train_losses, train_losses[1:])) and train_losses[-1] > 0\n", "assert cosines[-1] > 0.999\n", "\n", "for rate in [100.0, 1000.0]:\n", " trial = copy.deepcopy(initial_model)\n", " trace = fit(trial, Xtrain, ytrain, Xval, yval, lr=rate, epochs=200)\n", " print(f\"lr={rate:g}: first losses\", [round(v, 2) for v in trace[\"train_loss\"][:10]],\n", " f\"final {trace['train_loss'][-1]:.1e}\")\n", " assert np.isfinite(trace[\"train_loss\"]).all()" ] }, { "cell_type": "markdown", "id": "heading-16", "metadata": {}, "source": [ "## Optional B: a different training step ★★" ] }, { "cell_type": "markdown", "id": "suspect-explanation", "metadata": {}, "source": [ "`suspect_step` never clears the gradients, so each update uses the sum of all the gradients computed so far, most of them at older parameter values. This is no longer gradient descent. The loss can still go down, which is why the loss curve alone does not reveal the bug. A direct test: differentiate twice at the same parameters, without updating, and the stored gradient doubles. The fix is to set every `.grad` to `None` at the start of the step, as in `training_step`.\n", "\n", "Accumulating gradients is sometimes what we want, for example to combine several mini-batches into one update, as long as the loss is scaled correctly (see case 3 of the autograd detective in PT01). Here, instead, we update after every `backward()` and never clear." ] }, { "cell_type": "code", "execution_count": null, "id": "21fe67f8", "metadata": {}, "outputs": [], "source": [ "# Differentiate twice at the same parameters, without updating them.\n", "probe_model = LogisticRegression(4, 3)\n", "cross_entropy(probe_model(Xtrain), ytrain).backward()\n", "first = probe_model.weight.grad.clone()\n", "cross_entropy(probe_model(Xtrain), ytrain).backward()\n", "torch.testing.assert_close(probe_model.weight.grad, 2 * first)\n", "print(\"Same parameters, same data, twice the stored gradient.\")\n", "\n", "def fixed_step(model, X, y, lr):\n", " for parameter in model.parameters():\n", " parameter.grad = None\n", " return suspect_step(model, X, y, lr)" ] }, { "cell_type": "markdown", "id": "heading-19", "metadata": {}, "source": [ "## Optional C: a batch as large as the training set ★" ] }, { "cell_type": "markdown", "id": "minibatch-explanation", "metadata": {}, "source": [ "Each batch gradient is the average of the per-example gradients in that batch, so different examples give different averages. With a single batch containing every example, the average is the full-batch gradient, and shuffling only changes the order of the terms in the sum: the result agrees up to floating-point rounding, which is why the check uses `assert_close` and not exact equality. With `batch_size=len(ytrain) - 1` an epoch has two updates, the second computed from a single example, so its gradient is far noisier than the first." ] }, { "cell_type": "code", "execution_count": null, "id": "minibatch-activity-reference", "metadata": {}, "outputs": [], "source": [ "full_loader = DataLoader(TensorDataset(Xtrain, ytrain), batch_size=len(ytrain), shuffle=True,\n", " generator=torch.Generator().manual_seed(7))\n", "one_epoch, one_step = copy.deepcopy(initial_model), copy.deepcopy(initial_model)\n", "updates_in_epoch = 0\n", "for batch_X, batch_y in full_loader:\n", " training_step(one_epoch, batch_X, batch_y, lr=0.1)\n", " updates_in_epoch += 1\n", "training_step(one_step, Xtrain, ytrain, lr=0.1)\n", "assert updates_in_epoch == 1\n", "for loader_parameter, full_parameter in zip(one_epoch.parameters(), one_step.parameters()):\n", " torch.testing.assert_close(loader_parameter, full_parameter)\n", "print(\"One shuffled full-size batch gives the full-batch update.\")" ] }, { "cell_type": "markdown", "id": "heading-22", "metadata": {}, "source": [ "## Optional D: from logistic regression to an MLP ★★" ] }, { "cell_type": "markdown", "id": "mlp-reference-text", "metadata": {}, "source": [ "1. With `lr=10.0` the MLP's training loss jumps from about 1 to very large values within a few updates. In the recorded run it eventually comes back down, but the curve is erratic and the final validation loss is much worse than at `lr=0.1`; at `lr=30` the loss becomes NaN. The linear model's loss is convex and its gradients stay bounded, so on this separable data large steps only push the weights further in a good direction. The MLP's loss is not convex, and a large step can land in a region with much larger gradients, which makes the next step larger still.\n", "2. With all parameters at zero, every hidden unit outputs zero and receives zero gradient, and so does the output weight. Only the output bias learns, so the model can only learn the class frequencies: the loss stalls near 1.05 and the model predicts one class for every penguin. Random initialization breaks this symmetry. A zero start was fine for logistic regression because there are no hidden units to tell apart." ] }, { "cell_type": "code", "execution_count": null, "id": "mlp-reference", "metadata": {}, "outputs": [], "source": [ "torch.manual_seed(7)\n", "unstable_mlp = make_mlp()\n", "unstable_history = fit(unstable_mlp, Xtrain, ytrain, Xval, yval, lr=10.0, epochs=200)\n", "unstable_losses = torch.tensor(unstable_history[\"train_loss\"])\n", "print(\"lr=10: largest training loss\", unstable_losses.nan_to_num(float(\"inf\")).max().item())\n", "assert not torch.isfinite(unstable_losses).all() or unstable_losses.max() > 100\n", "\n", "zero_mlp = make_mlp()\n", "with torch.no_grad():\n", " for parameter in zero_mlp.parameters():\n", " parameter.zero_()\n", "zero_history = fit(zero_mlp, Xtrain, ytrain, Xval, yval, lr=0.1, epochs=200)\n", "print(f\"Zero initialization: final training loss {zero_history['train_loss'][-1]:.4f}\")\n", "for name, parameter in zero_mlp.named_parameters():\n", " print(name, \"still zero:\", bool((parameter == 0).all()))\n", "assert all((zero_mlp[i].weight == 0).all() for i in (0, 2))\n", "assert zero_history[\"train_loss\"][-1] > 1.0" ] }, { "cell_type": "markdown", "id": "heading-25", "metadata": {}, "source": [ "## Optional E: which examples drive the update?" ] }, { "cell_type": "markdown", "id": "heading-26", "metadata": {}, "source": [ "### Magnitude and direction" ] }, { "cell_type": "markdown", "id": "per-example-instructor", "metadata": {}, "source": [ "Examples with a large norm and a positive cosine contribute most to the mean gradient. Large gradients can cancel each other out: two examples pulling in opposite directions both have a large norm, but their sum is small.\n", "\n", "Changing only the label changes both the size and the direction of the gradient. Still, a large norm is not a test of label quality: a correctly labeled but hard example (ambiguous measurements, or a species that a linear boundary cannot separate well) can also disagree strongly with the current model. The cosine is always relative to the mean gradient. Near a minimum the mean gets small and its direction becomes unreliable, so another run from the learning-rate comparison can highlight different examples. Measuring how much one example influences the final trained model would need retraining, which is a different experiment.\n", "\n", "The loop and the transforms compute the same derivatives. `torch.func.grad` differentiates with respect to the explicit parameter dictionary, even though its values are detached, and it does not fill the module's `.grad` fields." ] }, { "cell_type": "markdown", "id": "heading-28", "metadata": {}, "source": [ "## Optional F: store an image in an MLP ★★★" ] }, { "cell_type": "markdown", "id": "image-reference-intro", "metadata": {}, "source": [ "The reference experiment runs the four prescribed configurations on CPU. The frequency matrix is a registered buffer: the optimizer does not update it, but it is saved with the model. The network never sees the formula that generated the image, only pixel values. This is a small run with one seed, not a tuned comparison of encodings or widths." ] }, { "cell_type": "code", "execution_count": null, "id": "image-reference-model", "metadata": {}, "outputs": [], "source": [ "class CoordinateMLP(torch.nn.Module):\n", " def __init__(self, width: int, fourier: bool):\n", " super().__init__()\n", " frequency_generator = torch.Generator().manual_seed(7)\n", " frequencies = 1.5 * torch.randn(16, 2, generator=frequency_generator) if fourier else torch.empty(0, 2)\n", " self.register_buffer(\"frequencies\", frequencies)\n", " input_features = 2 * len(frequencies) if fourier else 2\n", " self.layers = torch.nn.Sequential(\n", " torch.nn.Linear(input_features, width), torch.nn.ReLU(),\n", " torch.nn.Linear(width, width), torch.nn.ReLU(),\n", " torch.nn.Linear(width, 3), torch.nn.Sigmoid(),\n", " )\n", "\n", " def forward(self, coordinates: Float[torch.Tensor, \"pixels 2\"]) -> Float[torch.Tensor, \"pixels 3\"]:\n", " if len(self.frequencies):\n", " phase = 2 * torch.pi * coordinates @ self.frequencies.T\n", " coordinates = torch.cat([phase.sin(), phase.cos()], dim=1)\n", " return self.layers(coordinates)\n", "\n", "\n", "def fit_coordinate_mlp(width: int, fourier: bool):\n", " with torch.random.fork_rng(devices=[]):\n", " torch.manual_seed(7)\n", " coordinate_model = CoordinateMLP(width, fourier)\n", " optimizer = torch.optim.Adam(coordinate_model.parameters(), lr=0.01)\n", " trace = {\"update\": [], \"train_mse\": [], \"heldout_mse\": []}\n", " snapshots = {}\n", " for update in range(401):\n", " if update % 20 == 0:\n", " with torch.no_grad():\n", " reconstructed = coordinate_model(image_coordinates)\n", " trace[\"update\"].append(update)\n", " trace[\"train_mse\"].append(F.mse_loss(reconstructed[image_train_mask], image_rgb[image_train_mask]).item())\n", " trace[\"heldout_mse\"].append(F.mse_loss(reconstructed[image_heldout_mask], image_rgb[image_heldout_mask]).item())\n", " if update in (0, 100, 400):\n", " snapshots[update] = reconstructed.reshape(image_side, image_side, 3).clone()\n", " if update == 400:\n", " break\n", " optimizer.zero_grad(set_to_none=True)\n", " prediction = coordinate_model(image_coordinates[image_train_mask])\n", " image_loss = F.mse_loss(prediction, image_rgb[image_train_mask])\n", " image_loss.backward()\n", " optimizer.step()\n", " return coordinate_model, trace, snapshots\n", "\n", "image_runs = {}\n", "for encoding in (\"raw\", \"Fourier\"):\n", " for width in (16, 32):\n", " image_runs[(encoding, width)] = fit_coordinate_mlp(width, encoding == \"Fourier\")" ] }, { "cell_type": "code", "execution_count": null, "id": "image-reference-results", "metadata": {}, "outputs": [], "source": [ "image_summary_rows = []\n", "for (encoding, width), (coordinate_model, trace, snapshots) in image_runs.items():\n", " parameter_count = sum(p.numel() for p in coordinate_model.parameters())\n", " payload_bytes = sum(value.numel() * value.element_size() for value in coordinate_model.state_dict().values())\n", " image_summary_rows.append({\n", " \"encoding\": encoding, \"width\": width, \"parameters\": parameter_count,\n", " \"float32 payload bytes\": payload_bytes,\n", " \"train MSE\": trace[\"train_mse\"][-1], \"held-out MSE\": trace[\"heldout_mse\"][-1],\n", " })\n", "image_summary = pd.DataFrame(image_summary_rows)\n", "print(image_summary.to_string(index=False, float_format=lambda value: f\"{value:.6f}\"))\n", "print(\"Original uint8 RGB payload bytes:\", image_bytes.numel() * image_bytes.element_size())\n", "\n", "fig, axes = plt.subplots(2, 3, figsize=(8, 5.5))\n", "for row, encoding in enumerate((\"raw\", \"Fourier\")):\n", " for col, update in enumerate((0, 100, 400)):\n", " axes[row, col].imshow(image_runs[(encoding, 32)][2][update])\n", " axes[row, col].set_title(f\"{encoding}, width 32, step {update}\", fontsize=10)\n", " axes[row, col].axis(\"off\")\n", "fig.tight_layout()\n", "plt.show()\n", "\n", "fig, axes = plt.subplots(1, 3, figsize=(13, 3.5))\n", "for (encoding, width), (_, trace, _) in image_runs.items():\n", " label = f\"{encoding}, {width}\"\n", " style = \"-\" if encoding == \"raw\" else \"--\"\n", " axes[0].plot(trace[\"update\"], trace[\"train_mse\"], style, label=label)\n", " axes[1].plot(trace[\"update\"], trace[\"heldout_mse\"], style, label=label)\n", "for row in image_summary.to_dict(\"records\"):\n", " axes[2].scatter(row[\"parameters\"], row[\"held-out MSE\"], label=f\"{row['encoding']}, {row['width']}\")\n", "axes[0].set(xlabel=\"Update\", ylabel=\"Training pixel MSE\", yscale=\"log\")\n", "axes[1].set(xlabel=\"Update\", ylabel=\"Held-out pixel MSE\", yscale=\"log\")\n", "axes[2].set(xlabel=\"Trainable parameters\", ylabel=\"Held-out pixel MSE\", yscale=\"log\")\n", "axes[0].legend(fontsize=8)\n", "axes[2].legend(fontsize=8)\n", "fig.tight_layout()\n", "plt.show()\n", "\n", "fig, axes = plt.subplots(1, 2, figsize=(6, 3))\n", "with torch.no_grad():\n", " for ax, encoding in zip(axes, (\"raw\", \"Fourier\")):\n", " dense_rgb = image_runs[(encoding, 32)][0](coordinate_grid(64)).reshape(64, 64, 3)\n", " ax.imshow(dense_rgb)\n", " ax.set_title(f\"{encoding}: 64 by 64 query\")\n", " ax.axis(\"off\")\n", "fig.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "image-reference-discussion", "metadata": {}, "source": [ "The network sees only a quarter of the pixels; the others measure how well it interpolates. In the recorded CPU run, Fourier features fit the training pixels much more closely, while the raw-coordinate model with width 32 has the lowest held-out error. Fitting the observed pixels and filling in the missing ones are different things, and the training error alone cannot tell them apart. Compare the images and the held-out curves before giving Fourier features the credit for any improvement.\n", "\n", "The storage column counts every parameter and buffer, including the frequency matrix. It leaves out the code needed to decode the image, the architecture description and any file format overhead. It compares uncompressed sizes, not PNG or JPEG files, so even a network smaller than the raw image would not be a compression result without a codec comparison at equal quality.\n", "\n", "The 64 by 64 render evaluates the same function at more points; it adds no information, and outside the training range the function is even less constrained. Other seeds, images or Fourier scales may change the ranking. These are good follow-up questions, not conclusions of this four-run example." ] } ], "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 }