Personal blog written from scratch using Node.js, Bootstrap, and MySQL. https://jrtechs.net
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

230 lines
8.9 KiB

  1. High-performance parallel computing is all the buzz right now, and new technologies such as CUDA make it more accessible to do GPU computing. However, it is vital to know in what scenarios GPU/CPU processing is faster. This post explores several variables that affect CUDA vs. CPU performance.
  2. The full [Jupyter notebook](https://github.com/jrtechs/RandomScripts/blob/master/notebooks/cuda-vs-cpu.ipynb) for this blog post is posted on my GitHub.
  3. For reference, I am using an Nvidia GTX 1060 running CUDA version 10.2 on Linux.
  4. ```python
  5. !nvidia-smi
  6. ```
  7. ```
  8. Wed Jul 1 11:16:12 2020
  9. +-----------------------------------------------------------------------------+
  10. | NVIDIA-SMI 440.82 Driver Version: 440.82 CUDA Version: 10.2 |
  11. |-------------------------------+----------------------+----------------------+
  12. | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
  13. | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
  14. |===============================+======================+======================|
  15. | 0 GeForce GTX 1060.. Off | 00000000:01:00.0 On | N/A |
  16. | 0% 49C P2 26W / 120W | 2808MiB / 3016MiB | 2% Default |
  17. +-------------------------------+----------------------+----------------------+
  18. +-----------------------------------------------------------------------------+
  19. | Processes: GPU Memory |
  20. | GPU PID Type Process name Usage |
  21. |=============================================================================|
  22. | 0 1972 G /usr/libexec/Xorg 59MiB |
  23. | 0 2361 G /usr/libexec/Xorg 280MiB |
  24. | 0 2485 G /usr/bin/gnome-shell 231MiB |
  25. | 0 5777 G /usr/lib64/firefox/firefox 2MiB |
  26. | 0 33033 G /usr/lib64/firefox/firefox 4MiB |
  27. | 0 37575 G /usr/lib64/firefox/firefox 167MiB |
  28. | 0 37626 G /usr/lib64/firefox/firefox 2MiB |
  29. | 0 90844 C /home/jeff/Documents/python/ml/bin/python 1881MiB |
  30. +-----------------------------------------------------------------------------+
  31. ```
  32. For our first experiment, we take the sinusoidal mathematical function on every element in a matrix.
  33. The independent variable, in this case, is how large our matrix is. Note: the size is defined by the matrix's width, which means that the number of elements will grow exponentially compared to the width.
  34. ```python
  35. import torch
  36. import time # times in seconds
  37. def time_torch(size):
  38. x = torch.rand(size, size, device=torch.device("cuda"))
  39. start = time.time()
  40. x.sin_()
  41. end = time.time()
  42. return(end - start)
  43. def time_cpu(size):
  44. x = torch.rand(size, size, device=torch.device("cpu"))
  45. start = time.time()
  46. x.sin_()
  47. end = time.time()
  48. return(end - start)
  49. ```
  50. To make this easier to graph, we will create a wrapper function that will generate two lists: one for the CPU times and the other for the CUDA times.
  51. ```python
  52. def get_cuda_cpu_times(sizes):
  53. cpuTimes = []
  54. cudaTimes = []
  55. for s in sizes:
  56. cpuTimes += [time_cpu(s)]
  57. cudaTimes += [time_torch(s)]
  58. return cpuTimes, cudaTimes
  59. ```
  60. Some vanilla Matplotlib code can get used to plot the CUDA vs. CPU performances. Note: a lower execution time is better.
  61. ```python
  62. import matplotlib.pyplot as plt
  63. def plot_cuda_vs_cpu(cpuTimes, cudaTimes, sizes, xLab="Matrix Width"):
  64. plt.title("CUDA vs CPU")
  65. cpu_plot = plt.plot(sizes, cpuTimes, label="CPU")
  66. cuda_plot = plt.plot(sizes, cudaTimes, label="CUDA")
  67. plt.legend(bbox_to_anchor=(0.8, 0.98), loc='upper left', borderaxespad=0.)
  68. plt.xlabel(xLab)
  69. plt.ylabel('Execution Time (Seconds)')
  70. plt.show()
  71. sizes = range(1, 50, 1)
  72. cpu_t, cuda_t = get_cuda_cpu_times(sizes)
  73. plot_cuda_vs_cpu(cpu_t, cuda_t, sizes)
  74. ```
  75. ![png](media/cuda-performance/output_5_0.png)
  76. ```python
  77. sizes = range(1, 5000, 100)
  78. cpu_t, cuda_t = get_cuda_cpu_times(sizes)
  79. plot_cuda_vs_cpu(cpu_t, cuda_t, sizes)
  80. ```
  81. ![png](media/cuda-performance/output_6_0.png)
  82. It is interesting to note that it is faster to perform the CPU task for small matrixes. Where for larger arrays, the CUDA outperforms the CPU by large margins.
  83. On a large scale, it looks like the CUDA times are not increasing, but if we only plot the CUDA times, we can see that it also increases linearly.
  84. ```python
  85. cuda_plot = plt.plot(sizes, cuda_t, label="CUDA")
  86. plt.legend(bbox_to_anchor=(0.8, 0.98), loc='upper left', borderaxespad=0.)
  87. plt.xlabel('Matrix Size')
  88. plt.ylabel('Execution Time (Seconds)')
  89. plt.show()
  90. ```
  91. ![png](media/cuda-performance/output_7_0.png)
  92. It is useful to know that the GPU outperforms the CPU on larger matrixes, but that doesn't tell the whole story. There are reasons why we don't run everything on the GPU.
  93. It takes time to copy data between the GPU's memory and main memory (RAM).
  94. This code is similar to what we did previously, but this time, we initialize the matrix on the main memory and then transfer it to the GPU to perform the computation.
  95. ```python
  96. import time # times in seconds
  97. def time_torch_copy(size):
  98. x = torch.rand(size, size, device=torch.device("cpu"))
  99. start = time.time()
  100. x = x.cuda()
  101. x.sin_()
  102. end = time.time()
  103. return(end - start)
  104. def get_cuda_cpu_times_with_copy(sizes):
  105. cpuTimes = []
  106. cudaTimes = []
  107. for s in sizes:
  108. cpuTimes += [time_cpu(s)]
  109. cudaTimes += [time_torch_copy(s)]
  110. return cpuTimes, cudaTimes
  111. sizes = range(1, 5000, 100)
  112. cpu_t, cuda_t = get_cuda_cpu_times_with_copy(sizes)
  113. plot_cuda_vs_cpu(cpu_t, cuda_t, sizes)
  114. ```
  115. ![png](media/cuda-performance/output_9_0.png)
  116. After copying the matrix to the GPU, we see that the CUDA and CPU performances are nearly identical in time complexities.
  117. However, in real-world applications, we don't just leave the GPU data: we also need to copy it back to the main memory.
  118. This test initializes the matrix on the main memory, copies it to the GPU to operate, and then copies the array back to the main memory.
  119. ```python
  120. import time # times in seconds
  121. def time_torch_copy_and_back(size):
  122. x = torch.rand(size, size, device=torch.device("cpu"))
  123. start = time.time()
  124. x = x.cuda()
  125. x.sin_()
  126. x = x.cpu()
  127. end = time.time()
  128. return(end - start)
  129. def get_cuda_cpu_times_with_copy(sizes):
  130. cpuTimes = []
  131. cudaTimes = []
  132. for s in sizes:
  133. cpuTimes += [time_cpu(s)]
  134. cudaTimes += [time_torch_copy_and_back(s)]
  135. return cpuTimes, cudaTimes
  136. sizes = range(1, 5000, 100)
  137. cpu_t, cuda_t = get_cuda_cpu_times_with_copy(sizes)
  138. plot_cuda_vs_cpu(cpu_t, cuda_t, sizes)
  139. ```
  140. ![png](media/cuda-performance/output_10_0.png)
  141. In this trial, it is interesting that CUDA is slower than just running on the CPU by a significant margin.
  142. In the previous trial, we copied the matrix to the GPU to do a single operation, but in this trial, we vary the number of procedures performed on the same matrix.
  143. ```python
  144. def time_torch_operation_repetition(size, iterations):
  145. x = torch.rand(size, size, device=torch.device("cpu"))
  146. start = time.time()
  147. x = x.cuda()
  148. for _ in range(0, iterations):
  149. x.sin()
  150. end = time.time()
  151. return(end - start)
  152. def time_cpu_operation_repetition(size, iterations):
  153. x = torch.rand(size, size, device=torch.device("cpu"))
  154. start = time.time()
  155. for _ in range(0, iterations):
  156. x.sin()
  157. end = time.time()
  158. return(end - start)
  159. def get_cuda_cpu_times_with_iterations(iterations):
  160. cpuTimes = []
  161. cudaTimes = []
  162. for i in iterations:
  163. cpuTimes += [time_cpu_operation_repetition(300, i)]
  164. cudaTimes += [time_torch_operation_repetition(300, i)]
  165. return cpuTimes, cudaTimes
  166. iterations = range(1, 500, 5)
  167. cpu_t, cuda_t = get_cuda_cpu_times_with_iterations(iterations)
  168. plot_cuda_vs_cpu(cpu_t, cuda_t, iterations, xLab="Number of Operations")
  169. ```
  170. ![](media/cuda-performance/output_14_0.png)
  171. As we see in this trial, as we perform more consecutive operations on the matrix without changing devices, we see significant performance benefits for using CUDA.
  172. As we see, whether GPU vs. CPU computing is going to be faster isn't always a clear cut answer.
  173. The CPU is very good at performing tasks fast, but it is not excellent at performing data-parallel computations, which is where GPU computing excels.
  174. IO is another driving factor in whether doing GPU vs. CPU computing will be faster.
  175. If the program has a lot of IO bottlenecks, then CPU computing may be faster.
  176. When designing an application that leverages GPU processing, it is essential to limit the number of times needed to transfer data to the main memory.
  177. ![](media/cuda-performance/brother.jpg)