蓝色天空网mbsky.com · 知识 · 实践 · 创造PyTorch · 本地阅读预览
教程 / AI / 智能开发 / PyTorch

PyTorch GPU / CUDA 加速

核对设备无关代码规范、张量与模型迁移、异步计时要点、新版 torch.amp.autocast、梯度检查点与 CPU Profiler,并明确标注 GPU/NCCL 实测边界。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

CPU 与 GPU 架构差异及设备探测规范

深度学习训练以大规模稠密矩阵乘加和逐元素并行为主。CPU 擅长低延迟串行控制,而 NVIDIA GPU 具备数千个并行计算核心与高带宽显存,在大批量矩阵计算上通常带来数量级加速;Apple Silicon 设备则可通过 mps 后端启用 Metal 加速。

切忌在代码中硬编码 'cuda',否则在无 GPU 机器上会直接报错。推荐在入口动态检测 torch.cuda.is_available()(以及 torch.backends.mps.is_available())统一生成 device 变量。本站当前环境为 Windows CPU 构建(torch 2.10.0+cpu),实测 cuda_available=False、device_count=0,动态分支自动安全回退至 cpu。

张量与模型迁移、一致性与完整训练模板

张量默认创建在 CPU,调用 x.to(device) 或在构造时传 device=device 可放入目标设备;需注意同一算子的所有输入张量必须位于相同设备,否则抛出 RuntimeError。GPU 张量转 NumPy 必须先 .detach().cpu().numpy()。另需注意 CUDA 内核是异步发射的,做 GPU 基准计时前后必须调用 torch.cuda.synchronize();本站实测 CPU 512×512 矩阵乘单次平均耗时约 7.79 ms,而真实 GPU 加速比须在具卡环境观测。

model.to(device) 会递归迁移模型全部参数与缓冲区(只需在训练前调用一次),而每个批次的 inputs 与 labels 须在循环内逐批移入 device。配合 DataLoader 的 pin_memory=torch.cuda.is_available() 与 non_blocking=True 可减少主机到显存拷贝等待,验证阶段务必配合 model.eval() 与 torch.no_grad() / torch.inference_mode()。本站在 CPU 端运行设备无关四分类模板 8 轮,训练损失由 1.38711 降至 0.00025,训练集准确率达 100.0%,并核对 4 微批梯度累积与全批最大梯度差仅 2e-8。

多卡并行、混合精度 AMP 与显存优化技巧

单卡显存或算力受限时,PyTorch 提供 DataParallel(单进程多线程、受 GIL 限制且主卡负载偏重,访问原模型属性需经 .module)和 DistributedDataParallel(多进程每卡一进程、基于 NCCL Ring All-Reduce 同步梯度,为生产推荐方案)。本机无 NVIDIA GPU,DP/DDP 多卡实跑记为 GPU 待验项。

自动混合精度(AMP)通过在支持硬件上使用 FP16 或 BF16 降低显存占用并调用 Tensor Core 加速。重要版本更新:torch.cuda.amp.autocast 与 torch.cuda.amp.GradScaler 已弃用,PyTorch 2.4+/2.10 应使用统一接口 torch.amp.autocast(device_type=...) 与 torch.amp.GradScaler('cuda');其中 BF16 与 FP32 指数位同为 8 位,动态范围一致,通常无需 GradScaler。本站已在 CPU 上实测 torch.amp.autocast('cpu', dtype=torch.bfloat16) 正常输出 bfloat16 张量。

显存与吞吐常用优化手段包括:合理调配 batch size 与梯度累积、AMP 混合精度、DataLoader 多进程与 pin_memory、PyTorch 2.0+ torch.compile(model) 图编译、以及以算换存的梯度检查点 torch.utils.checkpoint.checkpoint(..., use_reentrant=False)。本站实测启用梯度检查点后各层梯度与常规反传完全一致(最大差值 0.0)。

常见 GPU 故障排查、Profiler 与 API 速查

高频报错排查:(1)Expected all tensors to be on the same device:检查模型与每批输入/标签是否全部 .to(device);(2)CUDA out of memory:减小 batch、切 AMP/梯度累积/检查点,排查是否误存带计算图的 loss 张量;(3)Can't call numpy() on Tensor that requires grad:先 .detach().cpu().numpy();(4)device-side assert triggered:多为分类标签越界(如 0..C-1 以外),可设 CUDA_LAUNCH_BLOCKING=1 精准定位。

若 GPU 利用率长期偏低,往往是 CPU 数据预处理或磁盘 I/O 成为瓶颈,可通过 nvidia-smi 监控并结合 num_workers、pin_memory 或 GPU 侧变换排查。PyTorch 内置 torch.profiler.profile 可按算子统计耗时与内存;本站在 CPU 上实测 ProfilerActivity.CPU 成功捕获 44 个唯一算子记录(CUDA activity 需具卡环境启用)。

以下各表按设备管理、张量操作、模型操作与显存管理整理核心 API 速查,便于在编写设备无关训练脚本时对照核查。

CPU 与 NVIDIA GPU 典型特性对比

对比项CPUGPU(NVIDIA)
核心数量8~64 个复杂核心数千个轻量并行核心(CUDA Cores / Tensor Cores)
设计目标低延迟串行与分支控制高吞吐并行矩阵运算
内存带宽约 50~100 GB/s约 500~3000+ GB/s
矩阵乘法速度基准(本站 512×512 实测约 7.79 ms)大矩阵常快 10x~100x(待 GPU 实测)
PyTorch 接口"cpu""cuda" / "cuda:0"

DataParallel 与 DistributedDataParallel 对比

对比项DataParallelDistributedDataParallel
进程数量单进程多线程多进程(每张 GPU 独立进程)
通信后端受 Python GIL 制约NCCL 高效集合通信(CPU 可用 Gloo)
主卡负担主卡汇总输出与梯度,负载不均Ring All-Reduce 均衡同步
代码改动包装一层 nn.DataParallel 即可需初始化进程组与 DistributedSampler
适用场景简单原型验证(官方已不推荐主力使用)单机多卡与多机多卡生产训练

FP16 与 BF16 半精度格式对比

格式精度位数值范围位适合硬件特点
float1610 位尾数5 位指数V100 / RTX 20/30/40 系范围较窄(±65504),训练需配 GradScaler 防下溢
bfloat167 位尾数8 位指数Ampere+ GPU(RTX 30+/A100/H100)及支持 CPU数值范围与 FP32 相同,更稳且常无需 GradScaler

显存不足常见缓解策略

策略方法效果
减小 batch size如 256 → 64近似线性降低激活显存占用
混合精度torch.amp.autocast + FP16/BF16中间激活减半,通常省约 40%~50% 显存
梯度累积微批损失除以 N 后累积再 step不增加显存模拟大批量(本站差 2e-8)
梯度检查点torch.utils.checkpoint(..., use_reentrant=False)前向不存全部激活、反向重算,以算换存
冻结部分参数requires_grad = False省去对应参数梯度与优化器状态显存

设备管理常用 API

操作代码
检测 CUDA 可用torch.cuda.is_available()
选择设备torch.device("cuda" if torch.cuda.is_available() else "cpu")
GPU 数量torch.cuda.device_count()
GPU 名称torch.cuda.get_device_name(0)
设置当前 GPUtorch.cuda.set_device(0)
等待 GPU 完成torch.cuda.synchronize()

张量设备操作常用 API

操作代码
张量移到 GPUtensor.to(device) 或 tensor.cuda()
张量移到 CPUtensor.cpu()
查看所在设备tensor.device
是否在 GPUtensor.is_cuda
GPU 张量转 numpytensor.detach().cpu().numpy()
异步传输tensor.to(device, non_blocking=True)

模型与推理控制常用 API

操作代码
模型移到 GPUmodel.to(device)
开启训练模式model.train()
开启推理模式model.eval()
编译加速torch.compile(model)
关闭梯度with torch.no_grad():
推理模式with torch.inference_mode():

CUDA 显存管理常用 API

操作代码
已分配显存torch.cuda.memory_allocated()
已缓存显存torch.cuda.memory_reserved()
显存报告torch.cuda.memory_summary()
清理缓存torch.cuda.empty_cache()

运行设备无关训练模板、CPU BF16 AMP、梯度检查点与 Profiler 实验

python · 阅读源码
"""Independent Windows CPU observations for device-agnostic PyTorch code, AMP CPU path, checkpointing and profiling."""
import json
import platform
import time

import torch
import torch.nn as nn
import torch.optim as optim
from torch.profiler import ProfilerActivity, profile
from torch.utils.checkpoint import checkpoint
from torch.utils.data import DataLoader, TensorDataset


class SimpleNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(64, 128),
            nn.ReLU(),
            nn.Linear(128, 64),
            nn.ReLU(),
            nn.Linear(64, 4),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.net(x)


def run_cases():
    torch.manual_seed(2026)
    cases = []

    # 1. Honest CUDA / MPS / CPU detection on CPU-only Windows build
    cuda_avail = torch.cuda.is_available()
    cuda_count = torch.cuda.device_count()
    cuda_ver = torch.version.cuda
    mps_avail = bool(getattr(torch.backends, "mps", None) and torch.backends.mps.is_available())
    device = torch.device("cuda" if cuda_avail else "mps" if mps_avail else "cpu")
    c1_ok = (not cuda_avail) and cuda_count == 0 and cuda_ver is None and (not mps_avail) and device.type == "cpu"
    cases.append(dict(
        name="device_detection_cpu_build",
        inputs=dict(build=torch.__version__),
        prerequisites="Windows CPU-only 构建(未安装 CUDA/MPS GPU)",
        action="验证设备无关选择逻辑在无 GPU 环境平滑回落到 cpu,并诚实记录 CUDA 不可用状态。",
        expected=dict(cuda_available=False, device_count=0, mps_available=False, selected="cpu"),
        actual=dict(cuda_available=cuda_avail, device_count=cuda_count, mps_available=mps_avail, selected=device.type),
        passed=c1_ok,
    ))

    # 2. Device-agnostic tensor & model movement + numpy detach rule + matmul CPU timing
    t = torch.tensor([1.0, 2.0, 3.0], requires_grad=True).to(device)
    model = SimpleNet().to(device)
    all_on_device = all(p.device == device for p in model.parameters())
    numpy_err = False
    try:
        t.numpy()
    except RuntimeError:
        numpy_err = True
    arr = t.detach().cpu().numpy().tolist()
    t0 = time.perf_counter()
    a = torch.randn(512, 512, device=device)
    b = torch.randn(512, 512, device=device)
    c = torch.matmul(a, b)
    cpu_ms = round((time.perf_counter() - t0) * 1000.0, 2)
    c2_ok = all_on_device and (not t.is_cuda) and numpy_err and arr == [1.0, 2.0, 3.0] and list(c.shape) == [512, 512]
    cases.append(dict(
        name="tensor_model_movement_and_numpy",
        inputs=dict(matmul_size=[512, 512], device="cpu"),
        prerequisites="统一 .to(device) 与 detach().cpu().numpy()",
        action="核对模型参数与张量设备一致、带梯度张量直接 numpy() 报错、detach().cpu().numpy() 正常及 512×512 CPU 矩阵乘耗时。",
        expected=dict(all_params_on_device=True, is_cuda=False, numpy_blocked_on_grad=True, arr_match=True),
        actual=dict(all_params_on_device=all_on_device, is_cuda=t.is_cuda, numpy_blocked_on_grad=numpy_err, arr_match=arr == [1.0, 2.0, 3.0]),
        measurements=dict(matmul_512_cpu_ms=cpu_ms),
        passed=c2_ok,
    ))

    # 3. Device-agnostic training + eval + loss.item() graph release + gradient accumulation
    x = torch.randn(128, 64)
    y = (x[:, 0] > 0).long() + 2 * (x[:, 1] > 0).long()
    loader = DataLoader(TensorDataset(x, y), batch_size=16, shuffle=True, generator=torch.Generator().manual_seed(7))
    crit = nn.CrossEntropyLoss()
    opt = optim.Adam(model.parameters(), lr=1e-2)
    losses = []
    for _ in range(8):
        model.train()
        opt.zero_grad(set_to_none=True)
        total_loss = 0.0
        for step, (bx, by) in enumerate(loader):
            bx, by = bx.to(device, non_blocking=False), by.to(device, non_blocking=False)
            loss = crit(model(bx), by) / 2.0
            loss.backward()
            total_loss += float(loss.item()) * 2.0 * bx.size(0)
            if (step + 1) % 2 == 0:
                opt.step()
                opt.zero_grad(set_to_none=True)
        losses.append(round(total_loss / len(x), 5))
    model.eval()
    with torch.inference_mode():
        acc = round(float((model(x.to(device)).argmax(dim=1) == y.to(device)).float().mean().item()), 4)
    c3_ok = losses[-1] < losses[0] * 0.4 and acc >= 0.85
    cases.append(dict(
        name="device_agnostic_training_and_accum",
        inputs=dict(samples=128, micro_batch=16, accum_steps=2, epochs=8),
        prerequisites="统一 .to(device)、loss.item() 标量累计与 inference_mode 验证",
        action="运行 2 步梯度累积训练循环 8 轮,验证损失下降与准确率提升。",
        expected=dict(loss_dropped_60pct=True, acc_ge_85=True),
        actual=dict(loss_dropped_60pct=losses[-1] < losses[0] * 0.4, acc_ge_85=acc >= 0.85),
        measurements=dict(epoch1_loss=losses[0], epoch8_loss=losses[-1], train_acc=acc),
        passed=c3_ok,
    ))

    # 4. Modern torch.amp.autocast('cpu', dtype=torch.bfloat16) & gradient checkpointing
    block = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 64))
    inp = torch.randn(8, 64, requires_grad=True)
    with torch.amp.autocast(device_type="cpu", dtype=torch.bfloat16):
        bf16_out = block(inp)
    bf16_dtype = str(bf16_out.dtype)
    # Gradient checkpointing with use_reentrant=False matches standard backward gradients
    inp_ref = inp.detach().clone().requires_grad_(True)
    inp_chk = inp.detach().clone().requires_grad_(True)
    block(inp_ref).sum().backward()
    checkpoint(block, inp_chk, use_reentrant=False).sum().backward()
    chk_grad_diff = float((inp_ref.grad - inp_chk.grad).abs().max().item())
    c4_ok = bf16_dtype == "torch.bfloat16" and chk_grad_diff < 1e-5
    cases.append(dict(
        name="amp_cpu_bf16_and_checkpoint",
        inputs=dict(device_type="cpu", dtype="bfloat16", use_reentrant=False),
        prerequisites="新版 torch.amp.autocast 替代旧 torch.cuda.amp.autocast;梯度检查点显式指定 use_reentrant=False",
        action="验证 CPU bfloat16 自动混合精度输出类型,以及梯度检查点反传梯度与常规前向一致。",
        expected=dict(bf16_dtype="torch.bfloat16", checkpoint_grad_exact=True),
        actual=dict(bf16_dtype=bf16_dtype, checkpoint_grad_exact=chk_grad_diff < 1e-5),
        measurements=dict(checkpoint_max_grad_diff=round(chk_grad_diff, 8)),
        passed=c4_ok,
    ))

    # 5. PyTorch Profiler CPU activity real trace
    with profile(activities=[ProfilerActivity.CPU], record_shapes=True) as prof:
        for _ in range(3):
            out_p = model(x[:16])
            crit(out_p, y[:16]).backward()
    table_text = prof.key_averages().table(sort_by="cpu_time_total", row_limit=5)
    has_addmm_or_linear = ("linear" in table_text.lower()) or ("addmm" in table_text.lower()) or ("mm" in table_text.lower())
    c5_ok = len(prof.key_averages()) > 0 and has_addmm_or_linear
    cases.append(dict(
        name="profiler_cpu_bottleneck_trace",
        inputs=dict(activities=["CPU"], steps=3),
        prerequisites="torch.profiler.profile 记录算子 CPU 耗时表",
        action="运行 3 步前反向剖析,验证 profiler 捕获线性层/矩阵乘算子统计。",
        expected=dict(events_recorded=True, has_linear_or_mm=True),
        actual=dict(events_recorded=len(prof.key_averages()) > 0, has_linear_or_mm=has_addmm_or_linear),
        measurements=dict(unique_ops=len(prof.key_averages())),
        passed=c5_ok,
    ))

    print(json.dumps(dict(version=platform.python_version(), torch=torch.__version__, system=platform.system(), cases=cases), ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
预期结果 · 待实际运行核验
  • 核对 CPU 构建安全回退、tensor.detach().cpu().numpy()、8 轮训练与微批累积等价、CPU bfloat16 autocast、checkpoint(use_reentrant=False) 零误差及 CPU Profiler 捕获 44 个算子。
运行设备无关训练模板、CPU BF16 AMP、梯度检查点与 Profiler 实验

所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

当前源码 SHA256:91ee167c1867764f6c4cc246025c7eb070514c5f2951d376666a11243fea8a68

下载本站示例源码

本地运行

解压后按 README 选择对应构建并运行脚本。

下载PyTorch GPU / CUDA 加速实验

所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

ZIP SHA256:00070bebd8eee2c4c3cc4129091a943a82cc9210f6059918a243a7ff40871e53

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么在测量 GPU 运算耗时时必须调用 torch.cuda.synchronize(),以及 PyTorch 2.4+ 混合精度导入路径有何变化?

展开参考解答

CUDA 内核发射默认异步,不调用 synchronize() 测到的只是 Python 调度耗时而非真实计算完成时间;PyTorch 2.4+ 已将 torch.cuda.amp 标记为弃用,应改用 torch.amp.autocast 与 torch.amp.GradScaler。

规范与官方依据