GPUs

:label:sec_use_gpu

In :numref:tab_intro_decade, we discussed the rapid growth of computation over the past two decades. In a nutshell, GPU performance has increased by a factor of 1000 every decade since 2000. This offers great opportunities but it also suggests a significant need to provide such performance.

In this section, we begin to discuss how to harness this computational performance for your research. First by using single GPUs and at a later point, how to use multiple GPUs and multiple servers (with multiple GPUs).

Specifically, we will discuss how to use a single NVIDIA GPU for calculations. First, make sure you have at least one NVIDIA GPU installed. Then, download the NVIDIA driver and CUDA and follow the prompts to set the appropriate path. Once these preparations are complete, the nvidia-smi command can be used to view the graphics card information.

```{.python .input}

@tab all

!nvidia-smi

  1. :begin_tab:`mxnet`
  2. You might have noticed that a MXNet tensor
  3. looks almost identical to a NumPy `ndarray`.
  4. But there are a few crucial differences.
  5. One of the key features that distinguishes MXNet
  6. from NumPy is its support for diverse hardware devices.
  7. In MXNet, every array has a context.
  8. So far, by default, all variables
  9. and associated computation
  10. have been assigned to the CPU.
  11. Typically, other contexts might be various GPUs.
  12. Things can get even hairier when
  13. we deploy jobs across multiple servers.
  14. By assigning arrays to contexts intelligently,
  15. we can minimize the time spent
  16. transferring data between devices.
  17. For example, when training neural networks on a server with a GPU,
  18. we typically prefer for the model's parameters to live on the GPU.
  19. Next, we need to confirm that
  20. the GPU version of MXNet is installed.
  21. If a CPU version of MXNet is already installed,
  22. we need to uninstall it first.
  23. For example, use the `pip uninstall mxnet` command,
  24. then install the corresponding MXNet version
  25. according to your CUDA version.
  26. Assuming you have CUDA 10.0 installed,
  27. you can install the MXNet version
  28. that supports CUDA 10.0 via `pip install mxnet-cu100`.
  29. :end_tab:
  30. :begin_tab:`pytorch`
  31. In PyTorch, every array has a device, we often refer it as a context.
  32. So far, by default, all variables
  33. and associated computation
  34. have been assigned to the CPU.
  35. Typically, other contexts might be various GPUs.
  36. Things can get even hairier when
  37. we deploy jobs across multiple servers.
  38. By assigning arrays to contexts intelligently,
  39. we can minimize the time spent
  40. transferring data between devices.
  41. For example, when training neural networks on a server with a GPU,
  42. we typically prefer for the model's parameters to live on the GPU.
  43. Next, we need to confirm that
  44. the GPU version of PyTorch is installed.
  45. If a CPU version of PyTorch is already installed,
  46. we need to uninstall it first.
  47. For example, use the `pip uninstall torch` command,
  48. then install the corresponding PyTorch version
  49. according to your CUDA version.
  50. Assuming you have CUDA 10.0 installed,
  51. you can install the PyTorch version
  52. that supports CUDA 10.0 via `pip install torch-cu100`.
  53. :end_tab:
  54. To run the programs in this section,
  55. you need at least two GPUs.
  56. Note that this might be extravagant for most desktop computers
  57. but it is easily available in the cloud, e.g.,
  58. by using the AWS EC2 multi-GPU instances.
  59. Almost all other sections do *not* require multiple GPUs.
  60. Instead, this is simply to illustrate
  61. how data flow between different devices.
  62. ## Computing Devices
  63. We can specify devices, such as CPUs and GPUs,
  64. for storage and calculation.
  65. By default, tensors are created in the main memory
  66. and then use the CPU to calculate it.
  67. :begin_tab:`mxnet`
  68. In MXNet, the CPU and GPU can be indicated by `cpu()` and `gpu()`.
  69. It should be noted that `cpu()`
  70. (or any integer in the parentheses)
  71. means all physical CPUs and memory.
  72. This means that MXNet's calculations
  73. will try to use all CPU cores.
  74. However, `gpu()` only represents one card
  75. and the corresponding memory.
  76. If there are multiple GPUs, we use `gpu(i)`
  77. to represent the $i^\mathrm{th}$ GPU ($i$ starts from 0).
  78. Also, `gpu(0)` and `gpu()` are equivalent.
  79. :end_tab:
  80. :begin_tab:`pytorch`
  81. In PyTorch, the CPU and GPU can be indicated by `torch.device('cpu')` and `torch.cuda.device('cuda')`.
  82. It should be noted that the `cpu` device
  83. means all physical CPUs and memory.
  84. This means that PyTorch's calculations
  85. will try to use all CPU cores.
  86. However, a `gpu` device only represents one card
  87. and the corresponding memory.
  88. If there are multiple GPUs, we use `torch.cuda.device(f'cuda{i}')`
  89. to represent the $i^\mathrm{th}$ GPU ($i$ starts from 0).
  90. Also, `gpu:0` and `gpu` are equivalent.
  91. :end_tab:
  92. ```{.python .input}
  93. from mxnet import np, npx
  94. from mxnet.gluon import nn
  95. npx.set_np()
  96. npx.cpu(), npx.gpu(), npx.gpu(1)

```{.python .input}

@tab pytorch

import torch from torch import nn

torch.device(‘cpu’), torch.cuda.device(‘cuda’), torch.cuda.device(‘cuda:1’)

  1. ```{.python .input}
  2. #@tab tensorflow
  3. import tensorflow as tf
  4. tf.device('/CPU:0'), tf.device('/GPU:0'), tf.device('/GPU:1')

We can query the number of available GPUs.

```{.python .input} npx.num_gpus()

  1. ```{.python .input}
  2. #@tab pytorch
  3. torch.cuda.device_count()

```{.python .input}

@tab tensorflow

len(tf.config.experimental.list_physical_devices(‘GPU’))

  1. Now we define two convenient functions that allow us
  2. to run code even if the requested GPUs do not exist.
  3. ```{.python .input}
  4. def try_gpu(i=0): #@save
  5. """Return gpu(i) if exists, otherwise return cpu()."""
  6. return npx.gpu(i) if npx.num_gpus() >= i + 1 else npx.cpu()
  7. def try_all_gpus(): #@save
  8. """Return all available GPUs, or [cpu()] if no GPU exists."""
  9. devices = [npx.gpu(i) for i in range(npx.num_gpus())]
  10. return devices if devices else [npx.cpu()]
  11. try_gpu(), try_gpu(10), try_all_gpus()

```{.python .input}

@tab pytorch

def try_gpu(i=0): #@save “””Return gpu(i) if exists, otherwise return cpu().””” if torch.cuda.device_count() >= i + 1: return torch.device(f’cuda:{i}’) return torch.device(‘cpu’)

def try_all_gpus(): #@save “””Return all available GPUs, or [cpu(),] if no GPU exists.””” devices = [torch.device(f’cuda:{i}’) for i in range(torch.cuda.device_count())] return devices if devices else [torch.device(‘cpu’)]

try_gpu(), try_gpu(10), try_all_gpus()

  1. ```{.python .input}
  2. #@tab tensorflow
  3. def try_gpu(i=0): #@save
  4. """Return gpu(i) if exists, otherwise return cpu()."""
  5. if len(tf.config.experimental.list_physical_devices('GPU')) >= i + 1:
  6. return tf.device(f'/GPU:{i}')
  7. return tf.device('/CPU:0')
  8. def try_all_gpus(): #@save
  9. """Return all available GPUs, or [cpu(),] if no GPU exists."""
  10. num_gpus = len(tf.config.experimental.list_physical_devices('GPU'))
  11. devices = [tf.device(f'/GPU:{i}') for i in range(num_gpus)]
  12. return devices if devices else [tf.device('/CPU:0')]
  13. try_gpu(), try_gpu(10), try_all_gpus()

Tensors and GPUs

By default, tensors are created on the CPU. We can query the device where the tensor is located.

```{.python .input} x = np.array([1, 2, 3]) x.ctx

  1. ```{.python .input}
  2. #@tab pytorch
  3. x = torch.tensor([1, 2, 3])
  4. x.device

```{.python .input}

@tab tensorflow

x = tf.constant([1, 2, 3]) x.device

  1. It is important to note that whenever we want
  2. to operate on multiple terms,
  3. they need to be on the same device.
  4. For instance, if we sum two tensors,
  5. we need to make sure that both arguments
  6. live on the same device---otherwise the framework
  7. would not know where to store the result
  8. or even how to decide where to perform the computation.
  9. ### Storage on the GPU
  10. There are several ways to store a tensor on the GPU.
  11. For example, we can specify a storage device when creating a tensor.
  12. Next, we create the tensor variable `X` on the first `gpu`.
  13. The tensor created on a GPU only consumes the memory of this GPU.
  14. We can use the `nvidia-smi` command to view GPU memory usage.
  15. In general, we need to make sure that we do not create data that exceed the GPU memory limit.
  16. ```{.python .input}
  17. X = np.ones((2, 3), ctx=try_gpu())
  18. X

```{.python .input}

@tab pytorch

X = torch.ones(2, 3, device=try_gpu()) X

  1. ```{.python .input}
  2. #@tab tensorflow
  3. with try_gpu():
  4. X = tf.ones((2, 3))
  5. X

Assuming that you have at least two GPUs, the following code will create a random tensor on the second GPU.

```{.python .input} Y = np.random.uniform(size=(2, 3), ctx=try_gpu(1)) Y

  1. ```{.python .input}
  2. #@tab pytorch
  3. Y = torch.randn(2, 3, device=try_gpu(1))
  4. Y

```{.python .input}

@tab tensorflow

with try_gpu(1): Y = tf.random.uniform((2, 3)) Y

  1. ### Copying
  2. If we want to compute `X + Y`,
  3. we need to decide where to perform this operation.
  4. For instance, as shown in :numref:`fig_copyto`,
  5. we can transfer `X` to the second GPU
  6. and perform the operation there.
  7. *Do not* simply add `X` and `Y`,
  8. since this will result in an exception.
  9. The runtime engine would not know what to do:
  10. it cannot find data on the same device and it fails.
  11. Since `Y` lives on the second GPU,
  12. we need to move `X` there before we can add the two.
  13. ![Copy data to perform an operation on the same device.](/uploads/projects/d2l-ai-CN/img/copyto.svg)
  14. :label:`fig_copyto`
  15. ```{.python .input}
  16. Z = X.copyto(try_gpu(1))
  17. print(X)
  18. print(Z)

```{.python .input}

@tab pytorch

Z = X.cuda(1) print(X) print(Z)

  1. ```{.python .input}
  2. #@tab tensorflow
  3. with try_gpu(1):
  4. Z = X
  5. print(X)
  6. print(Z)

Now that the data are on the same GPU (both Z and Y are), we can add them up.

```{.python .input}

@tab all

Y + Z

  1. :begin_tab:`mxnet`
  2. Imagine that your variable `Z` already lives on your second GPU.
  3. What happens if we still call `Z.copyto(gpu(1))`?
  4. It will make a copy and allocate new memory,
  5. even though that variable already lives on the desired device.
  6. There are times where, depending on the environment our code is running in,
  7. two variables may already live on the same device.
  8. So we want to make a copy only if the variables
  9. currently live in different devices.
  10. In these cases, we can call `as_in_ctx`.
  11. If the variable already live in the specified device
  12. then this is a no-op.
  13. Unless you specifically want to make a copy,
  14. `as_in_ctx` is the method of choice.
  15. :end_tab:
  16. :begin_tab:`pytorch`
  17. Imagine that your variable `Z` already lives on your second GPU.
  18. What happens if we still call `Z.cuda(1)`?
  19. It will return `Z` instead of making a copy and allocating new memory.
  20. :end_tab:
  21. :begin_tab:`tensorflow`
  22. Imagine that your variable `Z` already lives on your second GPU.
  23. What happens if we still call `Z2 = Z` under the same device scope?
  24. It will return `Z` instead of making a copy and allocating new memory.
  25. :end_tab:
  26. ```{.python .input}
  27. Z.as_in_ctx(try_gpu(1)) is Z

```{.python .input}

@tab pytorch

Z.cuda(1) is Z

  1. ```{.python .input}
  2. #@tab tensorflow
  3. with try_gpu(1):
  4. Z2 = Z
  5. Z2 is Z

Side Notes

People use GPUs to do machine learning because they expect them to be fast. But transferring variables between devices is slow. So we want you to be 100% certain that you want to do something slow before we let you do it. If the deep learning framework just did the copy automatically without crashing then you might not realize that you had written some slow code.

Also, transferring data between devices (CPU, GPUs, and other machines) is something that is much slower than computation. It also makes parallelization a lot more difficult, since we have to wait for data to be sent (or rather to be received) before we can proceed with more operations. This is why copy operations should be taken with great care. As a rule of thumb, many small operations are much worse than one big operation. Moreover, several operations at a time are much better than many single operations interspersed in the code unless you know what you are doing. This is the case since such operations can block if one device has to wait for the other before it can do something else. It is a bit like ordering your coffee in a queue rather than pre-ordering it by phone and finding out that it is ready when you are.

Last, when we print tensors or convert tensors to the NumPy format, if the data is not in the main memory, the framework will copy it to the main memory first, resulting in additional transmission overhead. Even worse, it is now subject to the dreaded global interpreter lock that makes everything wait for Python to complete.

Neural Networks and GPUs

Similarly, a neural network model can specify devices. The following code puts the model parameters on the GPU.

```{.python .input} net = nn.Sequential() net.add(nn.Dense(1)) net.initialize(ctx=try_gpu())

  1. ```{.python .input}
  2. #@tab pytorch
  3. net = nn.Sequential(nn.Linear(3, 1))
  4. net = net.to(device=try_gpu())

```{.python .input}

@tab tensorflow

strategy = tf.distribute.MirroredStrategy() with strategy.scope(): net = tf.keras.models.Sequential([ tf.keras.layers.Dense(1)])

  1. We will see many more examples of
  2. how to run models on GPUs in the following chapters,
  3. simply since they will become somewhat more computationally intensive.
  4. When the input is a tensor on the GPU, the model will calculate the result on the same GPU.
  5. ```{.python .input}
  6. #@tab all
  7. net(X)

Let us confirm that the model parameters are stored on the same GPU.

```{.python .input} net[0].weight.data().ctx

  1. ```{.python .input}
  2. #@tab pytorch
  3. net[0].weight.data.device

```{.python .input}

@tab tensorflow

net.layers[0].weights[0].device, net.layers[0].weights[1].device ```

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.

Summary

  • We can specify devices for storage and calculation, such as the CPU or GPU. By default, data are created in the main memory and then use the CPU for calculations.
  • The deep learning framework requires all input data for calculation to be on the same device, be it CPU or the same GPU.
  • You can lose significant performance by moving data without care. A typical mistake is as follows: computing the loss for every minibatch on the GPU and reporting it back to the user on the command line (or logging it in a NumPy ndarray) will trigger a global interpreter lock which stalls all GPUs. It is much better to allocate memory for logging inside the GPU and only move larger logs.

Exercises

  1. Try a larger computation task, such as the multiplication of large matrices, and see the difference in speed between the CPU and GPU. What about a task with a small amount of calculations?
  2. How should we read and write model parameters on the GPU?
  3. Measure the time it takes to compute 1000 matrix-matrix multiplications of $100 \times 100$ matrices and log the Frobenius norm of the output matrix one result at a time vs. keeping a log on the GPU and transferring only the final result.
  4. Measure how much time it takes to perform two matrix-matrix multiplications on two GPUs at the same time vs. in sequence on one GPU. Hint: you should see almost linear scaling.

:begin_tab:mxnet Discussions :end_tab:

:begin_tab:pytorch Discussions :end_tab:

:begin_tab:tensorflow Discussions :end_tab: