我编写了这个 pytorch 程序来在 GPU 上计算 5000*5000 矩阵乘法,迭代 100 次。
import torch
import numpy as np
import time
N = 5000
x1 = np.random.rand(N, N)
######## a 5000*5000 matrix multiplication on GPU, 100 iterations #######
x2 = torch.tensor(x1, dtype=torch.float32).to("cuda:0")
start_time = time.time()
for n in range(100):
G2 = x2.t() @ x2
print(G2.size())
print("It takes", time.time() - start_time, "seconds to compute")
print("G2.device:", G2.device)
start_time2 = time.time()
# G4 = torch.zeros((5,5),device="cuda:0")
G4 = G2[:5, :5]
print("G4.device:", G4.device)
print("G4======", G4)
# G5=G4.cpu()
# print("G5.device:",G5.device)
print("It takes", time.time() - start_time2, "seconds to transfer or display")
这是我笔记本电脑上的结果:
torch.Size([5000, 5000])
It takes 0.22243595123291016 seconds to compute
G2.device: cuda:0
G4.device: cuda:0
G4====== tensor([[1636.3195, 1227.1913, 1252.6871, 1242.4584, 1235.8160], [1227.1913, 1653.0522, 1260.2621, 1246.9526, 1250.2871], [1252.6871, 1260.2621, 1685.1147, 1257.2373, 1266.2213], [1242.4584, 1246.9526, 1257.2373, 1660.5951, 1239.5414], [1235.8160, 1250.2871, 1266.2213, 1239.5414, 1670.0034]], device='cuda:0')
It takes 60.13639569282532 seconds to transfer or display
Process finished with exit code 0
我很困惑为什么在 GPU 上显示变量 G5 需要这么多时间,因为它的大小只有 5*5。 顺便说一句,我使用“G5=G4.cpu()”将GPU上的变量传输到CPU,这也花费了很多时间。
我的开发环境(相当旧的笔记本电脑):
pytorch 1.0.0
CUDA 8.0
Nvidia GeForce GT 730m
Windows 10 专业版
当增加迭代次数时,计算时间并没有明显增加,但传输或显示却明显增加,为什么?谁能解释一下,万分感谢。
最佳答案
Pytorch CUDA 操作是异步的。 GPU 张量上的大多数操作实际上都是非阻塞的,直到请求派生结果为止。这意味着,在您请求张量的 CPU 版本之前,矩阵乘法等命令基本上是与您的代码并行处理的。当您停止计时器时,不能保证操作已完成。您可以阅读更多相关信息in the docs .
要正确计时代码块,您应该添加对 torch.cuda.synchronize
的调用。该函数应该调用两次,一次在启动计时器之前,一次在停止计时器之前。除了分析代码之外,您应该避免调用此函数,因为它可能会降低整体性能。
关于pytorch - 为什么在 Pytorch 中打印 GPU 张量的值需要这么长时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66477371/