Pytorch官方指南(二) 翻译版本

CUDA含义(CUDA SEMANTICS)

torch.cuda用于设置和运行cuda操作。它跟踪当前选定的GPU,默认情况下,您分配的所有CUDA Tensor都将在该设备上创建。

无论怎么样,一旦分配了一个张量,就可以对它进行操作,而不必考虑所选的设备,结果将始终与张量放在同一个设备上。

默认情况下不允许跨GPU操作,除了copy_u()和其他具有类似于copy的功能的方法,如to()cuda()。除非使用点对点内存访问,否则任何试图在分布于不同设备上的Tensor启动的操作尝试都将引发错误。
下面有一些例子:

cuda = torch.device('cuda')     # 默认的 CUDA 设备
cuda0 = torch.device('cuda:0')
cuda2 = torch.device('cuda:2')  # GPU 2 (这些设备以0为开始索引)

x = torch.tensor([1., 2.], device=cuda0)
# x.device is device(type='cuda', index=0)
y = torch.tensor([1., 2.]).cuda()
# y.device is device(type='cuda', index=0)

with torch.cuda.device(1):
    # 在 GPU 1 上分一块内存给tensor a
    a = torch.tensor([1., 2.], device=cuda)

    # 将一个tensor从 CPU 转换为 GPU 1 存储
    b = torch.tensor([1., 2.]).cuda()
    # a.device 和 b.device 都在第1GPU 设备上存储 device(type='cuda', index=1)

    # 你也可以使用``Tensor.to`` 来转换tensor:
    b2 = torch.tensor([1., 2.]).to(device=cuda)
    # b2.device 和 b.device 都在第1GPU 设备上存储 device(type='cuda', index=1)

    c = a + b
    # c.device在第1GPU 设备上存储 device(type='cuda', index=1)

    z = x + y
    # z.device在第0GPU 设备上存储 device(type='cuda', index=0)

    # 即使在上下文中,也可以指定设备
    # (或者给.cuda调用一个GPU索引)
    d = torch.randn(2, device=cuda2)
    e = torch.randn(2).to(cuda2)
    f = torch.randn(2).cuda(cuda2)
    # d.device, e.device, and f.device 都储存在 device(type='cuda', index=2)

异步执行(Asynchronous execution)

默认情况下,GPU操作是异步的。当您调用一个使用GPU的函数时,这些操作将排队到特定的设备,但不一定要在稍后执行。它允许我们并行地执行更多的计算,包括对CPU或其他GPU的操作。

一般来说,异步计算的效果对调用者是不可见的,因为
(1)每个设备按照它们排队的顺序执行操作
(2)PyTorch在CPU和GPU之间或两个GPU之间复制数据时自动执行必要的同步
因此,计算将继续进行,好像每个操作都是同步执行的。

您可以通过设置环境变量CUDA_LAUNCH_BLOCKING=1来强制同步计算。当GPU上发生错误时,这很方便。(对于异步执行,在实际执行操作之前不会报告此类错误,因此堆栈跟踪不会显示请求的位置。)

异步计算的一个结果是,没有同步的时间测量是不准确的。要获得精确的测量值,应在测量之前调用torch.cuda.synchronize(),或使用torch.cuda.Event记录以下时间:

start_event = torch.cuda.Event(enable_timing=True)
end_event = torch.cuda.Event(enable_timing=True)
start_event.record()

# 跑一些东西

end_event.record()
torch.cuda.synchronize()  # 等待时间被记录!
elapsed_time_ms = start_event.elapsed_time(end_event)
发布了14 篇原创文章 · 获赞 6 · 访问量 601

猜你喜欢

转载自blog.csdn.net/qq_38883844/article/details/104107821