{ "cells": [ { "cell_type": "markdown", "id": "8c75efd0", "metadata": {}, "source": [ "# PT01: Introduction to PyTorch\n", "\n", "This notebook covers the PyTorch we need for the first labs: tensors, batched linear models, gradients and parameter updates. If you have used PyTorch before, skim Sections 1 to 5 and try the short check at the end of Section 5. If you have not, read and run everything up to that check before PT02 (the [PyTorch documentation](https://docs.pytorch.org/docs/2.14/index.html) is a good companion). Knowing NumPy helps, since most of the array syntax is the same.\n", "\n", "Everything after the check is optional: a few short tensor exercises, a closer look at autograd with some debugging cases, and how tensors are stored in memory. You can come back to these later. Exercises are rated from 1 to 3 stars based on expected difficulty. The answers to the check and to the exercises are in a separate notebook, [PT01 solutions](https://colab.research.google.com/github/sscardapane/teaching-materials/blob/main/notebooks/PT01_Introduction_to_PyTorch_solutions.ipynb).\n", "\n", "A good habit: before running a cell, predict its output, or at least its shape. If something surprises you, change the example and run it again." ] }, { "cell_type": "markdown", "id": "4c3764fd", "metadata": {}, "source": [ "We annotate the shapes of function inputs and outputs with `jaxtyping`. For example, `Float[torch.Tensor, \"batch features\"]` is a floating-point tensor with two axes, named `batch` and `features`. The annotations are only documentation: nothing checks them when the code runs. The next cell installs the package, which you need on Colab." ] }, { "cell_type": "code", "execution_count": null, "id": "ba307eda", "metadata": {}, "outputs": [], "source": [ "%pip install jaxtyping" ] }, { "cell_type": "code", "execution_count": null, "id": "ea38c149", "metadata": {}, "outputs": [], "source": [ "import torch\n", "from jaxtyping import Float, Int\n", "from typing import Optional\n", "import torch.nn.functional as F\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": "pt01-checks", "metadata": { "cellView": "form" }, "outputs": [], "source": [ "#@title Checks for the optional exercises (run this cell; you do not need to read it)\n", "def _written(result, name):\n", " if result is None:\n", " print(f\"Write {name} first.\")\n", " return result is not None\n", "\n", "def check_sum_diagonals(sum_diagonals):\n", " if not _written(sum_diagonals(torch.eye(2)), \"sum_diagonals\"):\n", " return\n", " # A 3x3 matrix (the center is on both diagonals) and a 2x2 one whose diagonals differ.\n", " for A, expected in [(torch.arange(1., 10.).reshape(3, 3), 30.), (torch.tensor([[1., 2.], [3., 5.]]), 11.)]:\n", " result = sum_diagonals(A)\n", " assert torch.allclose(result, torch.tensor(expected)), f\"For the matrix\\n{A}\\nexpected {expected}, got {result}.\"\n", " print(\"sum_diagonals is correct.\")\n", "\n", "def check_normalize_rows(normalize_rows):\n", " # Square, so normalizing the wrong axis also runs; the second row is constant.\n", " A = torch.tensor([[1., 2., 4.], [4., 4., 4.], [0., 3., 12.]])\n", " if not _written(normalize_rows(A), \"normalize_rows\"):\n", " return\n", " result = normalize_rows(A)\n", " assert not torch.isnan(result).any(), \"The result contains nan: what happens to a constant row?\"\n", " expected = (A - A.mean(dim=1, keepdim=True)) / A.std(dim=1, correction=0, keepdim=True).clamp_min(1e-8)\n", " for i in range(3):\n", " assert torch.allclose(result[i], expected[i], atol=1e-6), f\"Row {i} should be {expected[i]}, got {result[i]}.\"\n", " print(\"normalize_rows is correct.\")\n", "\n", "def check_cosine_similarity(cosine_similarity):\n", " # Two parallel rows, an orthogonal one and a zero row.\n", " A = torch.tensor([[3., 4.], [6., 8.], [4., -3.], [0., 0.]])\n", " if not _written(cosine_similarity(A), \"cosine_similarity\"):\n", " return\n", " result = cosine_similarity(A)\n", " expected = torch.tensor([[1., 1., 0., 0.], [1., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 0.]])\n", " assert result.shape == (4, 4), f\"Expected shape (4, 4), got {tuple(result.shape)}.\"\n", " assert torch.allclose(result, expected, atol=1e-6), f\"For the rows\\n{A}\\nexpected\\n{expected}\\ngot\\n{result}\"\n", " print(\"cosine_similarity is correct.\")" ] }, { "cell_type": "markdown", "id": "d03d63f5", "metadata": {}, "source": [ "## 1. Tensors\n", "\n", "The basic data type is `torch.Tensor`, PyTorch's version of a NumPy array. We can build one from a list with `torch.tensor`, or with functions such as `torch.zeros` and `torch.randn`. In this course a batch of data has one example per row and one feature per column. Here $X \\sim (B,D)$, with $B=3$ examples and $D=2$ features." ] }, { "cell_type": "code", "execution_count": null, "id": "ddfaf252", "metadata": {}, "outputs": [], "source": [ "X = torch.tensor([[1., 2.], [3., 1.], [2., 4.]])\n", "print(X)\n", "print(\"Shape:\", X.shape)\n", "print(\"Dtype:\", X.dtype)\n", "print(\"Device:\", X.device)" ] }, { "cell_type": "markdown", "id": "c234a57b", "metadata": {}, "source": [ "Every tensor also lives on a device (CPU or GPU). `X.to(...)` moves it to another one; we do not need this yet.\n", "\n", "Indexing works as in NumPy. Look at the last two lines: indexing a single column drops that axis, while slicing keeps it." ] }, { "cell_type": "code", "execution_count": null, "id": "273d77c1", "metadata": {}, "outputs": [], "source": [ "print(\"Second example:\", X[1])\n", "print(\"First two examples:\\n\", X[:2])\n", "print(\"Last feature:\", X[:, -1], X[:, -1].shape)\n", "print(\"Last feature, keeping its axis:\\n\", X[:, -1:], X[:, -1:].shape)" ] }, { "cell_type": "markdown", "id": "cc4bd8d7", "metadata": {}, "source": [ "## 2. A batch of linear predictions\n", "\n", "For a single example $x$, a linear model with $C$ outputs computes $z=Wx+b$. With the examples stored as rows, we can process the whole batch at once:\n", "\n", "$$Z=XW^\\top+b.$$\n", "\n", "Here $W\\sim(C,D)$, $b\\sim(C,)$ and $Z\\sim(B,C)$. The bias is a single vector, and PyTorch *broadcasts* it: it is added to every row. `@` is matrix multiplication, while `*` is elementwise multiplication. The last line checks the first row of `Z` against the single-example formula." ] }, { "cell_type": "code", "execution_count": null, "id": "6f1cb911", "metadata": {}, "outputs": [], "source": [ "W = torch.tensor([[1., -1.], [0.5, 2.]]) # (C, D)\n", "b = torch.tensor([0.2, -0.3]) # (C,)\n", "Z = X @ W.T + b # (B, C)\n", "print(Z)\n", "torch.testing.assert_close(Z[0], W @ X[0] + b)" ] }, { "cell_type": "markdown", "id": "b68f56e2", "metadata": {}, "source": [ "Reductions such as `sum` and `mean` remove the axis they reduce over. With `keepdim=True` the axis stays, with size one, which is what we need when the result is broadcast back against the original tensor.\n", "\n", "For example, to center each feature we average over the examples (`dim=0`), not over the features. Change `dim=0` to `dim=1` below: what gets centered now?" ] }, { "cell_type": "code", "execution_count": null, "id": "5a34ba2b", "metadata": {}, "outputs": [], "source": [ "feature_mean = X.mean(dim=0, keepdim=True)\n", "centered = X - feature_mean\n", "print(\"Mean shape:\", feature_mean.shape)\n", "print(centered)\n", "torch.testing.assert_close(centered.mean(dim=0), torch.zeros(2), atol=1e-6, rtol=0)" ] }, { "cell_type": "markdown", "id": "863b7e11", "metadata": {}, "source": [ "## 3. Computing gradients\n", "\n", "Take a regression model $\\hat y=Xw+b$ with a mean squared error loss. We mark the tensors we want gradients for (the parameters) with `requires_grad=True`. Before running the next cell, predict the shapes of the loss, `w.grad` and `bias.grad`." ] }, { "cell_type": "code", "execution_count": null, "id": "1a5181d3", "metadata": {}, "outputs": [], "source": [ "y = torch.tensor([1., -1., 2.])\n", "w = torch.tensor([0.2, -0.1], requires_grad=True)\n", "bias = torch.tensor(0., requires_grad=True)\n", "\n", "prediction = X @ w + bias\n", "loss = ((prediction - y) ** 2).mean()\n", "print(\"Loss:\", loss.item(), \"Shape:\", loss.shape)\n", "print(\"Parameter is a leaf:\", w.is_leaf)\n", "print(\"Prediction is a leaf:\", prediction.is_leaf)\n", "loss.backward()\n", "print(\"w.grad:\", w.grad)\n", "print(\"bias.grad:\", bias.grad)" ] }, { "cell_type": "markdown", "id": "e5d3e162", "metadata": {}, "source": [ "Calling `backward()` on the scalar loss computes its gradient with respect to the tensors we created with `requires_grad=True`, and stores it in their `.grad` field. These tensors are called *leaves*. Intermediate results such as `prediction` take part in the computation too, but their gradients are not stored.\n", "\n", "During the forward pass, PyTorch records the operations it runs; `backward()` goes back through this record. Afterwards most of the record is freed, so each new gradient needs a new forward pass. We will see how this works in detail when we study automatic differentiation." ] }, { "cell_type": "markdown", "id": "3d4c998c", "metadata": {}, "source": [ "## 4. Updating the parameters\n", "\n", "A gradient descent step is $\\theta\\leftarrow\\theta-\\eta\\nabla L(\\theta)$. We run it inside `torch.no_grad()`: the update is not part of the model, so autograd should not record it (and PyTorch refuses to modify a leaf that requires gradients in place outside such a block). Then we clear the gradients, because `backward()` **adds** to `.grad` instead of overwriting it." ] }, { "cell_type": "code", "execution_count": null, "id": "763528a4", "metadata": {}, "outputs": [], "source": [ "lr = 0.01\n", "before = loss.item()\n", "with torch.no_grad():\n", " w -= lr * w.grad\n", " bias -= lr * bias.grad\n", "w.grad = None\n", "bias.grad = None\n", "\n", "after = ((X @ w + bias - y) ** 2).mean()\n", "print(f\"Loss before: {before:.4f}; after one update: {after.item():.4f}\")\n", "assert after.item() < before # This example uses a sufficiently small step." ] }, { "cell_type": "markdown", "id": "73515129", "metadata": {}, "source": [ "We can see this accumulation without training anything. Keep `a` fixed and differentiate the same function twice, with a new forward pass each time:" ] }, { "cell_type": "code", "execution_count": null, "id": "d8604392", "metadata": {}, "outputs": [], "source": [ "a = torch.tensor([1., 2.], requires_grad=True)\n", "a.square().sum().backward()\n", "first_gradient = a.grad.clone()\n", "a.square().sum().backward()\n", "print(\"First backward:\", first_gradient)\n", "print(\"Second backward:\", a.grad)\n", "torch.testing.assert_close(a.grad, 2 * first_gradient)\n", "a.grad = None" ] }, { "cell_type": "markdown", "id": "8c22431b", "metadata": {}, "source": [ "To log values during training, use `loss.item()`, which returns a plain Python number. If you need to keep a tensor, `tensor.detach()` returns one that is cut off from the recorded computation.\n", "\n", "`torch.autograd.grad` is a second way to call autograd: it returns the gradients instead of adding them to `.grad`. We will use it again when we study automatic differentiation." ] }, { "cell_type": "code", "execution_count": null, "id": "fe808200", "metadata": {}, "outputs": [], "source": [ "a = torch.tensor([1., 2.], requires_grad=True)\n", "(gradient,) = torch.autograd.grad(a.square().sum(), a)\n", "print(gradient)\n", "assert a.grad is None" ] }, { "cell_type": "markdown", "id": "b353a924", "metadata": {}, "source": [ "## 5. Classification uses the same steps\n", "\n", "For classification with $C$ classes, the model outputs $Z\\sim(B,C)$. These unnormalized scores are called *logits*. The targets $y\\sim(B,)$ are integer class indices. A softmax over each row turns the logits into probabilities, which is useful when we want to look at them.\n", "\n", "`F.cross_entropy` takes the **logits**, not the probabilities. It applies the softmax and the logarithm internally, in a numerically stable way." ] }, { "cell_type": "code", "execution_count": null, "id": "fcec9a6a", "metadata": {}, "outputs": [], "source": [ "logits = torch.tensor([[2., 0., -1.], [-1., 0., 2.]], requires_grad=True)\n", "labels = torch.tensor([0, 2], dtype=torch.long)\n", "classification_loss = F.cross_entropy(logits, labels)\n", "classification_loss.backward()\n", "print(\"Probabilities:\\n\", logits.detach().softmax(dim=-1))\n", "print(\"Loss:\", classification_loss.item())\n", "print(\"Gradient shape:\", logits.grad.shape)" ] }, { "cell_type": "markdown", "id": "32fe2595", "metadata": {}, "source": [ "Every training step has the same structure: clear the gradients, compute the predictions and a scalar loss, call `backward()`, update the parameters. For evaluation we only need the predictions, so there is no reason to record anything.\n", "\n", "Two tools are easy to confuse here. `model.eval()` changes how some layers behave, such as dropout and batch normalization, which we will see later. `torch.no_grad()` turns off recording. In PT02 we use both when evaluating a model.\n", "\n", "This is the end of the required part. Before PT02, make sure you can explain how the bias is broadcast, what shape each gradient has, and what happens if we forget to clear the gradients." ] }, { "cell_type": "markdown", "id": "c8c6288d", "metadata": {}, "source": [ "## Before PT02: a short check\n", "\n", "Answer these without running code first, then use the next cell to test your answers. The examples above contain the ideas, but not the answers.\n", "\n", "1. ★ `A` has shape `(3, 2)` and we want to center each **row**. `A - A.mean(dim=1)` raises an error: why, and what is the fix? Now take `S = torch.tensor([[1., 3.], [5., 7.]])`. Does `S - S.mean(dim=1)` raise an error? If not, what does it compute, and how does it differ from the correctly centered rows?\n", "2. ★★ `a = torch.tensor([1., 2.], requires_grad=True)`. We call `a.square().sum().backward()`, then `(3 * a).sum().backward()`, without clearing. What is `a.grad`, and of which function is it the gradient? We then update `a -= 0.1 * a.grad` inside `no_grad` and call `a.square().sum().backward()` once more, still without clearing. What are `a` and `a.grad` now, and what should `a.grad` have been?\n", "3. ★★ For `X @ W.T + b` with shapes `(5, 4)`, `(3, 4)` and `(3,)`, what are the shapes of the logits, of the mean cross-entropy loss, and of the two parameter gradients? What happens if we call `backward()` on `F.cross_entropy(logits, y, reduction=\"none\")` instead, and how can we get the same gradients as the mean loss from it?\n", "\n", "If one of these is unclear, go back to the corresponding example before PT02." ] }, { "cell_type": "code", "execution_count": null, "id": "d8d66913", "metadata": {}, "outputs": [], "source": [ "# Try your repairs and shape predictions here." ] }, { "cell_type": "markdown", "id": "tensor-challenges", "metadata": {}, "source": [ "## Optional: tensor semantics challenges\n", "\n", "Three short exercises that only need Sections 1 and 2, plus the softmax from Section 5. Each contains an expression that runs without errors but does not compute what we want. You can do them now or come back to them during a lab.\n", "\n", "For each one, predict the shape and values of the result before running the cell. Then explain the mistake and fix it. Finally, write assertions on the shape and on values you computed by hand, and check that at least one of them fails on the original expression." ] }, { "cell_type": "markdown", "id": "tensor-challenge-1", "metadata": {}, "source": [ "### 1. One error per example ★\n", "\n", "We have three predictions stored as a column, with shape `(3, 1)`, and three targets with shape `(3,)`. We want the three prediction errors and their mean squared value.\n", "\n", "What does each entry of `suspect_errors` compare? Fix the subtraction so that there is one error per example, in a tensor of shape `(3,)`. Would checking that the loss is a scalar catch this bug?" ] }, { "cell_type": "code", "execution_count": null, "id": "tensor-challenge-1-code", "metadata": {}, "outputs": [], "source": [ "predictions = torch.tensor([[1.], [2.], [4.]]) # (B, 1)\n", "targets = torch.tensor([0., 2., 5.]) # (B,)\n", "suspect_errors = predictions - targets\n", "suspect_mse = suspect_errors.square().mean()\n", "print(suspect_errors.shape, suspect_errors)\n", "print(\"MSE:\", suspect_mse)\n", "\n", "# Write the corrected errors and MSE, then add your assertions." ] }, { "cell_type": "markdown", "id": "tensor-challenge-2", "metadata": {}, "source": [ "### 2. Which axis contains the examples? ★★\n", "\n", "Each row of `batch` is an example with two features. The model predicts the first feature plus ten times the second, giving one prediction per row.\n", "\n", "The batch is square, so both `batch @ weights` and `batch.T @ weights` run. Predict `suspect_predictions`, then fix it and check your answer. Why can a shape assertion not catch this mistake? As a second test, add a third example `[5., 6.]` and predict what happens to each expression." ] }, { "cell_type": "code", "execution_count": null, "id": "tensor-challenge-2-code", "metadata": {}, "outputs": [], "source": [ "batch = torch.tensor([[1., 2.], [3., 4.]]) # (B, D)\n", "weights = torch.tensor([1., 10.]) # (D,)\n", "suspect_predictions = batch.T @ weights\n", "print(suspect_predictions.shape, suspect_predictions)\n", "\n", "# Compute one prediction per row, then add your assertions.\n", "# Repeat with a third example." ] }, { "cell_type": "markdown", "id": "tensor-challenge-3", "metadata": {}, "source": [ "### 3. One distribution per example ★★\n", "\n", "`scores` contains logits for three examples (rows) and three classes (columns). We want, for each example, a probability distribution over the classes.\n", "\n", "Predict which sums of `suspect_probabilities` equal one: the rows or the columns? Fix it and check that each example's probabilities sum to one. Why can neither a shape check nor a check that \"all entries are between 0 and 1\" catch this? Does the bug change any predicted class?" ] }, { "cell_type": "code", "execution_count": null, "id": "tensor-challenge-3-code", "metadata": {}, "outputs": [], "source": [ "scores = torch.tensor([[3., 1., 0.], [0., 0., 1.], [4., 0., 0.]]) # (B, C)\n", "suspect_probabilities = scores.softmax(dim=0)\n", "print(suspect_probabilities.shape, suspect_probabilities)\n", "print(\"Predicted classes:\", suspect_probabilities.argmax(dim=1))\n", "\n", "# Normalize over the classes, then add your assertions." ] }, { "cell_type": "markdown", "id": "autograd-tensor-fields", "metadata": {}, "source": [ "## Optional: a closer look at autograd\n", "\n", "This section goes deeper into Sections 3 and 4: what autograd stores on each tensor, and how to cut a tensor off from the recorded computation. The autograd detective cases after it build on this material.\n", "\n", "### What a tensor knows about autograd\n", "\n", "A few attributes tell us how autograd sees a tensor:\n", "\n", "| Attribute | Meaning |\n", "| --- | --- |\n", "| `requires_grad` | Autograd records the operations that use this tensor. |\n", "| `is_leaf` | No recorded operation produced this tensor. Parameters we create ourselves are leaves. Tensors that do not require gradients are also leaves. |\n", "| `grad_fn` | For a tensor produced by a recorded operation, the backward step of that operation. `None` for leaves. It is not a gradient. |\n", "| `grad` | Where `backward()` stores the gradient. It starts as `None` and, by default, is filled only for leaves. |\n", "| `retains_grad` | Whether an intermediate tensor was asked to keep its gradient with `retain_grad()`. |\n", "\n", "Consider the small computation $x \\rightarrow h = 3x \\rightarrow o = \\sum_i h_i^2$. Predict the attributes of the three tensors before running the cell. The exact name printed for `grad_fn` does not matter; what matters is whether it is `None`.\n", "\n", "References: [leaf tensors](https://docs.pytorch.org/docs/stable/generated/torch.Tensor.is_leaf.html), [leaf and non-leaf gradients](https://docs.pytorch.org/tutorials/beginner/understanding_leaf_vs_nonleaf_tutorial.html), [autograd mechanics](https://docs.pytorch.org/docs/stable/notes/autograd.html)." ] }, { "cell_type": "code", "execution_count": null, "id": "autograd-tensor-forward", "metadata": {}, "outputs": [], "source": [ "tensor_x = torch.tensor([1., 2.], requires_grad=True)\n", "tensor_h = 3 * tensor_x\n", "tensor_objective = tensor_h.square().sum()\n", "\n", "for name, t in [(\"x\", tensor_x), (\"h\", tensor_h), (\"objective\", tensor_objective)]:\n", " print(name, \"requires_grad:\", t.requires_grad, \"is_leaf:\", t.is_leaf,\n", " \"grad_fn:\", t.grad_fn, \"retains_grad:\", t.retains_grad)\n", "print(\"x.grad before backward:\", tensor_x.grad)\n", "assert tensor_x.is_leaf and tensor_x.grad_fn is None\n", "assert not tensor_h.is_leaf and tensor_h.grad_fn is not None\n", "assert tensor_x.grad is None" ] }, { "cell_type": "markdown", "id": "autograd-tensor-backward-text", "metadata": {}, "source": [ "So far nothing has been differentiated, and `x.grad` is still `None`. Calling `backward()` starts from the objective, with derivative 1, and applies the chain rule back to `x`: here $\\partial o/\\partial h = 2h = [6, 12]$ and $\\partial o/\\partial x = 3 \\cdot 2h = [18, 36]$.\n", "\n", "To see the gradient with respect to `h` as well, call `h.retain_grad()` **before** `backward()`. This only lets us look at it; the gradient that reaches `x` is the same either way." ] }, { "cell_type": "code", "execution_count": null, "id": "autograd-tensor-backward", "metadata": {}, "outputs": [], "source": [ "tensor_h.retain_grad()\n", "print(\"Before backward:\", tensor_x.grad, tensor_h.grad)\n", "tensor_objective.backward()\n", "print(\"After backward, x.grad:\", tensor_x.grad)\n", "print(\"After backward, h.grad:\", tensor_h.grad)\n", "print(\"h is still a non-leaf:\", not tensor_h.is_leaf)\n", "assert tensor_h.retains_grad and not tensor_x.retains_grad\n", "torch.testing.assert_close(tensor_h.grad, torch.tensor([6., 12.]))\n", "torch.testing.assert_close(tensor_x.grad, torch.tensor([18., 36.]))" ] }, { "cell_type": "markdown", "id": "autograd-tensor-lifetime", "metadata": {}, "source": [ "A `None` gradient is not a zero gradient. It means that `backward()` never reached the tensor, or that the tensor is an intermediate result whose gradient was not retained. A leaf that is reached always gets a tensor, possibly full of zeros.\n", "\n", "The stored gradients and the recorded computation are separate things. Setting `x.grad = None` clears the gradient and leaves the record alone. Each forward pass records new operations, and `backward()` normally frees what it needed from them (the tensor still shows a `grad_fn` afterwards).\n", "\n", "Do not confuse `h.retain_grad()` with `objective.backward(retain_graph=True)`. The first stores an intermediate gradient. The second keeps the record alive so that we can call `backward()` through it a second time, at the cost of memory; it does not clear or retain any `.grad`. In normal training we never need it, because each step runs a fresh forward pass. See [`backward`](https://docs.pytorch.org/docs/stable/generated/torch.Tensor.backward.html)." ] }, { "cell_type": "markdown", "id": "autograd-disconnect-text", "metadata": {}, "source": [ "### Cutting a connection\n", "\n", "Three operations that look similar but do different things:\n", "\n", "- `clone()` copies the data, and the copy stays connected: gradients flow back through it to the original.\n", "- `detach()` returns a tensor with no connection to the recorded computation. It does not copy anything: the two tensors share memory. Use `detach().clone()` for an independent snapshot.\n", "- Inside a `torch.no_grad()` block, new operations are not recorded. Tensors that already exist are unchanged.\n", "\n", "Calling `requires_grad_()` on a detached tensor makes it a new leaf; it does not restore the old connection. See [`detach`](https://docs.pytorch.org/docs/stable/generated/torch.Tensor.detach.html)." ] }, { "cell_type": "code", "execution_count": null, "id": "autograd-disconnect-code", "metadata": {}, "outputs": [], "source": [ "source = torch.tensor([1., 2.], requires_grad=True)\n", "connected_copy = source.clone()\n", "detached = source.detach()\n", "with torch.no_grad():\n", " untracked = 3 * source\n", "\n", "for name, t in [(\"source\", source), (\"clone\", connected_copy),\n", " (\"detach\", detached), (\"no_grad result\", untracked)]:\n", " print(name, \"requires_grad:\", t.requires_grad, \"is_leaf:\", t.is_leaf,\n", " \"grad_fn:\", t.grad_fn)\n", "assert source.requires_grad\n", "assert connected_copy.grad_fn is not None\n", "assert detached.grad_fn is None and not detached.requires_grad\n", "assert untracked.grad_fn is None and not untracked.requires_grad\n", "connected_copy.sum().backward()\n", "torch.testing.assert_close(source.grad, torch.ones(2))" ] }, { "cell_type": "markdown", "id": "autograd-detective", "metadata": {}, "source": [ "## Optional: autograd detective\n", "\n", "Four short cases that use the previous section. For each one, predict what happens before running it: an error, a missing (`None`) gradient, or a number. Then decide whether that is what the author wanted. Not every case is a bug.\n", "\n", "If a fix is needed, make the smallest one and add an assertion on the gradient you expect. Each case creates its own tensors, so you can run it on its own. The last case catches its error, so that running the whole notebook does not stop there." ] }, { "cell_type": "markdown", "id": "autograd-case-1-text", "metadata": {}, "source": [ "### 1. Did the gradient stop at the intermediate tensor? ★★\n", "\n", "We want the gradient of `sum(hidden**2)` with respect to both `leaf` and `hidden`. After `backward()`, what are `grad_fn`, `is_leaf` and `.grad` for each of them? Does `hidden.grad is None` mean that the gradient did not flow through `hidden`? Rebuild the computation so that both gradients are available. PyTorch prints a warning when we read `hidden.grad`; the warning is part of the answer." ] }, { "cell_type": "code", "execution_count": null, "id": "autograd-case-1", "metadata": {}, "outputs": [], "source": [ "leaf = torch.tensor([1., 2.], requires_grad=True)\n", "hidden = 3 * leaf\n", "hidden.square().sum().backward()\n", "print(\"leaf:\", leaf.is_leaf, leaf.grad_fn, leaf.grad)\n", "print(\"hidden:\", hidden.is_leaf, hidden.grad_fn, hidden.grad)\n", "\n", "# Rebuild, retain the missing gradient, and check both values." ] }, { "cell_type": "markdown", "id": "autograd-case-2-text", "metadata": {}, "source": [ "### 2. Can we reconnect a detached tensor? ★\n", "\n", "We want the gradient with respect to `original`. Someone detached an intermediate result, then turned gradients back on. Will `backward()` fail? Which tensor receives a gradient? Fix the code so that the gradient reaches `original`." ] }, { "cell_type": "code", "execution_count": null, "id": "autograd-case-2", "metadata": {}, "outputs": [], "source": [ "original = torch.tensor([1., 2.], requires_grad=True)\n", "restart = (3 * original).detach().requires_grad_()\n", "restart.square().sum().backward()\n", "print(\"restart:\", restart.is_leaf, restart.grad_fn, restart.grad)\n", "print(\"original.grad:\", original.grad)\n", "\n", "# Restore the intended differentiable path and check original.grad." ] }, { "cell_type": "markdown", "id": "autograd-case-3-text", "metadata": {}, "source": [ "### 3. Is accumulation always a mistake? ★★\n", "\n", "We want the gradient of the mean squared error over **all three examples**, but we process them in two microbatches of different sizes. The parameter does not change between the two `backward()` calls.\n", "\n", "Predict `parameter.grad` after each call. Should we clear it between the microbatches? Compare with a single `backward()` on the full batch. Then replace the normalization with `errors.square().mean() / len(microbatches)`: why does the result change here?" ] }, { "cell_type": "code", "execution_count": null, "id": "autograd-case-3", "metadata": {}, "outputs": [], "source": [ "parameter = torch.tensor(1., requires_grad=True)\n", "microbatches = [torch.tensor([1., 2.]), torch.tensor([3.])]\n", "num_examples = sum(len(values) for values in microbatches)\n", "for values in microbatches:\n", " errors = parameter * values # All targets are zero.\n", " (errors.square().sum() / num_examples).backward()\n", " print(\"Accumulated gradient:\", parameter.grad)\n", "\n", "# Compare with the gradient of a single full-batch mean loss." ] }, { "cell_type": "markdown", "id": "autograd-case-4-text", "metadata": {}, "source": [ "### 4. Is every in-place change safe inside `no_grad`? ★★★\n", "\n", "To differentiate a square, autograd needs the original value of `mutable`. What happens if we change that value before calling `backward()`, even inside `no_grad`? Reorder the code so that it takes one gradient step, with learning rate 0.1, from the original value.\n", "\n", "Then try modifying `mutable.detach()` in place before `backward()`. Does detaching protect the original data?" ] }, { "cell_type": "code", "execution_count": null, "id": "autograd-case-4", "metadata": {}, "outputs": [], "source": [ "mutable = torch.tensor([1., 2.], requires_grad=True)\n", "stale_loss = mutable.square().sum()\n", "with torch.no_grad():\n", " mutable.add_(1.)\n", "try:\n", " stale_loss.backward()\n", "except RuntimeError as error:\n", " print(\"Backward raised RuntimeError:\", str(error).splitlines()[0])\n", "\n", "# Rebuild from [1., 2.], differentiate, then update under no_grad." ] }, { "cell_type": "markdown", "id": "50f301fe", "metadata": {}, "source": [ "## Optional: views, copies and in-place operations\n", "\n", "Some indexing operations return a *view*, which shares memory with the original tensor; others return a copy. Slicing gives a view, while indexing with a list gives a copy:" ] }, { "cell_type": "code", "execution_count": null, "id": "b802e134", "metadata": {}, "outputs": [], "source": [ "A = torch.arange(6.).reshape(3, 2)\n", "view = A[:2]\n", "copy = A[[0, 1]]\n", "view[0, 0] = -10\n", "print(\"Original:\\n\", A)\n", "print(\"Copy made before the update:\\n\", copy)\n", "assert A[0, 0].item() == -10 and copy[0, 0].item() == 0\n", "\n", "# An underscore usually marks an in-place operation.\n", "A.add_(1)\n", "print(A)" ] }, { "cell_type": "markdown", "id": "fd1b5ba8", "metadata": {}, "source": [ "In-place operations need care when autograd is involved: `backward()` may need a value that the operation overwrites (see case 4 of the autograd detective). The update in Section 4 is safe because it runs after `backward()`.\n", "\n", "A tensor is stored as a flat block of memory plus *strides*: how many elements to skip to move one step along each axis. A transpose swaps the strides without moving any data, so the result is no longer *contiguous*. `reshape` returns a view when it can and copies otherwise. We will come back to memory layout when we talk about performance." ] }, { "cell_type": "code", "execution_count": null, "id": "e69666fd", "metadata": {}, "outputs": [], "source": [ "A = torch.arange(6.).reshape(3, 2)\n", "print(\"A:\", A.shape, A.stride(), A.is_contiguous())\n", "print(\"A.T:\", A.T.shape, A.T.stride(), A.T.is_contiguous())\n", "print(\"Flattened transpose:\", A.T.reshape(-1))" ] }, { "cell_type": "markdown", "id": "9c84aeec", "metadata": {}, "source": [ "## Optional: a few array operations\n", "\n", "Three short functions to write yourself, without loops over the elements. Each check cell tells you whether your version is still missing, and the checks include the edge cases mentioned below.\n", "\n", "### The two diagonals ★\n", "\n", "Sum the main diagonal and the anti-diagonal of a square matrix. When the size is odd, the center element is on both diagonals, so it is counted twice." ] }, { "cell_type": "code", "execution_count": null, "id": "0202983b", "metadata": { "tags": [ "exercise" ] }, "outputs": [], "source": [ "def sum_diagonals(A: Float[torch.Tensor, \"n n\"]) -> Optional[Float[torch.Tensor, \"\"]]:\n", " # Replace None with your implementation.\n", " return None" ] }, { "cell_type": "code", "execution_count": null, "id": "0202983b-check", "metadata": {}, "outputs": [], "source": [ "check_sum_diagonals(sum_diagonals)" ] }, { "cell_type": "markdown", "id": "aab7b1f3", "metadata": {}, "source": [ "### Normalizing the rows ★\n", "\n", "Normalize each row to mean zero and variance one. Variance here is the average squared deviation (`correction=0`). A constant row cannot be rescaled to unit variance, so it must become all zeros, without producing `nan`." ] }, { "cell_type": "code", "execution_count": null, "id": "52081f9c", "metadata": { "tags": [ "exercise" ] }, "outputs": [], "source": [ "def normalize_rows(A: Float[torch.Tensor, \"batch features\"], eps: float = 1e-8) -> Optional[Float[torch.Tensor, \"batch features\"]]:\n", " # Replace None with your implementation.\n", " return None" ] }, { "cell_type": "code", "execution_count": null, "id": "52081f9c-check", "metadata": {}, "outputs": [], "source": [ "check_normalize_rows(normalize_rows)" ] }, { "cell_type": "markdown", "id": "a0b71604", "metadata": {}, "source": [ "### Cosine similarity ★★\n", "\n", "Compute the cosine similarity between every pair of rows. Hint: normalize each row to unit length first; then a single matrix product gives all the pairs. We will meet this operation again with attention layers.\n", "\n", "Cosine similarity is undefined for a zero vector. Following `F.normalize`, we leave zero vectors at zero, so their similarity with every row is zero." ] }, { "cell_type": "code", "execution_count": null, "id": "33514e05", "metadata": { "tags": [ "exercise" ] }, "outputs": [], "source": [ "def cosine_similarity(A: Float[torch.Tensor, \"batch features\"]) -> Optional[Float[torch.Tensor, \"batch batch\"]]:\n", " # Replace None with your implementation.\n", " return None" ] }, { "cell_type": "code", "execution_count": null, "id": "33514e05-check", "metadata": {}, "outputs": [], "source": [ "check_cosine_similarity(cosine_similarity)" ] }, { "cell_type": "markdown", "id": "405c7398", "metadata": {}, "source": [ "## Further reading\n", "\n", "- [PyTorch tensor tutorial](https://docs.pytorch.org/tutorials/beginner/basics/tensorqs_tutorial.html)\n", "- [Autograd mechanics](https://docs.pytorch.org/docs/stable/notes/autograd.html)\n", "- [Tensor views](https://docs.pytorch.org/docs/stable/tensor_view.html)" ] } ], "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 }