{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "gpuType": "A100",
      "selectedAiContext": "default"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "code",
      "source": [
        "import torch"
      ],
      "metadata": {
        "id": "vPE96Pn0Tgup"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xk15fjhpYb2Q",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "4d4ffb5a-94dc-45bd-aa44-658f1f293a14"
      },
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "True"
            ]
          },
          "metadata": {},
          "execution_count": 2
        }
      ],
      "source": [
        "torch.cuda.is_available()"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import torch.nn.functional as F\n",
        "from torch.autograd import grad\n",
        "\n",
        "y = torch.tensor([1.0])\n",
        "x1 = torch.tensor([1.1])\n",
        "w1 = torch.tensor([2.2], requires_grad=True)\n",
        "b = torch.tensor([0.0], requires_grad=True)\n",
        "\n",
        "z = x1*w1 + b\n",
        "a = torch.sigmoid(z)\n",
        "\n",
        "loss = F.binary_cross_entropy(a, y)\n",
        "\n",
        "grad_L_w1 = grad(loss, w1, retain_graph=True)\n",
        "grad_L_b = grad(loss, b, retain_graph=True)\n",
        "\n",
        "print(grad_L_w1)\n",
        "print(grad_L_b)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "s6_hi4FW5V8w",
        "outputId": "c7a2f4df-c1d9-48eb-fdf6-02106d06ce00"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "(tensor([-0.0898]),)\n",
            "(tensor([-0.0817]),)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "loss.backward() # The easy way\n",
        "print(w1.grad)\n",
        "print(b.grad)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "qqe8ojc9-6qM",
        "outputId": "14bda073-2431-4255-87ea-040cbd4ba2fd"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "tensor([-0.0898])\n",
            "tensor([-0.0817])\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import torch.nn.functional as F\n",
        "from torch.autograd import grad\n",
        "\n",
        "y = torch.tensor([1.0, 1.0])\n",
        "x1 = torch.tensor([1.1])\n",
        "w1 = torch.tensor([2.2, 3.3], requires_grad=True)\n",
        "b = torch.tensor([0.0, 0.0], requires_grad=True)\n",
        "\n",
        "z = w1*x1 + b\n",
        "a = torch.sigmoid(z)\n",
        "print(a.grad_fn)\n",
        "\n",
        "loss = F.binary_cross_entropy(a, y)\n",
        "print(loss.grad_fn)\n",
        "\n",
        "grad_L_w1 = grad(loss, w1, retain_graph=True)\n",
        "grad_L_b = grad(loss, b, retain_graph=True)\n",
        "\n",
        "print(grad_L_w1)\n",
        "print(grad_L_b)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "8eb2cb08-2911-4e41-c4db-bae5d98ac03e",
        "id": "j484ZswV8v32"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "<SigmoidBackward0 object at 0x7c9e071f1a80>\n",
            "<BinaryCrossEntropyBackward0 object at 0x7c9e07323640>\n",
            "(tensor([-0.0449, -0.0142]),)\n",
            "(tensor([-0.0408, -0.0129]),)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "class NeuralNetwork(torch.nn.Module):\n",
        "  def __init__(self, num_inputs, num_outputs):\n",
        "    super().__init__()\n",
        "\n",
        "    self.layers = torch.nn.Sequential(\n",
        "        # first hidden layer\n",
        "        torch.nn.Linear(num_inputs, 30),\n",
        "        torch.nn.ReLU(),\n",
        "\n",
        "        # second hidden layer\n",
        "        torch.nn.Linear(30, 20),\n",
        "        torch.nn.ReLU(),\n",
        "\n",
        "        # output layer\n",
        "        torch.nn.Linear(20, num_outputs)\n",
        "    )\n",
        "\n",
        "  def forward(self, x):\n",
        "    logits = self.layers(x)\n",
        "    return logits"
      ],
      "metadata": {
        "id": "lch4wHLsBfE2"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "model = NeuralNetwork(50, 3)\n",
        "print(model)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "kWgz1we4DD7f",
        "outputId": "adef824f-c812-4ade-db27-6774cc485ef5"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "NeuralNetwork(\n",
            "  (layers): Sequential(\n",
            "    (0): Linear(in_features=50, out_features=30, bias=True)\n",
            "    (1): ReLU()\n",
            "    (2): Linear(in_features=30, out_features=20, bias=True)\n",
            "    (3): ReLU()\n",
            "    (4): Linear(in_features=20, out_features=3, bias=True)\n",
            "  )\n",
            ")\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "p = model.parameters()\n",
        "q = next(p)\n",
        "q.numel()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "HcyAuw1HEGe1",
        "outputId": "3c038330-8600-461d-a7d5-fed6d53f1880"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "1500"
            ]
          },
          "metadata": {},
          "execution_count": 8
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "num_params = sum([p.numel() for p in model.parameters() if p.requires_grad])\n",
        "print(num_params)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "a92HaQXRFQzg",
        "outputId": "4e9db300-fd87-4254-e4a3-edb8061d68d7"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "2213\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(model.layers[0].weight)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ZcIRMs8fGAs4",
        "outputId": "dfb5dbff-539e-4910-e2cc-fabdd3ae29ef"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Parameter containing:\n",
            "tensor([[-0.0082, -0.0547,  0.1369,  ...,  0.0176,  0.0738,  0.1222],\n",
            "        [-0.0353, -0.0381,  0.0007,  ..., -0.0873, -0.0254,  0.1021],\n",
            "        [-0.0712,  0.0232, -0.1079,  ...,  0.0369,  0.0421,  0.0522],\n",
            "        ...,\n",
            "        [ 0.1249,  0.1045, -0.0093,  ...,  0.0402,  0.0079, -0.0752],\n",
            "        [-0.0492, -0.0949,  0.0095,  ..., -0.0049,  0.1040,  0.0515],\n",
            "        [ 0.1242,  0.0859,  0.1203,  ..., -0.0817, -0.0041, -0.0403]],\n",
            "       requires_grad=True)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(model.layers[0])"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "XdGGCA4sw5dx",
        "outputId": "d6db0b8b-81b0-4a95-8888-67865b08540f"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Linear(in_features=50, out_features=30, bias=True)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(model.layers[0].weight.shape)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "uoWJrQHpGMNn",
        "outputId": "49a0040c-272a-4ec6-f1de-cc0409952df5"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "torch.Size([30, 50])\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(model.layers[0].bias)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "nlhXfziiGTbv",
        "outputId": "a78b756c-9c66-4367-b050-7d08907a462d"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Parameter containing:\n",
            "tensor([ 0.0214,  0.0271,  0.0977, -0.1119,  0.0430,  0.0557, -0.0228,  0.0450,\n",
            "         0.1171, -0.0895,  0.0828,  0.0666, -0.0439, -0.0972, -0.0658,  0.0010,\n",
            "         0.0505, -0.0840, -0.1035, -0.0178, -0.0104, -0.0219,  0.0562, -0.0741,\n",
            "         0.0420,  0.0271, -0.0961, -0.1094, -0.0678,  0.1323],\n",
            "       requires_grad=True)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(model.layers[0].bias.shape)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "RX6CpPUNGhIG",
        "outputId": "b991bf38-f48f-4a7e-b3c9-9e4d61ac8219"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "torch.Size([30])\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "torch.manual_seed(123)\n",
        "model = NeuralNetwork(50, 3)\n",
        "print(model.layers[0].weight)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "5iECmeW8Gxz-",
        "outputId": "c7f26d56-0eb1-472e-8594-46e46482f4f3"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Parameter containing:\n",
            "tensor([[-0.0577,  0.0047, -0.0702,  ...,  0.0222,  0.1260,  0.0865],\n",
            "        [ 0.0502,  0.0307,  0.0333,  ...,  0.0951,  0.1134, -0.0297],\n",
            "        [ 0.1077, -0.1108,  0.0122,  ...,  0.0108, -0.1049, -0.1063],\n",
            "        ...,\n",
            "        [-0.0787,  0.1259,  0.0803,  ...,  0.1218,  0.1303, -0.1351],\n",
            "        [ 0.1359,  0.0175, -0.0673,  ...,  0.0674,  0.0676,  0.1058],\n",
            "        [ 0.0790,  0.1343, -0.0293,  ...,  0.0344, -0.0971, -0.0509]],\n",
            "       requires_grad=True)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# put it to use\n",
        "torch.manual_seed(123)\n",
        "X = torch.rand([1, 50])\n",
        "out = model(X)\n",
        "print(out)\n",
        "print(out.grad_fn)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "qozOlcc7VR3t",
        "outputId": "9f5312ba-a6b1-4791-aec5-3befe3e2e20f"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "tensor([[-0.1262,  0.1080, -0.1792]], grad_fn=<AddmmBackward0>)\n",
            "<AddmmBackward0 object at 0x7c9e06aef970>\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# forward pass only, drop the backward-pass overhead (note the dropped gradient function)\n",
        "with torch.no_grad():\n",
        "  out = model(X)\n",
        "out"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "NAF89G_Zd3RA",
        "outputId": "1348485a-d0f5-498e-a201-4a1279544cc9"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "tensor([[-0.1262,  0.1080, -0.1792]])"
            ]
          },
          "metadata": {},
          "execution_count": 17
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# PyTorch networks conventionally outputs pre-activated logits for recisions of\n",
        "# numerical efficiency and stability. So if we want the softmax we have to take\n",
        "# it ourselves.\n",
        "with torch.no_grad():\n",
        "  out = torch.softmax(model(X), 1)\n",
        "print(out)\n",
        "print(torch.sum(out))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "uoNDi5iIeIil",
        "outputId": "df21e1db-bc94-4f22-d38c-55bb9687cc42"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "tensor([[0.3113, 0.3934, 0.2952]])\n",
            "tensor(1.)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Some sample train/test data to illustrate data loading.\n",
        "X_train = torch.tensor([\n",
        "    [-1.2, 3.1],\n",
        "    [-0.9, 2.9],\n",
        "    [-0.5, 2.6],\n",
        "    [2.3, -1.1],\n",
        "    [2.7, -1.5]\n",
        "])\n",
        "\n",
        "X_test = torch.tensor([\n",
        "    [-0.8, 2.8],\n",
        "    [2.6, -1.6]\n",
        "])\n",
        "\n",
        "y_train = torch.tensor([0, 0, 0, 1, 1])\n",
        "\n",
        "y_test = torch.tensor([0, 1])"
      ],
      "metadata": {
        "id": "nafKao7Zh5MF"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Create a toy dataset for use with a dataloader.\n",
        "\n",
        "from torch.utils.data import Dataset\n",
        "\n",
        "class ToyDataset(Dataset):\n",
        "  def __init__(self, X, y):\n",
        "    self.features = X\n",
        "    self.labels = y\n",
        "    return\n",
        "\n",
        "  def __len__(self):\n",
        "    return self.labels.shape[0]\n",
        "\n",
        "  def __getitem__(self, index):\n",
        "    x = self.features[index]\n",
        "    y = self.labels[index]\n",
        "    return x, y\n",
        "\n",
        "train_ds = ToyDataset(X_train, y_train)\n",
        "test_ds = ToyDataset(X_test, y_test)"
      ],
      "metadata": {
        "id": "aYle5KPTXKUj"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "print(len(train_ds))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "KBMPArbIZmZs",
        "outputId": "2e1a18c4-2868-485a-a1e6-42a5d696e932"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "5\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Now create a DataLoader to sample from our DataSet.\n",
        "# Note that we don't use any worker threads because\n",
        "# that won't improve performance meaningfully for such\n",
        "# tiny amounts of data, and in fact within a notebook\n",
        "# it can cause performance and stability issues.\n",
        "\n",
        "from torch.utils.data import DataLoader\n",
        "\n",
        "torch.manual_seed(123)\n",
        "\n",
        "train_loader = DataLoader(\n",
        "    dataset=train_ds,\n",
        "    batch_size=2,\n",
        "    shuffle=True,\n",
        "    num_workers=0\n",
        ")\n",
        "\n",
        "test_loader = DataLoader(\n",
        "    dataset=test_ds,\n",
        "    batch_size=2,\n",
        "    shuffle=False,\n",
        "    num_workers=0\n",
        ")"
      ],
      "metadata": {
        "id": "Yfdd7LboiscN"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Explorer the DataLoaders.\n",
        "\n",
        "print(f\"## Train\")\n",
        "for idx, (x, y) in enumerate(train_loader):\n",
        "  print(f\"**Batch:** {idx}\")\n",
        "  print(f\"- Features: {x}\")\n",
        "  print(f\"- Labels: {y}\\n\")\n",
        "\n",
        "print(f\"## Test\")\n",
        "for idx, (x, y) in enumerate(train_loader):\n",
        "  print(f\"**Batch:** {idx}\")\n",
        "  print(f\"- Features: {x}\")\n",
        "  print(f\"- Labels: {y}\\n\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "i0Edv1TDkpH3",
        "outputId": "2694b22d-7689-4ed6-e0d5-d2891b7722ab"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "## Train\n",
            "**Batch:** 0\n",
            "- Features: tensor([[ 2.3000, -1.1000],\n",
            "        [-0.9000,  2.9000]])\n",
            "- Labels: tensor([1, 0])\n",
            "\n",
            "**Batch:** 1\n",
            "- Features: tensor([[-1.2000,  3.1000],\n",
            "        [-0.5000,  2.6000]])\n",
            "- Labels: tensor([0, 0])\n",
            "\n",
            "**Batch:** 2\n",
            "- Features: tensor([[ 2.7000, -1.5000]])\n",
            "- Labels: tensor([1])\n",
            "\n",
            "## Test\n",
            "**Batch:** 0\n",
            "- Features: tensor([[-1.2000,  3.1000],\n",
            "        [-0.5000,  2.6000]])\n",
            "- Labels: tensor([0, 0])\n",
            "\n",
            "**Batch:** 1\n",
            "- Features: tensor([[ 2.3000, -1.1000],\n",
            "        [-0.9000,  2.9000]])\n",
            "- Labels: tensor([1, 0])\n",
            "\n",
            "**Batch:** 2\n",
            "- Features: tensor([[ 2.7000, -1.5000]])\n",
            "- Labels: tensor([1])\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Empirically, if the last batch in an epoch is substantially smaller than\n",
        "# earlier batches this disturbs training convergence. Create another\n",
        "# training dataloader that drops the last batch to prevent this.\n",
        "\n",
        "train_loader = DataLoader(\n",
        "    dataset=train_ds,\n",
        "    batch_size=2,\n",
        "    shuffle=True,\n",
        "    num_workers=0,\n",
        "    drop_last=True\n",
        ")"
      ],
      "metadata": {
        "id": "Cl2KYCd5lwBK"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "print(f\"## Train\")\n",
        "for idx, (x, y) in enumerate(train_loader):\n",
        "  print(f\"**Batch:** {idx}\")\n",
        "  print(f\"- Features: {x}\")\n",
        "  print(f\"- Labels: {y}\\n\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "OS6TA4BLmhiY",
        "outputId": "4056962e-e50f-4e8c-d5be-9f05bb0a1a2c"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "## Train\n",
            "**Batch:** 0\n",
            "- Features: tensor([[-0.9000,  2.9000],\n",
            "        [ 2.3000, -1.1000]])\n",
            "- Labels: tensor([0, 1])\n",
            "\n",
            "**Batch:** 1\n",
            "- Features: tensor([[ 2.7000, -1.5000],\n",
            "        [-0.5000,  2.6000]])\n",
            "- Labels: tensor([1, 0])\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Train a neural network on our training data set with stochastic gradient descent.\n",
        "\n",
        "torch.manual_seed(123)\n",
        "model = NeuralNetwork(num_inputs=2, num_outputs=2)\n",
        "optimizer = torch.optim.SGD(\n",
        "    model.parameters(), lr=0.5\n",
        ")\n",
        "\n",
        "num_epochs = 3\n",
        "for epoch in range(num_epochs):\n",
        "\n",
        "  print(f\"## Epoch {epoch}\")\n",
        "  model.train()\n",
        "  for batch, (features, labels) in enumerate(train_loader):\n",
        "\n",
        "    # The following will call model.forward() along with pre/post hooks and take\n",
        "    # care of some additional state management housekeeping.\n",
        "    # Calling model.forward() directly is usually a no-no.\n",
        "    logits = model(features)\n",
        "\n",
        "    loss = F.cross_entropy(logits, labels)\n",
        "\n",
        "    optimizer.zero_grad()\n",
        "    loss.backward()\n",
        "    optimizer.step()\n",
        "\n",
        "    print(f\"- Batch: {batch}, Loss: {loss:.2f}\")\n",
        "\n",
        "  print()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "8uSeV2sNoCu2",
        "outputId": "8c185eab-ee15-4069-8faa-7982bdd1c430"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "## Epoch 0\n",
            "- Batch: 0, Loss: 0.75\n",
            "- Batch: 1, Loss: 0.65\n",
            "\n",
            "## Epoch 1\n",
            "- Batch: 0, Loss: 0.44\n",
            "- Batch: 1, Loss: 0.13\n",
            "\n",
            "## Epoch 2\n",
            "- Batch: 0, Loss: 0.03\n",
            "- Batch: 1, Loss: 0.00\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# How many parameters does this neural network have?\n",
        "n = sum([p.numel() for p in model.parameters() if p.requires_grad==True])\n",
        "print(n)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "rVWKif7juO3S",
        "outputId": "14bc4f1f-c427-44ba-8284-f65f441789da"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "752\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Now make predictions, first putting the model into eval mode.\n",
        "model.eval()\n",
        "with torch.no_grad():\n",
        "  outputs = model(X_train)\n",
        "print(outputs)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "i4K4PimbckE3",
        "outputId": "a028ceff-6192-4584-b0ab-0418ddd9093b"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "tensor([[ 2.8569, -4.1618],\n",
            "        [ 2.5382, -3.7548],\n",
            "        [ 2.0944, -3.1820],\n",
            "        [-1.4814,  1.4816],\n",
            "        [-1.7176,  1.7342]])\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Use softmax to get class membership probabilities.\n",
        "torch.set_printoptions(sci_mode=False) # Don't print in scientific notation\n",
        "probas = torch.softmax(outputs, dim=1) # Rows sum to 1\n",
        "print(probas)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "XSkzty4Wc55F",
        "outputId": "f55c620b-e6a6-43c6-f4e9-0fe36e6239b0"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "tensor([[0.9991, 0.0009],\n",
            "        [0.9982, 0.0018],\n",
            "        [0.9949, 0.0051],\n",
            "        [0.0491, 0.9509],\n",
            "        [0.0307, 0.9693]])\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Convert to class labels by using argmax.\n",
        "predictions = torch.argmax(probas, dim=1) # Row-wise argmax\n",
        "print(predictions)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "HgI05WEldx2q",
        "outputId": "242bfc18-fd94-4166-8050-49de3443d605"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "tensor([0, 0, 0, 1, 1])\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Check for correctness\n",
        "predictions == y_train"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "dFAvWugBeDxv",
        "outputId": "e14c3f18-e496-40ea-95bd-8a934328e852"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "tensor([True, True, True, True, True])"
            ]
          },
          "metadata": {},
          "execution_count": 31
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Count correct predictions\n",
        "torch.sum(predictions == y_train)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "vO-kZUbPeJ5K",
        "outputId": "21481ddb-513b-43cb-d833-a3a7598417f8"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "tensor(5)"
            ]
          },
          "metadata": {},
          "execution_count": 32
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Create a general function for computing model accuracy.\n",
        "\n",
        "def compute_accuracy(model, dataloader):\n",
        "  total_samples = 0\n",
        "  total_correct = 0\n",
        "\n",
        "  for idx, (features, labels) in enumerate(dataloader):\n",
        "    with torch.no_grad():\n",
        "      logits = model(features)\n",
        "    probas = torch.softmax(logits, dim=1)\n",
        "    predictions = torch.argmax(probas, dim=1)\n",
        "    total_correct += torch.sum(predictions == labels).item()\n",
        "    total_samples += len(predictions)\n",
        "\n",
        "  result = total_correct / total_samples\n",
        "  return result\n",
        "\n",
        "acc = compute_accuracy(model, train_loader)\n",
        "print(f\"Accuracy on training data: {acc}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "WLXNO7BAoTBu",
        "outputId": "a0925b40-de1d-49ab-95a5-002eddebf1fa"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Accuracy on training data: 1.0\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Now evaluate our model against the test dataset.\n",
        "acc = compute_accuracy(model, test_loader)\n",
        "print(f\"Accuracy on test data: {acc}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "DMMRfM64r0d3",
        "outputId": "44459b95-f797-41fe-d4ad-e8f113993fe8"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Accuracy on test data: 1.0\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Save our model to disk.\n",
        "torch.save(model.state_dict(), \"model.pth\") # Extension is conventional."
      ],
      "metadata": {
        "id": "nAUkKOtcsJrC"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# To load a model we first create a model in code then load the state dict file.\n",
        "new_model = NeuralNetwork(num_inputs=2, num_outputs=2)\n",
        "state_dict = torch.load(\"model.pth\")\n",
        "new_model.load_state_dict(state_dict)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "LHAMjNGdsYzK",
        "outputId": "8fc6e1a9-9468-407c-d6c3-a8e686969935"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<All keys matched successfully>"
            ]
          },
          "metadata": {},
          "execution_count": 36
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Verify we have a GPU to work with.\n",
        "print(torch.cuda.is_available())"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "VuMWT_jvAiAu",
        "outputId": "6694c9a8-8c50-4eb0-edf9-ee83b79596e3"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "True\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Compare adding tensors on CPU vs GPU.\n",
        "tensor1 = torch.tensor([1., 2., 3.])\n",
        "tensor2 = torch.tensor([4., 5., 6.])\n",
        "print(\"CPU:\", tensor1 + tensor2)\n",
        "\n",
        "# Now on GPU.\n",
        "tensor1 = tensor1.to(\"cuda\")\n",
        "tensor2 = tensor1.to(\"cuda\")\n",
        "print(\"GPU:\", tensor1 + tensor2)\n",
        "\n",
        "# Can't mix CPU and GPU.\n",
        "tensor1 = tensor1.to(\"cpu\")\n",
        "try:\n",
        "  print(\"Mixed:\", tensor1 + tensor2)\n",
        "except Exception as e:\n",
        "  print(\"Exception:\", e)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "mUN0FnLQAvSZ",
        "outputId": "0e701671-b699-49d7-bf63-53642737df25"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "CPU: tensor([5., 7., 9.])\n",
            "GPU: tensor([2., 4., 6.], device='cuda:0')\n",
            "Exception: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Modify our training loop to use the CPU. Only three changes!\n",
        "\n",
        "torch.manual_seed(123)\n",
        "model = NeuralNetwork(num_inputs=2, num_outputs=2)\n",
        "optimizer = torch.optim.SGD(\n",
        "    model.parameters(), lr=0.5\n",
        ")\n",
        "\n",
        "# CHANGE 1: create a CUDA device if available, else fallback on the CPU.\n",
        "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
        "\n",
        "# CHANGE 2: move the model to the device.\n",
        "model.to(device)\n",
        "\n",
        "num_epochs = 3\n",
        "for epoch in range(num_epochs):\n",
        "\n",
        "  print(f\"## Epoch {epoch}\")\n",
        "  model.train()\n",
        "  for batch, (features, labels) in enumerate(train_loader):\n",
        "\n",
        "    # CHANGE 3: move data to the device.\n",
        "    features, labels = features.to(device), labels.to(device)\n",
        "\n",
        "    # The following will call model.forward() along with pre/post hooks and take\n",
        "    # care of some additional state management housekeeping.\n",
        "    # Calling model.forward() directly is usually a no-no.\n",
        "    logits = model(features)\n",
        "\n",
        "    loss = F.cross_entropy(logits, labels)\n",
        "\n",
        "    optimizer.zero_grad()\n",
        "    loss.backward()\n",
        "    optimizer.step()\n",
        "\n",
        "    print(f\"- Batch: {batch}, Loss: {loss:.2f}\")\n",
        "\n",
        "  print()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "38d2a879-3bc9-4919-82dc-e61b0fc8a8f2",
        "id": "yQAZfbdsCs_g"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "## Epoch 0\n",
            "- Batch: 0, Loss: 0.75\n",
            "- Batch: 1, Loss: 0.65\n",
            "\n",
            "## Epoch 1\n",
            "- Batch: 0, Loss: 0.44\n",
            "- Batch: 1, Loss: 0.13\n",
            "\n",
            "## Epoch 2\n",
            "- Batch: 0, Loss: 0.03\n",
            "- Batch: 1, Loss: 0.00\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Exercise A.4**\n",
        "\n",
        "Compare the run time of matrix multiplication on a CPU to a GPU. At what matrix size do you begin to see the matrix multiplication on the GPU being faster than on the CPU? Hint: use the %timeit command in Jupyter to compare the run time. For example, given matrices a and b, run the command %timeit a @ b in a new notebook cell."
      ],
      "metadata": {
        "id": "lMFJZHhsHKZs"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import time\n",
        "\n",
        "torch.manual_seed(123)\n",
        "\n",
        "print(f\"{'Dim':<10} | {'CPU (s)':<10} | {'GPU (s)':<10} | {'Delta (s)':<10}\")\n",
        "print(\"-\" * 50)\n",
        "\n",
        "for i in range(1, 21):\n",
        "    dim = i ** 2\n",
        "\n",
        "    # CPU matrix multiplication benchmarking\n",
        "    t1_cpu = torch.rand(dim, dim, device=\"cpu\")\n",
        "    t2_cpu = torch.rand(dim, dim, device=\"cpu\")\n",
        "\n",
        "    start_cpu = time.perf_counter()\n",
        "    res_cpu = torch.matmul(t1_cpu, t2_cpu)\n",
        "    end_cpu = time.perf_counter()\n",
        "    cpu_time = end_cpu - start_cpu\n",
        "\n",
        "    # GPU matrix multiplication benchmarking (with CUDA sync to ensure accurate timing)\n",
        "    if torch.cuda.is_available():\n",
        "        t1_gpu = torch.rand(dim, dim, device=\"cuda\")\n",
        "        t2_gpu = torch.rand(dim, dim, device=\"cuda\")\n",
        "\n",
        "        # Warmup\n",
        "        _ = torch.matmul(t1_gpu, t2_gpu)\n",
        "        torch.cuda.synchronize()\n",
        "\n",
        "        start_gpu = time.perf_counter()\n",
        "        res_gpu = torch.matmul(t1_gpu, t2_gpu)\n",
        "        torch.cuda.synchronize()\n",
        "        end_gpu = time.perf_counter()\n",
        "        gpu_time = end_gpu - start_gpu\n",
        "    else:\n",
        "        gpu_time = float(\"nan\")\n",
        "\n",
        "    delta = cpu_time - gpu_time\n",
        "\n",
        "    print(f\"{f'{dim}x{dim}':<10} | {cpu_time:<10.6f} | {gpu_time:<10.6f} | {delta:<10.6f}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "gVAFnWCUD4Hm",
        "outputId": "922e9d07-b27d-48a2-f572-43267459fe04"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Dim        | CPU (s)    | GPU (s)    | Delta (s) \n",
            "--------------------------------------------------\n",
            "1x1        | 0.000040   | 0.000050   | -0.000010 \n",
            "4x4        | 0.000023   | 0.000045   | -0.000022 \n",
            "9x9        | 0.000015   | 0.000038   | -0.000023 \n",
            "16x16      | 0.000014   | 0.000045   | -0.000032 \n",
            "25x25      | 0.000015   | 0.000043   | -0.000028 \n",
            "36x36      | 0.000015   | 0.000043   | -0.000028 \n",
            "49x49      | 0.000021   | 0.000044   | -0.000024 \n",
            "64x64      | 0.000074   | 0.000045   | 0.000029  \n",
            "81x81      | 0.000026   | 0.000044   | -0.000018 \n",
            "100x100    | 0.000029   | 0.000044   | -0.000016 \n",
            "121x121    | 0.000037   | 0.000046   | -0.000009 \n",
            "144x144    | 0.000040   | 0.000045   | -0.000006 \n",
            "169x169    | 0.000085   | 0.000047   | 0.000038  \n",
            "196x196    | 0.000121   | 0.000070   | 0.000050  \n",
            "225x225    | 0.000131   | 0.000049   | 0.000082  \n",
            "256x256    | 0.000139   | 0.000052   | 0.000086  \n",
            "289x289    | 0.000207   | 0.000047   | 0.000160  \n",
            "324x324    | 0.000224   | 0.000052   | 0.000172  \n",
            "361x361    | 0.000279   | 0.000052   | 0.000227  \n",
            "400x400    | 0.000315   | 0.000056   | 0.000259  \n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Across several trials I'm pretty consistently seeing on Colab with an A100 that the GPU pulls ahead reliably with a 169x169 matrix."
      ],
      "metadata": {
        "id": "lhpBZo0tHUSL"
      }
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "d8d1508e",
        "outputId": "bad2397f-df28-43e1-a28d-9bdacfdcf341"
      },
      "source": [
        "import torch\n",
        "\n",
        "# Get the number of available GPUs\n",
        "gpu_count = torch.cuda.device_count()\n",
        "print(f\"Number of GPUs available: {gpu_count}\")\n",
        "\n",
        "# Optional: Print the name of each GPU if available\n",
        "for i in range(gpu_count):\n",
        "    print(f\"GPU {i}: {torch.cuda.get_device_name(i)}\")"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Number of GPUs available: 1\n",
            "GPU 0: NVIDIA A100-SXM4-40GB\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "I only have one GPU available in my colab plan, and only one GPU in my physical puter, so this is as far as it goes for me."
      ],
      "metadata": {
        "id": "wpHvRxN9H3xC"
      }
    }
  ]
}