{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# For tips on running notebooks in Google Colab, see\n",
    "# https://docs.pytorch.org/tutorials/beginner/colab\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Training a Classifier\n",
    "\n",
    "This is it. You have seen how to define neural networks, compute loss\n",
    "and make updates to the weights of the network.\n",
    "\n",
    "Now you might be thinking,\n",
    "\n",
    "## What about data?\n",
    "\n",
    "Generally, when you have to deal with image, text, audio or video data,\n",
    "you can use standard python packages that load data into a numpy array.\n",
    "Then you can convert this array into a `torch.*Tensor`.\n",
    "\n",
    "-   For images, packages such as Pillow, OpenCV are useful\n",
    "-   For audio, packages such as scipy and librosa\n",
    "-   For text, either raw Python or Cython based loading, or NLTK and\n",
    "    SpaCy are useful\n",
    "\n",
    "Specifically for vision, we have created a package called `torchvision`,\n",
    "that has data loaders for common datasets such as ImageNet, CIFAR10,\n",
    "MNIST, etc. and data transformers for images, viz.,\n",
    "`torchvision.datasets` and `torch.utils.data.DataLoader`.\n",
    "\n",
    "This provides a huge convenience and avoids writing boilerplate code.\n",
    "\n",
    "For this tutorial, we will use the CIFAR10 dataset. It has the classes:\n",
    "'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse',\n",
    "'ship', 'truck'. The images in CIFAR-10 are of size 3x32x32, i.e.\n",
    "3-channel color images of 32x32 pixels in size.\n",
    "\n",
    "<figure>\n",
    "<img src=\"https://pytorch.org/tutorials/_static/img/cifar10.png\"\n",
    "alt=\"/_static/img/cifar10.png\" />\n",
    "<figcaption>cifar10</figcaption>\n",
    "</figure>\n",
    "\n",
    "## Training an image classifier\n",
    "\n",
    "We will do the following steps in order:\n",
    "\n",
    "1.  Load and normalize the CIFAR10 training and test datasets using\n",
    "    `torchvision`\n",
    "2.  Define a Convolutional Neural Network\n",
    "3.  Define a loss function\n",
    "4.  Train the network on the training data\n",
    "5.  Test the network on the test data\n",
    "\n",
    "### 1. Load and normalize CIFAR10\n",
    "\n",
    "Using `torchvision`, it's extremely easy to load CIFAR10.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torchvision\n",
    "from torchvision.transforms import v2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The output of torchvision datasets are PILImage images of range \\[0,\n",
    "1\\]. We transform them to Tensors of normalized range \\[-1, 1\\].\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"background-color: #54c7ec; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>NOTE:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<p>If you are running this tutorial on Windows or MacOS and encounter aBrokenPipeError or RuntimeError related to multiprocessing, try settingthe num_worker of torch.utils.data.DataLoader() to 0.</p>\n",
    "\n",
    "</div>\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "transform = v2.Compose([\n",
    "    v2.ToImage(),\n",
    "    v2.ToDtype(torch.float32, scale=True),\n",
    "    v2.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n",
    "\n",
    "batch_size = 4\n",
    "\n",
    "trainset = torchvision.datasets.CIFAR10(root='./data', train=True,\n",
    "                                        download=True, transform=transform)\n",
    "trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,\n",
    "                                          shuffle=True, num_workers=2)\n",
    "\n",
    "testset = torchvision.datasets.CIFAR10(root='./data', train=False,\n",
    "                                       download=True, transform=transform)\n",
    "testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,\n",
    "                                         shuffle=False, num_workers=2)\n",
    "\n",
    "classes = ('plane', 'car', 'bird', 'cat',\n",
    "           'deer', 'dog', 'frog', 'horse', 'ship', 'truck')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let us show some of the training images, for fun.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "# functions to show an image\n",
    "\n",
    "\n",
    "def imshow(img):\n",
    "    img = img / 2 + 0.5     # unnormalize\n",
    "    npimg = img.numpy()\n",
    "    plt.imshow(np.transpose(npimg, (1, 2, 0)))\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "# get some random training images\n",
    "dataiter = iter(trainloader)\n",
    "images, labels = next(dataiter)\n",
    "\n",
    "# show images\n",
    "imshow(torchvision.utils.make_grid(images))\n",
    "# print labels\n",
    "print(' '.join(f'{classes[labels[j]]:5s}' for j in range(batch_size)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 2. Define a Convolutional Neural Network\n",
    "\n",
    "Copy the neural network from the Neural Networks section before and\n",
    "modify it to take 3-channel images (instead of 1-channel images as it\n",
    "was defined).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "\n",
    "\n",
    "class Net(nn.Module):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "        self.conv1 = nn.Conv2d(3, 6, 5)\n",
    "        self.pool = nn.MaxPool2d(2, 2)\n",
    "        self.conv2 = nn.Conv2d(6, 16, 5)\n",
    "        self.fc1 = nn.Linear(16 * 5 * 5, 120)\n",
    "        self.fc2 = nn.Linear(120, 84)\n",
    "        self.fc3 = nn.Linear(84, 10)\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = self.pool(F.relu(self.conv1(x)))\n",
    "        x = self.pool(F.relu(self.conv2(x)))\n",
    "        x = torch.flatten(x, 1) # flatten all dimensions except batch\n",
    "        x = F.relu(self.fc1(x))\n",
    "        x = F.relu(self.fc2(x))\n",
    "        x = self.fc3(x)\n",
    "        return x\n",
    "\n",
    "\n",
    "net = Net()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3. Define a Loss function and optimizer\n",
    "\n",
    "Let\\'s use a Classification Cross-Entropy loss and SGD with momentum.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch.optim as optim\n",
    "\n",
    "criterion = nn.CrossEntropyLoss()\n",
    "optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 4. Train the network\n",
    "\n",
    "This is when things start to get interesting. We simply have to loop\n",
    "over our data iterator, and feed the inputs to the network and optimize.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "for epoch in range(2):  # loop over the dataset multiple times\n",
    "\n",
    "    running_loss = 0.0\n",
    "    for i, data in enumerate(trainloader, 0):\n",
    "        # get the inputs; data is a list of [inputs, labels]\n",
    "        inputs, labels = data\n",
    "\n",
    "        # zero the parameter gradients\n",
    "        optimizer.zero_grad()\n",
    "\n",
    "        # forward + backward + optimize\n",
    "        outputs = net(inputs)\n",
    "        loss = criterion(outputs, labels)\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "\n",
    "        # print statistics\n",
    "        running_loss += loss.item()\n",
    "        if i % 2000 == 1999:    # print every 2000 mini-batches\n",
    "            print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}')\n",
    "            running_loss = 0.0\n",
    "\n",
    "print('Finished Training')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let\\'s quickly save our trained model:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "PATH = './cifar_net.pt'\n",
    "torch.save(net.state_dict(), PATH)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "See [here](https://pytorch.org/docs/stable/notes/serialization.html) for\n",
    "more details on saving PyTorch models.\n",
    "\n",
    "# 5. Test the network on the test data\n",
    "\n",
    "We have trained the network for 2 passes over the training dataset. But\n",
    "we need to check if the network has learnt anything at all.\n",
    "\n",
    "We will check this by predicting the class label that the neural network\n",
    "outputs, and checking it against the ground-truth. If the prediction is\n",
    "correct, we add the sample to the list of correct predictions.\n",
    "\n",
    "Okay, first step. Let us display an image from the test set to get\n",
    "familiar.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "dataiter = iter(testloader)\n",
    "images, labels = next(dataiter)\n",
    "\n",
    "# print images\n",
    "imshow(torchvision.utils.make_grid(images))\n",
    "print('GroundTruth: ', ' '.join(f'{classes[labels[j]]:5s}' for j in range(4)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, let\\'s load back in our saved model (note: saving and re-loading\n",
    "the model wasn\\'t necessary here, we only did it to illustrate how to do\n",
    "so):\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "net = Net()\n",
    "net.load_state_dict(torch.load(PATH, weights_only=True))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Okay, now let us see what the neural network thinks these examples above\n",
    "are:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "outputs = net(images)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The outputs are energies for the 10 classes. The higher the energy for a\n",
    "class, the more the network thinks that the image is of the particular\n",
    "class. So, let\\'s get the index of the highest energy:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "_, predicted = torch.max(outputs, 1)\n",
    "\n",
    "print('Predicted: ', ' '.join(f'{classes[predicted[j]]:5s}'\n",
    "                              for j in range(4)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The results seem pretty good.\n",
    "\n",
    "Let us look at how the network performs on the whole dataset.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "correct = 0\n",
    "total = 0\n",
    "# since we're not training, we don't need to calculate the gradients for our outputs\n",
    "with torch.no_grad():\n",
    "    for data in testloader:\n",
    "        images, labels = data\n",
    "        # calculate outputs by running images through the network\n",
    "        outputs = net(images)\n",
    "        # the class with the highest energy is what we choose as prediction\n",
    "        _, predicted = torch.max(outputs, 1)\n",
    "        total += labels.size(0)\n",
    "        correct += (predicted == labels).sum().item()\n",
    "\n",
    "print(f'Accuracy of the network on the 10000 test images: {100 * correct // total} %')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That looks way better than chance, which is 10% accuracy (randomly\n",
    "picking a class out of 10 classes). Seems like the network learnt\n",
    "something.\n",
    "\n",
    "Hmmm, what are the classes that performed well, and the classes that did\n",
    "not perform well:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# prepare to count predictions for each class\n",
    "correct_pred = {classname: 0 for classname in classes}\n",
    "total_pred = {classname: 0 for classname in classes}\n",
    "\n",
    "# again no gradients needed\n",
    "with torch.no_grad():\n",
    "    for data in testloader:\n",
    "        images, labels = data\n",
    "        outputs = net(images)\n",
    "        _, predictions = torch.max(outputs, 1)\n",
    "        # collect the correct predictions for each class\n",
    "        for label, prediction in zip(labels, predictions):\n",
    "            if label == prediction:\n",
    "                correct_pred[classes[label]] += 1\n",
    "            total_pred[classes[label]] += 1\n",
    "\n",
    "\n",
    "# print accuracy for each class\n",
    "for classname, correct_count in correct_pred.items():\n",
    "    accuracy = 100 * float(correct_count) / total_pred[classname]\n",
    "    print(f'Accuracy for class: {classname:5s} is {accuracy:.1f} %')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Okay, so what next?\n",
    "\n",
    "How do we run these neural networks on the GPU?\n",
    "\n",
    "# Training on GPU\n",
    "\n",
    "Just like how you transfer a Tensor onto the GPU, you transfer the\n",
    "neural net onto the GPU.\n",
    "\n",
    "Let\\'s first define our device as the first visible cuda device if we\n",
    "have CUDA available:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "device = torch.device(torch.accelerator.current_accelerator().type if torch.accelerator.is_available() else 'cpu')\n",
    "\n",
    "# Assuming that we are on a CUDA machine, this should print a CUDA device:\n",
    "\n",
    "print(device)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The rest of this section assumes that `device` is a CUDA device.\n",
    "\n",
    "Then these methods will recursively go over all modules and convert\n",
    "their parameters and buffers to CUDA tensors:\n",
    "\n",
    "``` python\n",
    "net.to(device)\n",
    "```\n",
    "\n",
    "Remember that you will have to send the inputs and targets at every step\n",
    "to the GPU too:\n",
    "\n",
    "``` python\n",
    "inputs, labels = data[0].to(device), data[1].to(device)\n",
    "```\n",
    "\n",
    "Why don\\'t I notice MASSIVE speedup compared to CPU? Because your\n",
    "network is really small.\n",
    "\n",
    "**Exercise:** Try increasing the width of your network (argument 2 of\n",
    "the first `nn.Conv2d`, and argument 1 of the second `nn.Conv2d` -- they\n",
    "need to be the same number), see what kind of speedup you get.\n",
    "\n",
    "**Goals achieved**:\n",
    "\n",
    "-   Understanding PyTorch\\'s Tensor library and neural networks at a\n",
    "    high level.\n",
    "-   Train a small neural network to classify images\n",
    "\n",
    "# Training on multiple GPUs\n",
    "\n",
    "If you want to see even more MASSIVE speedup using all of your GPUs,\n",
    "please check out `data_parallel_tutorial`{.interpreted-text role=\"doc\"}.\n",
    "\n",
    "# Where do I go next?\n",
    "\n",
    "-   `Train neural nets to play video games </intermediate/reinforcement_q_learning>`{.interpreted-text\n",
    "    role=\"doc\"}\n",
    "-   [Train a state-of-the-art ResNet network on\n",
    "    imagenet](https://github.com/pytorch/examples/tree/main/imagenet)\n",
    "-   [Train a face generator using Generative Adversarial\n",
    "    Networks](https://github.com/pytorch/examples/tree/main/dcgan)\n",
    "-   [Train a word-level language model using Recurrent LSTM\n",
    "    networks](https://github.com/pytorch/examples/tree/main/word_language_model)\n",
    "-   [More examples](https://github.com/pytorch/examples)\n",
    "-   [More tutorials](https://github.com/pytorch/tutorials)\n",
    "-   [Discuss PyTorch on the Forums](https://discuss.pytorch.org/)\n",
    "-   [Chat with other users on\n",
    "    Slack](https://pytorch.slack.com/messages/beginner/)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "del dataiter"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
