{ "cells": [ { "cell_type": "markdown", "id": "solutions-intro", "metadata": {}, "source": [ "# PT01: Introduction to PyTorch: solutions\n", "\n", "The solutions to the exercises of [PT01](https://colab.research.google.com/github/sscardapane/teaching-materials/blob/main/notebooks/PT01_Introduction_to_PyTorch.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": [ "## Before PT02: a short check" ] }, { "cell_type": "markdown", "id": "6876cd0e", "metadata": {}, "source": [ "1. Reducing over `dim=1` gives shape `(3,)`, which does not broadcast against `(3, 2)`. Use `A.mean(dim=1, keepdim=True)`, with shape `(3, 1)`. With the square `S`, the row means `[2, 6]` have shape `(2,)` and broadcast as a **row**: the first mean is subtracted from the first column and the second from the second column. The result `[[-1, -3], [3, 1]]` has the right shape and no error, but the correct answer is `[[-1, 1], [-1, 1]]`. Square shapes hide axis mistakes.\n", "2. `[2, 4] + [3, 3] = [5, 7]`, the gradient of `a.square().sum() + (3 * a).sum()`: `backward()` adds, so the stored gradient belongs to the sum of the two functions. After the update `a = [0.5, 1.3]`, and the third call adds `[1.0, 2.6]`, giving `[6.0, 9.6]` instead of `[1.0, 2.6]`. Set `a.grad = None` before each backward call whose gradient we want on its own.\n", "3. Logits `(5, 3)`; mean loss `()`; weight gradient `(3, 4)`; bias gradient `(3,)`. With `reduction=\"none\"` the loss has shape `(5,)` and `backward()` raises an error, because it needs a scalar to start from. Calling `.mean()` first gives the same gradients as before.\n", "\n", "The code below checks the three answers." ] }, { "cell_type": "code", "execution_count": null, "id": "check-answers-code", "metadata": {}, "outputs": [], "source": [ "# Executable answers to the check.\n", "S = torch.tensor([[1., 3.], [5., 7.]])\n", "torch.testing.assert_close(S - S.mean(dim=1), torch.tensor([[-1., -3.], [3., 1.]]))\n", "torch.testing.assert_close(S - S.mean(dim=1, keepdim=True), torch.tensor([[-1., 1.], [-1., 1.]]))\n", "\n", "a = torch.tensor([1., 2.], requires_grad=True)\n", "a.square().sum().backward()\n", "(3 * a).sum().backward()\n", "torch.testing.assert_close(a.grad, torch.tensor([5., 7.]))\n", "with torch.no_grad():\n", " a -= 0.1 * a.grad\n", "a.square().sum().backward()\n", "torch.testing.assert_close(a, torch.tensor([0.5, 1.3]))\n", "torch.testing.assert_close(a.grad, torch.tensor([6.0, 9.6]))\n", "\n", "check_X, check_y = torch.randn(5, 4), torch.tensor([0, 2, 1, 1, 0])\n", "check_W = torch.randn(3, 4, requires_grad=True)\n", "check_b = torch.zeros(3, requires_grad=True)\n", "per_example = F.cross_entropy(check_X @ check_W.T + check_b, check_y, reduction=\"none\")\n", "assert per_example.shape == (5,)\n", "try:\n", " per_example.backward()\n", "except RuntimeError as error:\n", " print(\"Non-scalar backward:\", str(error).splitlines()[0])\n", "else:\n", " raise AssertionError(\"backward() on a vector loss should fail\")\n", "per_example.mean().backward()\n", "assert check_W.grad.shape == (3, 4) and check_b.grad.shape == (3,)\n", "mean_W_grad, mean_b_grad = torch.autograd.grad(\n", " F.cross_entropy(check_X @ check_W.T + check_b, check_y), (check_W, check_b))\n", "torch.testing.assert_close(check_W.grad, mean_W_grad)\n", "torch.testing.assert_close(check_b.grad, mean_b_grad)" ] }, { "cell_type": "markdown", "id": "heading-4", "metadata": {}, "source": [ "## Optional: tensor semantics challenges" ] }, { "cell_type": "markdown", "id": "heading-5", "metadata": {}, "source": [ "### 1. One error per example ★" ] }, { "cell_type": "markdown", "id": "tensor-challenge-solution-1", "metadata": {}, "source": [ "Broadcasting `(3, 1)` against `(3,)` produces a `(3, 3)` matrix: entry `(i, j)` compares prediction `i` with target `j`. Its rows are `[1, -1, -4]`, `[2, 0, -3]` and `[4, 2, -1]`, and the mean of the nine squares is `52/9`. The intended errors are `[1, 0, -1]`, with MSE `2/3`. Both losses are scalars, so checking the shape of the loss does not catch the bug; checking the shape of the errors does. `squeeze(-1)` removes only the last axis, so a batch with a single example keeps its batch axis." ] }, { "cell_type": "code", "execution_count": null, "id": "tensor-challenge-solutions-code-1", "metadata": {}, "outputs": [], "source": [ "errors = predictions.squeeze(-1) - targets\n", "mse = errors.square().mean()\n", "assert errors.shape == targets.shape == (3,)\n", "torch.testing.assert_close(errors, torch.tensor([1., 0., -1.]))\n", "torch.testing.assert_close(mse, torch.tensor(2. / 3.))" ] }, { "cell_type": "markdown", "id": "heading-8", "metadata": {}, "source": [ "### 2. Which axis contains the examples? ★★" ] }, { "cell_type": "markdown", "id": "tensor-challenge-solution-2", "metadata": {}, "source": [ "`batch.T @ weights` combines the first feature of every example with the first weight, and so on, which gives `[31, 42]`. The intended predictions are `[21, 43]`. The batch is square, so both results have shape `(2,)`: only a check on the values rejects the original. With three examples, `larger_batch.T` has shape `(2, 3)` and its product with `weights`, which has size two, raises a dimension mismatch." ] }, { "cell_type": "code", "execution_count": null, "id": "tensor-challenge-solutions-code-2", "metadata": {}, "outputs": [], "source": [ "row_predictions = batch @ weights\n", "assert row_predictions.shape == (batch.shape[0],)\n", "torch.testing.assert_close(row_predictions, torch.tensor([21., 43.]))\n", "\n", "larger_batch = torch.cat([batch, torch.tensor([[5., 6.]])], dim=0)\n", "larger_predictions = larger_batch @ weights\n", "assert larger_predictions.shape == (3,)\n", "torch.testing.assert_close(larger_predictions, torch.tensor([21., 43., 65.]))" ] }, { "cell_type": "markdown", "id": "heading-11", "metadata": {}, "source": [ "### 3. One distribution per example ★★" ] }, { "cell_type": "markdown", "id": "tensor-challenge-solution-3", "metadata": {}, "source": [ "`softmax(dim=0)` normalizes each column, so the three examples compete for each class. The columns sum to one, while the rows sum to about `1.05`, `0.80` and `1.15`, and every entry is still between 0 and 1. The first example is predicted as class 1 (probability `0.58`) although its largest logit is class 0: normalizing over the classes gives `[0.84, 0.11, 0.04]`. `dim=-1` names the class axis even if we later add more leading axes. For predictions alone the softmax is not needed: `scores.argmax(dim=-1)` gives the same classes." ] }, { "cell_type": "code", "execution_count": null, "id": "tensor-challenge-solutions-code-3", "metadata": {}, "outputs": [], "source": [ "probabilities = scores.softmax(dim=-1)\n", "assert probabilities.shape == scores.shape\n", "torch.testing.assert_close(probabilities.sum(dim=-1), torch.ones(3))\n", "torch.testing.assert_close(probabilities.argmax(dim=-1), scores.argmax(dim=-1))\n", "torch.testing.assert_close(probabilities.argmax(dim=-1), torch.tensor([0, 2, 0]))" ] }, { "cell_type": "markdown", "id": "heading-14", "metadata": {}, "source": [ "## Optional: autograd detective" ] }, { "cell_type": "markdown", "id": "heading-15", "metadata": {}, "source": [ "### 1. Did the gradient stop at the intermediate tensor? ★★" ] }, { "cell_type": "markdown", "id": "autograd-detective-solution-1", "metadata": {}, "source": [ "The gradient did pass through `hidden`. `leaf` is a leaf, with `grad_fn=None` and gradient `[18, 36]`. `hidden` is not a leaf and has a backward node: its gradient `[6, 12]` was computed along the way, but not stored, which is what the warning says. To keep it, call `retain_grad()` before `backward()`, on a fresh computation." ] }, { "cell_type": "code", "execution_count": null, "id": "autograd-detective-solutions-code-1", "metadata": {}, "outputs": [], "source": [ "leaf = torch.tensor([1., 2.], requires_grad=True)\n", "hidden = 3 * leaf\n", "hidden.retain_grad()\n", "hidden.square().sum().backward()\n", "assert leaf.is_leaf and not hidden.is_leaf\n", "torch.testing.assert_close(leaf.grad, torch.tensor([18., 36.]))\n", "torch.testing.assert_close(hidden.grad, torch.tensor([6., 12.]))" ] }, { "cell_type": "markdown", "id": "heading-18", "metadata": {}, "source": [ "### 2. Can we reconnect a detached tensor? ★" ] }, { "cell_type": "markdown", "id": "autograd-detective-solution-2", "metadata": {}, "source": [ "`backward()` succeeds, but on the wrong leaf: `restart.grad` is `[6, 12]`, while `original.grad` stays `None`. Turning gradients back on after `detach()` creates a new leaf; it does not restore the operation that connected the two tensors. The fix keeps that operation in the recorded computation." ] }, { "cell_type": "code", "execution_count": null, "id": "autograd-detective-solutions-code-2", "metadata": {}, "outputs": [], "source": [ "original = torch.tensor([1., 2.], requires_grad=True)\n", "connected = 3 * original\n", "connected.square().sum().backward()\n", "torch.testing.assert_close(original.grad, torch.tensor([18., 36.]))" ] }, { "cell_type": "markdown", "id": "heading-21", "metadata": {}, "source": [ "### 3. Is accumulation always a mistake? ★★" ] }, { "cell_type": "markdown", "id": "autograd-detective-solution-3", "metadata": {}, "source": [ "Here accumulation is intended. The gradient is `10/3` after the first call and `28/3` after the second, the same as one `backward()` on the full batch. Each microbatch contributes its sum of squared errors divided by the total number of examples, so clearing between the calls would throw away the first contribution. Dividing each microbatch mean by two instead gives `11.5`: the microbatch with one example then counts as much as the one with two." ] }, { "cell_type": "code", "execution_count": null, "id": "autograd-detective-solutions-code-3", "metadata": {}, "outputs": [], "source": [ "full_parameter = torch.tensor(1., requires_grad=True)\n", "all_values = torch.cat(microbatches)\n", "(full_parameter * all_values).square().mean().backward()\n", "torch.testing.assert_close(parameter.grad, full_parameter.grad)\n", "torch.testing.assert_close(parameter.grad, torch.tensor(28. / 3.))" ] }, { "cell_type": "markdown", "id": "heading-24", "metadata": {}, "source": [ "### 4. Is every in-place change safe inside `no_grad`? ★★★" ] }, { "cell_type": "markdown", "id": "autograd-detective-solution-4", "metadata": {}, "source": [ "`backward()` raises an error. The in-place update changed a value that backward needs (the square needs the original `mutable`); `no_grad` only means that the update itself is not recorded. Move the update after `backward()`. Modifying `mutable.detach()` in place changes the same memory and fails in the same way." ] }, { "cell_type": "code", "execution_count": null, "id": "autograd-detective-solutions-code-4", "metadata": {}, "outputs": [], "source": [ "mutable = torch.tensor([1., 2.], requires_grad=True)\n", "mutable.square().sum().backward()\n", "torch.testing.assert_close(mutable.grad, torch.tensor([2., 4.]))\n", "with torch.no_grad():\n", " mutable -= 0.1 * mutable.grad\n", "mutable.grad = None\n", "torch.testing.assert_close(mutable, torch.tensor([0.8, 1.6]))\n", "assert mutable.is_leaf and mutable.requires_grad" ] }, { "cell_type": "markdown", "id": "heading-27", "metadata": {}, "source": [ "## Optional: a few array operations" ] }, { "cell_type": "markdown", "id": "heading-28", "metadata": {}, "source": [ "### The two diagonals ★" ] }, { "cell_type": "markdown", "id": "0202983b-explanation", "metadata": {}, "source": [ "`A.diagonal()` returns the main diagonal. Flipping the columns with `A.flip(dims=[1])` turns the anti-diagonal into the main diagonal, so the same call returns it. For an odd size the center element appears in both sums, as required." ] }, { "cell_type": "code", "execution_count": null, "id": "0202983b-reference", "metadata": {}, "outputs": [], "source": [ "def sum_diagonals(A: Float[torch.Tensor, \"n n\"]) -> Optional[Float[torch.Tensor, \"\"]]:\n", " return A.diagonal().sum() + A.flip(dims=[1]).diagonal().sum()" ] }, { "cell_type": "markdown", "id": "heading-31", "metadata": {}, "source": [ "### Normalizing the rows ★" ] }, { "cell_type": "markdown", "id": "52081f9c-explanation", "metadata": {}, "source": [ "We reduce over `dim=1`, the features of each row, with `keepdim=True`, so the means and standard deviations have shape `(batch, 1)` and broadcast against `A`. The standard deviation of a constant row is zero. `clamp_min(eps)` replaces it with `eps`, so the centered row, which is all zeros, stays zero instead of becoming `0/0 = nan`." ] }, { "cell_type": "code", "execution_count": null, "id": "52081f9c-reference", "metadata": {}, "outputs": [], "source": [ "def normalize_rows(A: Float[torch.Tensor, \"batch features\"], eps: float = 1e-8) -> Optional[Float[torch.Tensor, \"batch features\"]]:\n", " centered = A - A.mean(dim=1, keepdim=True)\n", " std = A.std(dim=1, correction=0, keepdim=True)\n", " return centered / std.clamp_min(eps)" ] }, { "cell_type": "markdown", "id": "heading-34", "metadata": {}, "source": [ "### Cosine similarity ★★" ] }, { "cell_type": "markdown", "id": "33514e05-explanation", "metadata": {}, "source": [ "`F.normalize` divides each row by its Euclidean norm, so the dot product of two normalized rows is their cosine. `unit @ unit.T` computes all the pairs at once, with shape `(batch, batch)`. `F.normalize` divides by the larger of the norm and `eps`, so a zero row stays zero and all its similarities are zero." ] }, { "cell_type": "code", "execution_count": null, "id": "33514e05-reference", "metadata": {}, "outputs": [], "source": [ "def cosine_similarity(A: Float[torch.Tensor, \"batch features\"]) -> Optional[Float[torch.Tensor, \"batch batch\"]]:\n", " unit = F.normalize(A, p=2, dim=1, eps=1e-12)\n", " return unit @ unit.T" ] } ], "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 }