{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# P5 — Read PyTorch in Colab (CPU)\n",
    "\n",
    "No TODO functions. Run top to bottom and change only `hidden_width` from 4 to 6, then restore 4. This is an optional companion to P5, not a numbered Lab.\n",
    ""
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import io\n",
    "import torch\n",
    "from torch import nn\n",
    "\n",
    "torch.manual_seed(13)\n",
    "torch.set_num_threads(1)\n",
    "hidden_width = 4  # edit only this value to 6, then reset to 4\n",
    "\n",
    "class SmallClassifier(nn.Module):\n",
    "    def __init__(self, hidden=4):\n",
    "        super().__init__()\n",
    "        self.layers = nn.Sequential(nn.Linear(3, hidden), nn.ReLU(), nn.Linear(hidden, 2))\n",
    "    def forward(self, x):\n",
    "        return self.layers(x)\n",
    "\n",
    "model = SmallClassifier(hidden_width)\n",
    "features = torch.tensor([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]], dtype=torch.float32)\n",
    "targets = torch.tensor([0, 1], dtype=torch.long)\n",
    "logits = model(features)\n",
    "print(\"input:\", tuple(features.shape), features.dtype)\n",
    "print(\"output:\", tuple(logits.shape), logits.dtype)\n",
    "print(\"targets:\", tuple(targets.shape), targets.dtype)\n",
    "assert logits.shape == (2, 2)\n",
    ""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Five lines to read, not memorize\n",
    "\n",
    "1. `zero_grad` clears old gradients. 2. `model(features)` calls `forward`. 3. The loss compares outputs to class-index targets. 4. `backward` computes gradients. 5. `step` updates parameters. Run twice to see a loss change; changing hidden width changes parameter shapes.\n",
    ""
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "criterion = nn.CrossEntropyLoss()\n",
    "optimizer = torch.optim.SGD(model.parameters(), lr=0.1)\n",
    "before = float(criterion(model(features), targets))\n",
    "for _ in range(2):\n",
    "    optimizer.zero_grad()\n",
    "    predictions = model(features)\n",
    "    loss = criterion(predictions, targets)\n",
    "    loss.backward()\n",
    "    optimizer.step()\n",
    "after = float(criterion(model(features), targets))\n",
    "print(\"loss before/after:\", before, after)\n",
    "assert torch.isfinite(torch.tensor(after))\n",
    ""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## State is not the class definition\n",
    "\n",
    "`state_dict()` maps parameter names to tensors. Save and reload in memory here; no credentials, external datasets, local file or GPU required. Restore `hidden_width=4` and rerun all cells before moving on.\n",
    ""
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "keys = sorted(model.state_dict())\n",
    "print(\"state_dict keys:\", keys)\n",
    "buffer = io.BytesIO()\n",
    "torch.save(model.state_dict(), buffer)\n",
    "buffer.seek(0)\n",
    "restored = SmallClassifier(hidden_width)\n",
    "restored.load_state_dict(torch.load(buffer, map_location=\"cpu\", weights_only=True))\n",
    "restored.eval()\n",
    "model.eval()\n",
    "with torch.no_grad():\n",
    "    assert torch.allclose(restored(features), model(features))\n",
    "print(\"PASS: state_dict round trip\")\n",
    ""
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
