我编写了这个 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")
Run Code Online (Sandbox Code Playgroud)
这是我笔记本电脑上的结果:
火炬.Size([5000, 5000])
计算需要0.22243595123291016秒
G2.设备:cuda:0
G4.设备:cuda:0
G4====== 张量([[1636.3195, 1227.1913, 1252.6871, 1242.4584, 1235.8160], [1227.1913, 1653.0522, 1260.2621, 1246.9526, 1250.2871], [12 52.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]], 设备='cuda:0')
传输或显示需要60.13639569282532秒
进程已完成,退出代码为 0
我很困惑为什么要花这么多时间在 GPU 上显示变量 G5,因为它的大小只有 5*5。顺便说一句,我使用“G5=G4.cpu()”将GPU上的变量传输到CPU,这也花费了很多时间。
我的开发环境(相当旧的笔记本电脑):
火炬1.0.0
CUDA 8.0
英伟达 GeForce GT 730m
Windows 10 专业版
当增加迭代次数时,计算时间并没有明显增加,但传输或显示却明显增加,为什么?有人可以解释一下吗,非常感谢。
Pytorch CUDA 操作是异步的。GPU 张量上的大多数操作实际上都是非阻塞的,直到请求派生结果为止。这意味着,在您请求张量的 CPU 版本之前,矩阵乘法等命令基本上是与您的代码并行处理的。当您停止计时器时,不能保证操作已完成。您可以在文档中阅读有关此内容的更多信息。
为了正确地计时代码块,您应该添加对torch.cuda.synchronize
. 该函数应该调用两次,一次在启动计时器之前,一次在停止计时器之前。除了分析代码之外,您应该避免调用此函数,因为它可能会降低整体性能。