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.

79 lines
2.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 8.3 自动并行计算
上一节提到默认情况下GPU 操作是异步的。当调用一个使用 GPU 的函数时,这些操作会在特定的设备上排队,但不一定会在稍后执行。这允许我们并行更多的计算,包括 CPU 或其他 GPU 上的操作。
下面看一个简单的例子。
首先导入本节中实验所需的包或模块。注意需要至少2块GPU才能运行本节实验。
``` python
import torch
import time
assert torch.cuda.device_count() >= 2
```
我们先实现一个简单的计时类。
``` python
class Benchmark(): # 本类已保存在d2lzh_pytorch包中方便以后使用
def __init__(self, prefix=None):
self.prefix = prefix + ' ' if prefix else ''
def __enter__(self):
self.start = time.time()
def __exit__(self, *args):
print('%stime: %.4f sec' % (self.prefix, time.time() - self.start))
```
再定义`run`函数令它做20000次矩阵乘法。
``` python
def run(x):
for _ in range(20000):
y = torch.mm(x, x)
```
接下来分别在两块GPU上创建`Tensor`。
``` python
x_gpu1 = torch.rand(size=(100, 100), device='cuda:0')
x_gpu2 = torch.rand(size=(100, 100), device='cuda:1')
```
然后,分别使用它们运行`run`函数并打印运行所需时间。
``` python
with Benchmark('Run on GPU1.'):
run(x_gpu1)
torch.cuda.synchronize()
with Benchmark('Then run on GPU2.'):
run(x_gpu2)
torch.cuda.synchronize()
```
输出:
```
Run on GPU1. time: 0.2989 sec
Then run on GPU2. time: 0.3518 sec
```
尝试系统能自动并行这两个任务:
``` python
with Benchmark('Run on both GPU1 and GPU2 in parallel.'):
run(x_gpu1)
run(x_gpu2)
torch.cuda.synchronize()
```
输出:
```
Run on both GPU1 and GPU2 in parallel. time: 0.5076 sec
```
可以看到当两个计算任务一起执行时执行总时间小于它们分开执行的总和。这表明PyTorch能有效地实现在不同设备上自动并行计算。
-----------
> 注:本节与原书有很多不同,[原书传送门](https://zh.d2l.ai/chapter_computational-performance/auto-parallelism.html)