{ "nbformat": 4, "nbformat_minor": 5, "metadata": { "kernelspec": { "name": "python3", "display_name": "Python 3", "language": "python" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lab 1.2 · Build a tiny autograd engine\n", "\n", "**Goal:** build a scalar automatic differentiation engine (`Value` with `backward()`) from\n", "scratch in plain Python, check its gradients against numerical slopes, retrain the Lab 1.1\n", "neuron with backpropagation, measure how step time scales with the number of inputs for both\n", "methods, and diagnose three classic backpropagation bugs.\n", "\n", "**Runs on:** any laptop, CPU only, in under a minute. Python 3.10+; `matplotlib` for the plots.\n", "\n", "**Versions tested:** see the last cell's output (it prints them)." ], "id": "lab-1-2-backprop-00" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Before running any code, write down your answers to three questions:\n", "\n", "1. For the student in Ch 1.1 (`x1 = 6`, `x2 = 7.5`, `y = 1`, `w1 = 1.1`, `w2 = 0.8`,\n", " `b = −10.5`), the neuron outputs `p ≈ 0.891`. Should `dL/dw1`, `dL/dw2` and `dL/db` be\n", " **positive** or **negative**? Which of `dL/dw1` and `dL/dw2` should be larger in size?\n", "2. If you train the Lab 1.1 neuron from `(0, 0, 0)` for 3000 steps at `lr = 0.1` using\n", " backpropagation instead of numerical nudging, should you reach the **same** final weights\n", " (`w1 ≈ +1.116`, `w2 ≈ +0.826`, `b ≈ −10.459`), or slightly different ones?\n", "3. For a neuron with `n` inputs on 64 examples, how will the time for **one training step**\n", " grow with `n` for numerical gradients versus backpropagation? At `n = 512`, roughly how\n", " many times faster do you expect backpropagation to be?" ], "id": "lab-1-2-backprop-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · Build a tiny autograd engine\n", "\n", "Each `Value` wraps one scalar number (`data`), stores the gradient of the final loss with\n", "respect to itself (`grad`), remembers which `Value`s produced it (`_prev`), and holds a small\n", "function `_backward(grad)` that pushes its incoming gradient `grad` back to its inputs by\n", "multiplying by the local derivative.\n", "\n", "Two details do most of the real work:\n", "\n", "- Every `_backward` uses **`+=`**, not `=`, so gradients add whenever a value is used more than\n", " once in a graph.\n", "- `backward()` sorts the graph in **topological order** first, then walks it in reverse so a\n", " node's `_backward` never runs until every node that depends on it has finished adding to its\n", " `grad`." ], "id": "lab-1-2-backprop-02" }, { "cell_type": "code", "metadata": {}, "source": [ "import math\n", "\n", "\n", "class Value:\n", " def __init__(self, data, _children=(), _op=\"\", label=\"\"):\n", " self.data = float(data)\n", " self.grad = 0.0\n", " self._backward = lambda grad: None\n", " self._prev = tuple(_children)\n", " self._op = _op\n", " self.label = label\n", "\n", " def __repr__(self):\n", " name = f\"{self.label}=\" if self.label else \"\"\n", " return f\"Value({name}data={self.data:.6f}, grad={self.grad:.6f})\"\n", "\n", " def __add__(self, other):\n", " other = other if isinstance(other, Value) else Value(other)\n", " out = Value(self.data + other.data, (self, other), \"+\")\n", "\n", " def _backward(grad):\n", " self.grad += 1.0 * grad\n", " other.grad += 1.0 * grad\n", "\n", " out._backward = _backward\n", " return out\n", "\n", " def __mul__(self, other):\n", " other = other if isinstance(other, Value) else Value(other)\n", " out = Value(self.data * other.data, (self, other), \"*\")\n", "\n", " def _backward(grad):\n", " self.grad += other.data * grad\n", " other.grad += self.data * grad\n", "\n", " out._backward = _backward\n", " return out\n", "\n", " def __pow__(self, other):\n", " assert isinstance(other, (int, float)), \"power supports int/float exponents only\"\n", " out = Value(self.data ** other, (self,), f\"**{other}\")\n", "\n", " def _backward(grad):\n", " self.grad += other * (self.data ** (other - 1)) * grad\n", "\n", " out._backward = _backward\n", " return out\n", "\n", " def __neg__(self):\n", " return self * -1.0\n", "\n", " def __sub__(self, other):\n", " return self + (-other)\n", "\n", " def __radd__(self, other):\n", " return self + other\n", "\n", " def __rmul__(self, other):\n", " return self * other\n", "\n", " def __rsub__(self, other):\n", " return Value(other) + (-self)\n", "\n", " def __truediv__(self, other):\n", " other = other if isinstance(other, Value) else Value(other)\n", " return self * (other ** -1)\n", "\n", " def __rtruediv__(self, other):\n", " return Value(other) * (self ** -1)\n", "\n", " def exp(self):\n", " e = math.exp(self.data)\n", " out = Value(e, (self,), \"exp\")\n", "\n", " def _backward(grad):\n", " self.grad += e * grad\n", "\n", " out._backward = _backward\n", " return out\n", "\n", " def log(self):\n", " out = Value(math.log(self.data), (self,), \"log\")\n", "\n", " def _backward(grad):\n", " self.grad += (1.0 / self.data) * grad\n", "\n", " out._backward = _backward\n", " return out\n", "\n", " def sigmoid(self):\n", " s = 1.0 / (1.0 + math.exp(-self.data))\n", " out = Value(s, (self,), \"sigmoid\")\n", "\n", " def _backward(grad):\n", " self.grad += s * (1.0 - s) * grad\n", "\n", " out._backward = _backward\n", " return out\n", "\n", " def backward(self):\n", " topo = []\n", " visited = set()\n", "\n", " def build_topo(v):\n", " if v not in visited:\n", " visited.add(v)\n", " for child in v._prev:\n", " build_topo(child)\n", " topo.append(v)\n", "\n", " build_topo(self)\n", " self.grad = 1.0\n", " for v in reversed(topo):\n", " v._backward(v.grad)\n", "\n", "\n", "print(\"Value class ready.\")" ], "execution_count": null, "outputs": [], "id": "lab-1-2-backprop-03" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · Work the Ch 1.1 student by hand and check every gradient\n", "\n", "Take the single student from Ch 1.1's anatomy diagram: `x1 = 6.0` hours studied, `x2 = 7.5`\n", "hours slept, label `y = 1` (passed), with `w1 = 1.1`, `w2 = 0.8`, `b = −10.5`.\n", "\n", "Run one forward pass, then one call to `loss.backward()`, and inspect both the forward values\n", "and the gradients at every intermediate node." ], "id": "lab-1-2-backprop-04" }, { "cell_type": "code", "metadata": {}, "source": [ "x1 = Value(6.0, label=\"x1\")\n", "x2 = Value(7.5, label=\"x2\")\n", "w1 = Value(1.1, label=\"w1\")\n", "w2 = Value(0.8, label=\"w2\")\n", "b = Value(-10.5, label=\"b\")\n", "\n", "p1 = w1 * x1; p1.label = \"p1=w1*x1\"\n", "p2 = w2 * x2; p2.label = \"p2=w2*x2\"\n", "s = p1 + p2; s.label = \"s=p1+p2\"\n", "z = s + b; z.label = \"z=s+b\"\n", "p = z.sigmoid(); p.label = \"p=sig(z)\"\n", "lp = p.log(); lp.label = \"lp=log(p)\"\n", "loss_one = -lp; loss_one.label = \"L=-log(p)\"\n", "\n", "loss_one.backward()\n", "\n", "nodes = [x1, x2, w1, w2, b, p1, p2, s, z, p, lp, loss_one]\n", "print(f\"{'node':12s} {'data':>11s} {'grad (dL/dnode)':>16s}\")\n", "print(\"-\" * 41)\n", "for n in nodes:\n", " print(f\"{n.label:12s} {n.data:11.6f} {n.grad:16.6f}\")\n", "\n", "print(f\"\\nCheck shortcut dL/dz = p - y: p - 1 = {p.data - 1.0:.6f}, z.grad = {z.grad:.6f}\")" ], "execution_count": null, "outputs": [], "id": "lab-1-2-backprop-05" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now verify our autograd engine with a **numerical gradient check**. For every input `x_i`,\n", "compare the backprop gradient `g_bp` with the centred finite difference\n", "`g_num = (f(x_i + h) − f(x_i − h)) / (2h)`, and compute the relative error:\n", "\n", "`rel_err = |g_bp − g_num| / max(|g_bp|, |g_num|, 1e-8)`\n", "\n", "A healthy autograd engine matches numerical slopes to `1e-9` or better on smooth functions." ], "id": "lab-1-2-backprop-06" }, { "cell_type": "code", "metadata": {}, "source": [ "import random\n", "\n", "\n", "def grad_check(fn, raw_inputs, names=None, h=1e-5):\n", " vals = [Value(v) for v in raw_inputs]\n", " out = fn(vals)\n", " out.backward()\n", " bp_grads = [v.grad for v in vals]\n", "\n", " num_grads = []\n", " for i in range(len(raw_inputs)):\n", " up = list(raw_inputs); up[i] += h\n", " down = list(raw_inputs); down[i] -= h\n", " f_up = fn([Value(v) for v in up]).data\n", " f_down = fn([Value(v) for v in down]).data\n", " num_grads.append((f_up - f_down) / (2.0 * h))\n", "\n", " max_rel = 0.0\n", " for i, (g_bp, g_num) in enumerate(zip(bp_grads, num_grads)):\n", " rel = abs(g_bp - g_num) / max(abs(g_bp), abs(g_num), 1e-8)\n", " max_rel = max(max_rel, rel)\n", " if names is not None:\n", " print(f\" {names[i]:4s} backprop {g_bp:+.8f} numerical {g_num:+.8f} rel_err {rel:.2e}\")\n", " return max_rel\n", "\n", "\n", "def hand_loss_fn(params):\n", " w1_, w2_, b_ = params\n", " z_ = w1_ * 6.0 + w2_ * 7.5 + b_\n", " return -(z_.sigmoid().log())\n", "\n", "\n", "print(\"Gradient check on the Ch 1.1 worked student:\")\n", "hand_rel = grad_check(hand_loss_fn, [1.1, 0.8, -10.5], names=[\"w1\", \"w2\", \"b\"])\n", "print(f\"max relative error: {hand_rel:.2e}\\n\")\n", "\n", "\n", "def messy_expression(vals):\n", " # Uses +, -, *, /, **, exp, log, sigmoid, and reuses inputs multiple times\n", " a, b_, c = vals\n", " u = a * a + a * b_ - c\n", " v = (u * 0.3).sigmoid() + (b_ * 0.2).exp()\n", " return (v * v).log() / (a * a + 1.0)\n", "\n", "\n", "rng = random.Random(42)\n", "worst = 0.0\n", "for trial in range(5):\n", " xs = [rng.uniform(-2.0, 2.0) for _ in range(3)]\n", " rel = grad_check(messy_expression, xs)\n", " worst = max(worst, rel)\n", " print(f\"random trial {trial + 1} inputs {[round(x, 3) for x in xs]} max_rel_err {rel:.2e}\")\n", "print(f\"worst relative error across 5 random trials: {worst:.2e}\")" ], "execution_count": null, "outputs": [], "id": "lab-1-2-backprop-07" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Retrain the Lab 1.1 neuron with backpropagation\n", "\n", "Same 20 students, same starting weights `(0, 0, 0)`, same `lr = 0.1`, same 3000 steps. The\n", "only change is how we get the gradients: one call to `loss.backward()` instead of 6 separate\n", "loss evaluations." ], "id": "lab-1-2-backprop-08" }, { "cell_type": "code", "metadata": {}, "source": [ "STUDENTS = [\n", " (1.0, 8.0, 0), (2.0, 5.0, 0), (2.5, 9.0, 0), (3.0, 3.0, 0), (3.5, 7.0, 0),\n", " (4.0, 4.5, 0), (4.5, 8.5, 1), (5.0, 2.0, 0), (5.0, 7.0, 1), (5.5, 4.0, 0),\n", " (6.0, 7.5, 1), (6.0, 3.0, 0), (6.5, 5.5, 1), (7.0, 2.5, 0), (7.0, 8.0, 1),\n", " (7.5, 4.5, 1), (8.0, 6.0, 1), (8.5, 3.0, 1), (9.0, 7.0, 1), (3.0, 9.5, 1),\n", "]\n", "\n", "\n", "def loss_bp(w1, w2, b, data=STUDENTS):\n", " total = Value(0.0)\n", " for x1, x2, y in data:\n", " p = (w1 * x1 + w2 * x2 + b).sigmoid()\n", " term = -(p.log()) if y == 1 else -((1.0 - p).log())\n", " total = total + term\n", " return total / len(data)\n", "\n", "\n", "def accuracy_bp(w1, w2, b, data=STUDENTS):\n", " right = 0\n", " for x1, x2, y in data:\n", " z = w1.data * x1 + w2.data * x2 + b.data\n", " p = 1.0 / (1.0 + math.exp(-z))\n", " right += int((p > 0.5) == bool(y))\n", " return right, len(data)\n", "\n", "\n", "def train_bp(start=(0.0, 0.0, 0.0), lr=0.1, steps=3000, every=500, data=STUDENTS, zero_grad=True):\n", " w1, w2, b = [Value(v) for v in start]\n", " params = [w1, w2, b]\n", " history = []\n", " for step in range(steps + 1):\n", " if zero_grad:\n", " for p in params:\n", " p.grad = 0.0\n", " L = loss_bp(w1, w2, b, data=data)\n", " history.append(L.data)\n", " if step % every == 0:\n", " r, n = accuracy_bp(w1, w2, b, data=data)\n", " print(f\"step {step:5d} loss {L.data:.4f} correct {r}/{n} \"\n", " f\"w1 {w1.data:+.3f} w2 {w2.data:+.3f} b {b.data:+.3f}\")\n", " if step < steps:\n", " L.backward()\n", " for p in params:\n", " p.data -= lr * p.grad\n", " return [p.data for p in params], history\n", "\n", "\n", "learned_bp, history_bp = train_bp(start=(0.0, 0.0, 0.0), lr=0.1, steps=3000)" ], "execution_count": null, "outputs": [], "id": "lab-1-2-backprop-09" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Checkpoint\n", "\n", "Compare the lines above with Lab 1.1's checkpoint:\n", "\n", "- `step 0`: loss `0.6931`, `10/20`, `(0, 0, 0)`\n", "- `step 500`: loss `0.4112`, `19/20`, `w1 +0.427 w2 +0.265 b -3.490`\n", "- `step 1000`: loss `0.3158`, `20/20`, `w1 +0.634 w2 +0.442 b -5.644`\n", "- `step 3000`: loss `0.1928`, `20/20`, `w1 +1.116 w2 +0.826 b -10.459`\n", "\n", "Every number matches Lab 1.1 to three decimal places: backpropagation computes the **same**\n", "gradients as nudging, without nudging each weight one at a time." ], "id": "lab-1-2-backprop-10" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · Measure: numerical gradient vs backpropagation as the number of inputs grows\n", "\n", "With 3 parameters, nudging feels instant. Now scale a single neuron to `n = 2, 8, 32, 128, 512`\n", "inputs (`n + 1` parameters including the bias) on 64 random examples, and time one training\n", "step for both methods.\n", "\n", "To keep the comparison fair, the numerical gradient uses plain Python floats (no `Value`\n", "object overhead at all), while backpropagation uses our pure-Python `Value` class, running\n", "`backward()` per example and letting `+=` accumulate the average gradient into each weight." ], "id": "lab-1-2-backprop-11" }, { "cell_type": "code", "metadata": {}, "source": [ "import csv\n", "import time\n", "\n", "\n", "def make_dataset(n_inputs, n_examples=64, seed=42):\n", " r = random.Random(seed + n_inputs)\n", " scale = 1.0 / math.sqrt(n_inputs)\n", " data = []\n", " for _ in range(n_examples):\n", " xs = [r.gauss(0.0, scale) for _ in range(n_inputs)]\n", " y = 1 if sum(xs) > 0 else 0\n", " data.append((xs, y))\n", " return data\n", "\n", "\n", "def float_loss(weights, bias, data):\n", " total = 0.0\n", " for xs, y in data:\n", " z = bias\n", " for w, x in zip(weights, xs):\n", " z += w * x\n", " p = 1.0 / (1.0 + math.exp(-z))\n", " total += -math.log(p) if y == 1 else -math.log(1.0 - p)\n", " return total / len(data)\n", "\n", "\n", "def step_numerical(weights, bias, data, lr=0.1, h=1e-5):\n", " n = len(weights)\n", " w_grads = []\n", " for i in range(n):\n", " orig = weights[i]\n", " weights[i] = orig + h\n", " up = float_loss(weights, bias, data)\n", " weights[i] = orig - h\n", " down = float_loss(weights, bias, data)\n", " weights[i] = orig\n", " w_grads.append((up - down) / (2.0 * h))\n", " b_grad = (float_loss(weights, bias + h, data) - float_loss(weights, bias - h, data)) / (2.0 * h)\n", " for i in range(n):\n", " weights[i] -= lr * w_grads[i]\n", " return weights, bias - lr * b_grad\n", "\n", "\n", "def step_backprop(weights, bias, data, lr=0.1):\n", " for w in weights:\n", " w.grad = 0.0\n", " bias.grad = 0.0\n", " inv_n = 1.0 / len(data)\n", " total_loss = 0.0\n", " for xs, y in data:\n", " z = bias\n", " for w, x in zip(weights, xs):\n", " z = z + w * x\n", " p = z.sigmoid()\n", " term = (-(p.log()) if y == 1 else -((1.0 - p).log())) * inv_n\n", " total_loss += term.data\n", " term.backward()\n", " for w in weights:\n", " w.data -= lr * w.grad\n", " bias.data -= lr * bias.grad\n", " return total_loss\n", "\n", "\n", "def time_method(fn, repeats=3):\n", " fn() # warm-up\n", " times = []\n", " for _ in range(repeats):\n", " t0 = time.perf_counter()\n", " fn()\n", " times.append((time.perf_counter() - t0) * 1000.0)\n", " times.sort()\n", " return times[len(times) // 2]\n", "\n", "\n", "def run_benchmark(input_sizes=(2, 8, 32, 128, 512), n_examples=64):\n", " rows = []\n", " print(f\"{'n':>5s} {'params':>6s} {'numerical (ms)':>15s} {'backprop (ms)':>14s} {'speedup':>9s}\")\n", " print(\"-\" * 58)\n", " for n in input_sizes:\n", " data = make_dataset(n, n_examples)\n", " repeats = 5 if n <= 32 else 3\n", "\n", " w_num = [0.0] * n\n", " b_num = 0.0\n", "\n", " def run_num():\n", " nonlocal w_num, b_num\n", " w_num, b_num = step_numerical(w_num, b_num, data)\n", "\n", " num_ms = time_method(run_num, repeats=repeats)\n", "\n", " w_bp = [Value(0.0) for _ in range(n)]\n", " b_bp = Value(0.0)\n", "\n", " def run_bp():\n", " step_backprop(w_bp, b_bp, data)\n", "\n", " bp_ms = time_method(run_bp, repeats=repeats)\n", "\n", " ratio = num_ms / bp_ms\n", " rows.append({\n", " \"n_inputs\": n,\n", " \"n_params\": n + 1,\n", " \"n_examples\": n_examples,\n", " \"numerical_ms\": round(num_ms, 3),\n", " \"backprop_ms\": round(bp_ms, 3),\n", " \"speedup\": round(ratio, 2),\n", " })\n", " print(f\"{n:5d} {n + 1:6d} {num_ms:15.3f} {bp_ms:14.3f} {ratio:8.2f}x\")\n", " return rows\n", "\n", "\n", "bench_rows = run_benchmark()\n", "\n", "with open(\"step-time.csv\", \"w\", newline=\"\") as f:\n", " writer = csv.DictWriter(\n", " f,\n", " fieldnames=[\"n_inputs\", \"n_params\", \"n_examples\", \"numerical_ms\", \"backprop_ms\", \"speedup\"],\n", " )\n", " writer.writeheader()\n", " writer.writerows(bench_rows)\n", "print(\"\\nsaved step-time.csv,\", len(bench_rows), \"rows\")" ], "execution_count": null, "outputs": [], "id": "lab-1-2-backprop-12" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " import matplotlib.pyplot as plt\n", "\n", " ns = [r[\"n_inputs\"] for r in bench_rows]\n", " num_t = [r[\"numerical_ms\"] for r in bench_rows]\n", " bp_t = [r[\"backprop_ms\"] for r in bench_rows]\n", "\n", " fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))\n", " ax1.plot(ns, num_t, marker=\"o\", label=\"numerical gradient (floats)\")\n", " ax1.plot(ns, bp_t, marker=\"s\", label=\"backprop (Value)\")\n", " ax1.set_xlabel(\"number of inputs n\")\n", " ax1.set_ylabel(\"ms per training step (64 examples)\")\n", " ax1.set_title(\"Linear scale\")\n", " ax1.legend()\n", "\n", " ax2.plot(ns, num_t, marker=\"o\", label=\"numerical gradient (floats)\")\n", " ax2.plot(ns, bp_t, marker=\"s\", label=\"backprop (Value)\")\n", " ax2.set_xscale(\"log\", base=2)\n", " ax2.set_yscale(\"log\")\n", " ax2.set_xlabel(\"number of inputs n (log2)\")\n", " ax2.set_ylabel(\"ms per training step (log)\")\n", " ax2.set_title(\"Log-log scale (slopes show scaling)\")\n", " ax2.legend()\n", "\n", " plt.tight_layout()\n", " plt.show()\n", "except ImportError:\n", " print(\"matplotlib not installed: skip the plot (pip install matplotlib)\")" ], "execution_count": null, "outputs": [], "id": "lab-1-2-backprop-13" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Explore\n", "\n", "Change one knob at a time and answer the question next to it.\n", "\n", "| Knob | Try | Question |\n", "| --- | --- | --- |\n", "| `h` in `grad_check` | `1e-1`, `1e-3`, `1e-5`, `1e-12`, `1e-15` | Why does the relative error get *worse* at both ends (too big **and** too small)? |\n", "| sigmoid chain depth | `depth = 1, 4, 8, 16, 32` using the helper below | By what factor does `dy/dx` shrink per extra sigmoid layer? Why can it never exceed `0.25` per layer? |\n", "| learning rate | `train_bp(lr=0.05)`, `0.5`, `1.0` | Does `train_bp` hit the same instability at `lr = 1.0` as Lab 1.1? Why does backprop not fix a bad learning rate? |" ], "id": "lab-1-2-backprop-14" }, { "cell_type": "code", "metadata": {}, "source": [ "# Helper for the sigmoid-chain experiment: pass x through `depth` sigmoids in a row\n", "def sigmoid_chain_grad(depth, x0=0.0):\n", " x = Value(x0)\n", " y = x\n", " for _ in range(depth):\n", " y = y.sigmoid()\n", " y.backward()\n", " return y.data, x.grad\n", "\n", "\n", "for d in (1, 4, 8, 16, 32):\n", " out_val, g = sigmoid_chain_grad(d, x0=0.0)\n", " print(f\"depth {d:2d} output {out_val:.6f} dy/dx {g:.3e}\")\n", "\n", "# The h sweep (quoted in Ch 1.2): relative error of the numerical check vs backprop\n", "for h in (1e-1, 1e-3, 1e-5, 1e-12, 1e-15):\n", " print(f\"h={h:.0e} rel_err={grad_check(hand_loss_fn, [1.1, 0.8, -10.5], h=h):.2e}\")\n", "\n", "# Try the learning-rate experiments here." ], "execution_count": null, "outputs": [], "id": "lab-1-2-backprop-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Failure playground\n", "\n", "Three broken runs below mirror bugs that hit real autograd code. For each one: run the cell,\n", "read the symptom, diagnose the cause, and verify your fix. Hints are in Review 1.2; answers\n", "are not." ], "id": "lab-1-2-backprop-16" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 8a · The forgotten zero-grad\n", "\n", "We add the extra student `(2.0, 2.0, 1)` from Lab 1.1 Explore so the loss has a real finite\n", "minimum, and train at `lr = 0.1` — except we forget to reset `p.grad = 0.0` before each step." ], "id": "lab-1-2-backprop-17" }, { "cell_type": "code", "metadata": {}, "source": [ "STUDENTS_WITH_OUTLIER = STUDENTS + [(2.0, 2.0, 1)]\n", "\n", "print(\"With zero_grad=False (the bug):\")\n", "try:\n", " train_bp(start=(0.0, 0.0, 0.0), lr=0.1, steps=400, every=50,\n", " data=STUDENTS_WITH_OUTLIER, zero_grad=False)\n", "except Exception as e:\n", " print(\"CRASH:\", type(e).__name__, e)" ], "execution_count": null, "outputs": [], "id": "lab-1-2-backprop-18" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: the loss drops quickly to `0.4863` at step 50, then climbs all the way back to\n", "`0.6844` at step 150, falls again, and swings back to `12/21` correct at step 300 — never\n", "settling. Run the same call with `zero_grad=True` to compare. Why do the weights overshoot\n", "the bottom of the valley and swing back and forth like a pendulum? Print `w1.grad`, `w2.grad`,\n", "`b.grad` on steps 0, 1, 2 to verify your diagnosis." ], "id": "lab-1-2-backprop-19" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 8b · Overwriting instead of adding in `__mul__`\n", "\n", "Someone writes `=` instead of `+=` inside `__mul__`'s `_backward`." ], "id": "lab-1-2-backprop-20" }, { "cell_type": "code", "metadata": {}, "source": [ "class BrokenMulValue(Value):\n", " def __mul__(self, other):\n", " other = other if isinstance(other, Value) else BrokenMulValue(other)\n", " out = BrokenMulValue(self.data * other.data, (self, other), \"*\")\n", "\n", " def _backward(grad):\n", " self.grad = other.data * grad # <-- bug: '=' instead of '+='\n", " other.grad = self.data * grad # <-- bug: '=' instead of '+='\n", "\n", " out._backward = _backward\n", " return out\n", "\n", "\n", "x_ok = Value(3.0)\n", "(x_ok * x_ok).backward()\n", "\n", "x_bad = BrokenMulValue(3.0)\n", "(x_bad * x_bad).backward()\n", "\n", "h = 1e-5\n", "num_slope = ((3.0 + h) ** 2 - (3.0 - h) ** 2) / (2.0 * h)\n", "rel_err = abs(x_bad.grad - num_slope) / max(abs(x_bad.grad), abs(num_slope), 1e-8)\n", "\n", "print(\"x * x at x = 3.0:\")\n", "print(f\" numerical slope: {num_slope:.6f}\")\n", "print(f\" working Value grad: {x_ok.grad:.6f}\")\n", "print(f\" BrokenMulValue grad: {x_bad.grad:.6f} (relative error {rel_err:.2e})\")" ], "execution_count": null, "outputs": [], "id": "lab-1-2-backprop-21" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: `BrokenMulValue` passes a test on `a * b` when `a` and `b` are distinct nodes, yet\n", "fails `grad_check` on `x * x` with a 50% error. Trace both lines of `_backward(grad)` when\n", "`self` and `other` point to the same object. Can this same bug also fail even when `a` and\n", "`b` are different objects? Construct a two-line example using `a`, `b`, and `c`." ], "id": "lab-1-2-backprop-22" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 8c · Backward in the wrong order (no topological sort)\n", "\n", "Instead of sorting the graph topologically, someone walks backward breadth-first with a queue,\n", "visiting each node the first time they reach it." ], "id": "lab-1-2-backprop-23" }, { "cell_type": "code", "metadata": {}, "source": [ "from collections import deque\n", "\n", "\n", "def backward_no_topo(root):\n", " root.grad = 1.0\n", " queue = deque([root])\n", " seen = {root}\n", " while queue:\n", " v = queue.popleft()\n", " v._backward(v.grad)\n", " for child in v._prev:\n", " if child not in seen:\n", " seen.add(child)\n", " queue.append(child)\n", "\n", "\n", "def diamond_graph():\n", " x = Value(2.0, label=\"x\")\n", " a = x + 1.0; a.label = \"a=x+1\"\n", " b = a * 3.0; b.label = \"b=3*a\"\n", " out = a * b; out.label = \"out=a*b\"\n", " return x, a, b, out\n", "\n", "\n", "x1, a1, b1, out1 = diamond_graph()\n", "out1.backward()\n", "\n", "x2, a2, b2, out2 = diamond_graph()\n", "backward_no_topo(out2)\n", "\n", "h = 1e-5\n", "f_num = lambda t: (t + 1.0) * (3.0 * (t + 1.0))\n", "num_d = (f_num(2.0 + h) - f_num(2.0 - h)) / (2.0 * h)\n", "rel_err = abs(x2.grad - num_d) / max(abs(x2.grad), abs(num_d), 1e-8)\n", "\n", "print(f\"out = (x + 1) * (3 * (x + 1)) at x = 2.0 (out = {out1.data:.1f}):\")\n", "print(f\" numerical slope: {num_d:.6f}\")\n", "print(f\" topological backward(): x.grad = {x1.grad:.6f}, a.grad = {a1.grad:.6f}\")\n", "print(f\" wrong-order backward: x.grad = {x2.grad:.6f}, a.grad = {a2.grad:.6f} (rel_err {rel_err:.2e})\")" ], "execution_count": null, "outputs": [], "id": "lab-1-2-backprop-24" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: `a.grad` ends up with the right number (`18.0`), yet `x.grad` is only half of what it\n", "should be (`9.0` instead of `18.0`). Draw the four nodes (`x`, `a`, `b`, `out`) and list the\n", "exact order in which `backward_no_topo` calls `_backward`. Why did `a.grad` end up right\n", "while `x.grad` ended up wrong?" ], "id": "lab-1-2-backprop-25" }, { "cell_type": "code", "metadata": {}, "source": [ "import platform\n", "\n", "print(\"Versions tested:\", f\"Python {platform.python_version()} on {platform.system()} {platform.machine()}\")\n", "try:\n", " import matplotlib\n", " print(\"matplotlib\", matplotlib.__version__)\n", "except ImportError:\n", " pass" ], "execution_count": null, "outputs": [], "id": "lab-1-2-backprop-26" } ] }