5.7  GPU、设备与显存

从 2.4 节 开始,我们的 Trainer 一直接收 num_gpus 参数却客气地忽略了它。在前面几章的小模型上这无关紧要,因为 CPU 训练几秒钟就能跑完。然而一旦模型规模扩大,设备放置就会决定训练耗时是几秒还是几小时:一块现代桌面级 GPU 只需不到 2 毫秒就能完成两个 \(4096 \times 4096\) 矩阵相乘,而 CPU 需要十分之一秒甚至更久(我们将在 5.7.2.1 节 中实测对比)。这种澎湃算力伴随着一条严格的硬件约束:GPU 拥有独立板载显存(例如桌面显卡上的 24 GB),它所操作的每一个张量都必须驻留其中。

目标模型究竟装得下吗?贯穿本章的 80 亿参数模型在 bf16 下权重占用 16 GB,推理时轻松装入。但如果用 Adam 以 fp32 训练它,在存放任何一份激活值之前就需要 128 GB 的静态状态(5.2 节),远超任何单张 24 GB 或 80 GB 显卡。模型能否装入设备,以及 GPU 是持续满载计算还是停滞等待数据,都取决于每个张量驻留在何处以及消耗多少字节。

本节回答三个核心问题:张量和模型如何放置到 CPU 和 GPU 上并在两者间拷贝;异步 GPU 执行如何运作(以及如何准确评测 GPU 内核耗时);训练期间究竟是什么填满了 GPU 显存,包括激活检查点如何用额外计算换取大幅显存节省。随后我们将这一切接入全书余下部分使用的设备感知 Trainer。前面 5.2 节 和 5.5 节 核算了每个参数和每个数值的字节数,这里我们将这些字节落到真实硬件上(多 GPU 训练留待 第 13 章)。若当前没有可用 GPU,每个代码单元格都会优雅地回退到 CPU,即便耗时测量需要 GPU,也能验证逻辑正确性。

# Silence TensorFlow's C++ info and warning messages. TensorFlow reads this
# variable when it is first imported, so this cell runs before the imports.
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import time
from torch.utils.checkpoint import checkpoint
import time
import time
import time
torch.set_float32_matmul_precision('high')  # allow tf32 in fp32 matmuls

5.7.1 设备与放置

5.7.1.1 设备对象

每个张量都驻留在特定的设备上:要么是搭配主机内存的 CPU,要么是搭配板载显存的某块 GPU。在终端运行 nvidia-smi 可以列出机器上的每一块 NVIDIA GPU、其总显存与已用显存以及活动进程。尽管四个框架对设备的命名略有差异,但都遵循同一条基本原则:一次运算只在单个设备上执行,因此它的所有操作数都必须位于该设备上。

torch.device('cpu') 和 torch.device(f'cuda:{i}') 分别表示 CPU 和第 \(i\) 块 GPU。

tf.device('/CPU:0') 和 tf.device(f'/GPU:{i}') 创建设备放置作用域。

jax.devices('cpu')[0] 和 jax.devices('gpu')[i] 返回硬件设备句柄。

npx.cpu() 和 npx.gpu(i) 分别表示 CPU 和第 \(i\) 块 GPU(在 MXNet 2.0 之前称为 ctx)。

我们将设备查询封装为全书后续章节都会导入的三个小辅助函数:一个返回 CPU,一个返回第 \(i\) 块 GPU,还有一个统计可用 GPU 数量。

def cpu():
    """Get the CPU device."""
    return torch.device('cpu')

def gpu(i=0):
    """Get a GPU device."""
    return torch.device(f'cuda:{i}')

def num_gpus():
    """Get the number of available GPUs."""
    return torch.cuda.device_count()
def cpu():
    """Get the CPU device."""
    return tf.device('/CPU:0')

def gpu(i=0):
    """Get a GPU device."""
    return tf.device(f'/GPU:{i}')

def num_gpus():
    """Get the number of available GPUs."""
    return len(tf.config.experimental.list_physical_devices('GPU'))
def cpu():
    """Get the CPU device."""
    return jax.devices('cpu')[0]

def gpu(i=0):
    """Get a GPU device."""
    return jax.devices('gpu')[i]

def num_gpus():
    """Get the number of available GPUs."""
    try:
        return jax.device_count('gpu')
    except:
        return 0  # No GPU backend found
def cpu():
    """Get the CPU device."""
    return npx.cpu()

def gpu(i=0):
    """Get a GPU device."""
    return npx.gpu(i)

def num_gpus():
    """Get the number of available GPUs."""
    return npx.num_gpus()

构造设备对象总是会成功;只有当张量被放置到该设备上时,框架才会检查硬件是否存在。

默认情况下,TensorFlow 采用软放置(soft placement),如果请求的 GPU 作用域不存在,会静默回退到 CPU。

jax.devices('gpu') 会立即查询真实硬件,若没有 GPU 则直接报错。

构造设备对象总是会成功;只有当张量被放置到该设备上时,框架才会检查硬件是否存在。

基于 num_gpus,我们定义两个回退辅助函数:有 GPU 时选择 GPU,否则回退到 CPU,使同一份笔记本代码无需修改就能在笔记本电脑和 GPU 服务器上运行。

def try_gpu(i=0):
    """Return gpu(i) if exists, otherwise return cpu()."""
    if num_gpus() >= i + 1:
        return gpu(i)
    return cpu()

def try_all_gpus():
    """Return all available GPUs, or [cpu(),] if no GPU exists."""
    devices = [gpu(i) for i in range(num_gpus())]
    return devices if devices else [cpu()]

try_gpu(), try_gpu(10), try_all_gpus()
(device(type='cuda', index=0),
 device(type='cpu'),
 [device(type='cuda', index=0), device(type='cuda', index=1)])
(<tensorflow.python.eager.context._EagerDeviceContext at 0x70ea7c173d80>,
 <tensorflow.python.eager.context._EagerDeviceContext at 0x70ea7ce0a180>,
 [<tensorflow.python.eager.context._EagerDeviceContext at 0x70ea7c22f080>,
  <tensorflow.python.eager.context._EagerDeviceContext at 0x70ea7c22d4c0>])
(CudaDevice(id=0), CpuDevice(id=0), [CudaDevice(id=0), CudaDevice(id=1)])
(gpu(0), cpu(0), [gpu(0), gpu(1)])

其他加速器(如 Apple Silicon GPU mps 和 Google TPU)有各自的设备标识符,但下文介绍的放置原则对它们同样适用。全书以 CPU 和 CUDA GPU 为主。

5.7.1.2 设备上的数组

每个张量都通过 device 属性暴露其所在位置:

除非传入 device=,PyTorch 张量默认位于 CPU。

有可用 GPU 时,TensorFlow 张量默认位于第一块 GPU(也可通过 with tf.device(...): 显式指定)。

有可用 GPU 时,JAX 数组默认位于第一块 GPU(也可通过 jax.device_put 显式指定)。

除非传入 device=,MXNet 张量默认位于 CPU。

直接在目标设备上分配张量可以避免一次额外的 CPU 到 GPU 拷贝。下面将 X 放在第一块 GPU 上、将 Y 放在第二块 GPU 上(不足两块 GPU 时回退到 CPU),并尝试将它们相加:

X = torch.ones(2, 3, device=try_gpu())
Y = torch.rand(2, 3, device=try_gpu(1))
try:
    print(X + Y)
except RuntimeError as e:
    print(str(e).split(', but')[0])
Expected all tensors to be on the same device
with try_gpu():
    X = tf.ones((2, 3))
with try_gpu(1):
    Y = tf.random.uniform((2, 3))
print((X + Y).device)
/job:localhost/replica:0/task:0/device:GPU:0
X = jax.device_put(jnp.ones((2, 3)), try_gpu())
Y = jax.device_put(jax.random.uniform(d2l.get_key(), (2, 3)), try_gpu(1))
try:
    print(X + Y)
except ValueError as e:
    print(str(e).split('. ')[0])  # The first sentence names the problem
Received incompatible devices for jitted computation
X = mnp.ones((2, 3), device=try_gpu())
Y = mnp.random.uniform(size=(2, 3), device=try_gpu(1))
try:
    print(X + Y)
except Exception as e:
    print(str(e).splitlines()[0])
operands for add must be on the same device/context, got gpu(0) and gpu(1)

对位于不同设备上的张量执行加法会立即报错,防止意外触发跨设备传输。

在显式设备作用域之外,TensorFlow 会静默地将不匹配的操作数拷贝到默认设备上(除非启用 tf.config.experimental.set_device_policy('explicit'))。

对位于不同设备上的张量执行加法会立即报错,防止意外触发跨设备传输。

对位于不同设备上的张量执行加法会立即报错,防止意外触发跨设备传输。

5.7.1.3 在设备间拷贝

在设备间搬运张量比在设备上计算慢得多(5.7.2.1 节 将实测这一差距),因此静默拷贝不匹配的操作数会掩盖严重的性能缺陷。相反,我们在相加前先将 X 显式拷贝到 Y 所在的设备上(图 5.7.1)。

图 5.7.1: X 位于 GPU 0,Y 位于 GPU 1。将 X 拷贝为位于 GPU 1 的 Z(虚线)后,Y + Z 即可完全在 GPU 1 上运行。
Z = X.to(try_gpu(1))
(Y + Z).device
device(type='cuda', index=1)
with try_gpu(1):
    Z = tf.identity(X)  # The explicit copy: tf.identity in the target's scope
    print((Y + Z).device)  # The scope, not the operands, decides the device
/job:localhost/replica:0/task:0/device:GPU:1
Z = jax.device_put(X, try_gpu(1))
(Y + Z).device
CudaDevice(id=1)
Z = X.copyto(try_gpu(1))
(Y + Z).device
gpu(1)

现在加法顺利执行,结果与两个操作数一同落在第二块 GPU 上。实践准则很简单:在计算边界一次性传输数据(把张量移动到它已经驻留的设备上基本是空操作),并让内层循环的每一步运算都留在同一设备上。

执行此类移动的方法是 to_device,当数组已在目标设备上时它直接返回数组本身;而 copyto 总是执行拷贝。

5.7.1.4 设备上的模型

由于前向传播需要将输入与模型参数结合,整个模型必须与小批量数据位于同一设备上。得益于 5.1 节 中的模块树,每个框架都能通过一次调用移动或初始化全部参数。

net = nn.Sequential(nn.Linear(3, 1))
net = net.to(device=try_gpu())
net(X)
tensor([[-0.2254],
        [-0.2254]], device='cuda:0', grad_fn=<AddmmBackward0>)
net = tf.keras.Sequential([tf.keras.layers.Dense(1)])
with try_gpu():
    Y_hat = net(X)  # The first call creates the variables inside the scope
Y_hat
<tf.Tensor: shape=(2, 1), dtype=float32, numpy=
array([[-2.197855],
       [-2.197855]], dtype=float32)>
net = nnx.Sequential(nnx.Linear(3, 1, rngs=nnx.Rngs(d2l.get_key())))
nnx.update(net, jax.device_put(nnx.state(net), try_gpu()))
net(X)
Array([[0.8409575],
       [0.8409575]], dtype=float32)
net = nn.Sequential()
net.add(nn.Dense(1, in_units=3))
net.initialize(device=try_gpu())
net(X)
array([[-0.01747404],
       [-0.01747404]], device=gpu(0))

输入与参数同驻一处后,前向传播在该设备上执行,输出也返回在同一设备上。

牢记两条放置规则:在构造优化器之前将模型移动到目标设备或在其上初始化(使优化器矩估计分配在同一设备上),并在 forward 内部创建任何新张量时将其分配在 X.device 上,而非默认留在 CPU 上。

5.7.2 异步执行

5.7.2.1 执行队列

Python 调用 GPU 运算时,GPU 并非同步执行。相反,Python 只是将每次内核启动压入设备的命令队列便立即返回,让 CPU 在 GPU 顺序消化队列的同时继续准备后续工作。这种流水线机制隐藏了 Python 开销,却带来一个关键的计时陷阱:直接测量 Python 循环耗时测到的是入队时间,而非执行时间。下面我们连续入队 32 次 \(4096 \times 4096\) 矩阵乘法,并两次读取挂钟时间:一次在 Python 刚完成入队时,一次在设备完成计算后。

if torch.cuda.is_available():
    A = torch.randn(4096, 4096, device=gpu())
    A @ A
    torch.cuda.synchronize()  # Warm up and wait
    t = time.perf_counter()
    for _ in range(32):
        B = A @ A
    print(f'time to queue 32 matrix products: {time.perf_counter() - t:.4f} sec')
    torch.cuda.synchronize()
    print(f'time until they all finished:     {time.perf_counter() - t:.4f} sec')
else:
    print('No CUDA device: operations on the CPU run synchronously.')
time to queue 32 matrix products: 0.0010 sec
time until they all finished:     0.0535 sec
if num_gpus() > 0:
    with gpu():
        A = tf.random.normal((4096, 4096))
        A @ A
    tf.test.experimental.sync_devices()  # Warm up and wait
    t = time.perf_counter()
    with gpu():
        for _ in range(32):
            B = A @ A
    print(f'time to queue 32 matrix products: {time.perf_counter() - t:.4f} sec')
    tf.test.experimental.sync_devices()
    print(f'time until they all finished:     {time.perf_counter() - t:.4f} sec')
else:
    print('No GPU: eager operations on the CPU run synchronously.')
time to queue 32 matrix products: 0.0025 sec
time until they all finished:     0.0536 sec
A = jax.random.normal(d2l.get_key(), (4096, 4096))
(A @ A).block_until_ready()  # Warm up and wait
t = time.perf_counter()
for _ in range(32):
    B = A @ A
print(f'time to queue 32 matrix products: {time.perf_counter() - t:.4f} sec')
B.block_until_ready()  # The device runs the products in order
print(f'time until they all finished:     {time.perf_counter() - t:.4f} sec')
time to queue 32 matrix products: 0.0020 sec
time until they all finished:     0.0517 sec
A = mnp.random.normal(size=(4096, 4096), device=try_gpu())
mnp.dot(A, A)
npx.waitall()  # Warm up and wait
t = time.perf_counter()
for _ in range(32):
    B = mnp.dot(A, A)
print(f'time to queue 32 matrix products: {time.perf_counter() - t:.4f} sec')
npx.waitall()
print(f'time until they all finished:     {time.perf_counter() - t:.4f} sec')
time to queue 32 matrix products: 0.0023 sec
time until they all finished:     0.0545 sec

GPU 内核异步运行,而 CPU 运算同步运行;torch.cuda.synchronize() 会等待所有已入队的 GPU 工作完成。

GPU 内核异步运行,而 CPU 运算同步运行;tf.test.experimental.sync_devices() 会等待所有已入队的 GPU 工作完成。

JAX 在 CPU 和 GPU 上都采用异步派发;B.block_until_ready() 会阻塞直到计算完成。

MXNet 在 CPU 和 GPU 上都采用异步派发;npx.waitall() 会阻塞直到计算完成。

Python 仅用实际计算时间的一小部分就把全部 32 次矩阵乘法送入了队列。CPU 究竟何时才会阻塞等待?仅当 Python 需要在主机端拿到具体数值时——例如打印张量、将标量转为 Python 浮点数、转换为 NumPy 数组,或在 if 语句中根据张量值分支。每一个这样的同步点都会让 Python 停等 GPU 把队列排空到该值为止,而在 Python 赶上进度前 GPU 则处于空闲状态(图 5.7.2)。在每个小批量后都将损失记录为 Python 数值,相当于每步都插入一个同步气泡;正因如此,我们的 Trainer 将损失留在设备端的 d2l.Averager 中累加,每轮仅转换一次为 Python 浮点数(2.4 节)。

图 5.7.2: Python 将运算 op1 到 op4 依次入队并继续执行,同时 GPU 按顺序运行它们。将损失读取为 Python 数值是一个同步点:CPU 阻塞直到 GPU 排空队列;随后 Python 恢复运行,而在收到更多工作前 GPU 陷入空闲。

异步派发还决定了可信 GPU 基准测试的四条规则:(1)先运行预热调用,排除一次性内存分配、库初始化与 JIT 编译开销;(2)在启动计时器之前和停止计时器之前都立即同步设备;(3)对多次重复取平均;以及(4)使用 time.perf_counter 获得亚毫秒级分辨率。(上面的演示单元格虽然做了预热和同步,但报告的是 32 次乘法的总耗时;下面编写的 Benchmark 辅助类为本章及后续章节自动落实全部四条规则。)

class Benchmark:
    """Time a callable: warmup, then device-synchronized average seconds.
    `devices` lists the GPUs to wait for, by default the current one."""
    def __init__(self, f, warmup=3, repeats=10, desc='time', devices=None):
        def wait():  # CUDA runs asynchronously; the CPU does not
            if torch.cuda.is_available():
                for device in devices or [None]:
                    torch.cuda.synchronize(device)
        self.desc = desc
        for _ in range(warmup):
            f()
        wait()
        t0 = time.perf_counter()
        for _ in range(repeats):
            f()
        wait()
        self.time = (time.perf_counter() - t0) / repeats

    def __repr__(self):
        return f'{self.desc}: {1000 * self.time:.2f} ms/call'
class Benchmark:
    """Time a callable: warmup, then device-synchronized average seconds."""
    def __init__(self, f, warmup=3, repeats=10, desc='time'):
        self.desc = desc
        for _ in range(warmup):
            f()
        tf.test.experimental.sync_devices()
        t0 = time.perf_counter()
        for _ in range(repeats):
            f()
        tf.test.experimental.sync_devices()
        self.time = (time.perf_counter() - t0) / repeats

    def __repr__(self):
        return f'{self.desc}: {1000 * self.time:.2f} ms/call'
class Benchmark:
    """Time a callable: warmup, then device-synchronized average seconds."""
    def __init__(self, f, warmup=3, repeats=10, desc='time'):
        self.desc, out = desc, None
        for _ in range(warmup):
            out = f()
        jax.block_until_ready(out)
        t0 = time.perf_counter()
        for _ in range(repeats):
            out = f()
        jax.block_until_ready(out)
        self.time = (time.perf_counter() - t0) / repeats

    def __repr__(self):
        return f'{self.desc}: {1000 * self.time:.2f} ms/call'
class Benchmark:
    """Time a callable: warmup, then device-synchronized average seconds."""
    def __init__(self, f, warmup=3, repeats=10, desc='time'):
        self.desc = desc
        for _ in range(warmup):
            f()
        npx.waitall()
        t0 = time.perf_counter()
        for _ in range(repeats):
            f()
        npx.waitall()
        self.time = (time.perf_counter() - t0) / repeats

    def __repr__(self):
        return f'{self.desc}: {1000 * self.time:.2f} ms/call'

JAX 等待的是具体数组而非整块设备,因此被计时的函数必须返回其计算结果,而 Benchmark 会等待最后一次调用返回的值。

我们立刻用 Benchmark 检验前文的两个论断:在大矩阵乘法上 GPU 比 CPU 快多少,以及主机到设备传输相对于计算有多昂贵。下面分别计时 CPU(fp32)、GPU(tf32,见 5.5 节)和 GPU 16 位精度下的 \(4096 \times 4096\) 矩阵乘法,以及将单个 \(4096 \times 4096\) 矩阵从 CPU 内存拷贝到 GPU 的耗时。

if torch.cuda.is_available():
    A_cpu = A.cpu()  # The same matrix in main memory
    A16 = A.bfloat16()
    print(Benchmark(lambda: A_cpu @ A_cpu, warmup=1, repeats=3,
                    desc='product on the CPU, fp32'))
    print(Benchmark(lambda: A @ A, desc='product on the GPU, tf32'))
    print(Benchmark(lambda: A16 @ A16, desc='product on the GPU, bf16'))
    print(Benchmark(lambda: A_cpu.to(gpu()),
                    desc='copy from CPU to the GPU'))
else:
    print('No CUDA device: there is nothing to compare the CPU with.')
product on the CPU, fp32: 1423.37 ms/call
product on the GPU, tf32: 1.68 ms/call
product on the GPU, bf16: 0.91 ms/call
copy from CPU to the GPU: 5.32 ms/call
if num_gpus() > 0:
    with cpu():
        A_cpu = tf.identity(A)  # The same matrix in main memory
    A16 = tf.cast(A, tf.bfloat16)
    def cpu_product():
        with cpu():
            return A_cpu @ A_cpu
    @tf.function  # Eager mode would reuse a cached copy of A_cpu on the GPU
    def copy_to_gpu():
        with gpu():
            return tf.identity(A_cpu)
    print(Benchmark(cpu_product, warmup=1, repeats=3,
                    desc='product on the CPU, fp32'))
    print(Benchmark(lambda: A @ A, desc='product on the GPU, tf32'))
    print(Benchmark(lambda: A16 @ A16, desc='product on the GPU, bf16'))
    print(Benchmark(copy_to_gpu, desc='copy from CPU to the GPU'))
else:
    print('No GPU: there is nothing to compare the CPU with.')
product on the CPU, fp32: 1696.38 ms/call
product on the GPU, tf32: 1.69 ms/call
product on the GPU, bf16: 0.92 ms/call
copy from CPU to the GPU: 7.75 ms/call
if num_gpus() > 0:
    A_cpu = jax.device_put(A, cpu())  # The same matrix in main memory
    A16 = A.astype(jnp.bfloat16)
    print(Benchmark(lambda: A_cpu @ A_cpu, warmup=1, repeats=3,
                    desc='product on the CPU, fp32'))
    print(Benchmark(lambda: A @ A, desc='product on the GPU, tf32'))
    print(Benchmark(lambda: A16 @ A16, desc='product on the GPU, bf16'))
    # Wait for each copy, so that the copies are timed one at a time
    print(Benchmark(lambda: jax.device_put(A_cpu, gpu()).block_until_ready(),
                    desc='copy from CPU to the GPU'))
else:
    print('No GPU: there is nothing to compare the CPU with.')
product on the CPU, fp32: 136.53 ms/call
product on the GPU, tf32: 1.61 ms/call
product on the GPU, bf16: 0.86 ms/call
copy from CPU to the GPU: 8.55 ms/call
if num_gpus() > 0:
    A_cpu = A.copyto(cpu())  # The same matrix in main memory
    A16 = A.astype('float16')  # MXNet's matrix product rejects bf16
    print(Benchmark(lambda: mnp.dot(A_cpu, A_cpu), warmup=1, repeats=3,
                    desc='product on the CPU, fp32'))
    print(Benchmark(lambda: mnp.dot(A, A), desc='product on the GPU, tf32'))
    print(Benchmark(lambda: mnp.dot(A16, A16),
                    desc='product on the GPU, fp16'))
    print(Benchmark(lambda: A_cpu.copyto(gpu()),
                    desc='copy from CPU to the GPU'))
else:
    print('No GPU: there is nothing to compare the CPU with.')
product on the CPU, fp32: 277.79 ms/call
product on the GPU, tf32: 1.72 ms/call
product on the GPU, fp16: 0.88 ms/call
copy from CPU to the GPU: 6.45 ms/call

TensorFlow 默认对 fp32 矩阵乘法使用 tf32。

JAX 的默认矩阵乘法精度在这块 GPU 上选择 tf32。

MXNet 默认对 fp32 矩阵乘法使用 tf32。其矩阵乘法不接受 bf16,因此这里的 16 位乘法使用 fp16,它在相同的 Tensor Core 上以同等速率运行。

在现代 GPU 上,\(4096 \times 4096\) 矩阵乘法不到 2 ms 即可完成,而 CPU 需要约 100 ms 到 2 s(视 CPU 核心数而定,加速比约 \(100\times\) 到 \(1000\times\))。降到 16 位精度还能将 GPU 耗时再砍掉约一半,兑现了 5.5 节 中提到的 Tensor Core 加速效果。

特别留意最后一行:仅仅把矩阵从 CPU 内存拷贝到 GPU,耗时就比它到达后的矩阵乘法长三到六倍,尽管乘法对每个拷贝的元素都执行了 4096 次乘加运算。普通主机拷贝会先将数据暂存到锁页(pinned,page-locked)主机内存中,再由 GPU 的 DMA 引擎直接拉取;预先锁页存储小批量可以省去这层额外拷贝,并允许数据传输与计算重叠(13.2 节)。

5.7.3 GPU 显存

5.7.3.1 显存的三层视图

询问一个训练脚本占用了多少 GPU 显存,可能得到三个不同的数字,具体取决于你查询内存栈的哪一层。直接向 CUDA 驱动申请显存很慢,因此框架内部运行着一个缓存分配器(caching allocator):它先从驱动整块申请大片显存,再细分给各个张量,释放时也保留这些显存块以供复用,而非立即归还驱动。这形成了三层嵌套的显存视图(图 5.7.3):当前存活张量实际占用的字节数、框架分配器保留的更大显存池,以及 CUDA 驱动分配给该进程的总显存(即 nvidia-smi 显示的数字)。

图 5.7.3: 三层显存视图相互嵌套:驱动分配给进程的总显存(nvidia-smi 报告的数值)包含分配器保留的显存块,后者又包含存活数组。

torch.cuda.memory_allocated() 报告存活张量字节数,而 torch.cuda.memory_reserved() 报告缓存分配器的显存池大小。

tf.config.experimental.get_memory_info('GPU:0') 报告 TensorFlow GPU 分配器内的 'current' 与 'peak' 存活字节数。

gpu().memory_stats() 报告 JAX 预分配 GPU 显存池内的 'bytes_in_use' 与 'peak_bytes_in_use'。

npx.gpu_memory_info(0) 在调用 gpu().empty_cache() 后向 CUDA 驱动查询整张显卡的空闲与总字节数。

我们分配一个 1 GiB 的 float32 张量并立即删除它,观察这些计数器如何变化:

if torch.cuda.is_available():
    def report(tag):
        print(f'{tag}: {torch.cuda.memory_allocated() / 2**20:7.1f} MiB '
              f'allocated, {torch.cuda.memory_reserved() / 2**20:7.1f} MiB '
              'reserved')
    big = torch.zeros(256, 1024, 1024, device=gpu())  # 1 GiB of float32
    report('after creating big')
    del big
    report('after deleting it ')
else:
    print('No CUDA device: both counters read 0 on the CPU.')
after creating big:  1192.1 MiB allocated,  1302.0 MiB reserved
after deleting it :   168.1 MiB allocated,  1302.0 MiB reserved
if num_gpus() > 0:
    def report(tag):
        info = tf.config.experimental.get_memory_info('GPU:0')
        print(f'{tag}: {info["current"] / 2**20:7.1f} MiB in use, '
              f'{info["peak"] / 2**20:7.1f} MiB peak')
    with gpu():
        big = tf.zeros((256, 1024, 1024))  # 1 GiB of float32
    report('after creating big')
    del big
    report('after deleting it ')
else:
    print('No GPU: get_memory_info() tracks only GPU and TPU allocators.')
after creating big:  1184.0 MiB in use,  1184.0 MiB peak
after deleting it :   160.0 MiB in use,  1184.0 MiB peak
if num_gpus() > 0:
    def report(tag):
        s = gpu().memory_stats()
        print(f'{tag}: {s["bytes_in_use"] / 2**20:7.1f} MiB in use, '
              f'{s["peak_bytes_in_use"] / 2**20:7.1f} MiB peak')
    big = jnp.zeros((256, 1024, 1024))  # 1 GiB of float32
    big.block_until_ready()
    report('after creating big')
    del big
    report('after deleting it ')
else:
    print('No GPU: memory_stats() returns None on the CPU backend.')
after creating big:  1184.0 MiB in use,  1184.0 MiB peak
after deleting it :   160.0 MiB in use,  1184.0 MiB peak
if num_gpus() > 0:
    gpu().empty_cache()
    npx.waitall()
    free_start, _ = npx.gpu_memory_info(0)
    def report(tag):
        npx.waitall()
        free, _ = npx.gpu_memory_info(0)
        print(f'{tag}: {(free_start - free) / 2**20:7.1f} MiB more used')
    big = mnp.zeros((256, 1024, 1024), device=gpu())  # 1 GiB of float32
    report('after creating big')
    del big
    report('after deleting it ')
    gpu().empty_cache()
    report('after empty_cache ')
else:
    print('No GPU: gpu_memory_info() queries the CUDA driver.')
after creating big:  1024.0 MiB more used
after deleting it :  1024.0 MiB more used
after empty_cache :     0.0 MiB more used

MXNet 仅报告驱动级别的显存占用,只有调用 empty_cache() 归还显存块后该数值才会下降。

删除 big 释放了 1 GiB 的存活张量,但框架的缓存分配器仍将这 1 GiB 显存块留在保留池中,因此 nvidia-smi 的读数纹丝不动。(切勿在训练循环内部强行将显存块归还 CUDA 驱动,否则每一步都会引入缓慢的驱动级分配。)最外层的驱动视图设定了硬性的显存溢出上限,因为驱动无法分配超出显卡物理容量的显存。要诊断代码内部的显存究竟花在何处,我们查看存活字节计数器——尤其是单次调用期间触及的峰值显存,它决定了这一步是顺利完成还是因显存不足(OOM)崩溃。

torch.cuda.reset_peak_memory_stats() 与 torch.cuda.max_memory_allocated() 可精确测量任意调用的峰值存活显存增量:

由于 XLA 为编译后的函数静态规划内存,compiled.memory_analysis().temp_size_in_bytes 会报告输入和输出之外所需的临时工作区与激活字节数:

MXNet 的 C++ 缓存分配器未向 Python 暴露存活张量或峰值字节计数器;可使用 nvidia-smi 或框架级性能分析器检查设备显存。

def peak_memory(f, *args):
    """Extra peak GPU memory allocated by f(*args), in bytes."""
    torch.cuda.synchronize()
    torch.cuda.reset_peak_memory_stats()
    base = torch.cuda.memory_allocated()
    f(*args)
    torch.cuda.synchronize()
    return torch.cuda.max_memory_allocated() - base
def peak_memory(f, *args):
    """Temporary memory that XLA reserves to run jax.jit(f) on args, in
    bytes."""
    compiled = jax.jit(f).lower(*args).compile()
    return compiled.memory_analysis().temp_size_in_bytes

5.7.3.2 训练期间的显存

在 5.2 节 中,我们确立了 fp32 Adam 训练的静态显存下限:\(N\) 个参数需要 \(16N\) 字节(\(4N\) 权重、\(4N\) 梯度和 \(8N\) Adam 矩估计)。在实际训练步中,第四项加入了进来:激活值。反向传播必须保留前向传播的中间输出直至反向扫描消耗它们;与静态的 \(16N\) 不同,激活显存随小批量大小和层宽线性增长。我们可以在测量前先算出来:考虑一个接收 1024 维输入、含三个宽度 4096 隐藏层的 MLP(\(N \approx 3.8 \times 10^7\) 个参数,因此 \(4N \approx 144\) MiB),小批量大小为 4096。三个隐藏层输出各自都是 \(4096 \times 4096\) 的 fp32 张量,每个占 64 MiB(合计 192 MiB),已经比权重本身多出三分之一。

由于 MXNet 未在 Python 中暴露每步存活字节分配器计数器,本小节不提供 MXNet 代码;下文的 \(16N\) 加激活值解析预算同样适用。

if torch.cuda.is_available():
    start = torch.cuda.memory_allocated()
    def allocated():  # Memory in use beyond that at the start of the cell
        return f'{(torch.cuda.memory_allocated() - start) / 2**20:7.1f} MiB'
    net = nn.Sequential(nn.Linear(1024, 4096), nn.ReLU(),
                        nn.Linear(4096, 4096), nn.ReLU(),
                        nn.Linear(4096, 4096), nn.ReLU(),
                        nn.Linear(4096, 10)).to(gpu())
    optimizer = torch.optim.Adam(net.parameters())
    X = torch.randn(4096, 1024, device=gpu())
    y = torch.randint(0, 10, (4096,), device=gpu())
    print('weights           ', allocated())
    loss = F.cross_entropy(net(X), y)
    print('+ activations     ', allocated())
    loss.backward()
    print('+ gradients       ', allocated())
    optimizer.step()
    print('+ optimizer state ', allocated())
else:
    print('No CUDA device: run this cell on a GPU to see the four readings.')
weights              160.2 MiB
+ activations        353.4 MiB
+ gradients          313.6 MiB
+ optimizer state    602.0 MiB
if num_gpus() > 0:
    start = tf.config.experimental.get_memory_info('GPU:0')['current']
    def in_use():  # Memory in use beyond that at the start of the cell
        info = tf.config.experimental.get_memory_info('GPU:0')
        return f'{(info["current"] - start) / 2**20:7.1f} MiB'
    with gpu():
        net = tf.keras.Sequential(
            [tf.keras.layers.Dense(4096, activation='relu'),
             tf.keras.layers.Dense(4096, activation='relu'),
             tf.keras.layers.Dense(4096, activation='relu'),
             tf.keras.layers.Dense(10)])
        X = tf.random.normal((4096, 1024))
        y = tf.random.uniform((4096,), 0, 10, dtype=tf.int32)
        net(X)  # The first call creates the variables
    optimizer = tf.keras.optimizers.Adam()
    loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
    print('weights           ', in_use())
    with tf.GradientTape() as tape:
        loss = loss_fn(y, net(X, training=True))
    print('+ activations     ', in_use())
    grads = tape.gradient(loss, net.trainable_variables)
    print('+ gradients       ', in_use())
    optimizer.apply_gradients(zip(grads, net.trainable_variables))
    print('+ optimizer state ', in_use())
else:
    print('No GPU: run this cell on a GPU to see the four readings.')
weights              160.2 MiB
+ activations        352.5 MiB
+ gradients          304.4 MiB
+ optimizer state    592.8 MiB
if num_gpus() > 0:
    start = gpu().memory_stats()['bytes_in_use']
    def in_use():  # Memory in use beyond that at the start of the cell
        s = gpu().memory_stats()
        return f'{(s["bytes_in_use"] - start) / 2**20:7.1f} MiB'
    rngs = nnx.Rngs(d2l.get_key())
    net = nnx.Sequential(nnx.Linear(1024, 4096, rngs=rngs), nnx.relu,
                         nnx.Linear(4096, 4096, rngs=rngs), nnx.relu,
                         nnx.Linear(4096, 4096, rngs=rngs), nnx.relu,
                         nnx.Linear(4096, 10, rngs=rngs))
    key1, key2 = jax.random.split(d2l.get_key())
    X = jax.random.normal(key1, (4096, 1024))
    y = jax.random.randint(key2, (4096,), 0, 10)
    def loss(model):
        logits = model(X)
        return optax.softmax_cross_entropy_with_integer_labels(
            logits, y).mean()
    jax.block_until_ready(nnx.state(net))
    print('weights                ', in_use())
    grads = jax.block_until_ready(nnx.grad(loss)(net))
    print('+ gradients            ', in_use())
    optimizer = nnx.Optimizer(net, optax.adam(1e-3), wrt=nnx.Param)
    jax.block_until_ready(optimizer.opt_state)
    print('+ optimizer state      ', in_use())
    graphdef, params = nnx.split(net)
    grad_fn = jax.grad(lambda params: loss(nnx.merge(graphdef, params)))
    planned = peak_memory(grad_fn, params)
    print(f'activations (planned)  {planned / 2**20:7.1f} MiB')
else:
    print('No GPU: run this cell on a GPU to see the terms arrive.')
weights                   160.2 MiB
+ gradients               304.4 MiB
+ optimizer state         593.0 MiB
activations (planned)    192.0 MiB

读数完整勾勒出单个训练步的生命周期:首先是权重(\(4N\) 字节)和输入驻留显存;前向传播追加保存下来的激活值(约 192 MiB,超过权重);反向传播消耗并释放这些激活值,同时物化梯度(\(4N\));首次优化器更新则分配 Adam 的两阶矩(\(8N\))。图 5.7.4 绘制了不含 16 MiB 输入批量的这四个阶段。从第二步起,显存在每一步内起落循环:前向传播在权重和 Adam 矩之上叠加激活值,反向传播再用梯度替换它们。峰值至多为静态的 \(16N\) 加上激活值;若循环在下一轮前向传播前先释放旧梯度,峰值最多可再低 \(4N\)。当激活值把显存推过红线时,缩小小批量大小是最快的调节杆,因为它无需改动架构就能压低激活显存占用。相反,如果显存一步接一步地持续攀升,就该排查是否有内存泄漏让旧计算图存活着——最常见的元凶是把未脱离计算图的原始损失张量直接追加到 Python 列表中。

optimizer.zero_grad() 默认释放梯度(set_to_none=True),因此在进入前向传播前调用它的循环在保存激活值时只持有 \(12N\) 而非 \(16N\) 字节。

图 5.7.4: 宽度为 4096、小批量大小为 4096 的 MLP 在首个训练步各阶段结束后的显存占用(未计入输入批量)。前向传播在权重(\(4N\))基础上增加三份保存的激活值;反向传播释放激活值并留下梯度(\(4N\));优化器步骤再增加 Adam 的两阶矩(\(8N\))。

5.7.3.3 激活检查点

控制激活显存还有第二条架构级杠杆。标准反向传播保存每一层的中间输出,只为了在反向扫描时读取一次。激活检查点(activation checkpointing,又称梯度检查点或重物化,(Chen 等 2016年))在前向传播期间丢弃大部分中间激活值,仅保留选定分段边界处的输入,待反向传播时再按需现场重算每段内部的激活值。(尽管名字里都有“检查点”,这项内存技术与 5.6 节 中的磁盘检查点毫无关系。)

将 \(K\) 个均匀层划分为每段 \(s\) 层,只需保存 \(K/s\) 个分段边界加上当前活动段内的 \(s\) 份存活激活值(约 \(K/s + s\) 个张量,而非 \(K\) 个)。取 \(s = \sqrt{K}\) 可将峰值激活显存从 \(O(K)\) 降至 \(O(\sqrt{K})\)。代价是反向传播期间每段多算一次前向传播(图 5.7.5)。由于线性层的反向传播执行两次矩阵乘法(输入梯度与权重梯度),而前向传播只执行一次,多加一次前向传播会把单步总计算量从约 3 倍前向等效开销增至 4 倍:粗略上界约增加 33%,具体取决于硬件与层类型组合。

图 5.7.5: (a)标准反向传播保存每一层的激活值。(b)激活检查点仅保存分段边界的输入(实心),并在反向传播期间重算每段内部的激活值(空心)。将 \(K\) 层按每段 \(\sqrt{K}\) 层分组时,保存的激活值从 \(O(K)\) 降至 \(O(\sqrt{K})\),代价是多执行一次前向传播。

激活检查点在相同模块深度堆叠的架构上大放异彩,例如我们的残差 MLP(5.1 节)和现代 Transformer。下面定义权重服从 \(\mathcal{N}(0, 0.01^2)\)、偏置为零的 ResidualBlock,以及按分段组合模块并支持可选检查点的 run_stack 辅助函数。

class ResidualBlock(nn.Module):
    def __init__(self, num_hiddens):
        super().__init__()
        self.body = nn.Sequential(
            nn.Linear(num_hiddens, num_hiddens), nn.ReLU(),
            nn.Linear(num_hiddens, num_hiddens))
        for layer in self.body[0], self.body[2]:
            nn.init.normal_(layer.weight, std=0.01)
            nn.init.zeros_(layer.bias)

    def forward(self, X):
        return X + self.body(X)

def run_stack(blocks, X, use_checkpoint=False, segment_size=4):
    for start in range(0, len(blocks), segment_size):
        stop = min(start + segment_size, len(blocks))
        # Bind this segment's range now: the backward pass calls segment
        # again after the loop has moved on
        def segment(X, start=start, stop=stop):
            for i in range(start, stop):
                X = blocks[i](X)
            return X
        X = checkpoint(segment, X, use_reentrant=False) \
            if use_checkpoint else segment(X)
    return X
class ResidualBlock(tf.keras.layers.Layer):
    def __init__(self, num_hiddens, **kwargs):
        super().__init__(**kwargs)
        normal = tf.keras.initializers.RandomNormal  # One instance per layer
        self.body = tf.keras.Sequential([
            tf.keras.layers.Dense(num_hiddens, activation='relu',
                                  kernel_initializer=normal(stddev=0.01)),
            tf.keras.layers.Dense(num_hiddens,
                                  kernel_initializer=normal(stddev=0.01))])

    def call(self, X):
        return X + self.body(X)

def run_stack(blocks, X, use_checkpoint=False, segment_size=4):
    for start in range(0, len(blocks), segment_size):
        # Bind this segment's blocks now: the backward pass calls segment
        # again after the loop has moved on
        def segment(X, segment_blocks=blocks[start:start + segment_size]):
            for blk in segment_blocks:
                X = blk(X)
            return X
        f = tf.recompute_grad(segment) if use_checkpoint else segment
        X = f(X)
    return X
class ResidualBlock(nnx.Module):
    def __init__(self, num_hiddens, *, rngs):
        normal = nnx.initializers.normal(0.01)
        self.body = nnx.Sequential(
            nnx.Linear(num_hiddens, num_hiddens, kernel_init=normal,
                       rngs=rngs), nnx.relu,
            nnx.Linear(num_hiddens, num_hiddens, kernel_init=normal,
                       rngs=rngs))

    def __call__(self, X):
        return X + self.body(X)

def run_stack(graphdef, states, X, use_checkpoint=False, segment_size=4):
    def segment(segment_states, X):
        for state in segment_states:
            X = nnx.merge(graphdef, state)(X)
        return X
    f = jax.checkpoint(segment) if use_checkpoint else segment
    for start in range(0, len(states), segment_size):
        X = f(states[start:start + segment_size], X)
    return X

torch.utils.checkpoint.checkpoint(segment, X, use_reentrant=False) 会丢弃 segment 内部的中间激活值、保存并恢复 RNG 状态(保证暂退法一致),并在 backward() 期间重新运行 segment。

tf.recompute_grad(segment) 包装 segment,使 GradientTape 仅保留其分段边界输入,并在反向扫描时重算内部激活值。

jax.checkpoint(或 jax.remat)变换纯函数(经由 nnx.split 获得),使 jax.grad 仅保存分段边界输入并在反向传播期间重物化内部激活值。

MXNet 在 Python 中未提供逐分段检查点 API(仅对混合化计算图提供进程级环境变量 MXNET_BACKWARD_DO_MIRROR=1),因此本小节不含 MXNet 代码。

先做一次合理性检查:重算激活值绝不能改变数学结果。我们在一个拆分为两段检查点的 8 块堆叠上验证,所有梯度都与标准反向传播完全一致。

blocks = nn.Sequential(*[ResidualBlock(64) for _ in range(8)])
X = torch.randn(32, 64)

def stack_grads(use_checkpoint):
    blocks.zero_grad(set_to_none=True)
    run_stack(blocks, X, use_checkpoint).sum().backward()
    return [p.grad.clone() for p in blocks.parameters()]

for g, g_ckpt in zip(stack_grads(False), stack_grads(True)):
    assert torch.allclose(g, g_ckpt)
print('checkpointed gradients match the ordinary ones')
checkpointed gradients match the ordinary ones
blocks = [ResidualBlock(64) for _ in range(8)]
X = tf.random.normal((32, 64))

def stack_grads(use_checkpoint):
    with tf.GradientTape() as tape:
        loss = tf.reduce_sum(run_stack(blocks, X, use_checkpoint))
    params = [v for blk in blocks for v in blk.trainable_variables]
    return tape.gradient(loss, params)

for g, g_ckpt in zip(stack_grads(False), stack_grads(True)):
    assert np.allclose(g, g_ckpt)
print('checkpointed gradients match the ordinary ones')
checkpointed gradients match the ordinary ones
X = jax.random.normal(d2l.get_key(), (32, 64))
blocks = [ResidualBlock(64, rngs=nnx.Rngs(d2l.get_key())) for _ in range(8)]
split_blocks = [nnx.split(block) for block in blocks]
graphdef = split_blocks[0][0]
states = [state for _, state in split_blocks]

def stack_grads(use_checkpoint):
    loss = lambda states: run_stack(graphdef, states, X,
                                    use_checkpoint).sum()
    return jax.tree_util.tree_leaves(jax.grad(loss)(states))

for g, g_ckpt in zip(stack_grads(False), stack_grads(True)):
    assert jnp.allclose(g, g_ckpt)
print('checkpointed gradients match the ordinary ones')
checkpointed gradients match the ordinary ones

上述正确性检查在任何设备上都能跑;为了实测显存与计算的权衡,我们在 GPU 上使用更深的 16 块堆叠(宽度 1024、批量大小 8192),按每四块为一段分组,并用 Benchmark 报告单步显存(参数与输入之外的峰值显存)和挂钟时间。

if torch.cuda.is_available():
    blocks = nn.Sequential(*[ResidualBlock(1024) for _ in range(16)]).to(gpu())
    X = torch.randn(8192, 1024, device=gpu())
    def step(use_checkpoint):
        blocks.zero_grad(set_to_none=True)
        run_stack(blocks, X, use_checkpoint).sum().backward()
    for use_checkpoint in (False, True):
        timing = Benchmark(lambda: step(use_checkpoint))
        blocks.zero_grad(set_to_none=True)  # Gradients count as step memory
        peak = peak_memory(step, use_checkpoint)
        print(f'checkpointing={use_checkpoint!s:5}  step memory '
              f'{peak / 2**20:5.0f} MiB, {timing.time * 1e3:5.1f} ms per step')
else:
    print('No CUDA device: the peak-memory comparison needs a GPU.')
checkpointing=False  step memory  1096 MiB,  25.5 ms per step
checkpointing=True   step memory   452 MiB,  32.3 ms per step
if num_gpus() > 0:
    with gpu():
        blocks = [ResidualBlock(1024) for _ in range(16)]
        X = tf.random.normal((8192, 1024))
        run_stack(blocks, X)  # Create the variables
    params = [v for blk in blocks for v in blk.trainable_variables]
    @tf.function  # One graph for each value of use_checkpoint
    def step(use_checkpoint):
        with tf.GradientTape() as tape:
            loss = tf.reduce_sum(run_stack(blocks, X, use_checkpoint))
        return tape.gradient(loss, params)
    for use_checkpoint in (False, True):
        step(use_checkpoint)  # Trace and warm up
        tf.test.experimental.sync_devices()
        start = tf.config.experimental.get_memory_info('GPU:0')['current']
        tf.config.experimental.reset_memory_stats('GPU:0')
        timing = Benchmark(lambda: step(use_checkpoint), warmup=0)
        peak = tf.config.experimental.get_memory_info('GPU:0')['peak'] - start
        print(f'checkpointing={use_checkpoint!s:5}  step memory '
              f'{peak / 2**20:5.0f} MiB, {timing.time * 1e3:5.1f} ms per step')
else:
    print('No GPU: the peak-memory comparison needs a GPU.')
checkpointing=False  step memory  1152 MiB,  24.4 ms per step
checkpointing=True   step memory   512 MiB,  30.0 ms per step
if num_gpus() > 0:
    X = jax.random.normal(d2l.get_key(), (8192, 1024))
    blocks = [ResidualBlock(1024, rngs=nnx.Rngs(d2l.get_key()))
              for _ in range(16)]
    split_blocks = [nnx.split(block) for block in blocks]
    graphdef = split_blocks[0][0]
    states = [state for _, state in split_blocks]
    for use_checkpoint in (False, True):
        step = jax.jit(jax.grad(lambda states: run_stack(
            graphdef, states, X, use_checkpoint).sum()))
        plan = step.lower(states).compile().memory_analysis()
        timing = Benchmark(lambda: step(states))
        peak = plan.temp_size_in_bytes + plan.output_size_in_bytes
        print(f'checkpointing={use_checkpoint!s:5}  step memory '
              f'{peak / 2**20:5.0f} MiB, {timing.time * 1e3:5.1f} ms per step')
else:
    print('No GPU: the peak-memory comparison needs a GPU.')
checkpointing=False  step memory  1152 MiB,  22.7 ms per step
checkpointing=True   step memory   512 MiB,  27.6 ms per step

与所有需要计时的 TensorFlow 代码一样,这一步使用 tf.function 编译。

单步显存是编译后的单步计划在输入之外使用的显存:主要是激活值等临时数组,加上作为输出的梯度。peak_bytes_in_use 不适用,因为 JAX 无法重置它,且前面的单元格已经将其推高。

不开启检查点时,反向传播必须同时持有全部 16 个块的激活值;按每四块分组后,只需保留四个分段边界加一个活动段,单步显存从约 1.1 GiB 降至 0.4–0.5 GiB,而计算时间仅增加约四分之一(落在我们粗估的 33% 上界之内)。如此划算的交换使激活检查点成为训练大型 Transformer 与深层视觉模型的标准配置。

5.7.4 设备感知的 Trainer

现在我们终于可以把 num_gpus 真正接入 d2l.Trainer 了。将前文规则落到代码只需两步:在训练开始前把模型参数放到目标设备上,并在每一步开始时把每个小批量搬到该设备上。

@d2l.add_to_class(d2l.Trainer)
def __init__(self, max_epochs, num_gpus=0, gradient_clip_val=0):
    self.save_hyperparameters()
    self.gpus = [d2l.gpu(i) for i in range(min(num_gpus, d2l.num_gpus()))]
    self.board = d2l.ProgressBoard(xlabel='epoch', ylabel='loss')

@d2l.add_to_class(d2l.Trainer)
def prepare_batch(self, batch):
    if self.gpus:
        batch = [d2l.to(a, self.gpus[0]) for a in batch]
    return batch

@d2l.add_to_class(d2l.Trainer)
def prepare_model(self, model):
    self.model = model
    if self.gpus:
        model.to(self.gpus[0])
        # Pick convolution algorithms by timing, unless determinism is wanted
        torch.backends.cudnn.benchmark = not (
            torch.are_deterministic_algorithms_enabled()
            or torch.backends.cudnn.deterministic)
    # Lazy parameters get their shapes from a dry pass on the device, then
    # the model's weight_init, if it has one, before the optimizer exists
    if any(isinstance(p, nn.parameter.UninitializedParameter)
           for p in model.parameters()):
        loader = (self.train_dataloader if self.train_dataloader is not None
                  else self.val_dataloader)  # `evaluate` has no training data
        batch = self.prepare_batch(next(iter(loader)))
        model.apply_init(batch[:-1], getattr(model, 'weight_init', None))
@d2l.add_to_class(d2l.Trainer)
def __init__(self, max_epochs, num_gpus=0, gradient_clip_val=0):
    self.save_hyperparameters()
    self.gpus = [d2l.gpu(i) for i in range(min(num_gpus, d2l.num_gpus()))]
    self.board = d2l.ProgressBoard(xlabel='epoch', ylabel='loss')

@d2l.add_to_class(d2l.Trainer)
def prepare_batch(self, batch):
    if self.gpus:
        # tf.data.Dataset emits batches on CPU. Re-wrap them inside the
        # GPU device context so subsequent ops keep their inputs on-device
        # rather than incurring an implicit copy each step.
        with self.gpus[0]:
            batch = [tf.identity(a) for a in batch]
    return batch
@d2l.add_to_class(d2l.Trainer)
def __init__(self, max_epochs, num_gpus=0, gradient_clip_val=0):
    self.save_hyperparameters()
    self.gpus = [d2l.gpu(i) for i in range(min(num_gpus, d2l.num_gpus()))]
    self.board = d2l.ProgressBoard(xlabel='epoch', ylabel='loss')

@d2l.add_to_class(d2l.Trainer)
def prepare_batch(self, batch):
    if self.gpus:
        batch = [d2l.to(a, self.gpus[0]) for a in batch]
    return batch
@d2l.add_to_class(d2l.Trainer)
def __init__(self, max_epochs, num_gpus=0, gradient_clip_val=0):
    self.save_hyperparameters()
    self.gpus = [d2l.gpu(i) for i in range(min(num_gpus, d2l.num_gpus()))]
    self.board = d2l.ProgressBoard(xlabel='epoch', ylabel='loss')

@d2l.add_to_class(d2l.Trainer)
def prepare_batch(self, batch):
    # Move to the CPU too: a DataLoader with worker processes delivers its
    # minibatches in shared memory, cpu_shared(0), and a hybridized model
    # refuses inputs that are not on the device of its parameters, cpu(0)
    device = self.gpus[0] if self.gpus else d2l.cpu()
    return [a.to_device(device) for a in batch]

@d2l.add_to_class(d2l.Trainer)
def prepare_model(self, model):
    self.model = model
    if self.gpus:
        # Works even while the parameters still wait for their shapes
        model.reset_device(self.gpus[0])

使用 min(num_gpus, d2l.num_gpus()) 将 num_gpus 视为上限而非硬性要求:在纯 CPU 机器上,self.gpus 为空,训练无缝回退到 CPU 运行——这正是本书余下所有 Trainer(num_gpus=1) 调用背后的回退机制。

GPU 实际训练一个小模型能快多少?尽管前面 \(4096 \times 4096\) 矩阵乘法提速了约 \(100\times\) 甚至更多,端到端训练循环还包含数据加载、Python 派发和规模小得多的网络层。下面我们在 Fashion-MNIST 上实测一个由两个 256 宽残差块(5.7.3.3 节)构成的分类器,权重从 \(\mathcal{N}(0, 0.01^2)\) 初始化、偏置为零。

class ResidualBlock(nn.Block):
    def __init__(self, num_hiddens):
        super().__init__()
        self.body = nn.Sequential()
        self.body.add(nn.Dense(num_hiddens, activation='relu',
                               in_units=num_hiddens),
                      nn.Dense(num_hiddens, in_units=num_hiddens))

    def forward(self, X):
        return X + self.body(X)

class ResMLPClassifier(d2l.Classifier):
    def __init__(self, num_hiddens=256, num_blocks=2, lr=0.1):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Sequential()
        self.net.add(nn.Dense(num_hiddens, activation='relu', in_units=784),
                     *[ResidualBlock(num_hiddens) for _ in range(num_blocks)],
                     nn.Dense(10, in_units=num_hiddens))
        self.net.initialize(init.Normal(sigma=0.01))
class ResMLPClassifier(d2l.Classifier):
    def __init__(self, num_hiddens=256, num_blocks=2, lr=0.1):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Sequential(
            nn.Flatten(), nn.Linear(784, num_hiddens), nn.ReLU(),
            *[ResidualBlock(num_hiddens) for _ in range(num_blocks)],
            nn.Linear(num_hiddens, 10))
        for layer in self.net[1], self.net[-1]:  # The blocks set their own
            nn.init.normal_(layer.weight, std=0.01)
            nn.init.zeros_(layer.bias)
class ResMLPClassifier(d2l.Classifier):
    def __init__(self, num_hiddens=256, num_blocks=2, lr=0.1):
        super().__init__()
        self.save_hyperparameters()
        normal = tf.keras.initializers.RandomNormal  # One instance per layer
        self.net = tf.keras.Sequential([
            tf.keras.layers.Flatten(),
            tf.keras.layers.Dense(num_hiddens, activation='relu',
                                  kernel_initializer=normal(stddev=0.01)),
            *[ResidualBlock(num_hiddens) for _ in range(num_blocks)],
            tf.keras.layers.Dense(10, kernel_initializer=normal(stddev=0.01))])
class ResMLPClassifier(d2l.Classifier):
    def __init__(self, num_hiddens=256, num_blocks=2, lr=0.1, rngs=None):
        super().__init__()
        self.save_hyperparameters(ignore=['rngs'])
        rngs = nnx.Rngs(d2l.get_key()) if rngs is None else rngs
        normal = nnx.initializers.normal(0.01)
        self.net = nnx.Sequential(
            lambda x: x.reshape((x.shape[0], -1)),
            nnx.Linear(784, num_hiddens, kernel_init=normal, rngs=rngs),
            nnx.relu,
            *[ResidualBlock(num_hiddens, rngs=rngs) for _ in range(num_blocks)],
            nnx.Linear(num_hiddens, 10, kernel_init=normal, rngs=rngs))

由于上文不含 MXNet 检查点代码,本单元格定义了 5.1 节 中残差块的 Gluon 版本;模型的 initialize 从 \(\mathcal{N}(0, 0.01^2)\) 采样全部权重。

我们对比在 Fashion-MNIST 上设置 num_gpus=0 与 num_gpus=1 预热后单轮训练的耗时:

data = d2l.FashionMNIST(batch_size=256)

def epoch_time(num_gpus):
    model = ResMLPClassifier()
    trainer = d2l.Trainer(max_epochs=1, num_gpus=num_gpus)
    trainer.board.display = False
    trainer.fit(model, data)  # The first epoch warms up
    return Benchmark(trainer.fit_epoch, warmup=0, repeats=1).time

for gpus in (0, 1):
    print(f'num_gpus={gpus}: {epoch_time(num_gpus=gpus):.1f} sec per epoch')
num_gpus=0: 2.9 sec per epoch
num_gpus=1: 1.1 sec per epoch
data = d2l.FashionMNIST(batch_size=256)

def epoch_time(num_gpus):
    model = ResMLPClassifier()
    trainer = d2l.Trainer(max_epochs=1, num_gpus=num_gpus)
    trainer.board.display = False
    # TensorFlow runs operations on a GPU whenever there is one, and
    # num_gpus=0 only keeps the minibatches where they are: the CPU scope
    # keeps the whole run on the CPU
    with try_gpu() if num_gpus else cpu():
        trainer.fit(model, data)  # The first epoch warms up and compiles
        return Benchmark(trainer.fit_epoch, warmup=0, repeats=1).time

for gpus in (0, 1):
    print(f'num_gpus={gpus}: {epoch_time(num_gpus=gpus):.1f} sec per epoch')
num_gpus=0: 2.4 sec per epoch
num_gpus=1: 0.7 sec per epoch
data = d2l.FashionMNIST(batch_size=256)

def epoch_time(num_gpus):
    # JAX creates the parameters, and runs on the minibatches, on the default
    # device, the GPU whenever there is one: num_gpus=0 alone would not move
    # the run to the CPU, so we set the default device
    with jax.default_device(try_gpu() if num_gpus else cpu()):
        model = ResMLPClassifier()
        trainer = d2l.Trainer(max_epochs=1, num_gpus=num_gpus)
        trainer.board.display = False
        trainer.fit(model, data)  # The first epoch warms up and compiles
        return Benchmark(trainer.fit_epoch, warmup=0, repeats=1).time

for gpus in (0, 1):
    print(f'num_gpus={gpus}: {epoch_time(num_gpus=gpus):.1f} sec per epoch')
num_gpus=0: 1.3 sec per epoch
num_gpus=1: 0.7 sec per epoch
data = d2l.FashionMNIST(batch_size=256)

def epoch_time(num_gpus):
    model = ResMLPClassifier()
    trainer = d2l.Trainer(max_epochs=1, num_gpus=num_gpus)
    trainer.board.display = False
    trainer.fit(model, data)  # The first epoch warms up
    return Benchmark(trainer.fit_epoch, warmup=0, repeats=1).time

for gpus in (0, 1):
    print(f'num_gpus={gpus}: {epoch_time(num_gpus=gpus):.1f} sec per epoch')
num_gpus=0: 2.7 sec per epoch
num_gpus=1: 1.0 sec per epoch

这里的加速比是一次有益的现实检验:在这个微小的 Fashion-MNIST 网络上,GPU 单轮耗时至多只比 CPU 快几倍,远不及 \(4096 \times 4096\) 矩阵乘法上的 \(100\times\) 增益。这里最大的矩阵也不过 \(784 \times 256\),GPU 远远吃不饱,数据加载与内核启动开销主导了挂钟时间。只有当大型卷积、注意力头和宽线性层主导计算量时——正如从下一章开始那样——GPU 才会真正大显身手。

从显存角度看,这个小型 SGD 模型绰绰有余,还剩数 GB 空间。但回到我们的 80 亿参数模型:缩小批量大小和启用激活检查点虽然能驯服激活显存,却动不了 fp32 权重、梯度和 Adam 矩所占的 128 GB 静态下限,而且别忘了 Trainer 无法在触发 OOM 前提前预警。粗估显存预算依然必不可少,而突破单卡显存极限则将把我们带入 第 13 章 的多 GPU 并行训练。

5.7.5 小结

每个张量和模型参数都驻留在特定设备上,每次运算都要求所有操作数位于同一设备。由于主机与设备间的数据传输远慢于 GPU 计算,应当预先一次性放置模型、在单步边界传输小批量,并让内层循环全程留在设备端。GPU 从命令队列异步执行,这意味着 Python 仅在同步点(例如将标量转为 Python 浮点数或转换为 NumPy)才会停顿,而可靠的基准测试需要预热、显式同步和多次重复。训练显存由静态模型/优化器状态和依赖批量的激活值构成;激活检查点以大约多一次前向传播的代价,将激活显存从 \(O(K)\) 降至 \(O(\sqrt{K})\)。最后,设备感知的 Trainer 自动完成单 GPU 放置,并在无 GPU 时干净回退到 CPU。

5.7.6 练习

  1. [code] 峰值显存。参照 5.7.3.2 节,取一个宽度依次为 1024、4096、4096、4096、输出为 10 的四层 MLP,用 Adam 训练。利用该小节的核算方法,预测批量大小为 64、256 和 1024 时单步训练的峰值显存,计入权重、梯度、优化器状态以及反向传播保留的激活值。随后在 GPU 上实测峰值。预测在何处出现偏差,遗漏了哪些开销?

  2. 检查点算术。针对由十六个宽度 1024 的 ResidualBlock 组成的堆叠、批量大小 8192,在纸上推演 图 5.7.5 的调度方案。

    1. 列出单个块内部反向传播必须保留的数组,并统计其元素个数。
    2. 计算不启用检查点,以及按 1、2、4、8 块分段时,反向传播峰值持有的激活显存,并说明每种方案重复计算了多少前向工作量。
    3. 这里你会选择哪种分段大小?它与 5.7.3.3 节 中约 \(\sqrt{K}\) 层一段的法则有何关系?
  3. [code] 异步派发。● 以下两小问均遵循 5.7.2.1 节 的计时规则。

    1. 对从 256 到 8192 的 \(n\),分别计时一个 \(n \times n\) 矩阵在 CPU 与 GPU 间往返一次的耗时,以及在设备上执行一次 \(n \times n\) 矩阵乘法的耗时。找出两者耗时相等的 \(n\)(若在该范围内未相交,则按各自随 \(n\) 的增长规律外推)。根据你的 GPU 标称主机到设备带宽与矩阵乘法吞吐量预测这一交叉点,并解释预测与实测之间的差异。
    2. 如果你有两块 GPU,先计时在单块 GPU 上执行 1000 次 \(4096 \times 4096\) 矩阵乘法,再计时从同一循环向两块 GPU 各派发 500 次乘法。测量扩展比,解释异步派发如何让 Python 同时驱动两块设备,并指出偏离线性扩展的原因。用 num_gpus() >= 2 保护该实验。
  4. [code] 同步点。● 考察 5.7.4 节 中在 GPU 上训练 ResMLPClassifier 的过程。

    1. 阅读 Trainer.fit_epoch、Trainer.prepare_batch、Averager 及模型代码,列出单个训练步中的每一个同步点。将每处归类为保证循环正确所不可避免的同步,或可避免的观测开销,并说明理由。
    2. 假设循环在每一步结束后都将损失读入 Python 浮点数。根据你的清单预测这一读出操作会使默认 ResMLPClassifier 和 ResMLPClassifier(num_hiddens=2048, num_blocks=8) 变慢多少。随后分别计时两个模型开启与关闭该读出时的单轮耗时,并解释这四个数字。

    改编自 PyTorch 文档 CUDA semantics。

讨论