GPU、设备与显存

Dive into Deep Learning · §5.7

GPU、设备与显存预算
设备放置 · PCIe 拷贝瓶颈 · 异步命令队列 · 三层显存视图 · O(\sqrt{K}) 激活检查点

为何设备放置与显存预算决定模型规模

硬件吞吐量对比 HBM 容量

  • 独立板载显存(HBM):8B 模型做 bf16 推理(16 GB 权重)可轻松装入 24 GB GPU,但 fp32 Adam 训练在存放任何激活值前就需要 128 GB 静态状态。
  • 同设备约束:跨设备 PCIe 传输比矩阵乘法慢 3\text{--}6\times;所有输入、权重与缓冲区都必须驻留在同一设备上。
  • 异步命令队列:Python 将 GPU 内核入队后立即返回;每步向主机读出标量都会阻塞流水线。

查询硬件设备并优雅回退到 CPU

设备抽象

每个张量都驻留在特定设备上(cpu()、gpu(i))。我们的 try_gpu(i) 辅助函数在 GPU i 可用时选择它,否则干净地回退到 CPU,使笔记本在任何机器上都无需修改即可运行:

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)])

运算拒绝跨设备操作数

杜绝静默跨设备拷贝

  • 将 X 放在 GPU 0、将 Y 放在 GPU 1(或 CPU)并计算 X + Y 会立即触发运行时错误,防止隐式 PCIe 拷贝拖垮训练循环:
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

显式设备传输:在边界拷贝一次

在设备间移动张量

要组合来自不同设备的张量,先将 X 显式拷贝到 Y 的设备上:

Z = X.to(try_gpu(1))
(Y + Z).device
device(type='cuda', index=1)
  • 传输纪律:在循环边界一次性移动数据,并让内层循环的每步运算都留在单个设备上。

将整棵模型树放置到目标设备

参数与输入同驻一处

  • 在构造优化器之前将模型移动或初始化到目标 GPU 上(使 Adam 矩估计分配在 GPU 上),并在 forward 内部将新张量分配在 X.device 上:
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>)

异步 GPU 执行:命令队列

Python 如何驱动 GPU

Python 不会等待 B = A @ A 算完:它将内核启动压入 GPU 的执行队列后便继续向下运行:

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
  • 入队对比计算:在 CPU 上入队 32 次 4096 \times 4096 矩阵乘法只需几毫秒,而 GPU 排空队列需要几十毫秒。

同步点会阻塞 CPU–GPU 流水线

切勿打断流水线

  • 什么触发同步停顿:调用 loss.item()、float(loss)、print(tensor)、.numpy() 或按张量值分支(if loss < best:)会迫使 CPU 阻塞直到 GPU 完成所有已入队工作,在 Python 赶上之前让 GPU 闲置。
  • 系统最佳实践:在设备端张量中累加每步损失,每轮结束时才转换为 Python 浮点数一次。

准确评测 GPU 基准的四条规则

异步内核计时

  • 预热 + 双端同步:先跑预热迭代,启动 perf_counter() 前同步一次,停止计时前再同步一次。

遵循规则的 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'

4096×4096 矩阵乘法对比 PCIe 主机到设备拷贝

计算吞吐量对比内存带宽

分别计时 CPU(fp32)和 GPU(tf32 与 16 位)上的 4096 \times 4096 矩阵乘法,以及 CPU 到 GPU 拷贝,揭示深度学习的根本硬件瓶颈:

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
  • GPU 计算快 100\text{--}1000\times:Tensor Core 在 2 ms 内完成 4096^3 \approx 6.9 \times 10^{10} 次乘加(16 位精度还能再减半)。
  • PCIe 拷贝比矩阵乘法慢 3\text{--}6\times:通过 PCIe 拷贝 4096^2 \times 4\text{ B} = 64\text{ MiB} 耗时,竟超过数据到达 GPU 后对每个元素执行 4096 次乘加的总耗时。

GPU 显存的三层嵌套视图

存活张量对比缓存分配器对比 CUDA 驱动

询问一个进程占用多少 GPU 显存,查询内存层次的不同层面会得到三个不同答案:

after creating big:  1192.1 MiB allocated,  1302.0 MiB reserved
after deleting it :   168.1 MiB allocated,  1302.0 MiB reserved
  • 为何 del big 后 nvidia-smi 不变:框架使用缓存分配器,将释放的 GPU 显存块保留在显存池中以便立即复用,避免缓慢的 CUDA 驱动调用。

解剖单个训练步中的显存变化

权重 + 激活值 + 梯度 + 优化器矩

追踪 3 隐藏层 MLP(1024 \to 4096 \to 4096 \to 4096 \to 10,4N \approx 144\text{ MiB} 权重,批量大小 B = 4096)单步训练的存活 GPU 显存,可见四项显存如何依次登场:

weights              160.2 MiB
+ activations        353.4 MiB
+ gradients          313.6 MiB
+ optimizer state    602.0 MiB
  • 激活值超过权重(+192\text{ MiB}):三个 4096 \times 4096 隐藏输出(3 \times 64\text{ MiB} = 192\text{ MiB})在 forward 期间驻留显存,并在 backward 期间随梯度(+144\text{ MiB})与 Adam 矩(+288\text{ MiB})物化而释放。

8B 模型能装入 24 GB 还是 80 GB GPU?

静态显存预算对比动态显存预算

  • 推理(bf16 占 16 GB 对比 fp32 占 32 GB):bf16 可装入单张 24 GB GPU,剩余 8 GB 留给 KV 缓存与激活值。
  • 训练(仅调输出头 38.3 GB 对比全量 fp32 Adam 128 GB):仅微调输出头可装入单张 80 GB GPU;全量 fp32 Adam 需 \ge 2 张 GPU。
  • 激活值 OOM(O(K \cdot B \cdot T \cdot d)):先将微批量大小 B 减半,再开启激活检查点。

激活检查点:多一次前向换取 O(√K) 显存

以计算换激活显存

激活检查点(Chen et al., 2016)仅保存分段边界,其余在 backward 期间重算:

  • 峰值激活值从 O(K) \to O(\sqrt{K}):将 K 层按每段 s 层切分,只保留 K/s 个边界张量加 s 个活动段内部张量(共 K/s + s 个,在 s = \sqrt{K} 时取最小值 2\sqrt{K})。
  • 有界计算开销:重算每段多出一次前向传播(单步耗时约增加 20\text{--}30\%)。

实现逐分段激活检查点

为残差块堆叠设置检查点

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
  • 将 ResidualBlock 模块按 segment_size = 4 分组并用框架检查点包装器包裹每段,即可在 O(\sqrt{K}) 显存内算出精确梯度。

检查点梯度与普通反向传播一致

为残差块堆叠设置检查点

  • 重算激活值绝不能改变数学结果:在拆为两段的八块堆叠上,每个梯度都与标准反向传播一致:
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

实测:耗时多 ~25%,单步显存降幅超 50%

GPU 上的 16 个残差块

在 16 块残差堆叠(d = 1024,批量大小 B = 8192,每四块一段)上,激活检查点将峰值单步显存从 \sim 1.1\text{ GiB} 压低至 \sim 0.45\text{--}0.5\text{ GiB}:

checkpointing=False  step memory  1096 MiB,  25.5 ms per step
checkpointing=True   step memory   452 MiB,  32.3 ms per step

将自动设备放置接入 d2l.Trainer

设备感知的 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')

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

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.Trainer 在 prepare_model 中将模型移至 self.gpus[0],在 prepare_batch 中移动每个小批量,无 GPU 时回退到 CPU。

在 CPU 与 GPU 上计时设备感知 Trainer

设备感知的 Trainer

num_gpus=0: 2.9 sec per epoch
num_gpus=1: 1.1 sec per epoch
  • 为何小模型的 GPU 加速有限:在 256 宽 Fashion-MNIST MLP 上,矩阵至多 784 \times 256,数据加载与 Python 内核启动延迟占主导;待宽层、卷积与注意力主导计算后,GPU 才释放 100\times 加速。

概念自测:异步队列与激活显存

概念自测

用以下三个场景检验你的系统直觉:

  1. 某训练循环在 GPU 上每个小批量步骤都执行 if loss < best_loss: best_loss = loss。为何这短短一句 if 会损害 GPU 利用率,应当如何改写?
  2. 一个深层 Transformer 堆叠了 K = 36 个相同块。不启用检查点(s = 36)、每块设检查点(s = 1)以及取最优分段大小 s = \sqrt{36} = 6 时,反向传播峰值各需保留多少个块输入激活张量?
  3. 删除一个 2 GiB GPU 张量后,框架的已分配显存计数器下降了 2 GiB,但 nvidia-smi 毫无变化。原因何在?

答案:

  1. 求值 Python bool(loss < best_loss)会在每一步强制 CPU–GPU 同步,排空命令队列。修复方案:在设备端更新 best_loss = minimum(best_loss, loss),每轮仅读回主机一次。
  2. 峰值保存的块激活数(K/s + s):不设检查点保留 36 个;s = 1 保留 36/1 + 1 = 37 个;最优 s = 6 仅保留 36/6 + 6 = 12 个(降幅 3\times)。
  3. 缓存分配器将释放的显存块保留在显存池中以备后续张量复用,不归还给 CUDA 驱动(nvidia-smi)。

小结:GPU、设备与显存预算

核心要点

  • 同驻与异步队列:构造优化器前先将模型移至 GPU,在边界一次性传输小批量,避免每步主机同步停顿。
  • 基准测试与显存视图:GPU 计时务必预热并双端同步;区分存活已分配字节、缓存分配器显存池与 nvidia-smi。
  • 激活检查点:将 K 层按 s = \sqrt{K} 分段,以约 \sim 25\text{--}33\% 额外计算将激活显存从 O(K) 降至 O(\sqrt{K})。