{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "id": "step-0",
   "metadata": {},
   "source": [
    "# PyTorch \u00b7 single-GPU training\n",
    "\n",
    "Fit a small classifier to reproducible synthetic observations. This checks CUDA training and checkpoint reload without downloading a dataset.\n",
    "\n",
    "Run cells in order. Package and weight downloads use instance time and disk. Export outputs before releasing the instance."
   ]
  },
  {
   "cell_type": "code",
   "id": "step-1",
   "metadata": {},
   "source": [
    "import torch\n",
    "if not torch.cuda.is_available():\n",
    "    raise RuntimeError(\"Choose a CUDA-enabled PyTorch kernel before continuing.\")\n",
    "print(torch.cuda.get_device_name(), torch.__version__)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "id": "step-2",
   "metadata": {},
   "source": [
    "from pathlib import Path\n",
    "torch.manual_seed(42)\n",
    "x = torch.randn(2048, 8, device=\"cuda\")\n",
    "y = (x[:, 0] + x[:, 1] > 0).long()\n",
    "model = torch.nn.Linear(8, 2).cuda()\n",
    "opt = torch.optim.Adam(model.parameters(), lr=0.03)\n",
    "for step in range(80):\n",
    "    loss = torch.nn.functional.cross_entropy(model(x[:1536]), y[:1536])\n",
    "    opt.zero_grad()\n",
    "    loss.backward()\n",
    "    opt.step()\n",
    "with torch.no_grad():\n",
    "    print(\"Held-out accuracy:\", (model(x[1536:]).argmax(1) == y[1536:]).float().mean().item())\n",
    "path = Path(\"pytorch-classifier.pt\")\n",
    "torch.save({\"model\": model.state_dict(), \"optimizer\": opt.state_dict(), \"step\": step + 1}, path)\n",
    "restored = torch.nn.Linear(8, 2).cuda()\n",
    "restored.load_state_dict(torch.load(path, weights_only=True)[\"model\"])\n",
    "torch.testing.assert_close(restored(x[:4]), model(x[:4]))\n",
    "print(path.resolve())"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "id": "export-note",
   "metadata": {},
   "source": [
    "## Optional: check an inference export on the host CPU\n",
    "\n",
    "Run after training with PyTorch 2.8 or a compatible version. The sample input is one observation with eight float32 features. Download both artifacts before releasing the instance."
   ]
  },
  {
   "cell_type": "code",
   "id": "export-cpu",
   "metadata": {},
   "source": [
    "cpu_model = torch.nn.Linear(8, 2).eval()\n",
    "cpu_model.load_state_dict(torch.load(path, map_location=\"cpu\", weights_only=True)[\"model\"])\n",
    "sample = torch.tensor([[0.5, -0.25, 0, 0, 0, 0, 0, 0]], dtype=torch.float32)\n",
    "export_path = Path(\"classifier-host.pt2\")\n",
    "torch.export.save(torch.export.export(cpu_model, (sample,)), export_path)\n",
    "loaded = torch.export.load(export_path).module()\n",
    "with torch.no_grad():\n",
    "    torch.testing.assert_close(loaded(sample), cpu_model(sample))\n",
    "print(\"Host export verified:\", export_path.resolve())"
   ],
   "outputs": [],
   "execution_count": null
  }
 ]
}
