{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# GPUs\n",
    ":label:`sec_use_gpu`\n",
    "\n",
    "In :numref:`tab_intro_decade`, we discussed the rapid growth\n",
    "of computation over the past two decades.\n",
    "In a nutshell, GPU performance has increased\n",
    "by a factor of 1000 every decade since 2000.\n",
    "This offers great opportunities but it also suggests\n",
    "a significant need to provide such performance.\n",
    "\n",
    "\n",
    "In this section, we begin to discuss how to harness\n",
    "this computational performance for your research.\n",
    "First by using single GPUs and at a later point,\n",
    "how to use multiple GPUs and multiple servers (with multiple GPUs).\n",
    "\n",
    "Specifically, we will discuss how\n",
    "to use a single NVIDIA GPU for calculations.\n",
    "First, make sure you have at least one NVIDIA GPU installed.\n",
    "Then, download the [NVIDIA driver and CUDA](https://developer.nvidia.com/cuda-downloads)\n",
    "and follow the prompts to set the appropriate path.\n",
    "Once these preparations are complete,\n",
    "the `nvidia-smi` command can be used\n",
    "to (**view the graphics card information**).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "origin_pos": 1,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Thu Mar 24 10:54:49 2022       \r\n",
      "+-----------------------------------------------------------------------------+\r\n",
      "| NVIDIA-SMI 460.27.04    Driver Version: 460.27.04    CUDA Version: 11.2     |\r\n",
      "|-------------------------------+----------------------+----------------------+\r\n",
      "| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\r\n",
      "| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\r\n",
      "|                               |                      |               MIG M. |\r\n",
      "|===============================+======================+======================|\r\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "|   0  Tesla V100-SXM2...  Off  | 00000000:00:1B.0 Off |                    0 |\r\n",
      "| N/A   43C    P0    52W / 300W |   1722MiB / 16160MiB |     13%      Default |\r\n",
      "|                               |                      |                  N/A |\r\n",
      "+-------------------------------+----------------------+----------------------+\r\n",
      "|   1  Tesla V100-SXM2...  Off  | 00000000:00:1C.0 Off |                    0 |\r\n",
      "| N/A   38C    P0    54W / 300W |   1756MiB / 16160MiB |     17%      Default |\r\n",
      "|                               |                      |                  N/A |\r\n",
      "+-------------------------------+----------------------+----------------------+\r\n",
      "|   2  Tesla V100-SXM2...  Off  | 00000000:00:1D.0 Off |                    0 |\r\n",
      "| N/A   52C    P0    55W / 300W |      0MiB / 16160MiB |      0%      Default |\r\n",
      "|                               |                      |                  N/A |\r\n",
      "+-------------------------------+----------------------+----------------------+\r\n",
      "|   3  Tesla V100-SXM2...  Off  | 00000000:00:1E.0 Off |                    0 |\r\n",
      "| N/A   59C    P0    59W / 300W |      0MiB / 16160MiB |      4%      Default |\r\n",
      "|                               |                      |                  N/A |\r\n",
      "+-------------------------------+----------------------+----------------------+\r\n",
      "                                                                               \r\n",
      "+-----------------------------------------------------------------------------+\r\n",
      "| Processes:                                                                  |\r\n",
      "|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\r\n",
      "|        ID   ID                                                   Usage      |\r\n",
      "|=============================================================================|\r\n",
      "|    0   N/A  N/A      3952      C   ...l-en-release-0/bin/python     1719MiB |\r\n",
      "|    1   N/A  N/A      3952      C   ...l-en-release-0/bin/python     1753MiB |\r\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+-----------------------------------------------------------------------------+\r\n"
     ]
    }
   ],
   "source": [
    "!nvidia-smi"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 2,
    "tab": [
     "mxnet"
    ]
   },
   "source": [
    "You might have noticed that a MXNet tensor\n",
    "looks almost identical to a NumPy `ndarray`.\n",
    "But there are a few crucial differences.\n",
    "One of the key features that distinguishes MXNet\n",
    "from NumPy is its support for diverse hardware devices.\n",
    "\n",
    "In MXNet, every array has a context.\n",
    "So far, by default, all variables\n",
    "and associated computation\n",
    "have been assigned to the CPU.\n",
    "Typically, other contexts might be various GPUs.\n",
    "Things can get even hairier when\n",
    "we deploy jobs across multiple servers.\n",
    "By assigning arrays to contexts intelligently,\n",
    "we can minimize the time spent\n",
    "transferring data between devices.\n",
    "For example, when training neural networks on a server with a GPU,\n",
    "we typically prefer for the model's parameters to live on the GPU.\n",
    "\n",
    "Next, we need to confirm that\n",
    "the GPU version of MXNet is installed.\n",
    "If a CPU version of MXNet is already installed,\n",
    "we need to uninstall it first.\n",
    "For example, use the `pip uninstall mxnet` command,\n",
    "then install the corresponding MXNet version\n",
    "according to your CUDA version.\n",
    "Assuming you have CUDA 10.0 installed,\n",
    "you can install the MXNet version\n",
    "that supports CUDA 10.0 via `pip install mxnet-cu100`.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 4
   },
   "source": [
    "To run the programs in this section,\n",
    "you need at least two GPUs.\n",
    "Note that this might be extravagant for most desktop computers\n",
    "but it is easily available in the cloud, e.g.,\n",
    "by using the AWS EC2 multi-GPU instances.\n",
    "Almost all other sections do *not* require multiple GPUs.\n",
    "Instead, this is simply to illustrate\n",
    "how data flow between different devices.\n",
    "\n",
    "## [**Computing Devices**]\n",
    "\n",
    "We can specify devices, such as CPUs and GPUs,\n",
    "for storage and calculation.\n",
    "By default, tensors are created in the main memory\n",
    "and then use the CPU to calculate it.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 5,
    "tab": [
     "mxnet"
    ]
   },
   "source": [
    "In MXNet, the CPU and GPU can be indicated by `cpu()` and `gpu()`.\n",
    "It should be noted that `cpu()`\n",
    "(or any integer in the parentheses)\n",
    "means all physical CPUs and memory.\n",
    "This means that MXNet's calculations\n",
    "will try to use all CPU cores.\n",
    "However, `gpu()` only represents one card\n",
    "and the corresponding memory.\n",
    "If there are multiple GPUs, we use `gpu(i)`\n",
    "to represent the $i^\\mathrm{th}$ GPU ($i$ starts from 0).\n",
    "Also, `gpu(0)` and `gpu()` are equivalent.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "origin_pos": 7,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(cpu(0), gpu(0), gpu(1))"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from mxnet import np, npx\n",
    "from mxnet.gluon import nn\n",
    "\n",
    "npx.set_np()\n",
    "\n",
    "npx.cpu(), npx.gpu(), npx.gpu(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 10
   },
   "source": [
    "We can (**query the number of available GPUs.**)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "origin_pos": 11,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "npx.num_gpus()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 14
   },
   "source": [
    "Now we [**define two convenient functions that allow us\n",
    "to run code even if the requested GPUs do not exist.**]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "origin_pos": 15,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(gpu(0), cpu(0), [gpu(0), gpu(1)])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def try_gpu(i=0):  #@save\n",
    "    \"\"\"Return gpu(i) if exists, otherwise return cpu().\"\"\"\n",
    "    return npx.gpu(i) if npx.num_gpus() >= i + 1 else npx.cpu()\n",
    "\n",
    "def try_all_gpus():  #@save\n",
    "    \"\"\"Return all available GPUs, or [cpu()] if no GPU exists.\"\"\"\n",
    "    devices = [npx.gpu(i) for i in range(npx.num_gpus())]\n",
    "    return devices if devices else [npx.cpu()]\n",
    "\n",
    "try_gpu(), try_gpu(10), try_all_gpus()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 18
   },
   "source": [
    "## Tensors and GPUs\n",
    "\n",
    "By default, tensors are created on the CPU.\n",
    "We can [**query the device where the tensor is located.**]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "origin_pos": 19,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "cpu(0)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = np.array([1, 2, 3])\n",
    "x.ctx"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 22
   },
   "source": [
    "It is important to note that whenever we want\n",
    "to operate on multiple terms,\n",
    "they need to be on the same device.\n",
    "For instance, if we sum two tensors,\n",
    "we need to make sure that both arguments\n",
    "live on the same device---otherwise the framework\n",
    "would not know where to store the result\n",
    "or even how to decide where to perform the computation.\n",
    "\n",
    "### Storage on the GPU\n",
    "\n",
    "There are several ways to [**store a tensor on the GPU.**]\n",
    "For example, we can specify a storage device when creating a tensor.\n",
    "Next, we create the tensor variable `X` on the first `gpu`.\n",
    "The tensor created on a GPU only consumes the memory of this GPU.\n",
    "We can use the `nvidia-smi` command to view GPU memory usage.\n",
    "In general, we need to make sure that we do not create data that exceed the GPU memory limit.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "origin_pos": 23,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1., 1., 1.],\n",
       "       [1., 1., 1.]], ctx=gpu(0))"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = np.ones((2, 3), ctx=try_gpu())\n",
    "X"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 26
   },
   "source": [
    "Assuming that you have at least two GPUs, the following code will (**create a random tensor on the second GPU.**)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "origin_pos": 27,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.67478997, 0.07540122, 0.9956977 ],\n",
       "       [0.09488854, 0.415456  , 0.11231736]], ctx=gpu(1))"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Y = np.random.uniform(size=(2, 3), ctx=try_gpu(1))\n",
    "Y"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 30
   },
   "source": [
    "### Copying\n",
    "\n",
    "[**If we want to compute `X + Y`,\n",
    "we need to decide where to perform this operation.**]\n",
    "For instance, as shown in :numref:`fig_copyto`,\n",
    "we can transfer `X` to the second GPU\n",
    "and perform the operation there.\n",
    "*Do not* simply add `X` and `Y`,\n",
    "since this will result in an exception.\n",
    "The runtime engine would not know what to do:\n",
    "it cannot find data on the same device and it fails.\n",
    "Since `Y` lives on the second GPU,\n",
    "we need to move `X` there before we can add the two.\n",
    "\n",
    "![Copy data to perform an operation on the same device.](../img/copyto.svg)\n",
    ":label:`fig_copyto`\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "origin_pos": 31,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1. 1. 1.]\n",
      " [1. 1. 1.]] @gpu(0)\n",
      "[[1. 1. 1.]\n",
      " [1. 1. 1.]] @gpu(1)\n"
     ]
    }
   ],
   "source": [
    "Z = X.copyto(try_gpu(1))\n",
    "print(X)\n",
    "print(Z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 34
   },
   "source": [
    "Now that [**the data are on the same GPU\n",
    "(both `Z` and `Y` are),\n",
    "we can add them up.**]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "origin_pos": 35,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1.6747899, 1.0754012, 1.9956977],\n",
       "       [1.0948886, 1.415456 , 1.1123173]], ctx=gpu(1))"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Y + Z"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 36,
    "tab": [
     "mxnet"
    ]
   },
   "source": [
    "Imagine that your variable `Z` already lives on your second GPU.\n",
    "What happens if we still call  `Z.copyto(gpu(1))`?\n",
    "It will make a copy and allocate new memory,\n",
    "even though that variable already lives on the desired device.\n",
    "There are times where, depending on the environment our code is running in,\n",
    "two variables may already live on the same device.\n",
    "So we want to make a copy only if the variables\n",
    "currently live in different devices.\n",
    "In these cases, we can call `as_in_ctx`.\n",
    "If the variable already live in the specified device\n",
    "then this is a no-op.\n",
    "Unless you specifically want to make a copy,\n",
    "`as_in_ctx` is the method of choice.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "origin_pos": 39,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Z.as_in_ctx(try_gpu(1)) is Z"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 42
   },
   "source": [
    "### Side Notes\n",
    "\n",
    "People use GPUs to do machine learning\n",
    "because they expect them to be fast.\n",
    "But transferring variables between devices is slow.\n",
    "So we want you to be 100% certain\n",
    "that you want to do something slow before we let you do it.\n",
    "If the deep learning framework just did the copy automatically\n",
    "without crashing then you might not realize\n",
    "that you had written some slow code.\n",
    "\n",
    "Also, transferring data between devices (CPU, GPUs, and other machines)\n",
    "is something that is much slower than computation.\n",
    "It also makes parallelization a lot more difficult,\n",
    "since we have to wait for data to be sent (or rather to be received)\n",
    "before we can proceed with more operations.\n",
    "This is why copy operations should be taken with great care.\n",
    "As a rule of thumb, many small operations\n",
    "are much worse than one big operation.\n",
    "Moreover, several operations at a time\n",
    "are much better than many single operations interspersed in the code\n",
    "unless you know what you are doing.\n",
    "This is the case since such operations can block if one device\n",
    "has to wait for the other before it can do something else.\n",
    "It is a bit like ordering your coffee in a queue\n",
    "rather than pre-ordering it by phone\n",
    "and finding out that it is ready when you are.\n",
    "\n",
    "Last, when we print tensors or convert tensors to the NumPy format,\n",
    "if the data is not in the main memory,\n",
    "the framework will copy it to the main memory first,\n",
    "resulting in additional transmission overhead.\n",
    "Even worse, it is now subject to the dreaded global interpreter lock\n",
    "that makes everything wait for Python to complete.\n",
    "\n",
    "\n",
    "## [**Neural Networks and GPUs**]\n",
    "\n",
    "Similarly, a neural network model can specify devices.\n",
    "The following code puts the model parameters on the GPU.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "origin_pos": 43,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "net = nn.Sequential()\n",
    "net.add(nn.Dense(1))\n",
    "net.initialize(ctx=try_gpu())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 46
   },
   "source": [
    "We will see many more examples of\n",
    "how to run models on GPUs in the following chapters,\n",
    "simply since they will become somewhat more computationally intensive.\n",
    "\n",
    "When the input is a tensor on the GPU, the model will calculate the result on the same GPU.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "origin_pos": 47,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.04995865],\n",
       "       [0.04995865]], ctx=gpu(0))"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net(X)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 48
   },
   "source": [
    "Let us (**confirm that the model parameters are stored on the same GPU.**)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "origin_pos": 49,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "gpu(0)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net[0].weight.data().ctx"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 52
   },
   "source": [
    "In short, as long as all data and parameters are on the same device, we can learn models efficiently. In the following chapters we will see several such examples.\n",
    "\n",
    "## Summary\n",
    "\n",
    "* We can specify devices for storage and calculation, such as the CPU or GPU.\n",
    "  By default, data are created in the main memory\n",
    "  and then use the CPU for calculations.\n",
    "* The deep learning framework requires all input data for calculation\n",
    "  to be on the same device,\n",
    "  be it CPU or the same GPU.\n",
    "* You can lose significant performance by moving data without care.\n",
    "  A typical mistake is as follows: computing the loss\n",
    "  for every minibatch on the GPU and reporting it back\n",
    "  to the user on the command line (or logging it in a NumPy `ndarray`)\n",
    "  will trigger a global interpreter lock which stalls all GPUs.\n",
    "  It is much better to allocate memory\n",
    "  for logging inside the GPU and only move larger logs.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Try a larger computation task, such as the multiplication of large matrices,\n",
    "   and see the difference in speed between the CPU and GPU.\n",
    "   What about a task with a small amount of calculations?\n",
    "1. How should we read and write model parameters on the GPU?\n",
    "1. Measure the time it takes to compute 1000\n",
    "   matrix-matrix multiplications of $100 \\times 100$ matrices\n",
    "   and log the Frobenius norm of the output matrix one result at a time\n",
    "   vs. keeping a log on the GPU and transferring only the final result.\n",
    "1. Measure how much time it takes to perform two matrix-matrix multiplications\n",
    "   on two GPUs at the same time vs. in sequence\n",
    "   on one GPU. Hint: you should see almost linear scaling.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 53,
    "tab": [
     "mxnet"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/62)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}