{ "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.3 · Layers and PyTorch\n", "\n", "**Goal:** solve Lab 1.1's `XOR_LIKE` playground with a two-layer network (first by hand, then\n", "trained in PyTorch), measure how hidden width controls what a network can learn on a curved 2-D\n", "dataset, time a training step on CPU versus GPU, and break the training loop four ways.\n", "\n", "**Runs on:** any laptop (CPU, plus the Apple GPU `mps` on Apple Silicon or an NVIDIA GPU `cuda`\n", "when present); also Kaggle or Colab. Install locally with `uv run --with torch --with matplotlib`.\n", "\n", "**Versions tested:** printed by the last cell." ], "id": "lab-1-3-layers-00" }, { "cell_type": "code", "metadata": {}, "source": [ "import csv\n", "import math\n", "import pathlib\n", "import platform\n", "import time\n", "\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "\n", "DEVICES = [\"cpu\"]\n", "if torch.cuda.is_available():\n", " DEVICES.append(\"cuda\")\n", "elif torch.backends.mps.is_available():\n", " DEVICES.append(\"mps\")\n", "\n", "print(\"PyTorch\", torch.__version__, \"| devices available:\", DEVICES)\n", "\n", "\n", "def sync(device):\n", " if device == \"cuda\":\n", " torch.cuda.synchronize()\n", " elif device == \"mps\":\n", " torch.mps.synchronize()\n", "\n", "\n", "def out_dir():\n", " for candidate in (pathlib.Path(\"data\"), pathlib.Path(\"../data\")):\n", " if candidate.is_dir():\n", " d = candidate / \"lab-1-3-layers\"\n", " d.mkdir(parents=True, exist_ok=True)\n", " return d\n", " return pathlib.Path(\".\")\n", "\n", "\n", "# Lab 1.1's failure playground 7c: a pattern no single straight line can split.\n", "XOR_LIKE = [\n", " (2, 2, 1), (2, 8, 0), (8, 2, 0), (8, 8, 1),\n", " (1, 1, 1), (1, 9, 0), (9, 1, 0), (9, 9, 1),\n", "]\n", "X_xor = torch.tensor([[x1, x2] for x1, x2, _ in XOR_LIKE], dtype=torch.float32)\n", "y_xor = torch.tensor([[y] for _, _, y in XOR_LIKE], dtype=torch.float32)\n", "print(\"XOR_LIKE shapes: X =\", tuple(X_xor.shape), \"y =\", tuple(y_xor.shape))" ], "execution_count": null, "outputs": [], "id": "lab-1-3-layers-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Before running the cells below, write down your answers:\n", "\n", "1. A `2 → 2 → 1` network has 2 inputs, 2 hidden neurons, and 1 output neuron. How many learnable\n", " numbers (weights and biases combined) does it have in total?\n", "2. If you stack two linear layers with **no** activation function between them and train on\n", " `XOR_LIKE`, what is the lowest loss you expect the network to reach?\n", "3. On 400 points arranged in two interleaved spirals, how accurate do you expect a single hidden\n", " layer of `1`, `2`, `4`, `8`, and `32` ReLU units to be?\n", "4. Compare a tiny `2 → 2 → 1` network (batch 8) against a larger `512 → 2048 → 512` MLP\n", " (batch 256). On a GPU (`mps` or `cuda`), which one will beat the CPU, and which one will be\n", " *slower* than the CPU?" ], "id": "lab-1-3-layers-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · By hand: two lines solve `XOR_LIKE`\n", "\n", "One straight line could not separate the 8 points in Lab 1.1 (loss stayed at `0.6931`). Two lines\n", "can:\n", "\n", "- **Hidden neuron 1** (`z1 = -x1 + x2 - 3`, then `h1 = ReLU(z1)`): fires only in the top-left\n", " corner `(1, 9)` and `(2, 8)`, where `x2 - x1 > 3`.\n", "- **Hidden neuron 2** (`z2 = +x1 - x2 - 3`, then `h2 = ReLU(z2)`): fires only in the bottom-right\n", " corner `(8, 2)` and `(9, 1)`, where `x1 - x2 > 3`.\n", "- **Output neuron** (`z_out = -2·h1 - 2·h2 + 3`): starts at `+3` (predict pass) and turns negative\n", " whenever either corner neuron fires.\n", "\n", "Written as matrix multiplies, all 8 points run in a single pass: `[8, 2] @ [2, 2] + [2] → [8, 2]`,\n", "ReLU, then `[8, 2] @ [2, 1] + [1] → [8, 1]`." ], "id": "lab-1-3-layers-03" }, { "cell_type": "code", "metadata": {}, "source": [ "W1 = torch.tensor([[-1.0, 1.0],\n", " [ 1.0, -1.0]]) # shape [2, 2] (columns are the 2 hidden neurons)\n", "b1 = torch.tensor([-3.0, -3.0]) # shape [2]\n", "W2 = torch.tensor([[-2.0],\n", " [-2.0]]) # shape [2, 1]\n", "b2 = torch.tensor([3.0]) # shape [1]\n", "\n", "z1 = X_xor @ W1 + b1 # [8, 2] @ [2, 2] + [2] -> [8, 2]\n", "h = torch.relu(z1) # [8, 2]\n", "z_out = h @ W2 + b2 # [8, 2] @ [2, 1] + [1] -> [8, 1]\n", "probs = torch.sigmoid(z_out)\n", "preds = (z_out > 0).int()\n", "\n", "loss_hand = F.binary_cross_entropy_with_logits(z_out, y_xor).item()\n", "correct_hand = int((preds == y_xor.int()).sum().item())\n", "\n", "print(f\"Shapes: X{tuple(X_xor.shape)} -> z1{tuple(z1.shape)} -> h{tuple(h.shape)} -> z_out{tuple(z_out.shape)}\")\n", "print(f\"Hand-set weights: {correct_hand}/{len(XOR_LIKE)} correct, loss {loss_hand:.4f}\\n\")\n", "print(\" point y | z1 z2 | h1 h2 | z_out p pred\")\n", "print(\" ----------+--------------+------------+--------------------\")\n", "for i, (x1, x2, y) in enumerate(XOR_LIKE):\n", " print(f\" ({x1},{x2}) {y} | {z1[i,0]:+5.1f} {z1[i,1]:+5.1f} | \"\n", " f\"{h[i,0]:4.1f} {h[i,1]:4.1f} | {z_out[i,0]:+5.1f} {probs[i,0]:.4f} {preds[i,0].item()}\")\n", "\n", "# Verify the collapse when ReLU is omitted:\n", "z_no_relu = (X_xor @ W1 + b1) @ W2 + b2\n", "W_eff = W1 @ W2\n", "b_eff = b1 @ W2 + b2\n", "z_collapsed = X_xor @ W_eff + b_eff\n", "print(\"\\nWithout ReLU: W_eff =\", W_eff.squeeze().tolist(), \"b_eff =\", b_eff.tolist())\n", "print(\"Max diff between two linear layers and collapsed one:\", (z_no_relu - z_collapsed).abs().max().item())" ], "execution_count": null, "outputs": [], "id": "lab-1-3-layers-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · PyTorch basics: autograd, `nn.Module` and the 5-line training loop\n", "\n", "In Ch 1.2 you built a scalar `Value` class that recorded operations and ran `.backward()` to fill\n", "`.grad`. PyTorch does the exact same thing on whole tensors at once. Watch one small example\n", "before wrapping layers in `nn.Module`:" ], "id": "lab-1-3-layers-05" }, { "cell_type": "code", "metadata": {}, "source": [ "w_demo = torch.tensor(2.0, requires_grad=True)\n", "x_demo = torch.tensor(3.0)\n", "b_demo = torch.tensor(-1.0, requires_grad=True)\n", "z_demo = w_demo * x_demo + b_demo # 2*3 - 1 = 5\n", "loss_demo = (z_demo - 8.0) ** 2 # (5 - 8)^2 = 9\n", "loss_demo.backward()\n", "print(f\"z={z_demo.item():.1f}, loss={loss_demo.item():.1f}, d(loss)/dw={w_demo.grad.item():.1f}, d(loss)/db={b_demo.grad.item():.1f}\")\n", "\n", "# Evaluation and parameter updates happen inside torch.no_grad() so PyTorch does not build a graph:\n", "with torch.no_grad():\n", " w_demo -= 0.1 * w_demo.grad\n", "print(f\"after one manual step: w={w_demo.item():.2f}\")" ], "execution_count": null, "outputs": [], "id": "lab-1-3-layers-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let PyTorch build and train the `2 → 2 → 1` network from random initial weights (fixed seed).\n", "Notice three things:\n", "\n", "1. `nn.Linear(in_features, out_features)` creates `weight` (stored with shape `[out, in]`, so\n", " PyTorch computes `x @ weight.T + bias`) and `bias` (`[out]`), both with `requires_grad=True`.\n", "2. The network returns raw **logits** (`z_out`), not probabilities. Passing logits to\n", " `F.binary_cross_entropy_with_logits` computes the sigmoid and the log together in the\n", " numerically stable form from Lab 1.1's failure playground 7b.\n", "3. Every training step is the same 5 lines: forward → loss → `zero_grad()` → `backward()` → `step()`." ], "id": "lab-1-3-layers-07" }, { "cell_type": "code", "metadata": {}, "source": [ "class MLP(nn.Module):\n", " def __init__(self, in_dim, hidden_dim, out_dim=1):\n", " super().__init__()\n", " self.fc1 = nn.Linear(in_dim, hidden_dim)\n", " self.fc2 = nn.Linear(hidden_dim, out_dim)\n", "\n", " def forward(self, x):\n", " h = F.relu(self.fc1(x))\n", " return self.fc2(h)\n", "\n", "\n", "def count_params(model):\n", " return sum(p.numel() for p in model.parameters())\n", "\n", "\n", "torch.manual_seed(1)\n", "xor_model = MLP(in_dim=2, hidden_dim=2, out_dim=1)\n", "print(\"fc1.weight shape:\", tuple(xor_model.fc1.weight.shape),\n", " \"fc2.weight shape:\", tuple(xor_model.fc2.weight.shape))\n", "print(\"total parameters:\", count_params(xor_model))\n", "\n", "optimizer = torch.optim.SGD(xor_model.parameters(), lr=0.1)\n", "xor_history = []\n", "\n", "for step in range(2001):\n", " logits = xor_model(X_xor) # 1. forward\n", " loss = F.binary_cross_entropy_with_logits(logits, y_xor) # 2. loss\n", " xor_history.append(loss.item())\n", " if step in (0, 200, 500, 1000, 2000):\n", " with torch.no_grad():\n", " acc = int(((logits > 0).float() == y_xor).sum().item())\n", " print(f\"step {step:4d} loss {loss.item():.4f} correct {acc}/{len(XOR_LIKE)}\")\n", " if step < 2000:\n", " optimizer.zero_grad() # 3. clear old gradients\n", " loss.backward() # 4. backprop\n", " optimizer.step() # 5. update weights\n", "\n", "with torch.no_grad():\n", " probs_learned = torch.sigmoid(xor_model(X_xor)).squeeze()\n", "print(\"\\nLearned predictions:\")\n", "for (x1, x2, y), p in zip(XOR_LIKE, probs_learned):\n", " print(f\" ({x1},{x2}) actual={y} p={p.item():.4f} pred={int(p.item() > 0.5)}\")" ], "execution_count": null, "outputs": [], "id": "lab-1-3-layers-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plot the loss curve and the learned decision regions as a 2-D grid over `[0, 10] × [0, 10]`." ], "id": "lab-1-3-layers-09" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " import matplotlib.pyplot as plt\n", "\n", " fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))\n", " ax1.plot(xor_history)\n", " ax1.set_xlabel(\"step\"); ax1.set_ylabel(\"loss\"); ax1.set_title(\"XOR_LIKE loss (SGD, lr=0.1)\")\n", "\n", " grid_1d = torch.linspace(0, 10, 101)\n", " gx1, gx2 = torch.meshgrid(grid_1d, grid_1d, indexing=\"xy\")\n", " grid_pts = torch.stack([gx1.reshape(-1), gx2.reshape(-1)], dim=1)\n", " with torch.no_grad():\n", " grid_p = torch.sigmoid(xor_model(grid_pts)).reshape(gx1.shape)\n", "\n", " ax2.contourf(gx1.numpy(), gx2.numpy(), grid_p.numpy(), levels=[0, 0.5, 1], alpha=0.25)\n", " ax2.contour(gx1.numpy(), gx2.numpy(), grid_p.numpy(), levels=[0.5], linewidths=1.5)\n", " for x1, x2, y in XOR_LIKE:\n", " ax2.scatter(x1, x2, marker=\"o\" if y else \"x\", s=70, color=\"black\")\n", " ax2.set_xlim(0, 10); ax2.set_ylim(0, 10)\n", " ax2.set_xlabel(\"x1\"); ax2.set_ylabel(\"x2\")\n", " ax2.set_title(\"Learned decision regions (o = 1, x = 0)\")\n", " plt.tight_layout(); plt.show()\n", "except ImportError:\n", " print(\"matplotlib not installed: skip the plot\")" ], "execution_count": null, "outputs": [], "id": "lab-1-3-layers-10" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Harder 2-D data: how hidden width controls capacity\n", "\n", "Eight points need only two lines. What about **400 points arranged in two interleaved spirals**?\n", "Below we generate the spirals deterministically and train `2 → H → 1` networks for\n", "`H = 1, 2, 4, 8, 32`. Here we also swap SGD for **Adam** (`torch.optim.Adam`), which adapts each\n", "weight's step size automatically and is the default optimizer for neural networks and LLMs." ], "id": "lab-1-3-layers-11" }, { "cell_type": "code", "metadata": {}, "source": [ "def make_spirals(n_per_class=200, turns=1.0, noise=0.08, seed=42):\n", " g = torch.Generator().manual_seed(seed)\n", " xs, ys = [], []\n", " for label in (0, 1):\n", " t = torch.linspace(0.15, 1.0, n_per_class)\n", " angle = t * turns * 2 * math.pi + label * math.pi\n", " r = t\n", " x1 = r * torch.cos(angle) + noise * torch.randn(n_per_class, generator=g)\n", " x2 = r * torch.sin(angle) + noise * torch.randn(n_per_class, generator=g)\n", " xs.append(torch.stack([x1, x2], dim=1))\n", " ys.append(torch.full((n_per_class, 1), float(label)))\n", " return torch.cat(xs, dim=0), torch.cat(ys, dim=0)\n", "\n", "\n", "X_sp, y_sp = make_spirals()\n", "HIDDEN_SIZES = [1, 2, 4, 8, 32]\n", "spiral_rows = []\n", "spiral_models = {}\n", "\n", "for h_dim in HIDDEN_SIZES:\n", " torch.manual_seed(5)\n", " model = MLP(in_dim=2, hidden_dim=h_dim, out_dim=1)\n", " opt = torch.optim.Adam(model.parameters(), lr=0.03)\n", " for _ in range(2000):\n", " opt.zero_grad()\n", " loss = F.binary_cross_entropy_with_logits(model(X_sp), y_sp)\n", " loss.backward()\n", " opt.step()\n", " with torch.no_grad():\n", " logits = model(X_sp)\n", " final_loss = F.binary_cross_entropy_with_logits(logits, y_sp).item()\n", " final_acc = ((logits > 0).float() == y_sp).float().mean().item()\n", " row = {\n", " \"hidden\": h_dim,\n", " \"params\": count_params(model),\n", " \"accuracy\": round(final_acc, 4),\n", " \"loss\": round(final_loss, 4),\n", " }\n", " spiral_rows.append(row)\n", " spiral_models[h_dim] = model\n", " print(f\"hidden={h_dim:2d} params={row['params']:3d} acc={final_acc*100:5.1f}% loss={final_loss:.4f}\")\n", "\n", "hidden_csv = out_dir() / \"hidden-size.csv\"\n", "with hidden_csv.open(\"w\", newline=\"\") as f:\n", " w = csv.DictWriter(f, fieldnames=[\"hidden\", \"params\", \"accuracy\", \"loss\"], lineterminator=\"\\n\")\n", " w.writeheader()\n", " w.writerows(spiral_rows)\n", "print(\"saved\", hidden_csv)" ], "execution_count": null, "outputs": [], "id": "lab-1-3-layers-12" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " import matplotlib.pyplot as plt\n", "\n", " fig, axes = plt.subplots(1, 4, figsize=(15, 3.6))\n", " hs = [r[\"hidden\"] for r in spiral_rows]\n", " accs = [r[\"accuracy\"] * 100 for r in spiral_rows]\n", " axes[0].plot(hs, accs, marker=\"o\")\n", " axes[0].set_xscale(\"log\", base=2)\n", " axes[0].set_xticks(hs); axes[0].set_xticklabels([str(h) for h in hs])\n", " axes[0].set_ylim(45, 105)\n", " axes[0].set_xlabel(\"hidden units\"); axes[0].set_ylabel(\"train accuracy (%)\")\n", " axes[0].set_title(\"Capacity vs hidden size\")\n", "\n", " g1 = torch.linspace(-1.3, 1.3, 120)\n", " gx1, gx2 = torch.meshgrid(g1, g1, indexing=\"xy\")\n", " gpts = torch.stack([gx1.reshape(-1), gx2.reshape(-1)], dim=1)\n", " for ax, h_dim in zip(axes[1:], [1, 4, 32]):\n", " with torch.no_grad():\n", " gp = torch.sigmoid(spiral_models[h_dim](gpts)).reshape(gx1.shape)\n", " ax.contourf(gx1.numpy(), gx2.numpy(), gp.numpy(), levels=[0, 0.5, 1], alpha=0.25)\n", " ax.contour(gx1.numpy(), gx2.numpy(), gp.numpy(), levels=[0.5], linewidths=1.2)\n", " c0 = (y_sp.squeeze() == 0)\n", " c1 = (y_sp.squeeze() == 1)\n", " ax.scatter(X_sp[c0, 0], X_sp[c0, 1], s=8, marker=\"x\", color=\"black\", alpha=0.7)\n", " ax.scatter(X_sp[c1, 0], X_sp[c1, 1], s=8, marker=\"o\", color=\"black\", alpha=0.7)\n", " acc_pct = next(r[\"accuracy\"] * 100 for r in spiral_rows if r[\"hidden\"] == h_dim)\n", " ax.set_title(f\"hidden={h_dim} ({acc_pct:.1f}%)\")\n", " ax.set_xlim(-1.3, 1.3); ax.set_ylim(-1.3, 1.3)\n", " plt.tight_layout(); plt.show()\n", "except ImportError:\n", " print(\"matplotlib not installed: skip the plot\")" ], "execution_count": null, "outputs": [], "id": "lab-1-3-layers-13" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Moving to a GPU: time per training step\n", "\n", "Moving a model and its batch to a GPU is `.to(device)` on both. Just as in Lab 0.1, we warm up\n", "first and call `sync(device)` so the stopwatch waits for the GPU to finish. Compare a tiny\n", "`2 → 2 → 1` network (batch 8) against a larger `512 → 2048 → 512` MLP (batch 256) — the same\n", "4× expansion shape used inside every transformer's feed-forward block." ], "id": "lab-1-3-layers-14" }, { "cell_type": "code", "metadata": {}, "source": [ "def time_train_step(d_in, d_hidden, d_out, batch_size, device, warmup=5, repeats=30):\n", " torch.manual_seed(0)\n", " model = MLP(d_in, d_hidden, d_out).to(device)\n", " opt = torch.optim.SGD(model.parameters(), lr=0.01)\n", " xb = torch.randn(batch_size, d_in, device=device)\n", " yb = torch.randn(batch_size, d_out, device=device)\n", "\n", " for _ in range(warmup):\n", " opt.zero_grad()\n", " F.mse_loss(model(xb), yb).backward()\n", " opt.step()\n", " sync(device)\n", "\n", " times_ms = []\n", " for _ in range(repeats):\n", " t0 = time.perf_counter()\n", " opt.zero_grad()\n", " F.mse_loss(model(xb), yb).backward()\n", " opt.step()\n", " sync(device)\n", " times_ms.append((time.perf_counter() - t0) * 1000.0)\n", " times_ms.sort()\n", " return times_ms[len(times_ms) // 2], count_params(model)\n", "\n", "\n", "machine_name = (\n", " torch.cuda.get_device_name(0)\n", " if torch.cuda.is_available()\n", " else f\"{platform.system()} {platform.machine()}\"\n", ")\n", "BENCHMARKS = [\n", " (\"tiny_2_2_1\", 2, 2, 1, 8),\n", " (\"big_512_2048_512\", 512, 2048, 512, 256),\n", "]\n", "speed_rows = []\n", "\n", "for label, d_in, d_h, d_out, bs in BENCHMARKS:\n", " for dev in DEVICES:\n", " med_ms, n_params = time_train_step(d_in, d_h, d_out, bs, dev)\n", " row = {\n", " \"machine\": machine_name,\n", " \"model\": label,\n", " \"d_in\": d_in,\n", " \"d_hidden\": d_h,\n", " \"d_out\": d_out,\n", " \"batch_size\": bs,\n", " \"params\": n_params,\n", " \"device\": dev,\n", " \"ms_per_step\": round(med_ms, 3),\n", " }\n", " speed_rows.append(row)\n", " print(f\"{label:18s} params={n_params:9,d} batch={bs:3d} {dev:4s} {med_ms:7.3f} ms/step\")\n", "\n", "speed_csv = out_dir() / \"device-speed.csv\"\n", "with speed_csv.open(\"w\", newline=\"\") as f:\n", " w = csv.DictWriter(\n", " f,\n", " fieldnames=[\"machine\", \"model\", \"d_in\", \"d_hidden\", \"d_out\", \"batch_size\", \"params\", \"device\", \"ms_per_step\"],\n", " lineterminator=\"\\n\",\n", " )\n", " w.writeheader()\n", " w.writerows(speed_rows)\n", "print(\"saved\", speed_csv)" ], "execution_count": null, "outputs": [], "id": "lab-1-3-layers-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · Checkpoint\n", "\n", "Compare your outputs against the book's reference run (the last digit can differ across PyTorch\n", "versions and hardware; GPU step times depend on your machine):\n", "\n", "- **Hand-set `2 → 2 → 1` on `XOR_LIKE`:** `8/8` correct, loss `0.0367`, `9` parameters.\n", "- **PyTorch `MLP(2, 2, 1)` on `XOR_LIKE` (`seed=1`, SGD `lr=0.1`):**\n", "\n", "```text\n", "step 0 loss 0.7375 correct 6/8\n", "step 200 loss 0.1573 correct 8/8\n", "step 500 loss 0.0493 correct 8/8\n", "step 1000 loss 0.0195 correct 8/8\n", "step 2000 loss 0.0082 correct 8/8\n", "```\n", "\n", "- **Two interleaved spirals (`400` points, `seed=5`, Adam `lr=0.03`):**\n", "\n", "```text\n", "hidden= 1 params= 5 acc= 59.0% loss=0.5829\n", "hidden= 2 params= 9 acc= 76.0% loss=0.4106\n", "hidden= 4 params= 17 acc= 96.2% loss=0.0855\n", "hidden= 8 params= 33 acc= 98.8% loss=0.0246\n", "hidden=32 params=129 acc=100.0% loss=0.0005\n", "```\n", "\n", "- **Device speed:** on a GPU, the tiny `2 → 2 → 1` step is *slower* than on CPU (launch\n", " overhead), while the `512 → 2048 → 512` step (batch 256) is *faster* than on CPU." ], "id": "lab-1-3-layers-16" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Explore\n", "\n", "Change one knob at a time and write one sentence on what changed and why.\n", "\n", "| Knob | Try | Question |\n", "| --- | --- | --- |\n", "| hidden size | `hidden=16` and `hidden=64` on the spirals | How does accuracy change beyond `32`? Does training take noticeably longer? |\n", "| depth | add a second hidden layer (`2 → 8 → 8 → 1`) on the spirals | Compare its accuracy and parameter count against the wider single-layer `2 → 32 → 1`. |\n", "| activation | replace `F.relu` with `torch.sigmoid` and `torch.tanh` on `XOR_LIKE` and spirals | Which trains fastest? Which struggles when you also change the random seed? |\n", "| optimizer | train the `hidden=32` spiral network with `SGD(lr=0.03)` and `SGD(lr=0.3)` vs `Adam(lr=0.03)` | Why does Adam reach low loss in fewer steps without careful learning-rate tuning? |\n", "| learning rate | try `lr=0.001`, `lr=0.1`, `lr=1.0` on `XOR_LIKE` with SGD | Where is the useful range, and what happens above it? |" ], "id": "lab-1-3-layers-17" }, { "cell_type": "code", "metadata": {}, "source": [ "# your experiments here" ], "execution_count": null, "outputs": [], "id": "lab-1-3-layers-18" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Failure playground\n", "\n", "Four networks below are broken in the ways PyTorch code most often breaks. For each: run it,\n", "read the symptom, find the cause, and fix it. Hints are in Review 1.3; answers are not." ], "id": "lab-1-3-layers-19" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 8a · The activation removed\n", "\n", "A colleague simplifies the network by dropping `ReLU` between the two `nn.Linear` layers." ], "id": "lab-1-3-layers-20" }, { "cell_type": "code", "metadata": {}, "source": [ "torch.manual_seed(1)\n", "linear_only = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 1))\n", "opt_a = torch.optim.SGD(linear_only.parameters(), lr=0.1)\n", "for step in range(2000):\n", " opt_a.zero_grad()\n", " loss_a = F.binary_cross_entropy_with_logits(linear_only(X_xor), y_xor)\n", " loss_a.backward()\n", " opt_a.step()\n", "\n", "with torch.no_grad():\n", " logits_a = linear_only(X_xor)\n", " acc_a = int(((logits_a > 0).float() == y_xor).sum().item())\n", " final_loss_a = F.binary_cross_entropy_with_logits(logits_a, y_xor).item()\n", "print(f\"8a (no activation): correct {acc_a}/{len(XOR_LIKE)}, loss {final_loss_a:.4f}\")" ], "execution_count": null, "outputs": [], "id": "lab-1-3-layers-21" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: two layers, 9 parameters, zero errors — yet the loss is stuck at **0.6931**, identical\n", "to Lab 1.1's single neuron. Why did adding a hidden layer buy nothing here? Prove it by multiplying\n", "the two weight matrices together." ], "id": "lab-1-3-layers-22" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 8b · `optimizer.zero_grad()` forgotten\n", "\n", "A colleague deletes the \"boring boilerplate line\" `optimizer.zero_grad()` from the loop." ], "id": "lab-1-3-layers-23" }, { "cell_type": "code", "metadata": {}, "source": [ "torch.manual_seed(1)\n", "model_b = MLP(2, 2, 1)\n", "opt_b = torch.optim.SGD(model_b.parameters(), lr=0.1)\n", "for step in range(201):\n", " loss_b = F.binary_cross_entropy_with_logits(model_b(X_xor), y_xor)\n", " loss_b.backward()\n", " grad_sum = sum(p.grad.norm().item() for p in model_b.parameters())\n", " opt_b.step()\n", " if step in (0, 1, 2, 5, 20, 50, 100, 200):\n", " print(f\"8b step {step:3d} loss {loss_b.item():.4f} sum(||grad||) {grad_sum:7.2f}\")" ], "execution_count": null, "outputs": [], "id": "lab-1-3-layers-24" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: the gradient norm keeps climbing even though the loss stops falling, and the loss\n", "stalls around 0.5 instead of settling toward zero. Why does PyTorch *add* new gradients into `.grad` by\n", "default instead of overwriting them? (Hint: Ch 1.2's \"gradients add\", and Vol 5's gradient\n", "accumulation.)" ], "id": "lab-1-3-layers-25" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 8c · Dead ReLUs from a learning rate too high\n", "\n", "A colleague uses a wide hidden layer (16 ReLU units) on `XOR_LIKE` and sets `lr = 2.0`." ], "id": "lab-1-3-layers-26" }, { "cell_type": "code", "metadata": {}, "source": [ "torch.manual_seed(0)\n", "model_c = MLP(2, 16, 1)\n", "opt_c = torch.optim.SGD(model_c.parameters(), lr=2.0)\n", "for step in range(200):\n", " opt_c.zero_grad()\n", " loss_c = F.binary_cross_entropy_with_logits(model_c(X_xor), y_xor)\n", " loss_c.backward()\n", " opt_c.step()\n", "\n", "with torch.no_grad():\n", " h_c = F.relu(model_c.fc1(X_xor)) # shape [8, 16]\n", " dead_mask = h_c.max(dim=0).values == 0 # True if unit outputs 0 on all 8 inputs\n", " n_dead = int(dead_mask.sum().item())\n", " final_loss_c = F.binary_cross_entropy_with_logits(model_c(X_xor), y_xor).item()\n", "print(f\"8c (lr=2.0): dead hidden units = {n_dead}/16 ({100 * n_dead / 16:.0f}%), loss = {final_loss_c:.4f}\")" ], "execution_count": null, "outputs": [], "id": "lab-1-3-layers-27" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: the loss freezes at `0.6931` and all (or nearly all) hidden units output `0` on every\n", "input point. Inspect `model_c.fc1.bias` and `model_c.fc1.weight`: why can those units *never*\n", "recover on later steps once they die? What two changes prevent this?" ], "id": "lab-1-3-layers-28" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 8d · The shape mismatch\n", "\n", "The single most common bug in PyTorch code: two layers whose dimensions do not agree." ], "id": "lab-1-3-layers-29" }, { "cell_type": "code", "metadata": {}, "source": [ "bad_layer = nn.Linear(3, 4)\n", "try:\n", " out = bad_layer(X_xor)\n", "except RuntimeError as e:\n", " print(\"8d RuntimeError:\", e)" ], "execution_count": null, "outputs": [], "id": "lab-1-3-layers-30" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: a `RuntimeError` mentioning two matrix shapes. Read the numbers in the error message:\n", "where did `(8x2)` come from, where did `(3x4)` come from (even though `bad_layer.weight.shape` is\n", "`(4, 3)`!), and which single number fixes the layer so it accepts `X_xor`?" ], "id": "lab-1-3-layers-31" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\n", " \"Versions tested:\",\n", " f\"Python {platform.python_version()},\",\n", " f\"PyTorch {torch.__version__},\",\n", " end=\" \",\n", ")\n", "try:\n", " import matplotlib\n", " print(f\"matplotlib {matplotlib.__version__},\", end=\" \")\n", "except ImportError:\n", " pass\n", "print(f\"{platform.system()} {platform.machine()} ({', '.join(DEVICES)})\")" ], "execution_count": null, "outputs": [], "id": "lab-1-3-layers-32" } ] }