PyTorch从入门到熟悉 · 第11/20篇

GPU加速:CUDA编程与设备管理

从设备迁移到自定义CUDA核函数,全面掌握PyTorch GPU加速的核心技术与性能优化策略。

生成日期:2026年11月6日 · 面向大模型开发 · 返回目录

GPU是深度学习的基石。理解PyTorch如何管理GPU设备、如何利用CUDA加速计算、以及如何编写自定义CUDA扩展,是构建高效大模型训练流水线的关键技能。本章将从基础的设备管理出发,逐步深入到多GPU并行、CUDA内存管理、GPU监控,最后覆盖自定义CUDA核函数编写与性能优化。

前置条件

阅读本章前,请确保你已安装CUDA Toolkit和匹配的NVIDIA驱动,并且PyTorch能够检测到GPU。运行 torch.cuda.is_available() 返回 True 是基本前提。

一、设备管理基础

1.1 torch.device 对象

在PyTorch中,torch.device 是描述张量所在计算设备的抽象对象。它可以指向CPU或某块特定的GPU。正确使用设备对象是避免"设备不匹配"错误的第一步。

Python
import torch

# 创建设备对象
device_cpu = torch.device('cpu')
device_cuda = torch.device('cuda')       # 默认GPU(cuda:0)
device_gpu1 = torch.device('cuda:1')     # 第二块GPU

# 检查CUDA是否可用
print(torch.cuda.is_available())        # True
print(torch.cuda.device_count())         # GPU数量
print(torch.cuda.get_device_name(0))    # GPU型号名称
print(torch.cuda.current_device())       # 当前默认设备索引

1.2 张量的设备迁移

张量创建时默认位于CPU上。使用 .to()、.cuda() 或 .cpu() 方法可以将张量迁移到目标设备。.to() 是最推荐的方式,因为它可以同时处理设备和数据类型转换。

Python
# 在CPU上创建张量
x = torch.randn(1000, 1000)

# 方式一:.to() —— 推荐
x_gpu = x.to(device_cuda)           # 迁移到GPU
x_gpu = x.to('cuda')               # 字符串也行
x_gpu = x.to('cuda:0', dtype=torch.float16)  # 同时转设备和类型

# 方式二:.cuda() / .cpu()
x_gpu = x.cuda()                   # 迁移到默认GPU
x_gpu = x.cuda(1)                 # 迁移到cuda:1
x_cpu = x_gpu.cpu()                # 迁回CPU

# 直接在GPU上创建
y = torch.randn(1000, 1000, device=device_cuda)
z = torch.zeros(500, device='cuda')
常见陷阱:跨设备运算

两个位于不同设备的张量不能直接运算,会抛出 RuntimeError: Expected all tensors to be on the same device。务必确保参与运算的所有张量在同一设备上。

1.3 模型的设备迁移

模型迁移到GPU与张量类似,使用 model.to(device)。迁移后,模型的所有参数和缓冲区都会移到目标设备。但输入数据需要手动迁移到同一设备。

Python
import torch.nn as nn

model = nn.Linear(784, 10)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# 模型迁移到GPU
model = model.to(device)

# 训练时输入也必须在同一设备
for x_batch, y_batch in dataloader:
    x_batch = x_batch.to(device)   # 关键!
    y_batch = y_batch.to(device)
    pred = model(x_batch)          # 在GPU上计算
    loss = criterion(pred, y_batch)
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()

1.4 设备上下文管理器

使用 torch.cuda.device(n) 上下文管理器可以临时切换默认GPU设备,退出后恢复原设备。这在多GPU场景中很有用。

Python
# 临时使用cuda:1作为默认设备
with torch.cuda.device(1):
    a = torch.randn(100)           # 创建在cuda:1上
    b = torch.randn(100)           # 也创建在cuda:1上
    c = a + b                     # 运算在cuda:1上

# 退出后恢复原默认设备
d = torch.randn(100)               # 创建在cuda:0上(默认)

二、多GPU并行策略

2.1 检测与管理多GPU

在多GPU系统上,PyTorch提供了多种方式来检测和利用多块GPU。理解GPU拓扑和显存分布对于选择并行策略至关重要。

Python
# 获取GPU数量
n_gpus = torch.cuda.device_count()
print(f"检测到 {n_gpus} 块GPU")

# 遍历所有GPU的信息
for i in range(n_gpus):
    print(f"GPU {i}: {torch.cuda.get_device_name(i)}")
    print(f"  总显存: {torch.cuda.get_device_properties(i).total_memory / 1e9:.1f} GB")

# 设置可见GPU(等价于CUDA_VISIBLE_DEVICES环境变量)
# 必须在所有CUDA操作之前调用
# torch.cuda.set_device(0)  # 设置默认GPU

2.2 DataParallel (DP)

DataParallel 是最简单的多GPU并行方式,只需一行代码包装模型。它采用单进程多线程模式,将输入数据按维度0分割到各GPU上分别计算,然后汇总梯度。但由于GIL限制和主GPU瓶颈,性能通常不如DDP。

Python
model = MyModel()
# 一行代码实现多GPU数据并行
model = nn.DataParallel(model, device_ids=[0, 1, 2, 3])
model = model.to('cuda')

# 使用方式与单GPU完全相同
output = model(input_data)

2.3 DistributedDataParallel (DDP)

DistributedDataParallel 是推荐的多GPU并行方式。它采用多进程模式,每个GPU对应一个独立进程,避免了GIL瓶颈。DDP通过梯度all-reduce实现参数同步,性能远优于DP。

Python
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP

# 初始化进程组
dist.init_process_group(backend='nccl')
local_rank = dist.get_rank()
torch.cuda.set_device(local_rank)

# 每个进程创建模型并迁移到对应GPU
model = MyModel().to(local_rank)
model = DDP(model, device_ids=[local_rank])

# 使用DistributedSampler分配数据
sampler = torch.utils.data.distributed.DistributedSampler(dataset)
dataloader = DataLoader(dataset, batch_size=32, sampler=sampler)
特性DataParallel (DP)DistributedDataParallel (DDP)
进程模型单进程多线程多进程,每GPU一个
通信方式主GPU广播梯度All-Reduce
受GIL限制是否
多机支持不支持支持
推荐程度不推荐(已过时)强烈推荐
启动方式直接Python运行torchrun / mp.spawn

三、CUDA内存管理

3.1 显存分配机制

PyTorch使用缓存分配器(caching allocator)管理GPU显存。当张量被释放时,显存不会立即归还给CUDA驱动,而是缓存在PyTorch内部,供后续分配重用。这大大减少了向CUDA驱动申请显存的开销,但也意味着 nvidia-smi 显示的显存占用可能高于实际使用量。

Python
# 当前已分配显存(字节)
print(torch.cuda.memory_allocated())        # PyTorch张量占用的
print(torch.cuda.memory_reserved())          # 缓存分配器预留的
print(torch.cuda.max_memory_allocated())     # 峰值已分配
print(torch.cuda.max_memory_reserved())       # 峰值预留

# 以GB为单位更直观
print(f"已分配: {torch.cuda.memory_allocated() / 1e9:.2f} GB")
print(f"已预留: {torch.cuda.memory_reserved() / 1e9:.2f} GB")

3.2 显存清理与回收

当显存碎片化严重或需要释放缓存时,可以使用 empty_cache()。但注意这只会将未使用的缓存归还给CUDA驱动,不会释放正在使用的张量。

Python
# 模拟一些显存使用
x = torch.randn(10000, 10000, device='cuda')
del x  # 删除张量引用

# 释放缓存分配器中未使用的显存
torch.cuda.empty_cache()

# 查看释放后的显存
print(f"预留显存: {torch.cuda.memory_reserved() / 1e9:.2f} GB")

3.3>OOM(显存不足)处理策略

OOM是GPU训练中最常见的错误之一。以下是系统性的排查和处理方法:

Python
try:
    output = model(large_input)
    loss = criterion(output, target)
    loss.backward()
except RuntimeError as e:
    if 'out of memory' in str(e):
        print("OOM! 尝试恢复...")
        torch.cuda.empty_cache()
        # 减小batch size重试
        # 或使用梯度累积
        # 或启用混合精度训练
    else:
        raise e
OOM常见原因
  • Batch size过大——减小batch size或使用梯度累积
  • 中间结果未释放——使用 torch.no_grad() 包裹推理代码
  • 梯度累积过多——定期 optimizer.zero_grad()
  • 模型过大——使用FSDP或模型并行
  • 数据未释放——检查是否有循环引用导致张量未回收

3.4 内存碎片化分析

显存碎片化会导致虽然总空闲显存足够,但无法分配连续的大块显存。PyTorch提供了内存快照工具来分析碎片化情况。

Python
# 获取内存快照(PyTorch 2.0+)
snapshot = torch.cuda.memory_snapshot()
print(f"分配段数: {len(snapshot)}")

# 设置内存分配器统计
torch.cuda.memory._set_allocator_settings("expandable_segments:True")
# expandable_segments可以减少碎片化

# 获取详细内存信息
free, total = torch.cuda.mem_get_info()
print(f"空闲: {free / 1e9:.2f} GB, 总计: {total / 1e9:.2f} GB")

四、GPU监控与诊断

4.1 nvidia-smi 集成

nvidia-smi 是NVIDIA提供的GPU监控工具,可以查看显存使用、GPU利用率、温度等信息。在Python中可以通过subprocess调用。

Python
import subprocess

# 获取nvidia-smi输出
result = subprocess.run(['nvidia-smi', '--query-gpu',
    'index,name,memory.used,memory.total,utilization.gpu,temperature.gpu',
    '--format=csv,noheader,nounits'], capture_output=True, text=True)

for line in result.stdout.strip().split('\n'):
    idx, name, mem_used, mem_total, util, temp = line.split(', ')
    print(f"GPU {idx} ({name}): {mem_used}/{mem_total}MB, {util}% util, {temp}°C")

4.2 PyTorch内置监控

PyTorch提供了丰富的GPU监控API,可以在训练过程中实时获取显存和计算信息。

Python
# 训练过程中的监控装饰器
def monitor_gpu(func):
    def wrapper(*args, **kwargs):
        torch.cuda.reset_peak_memory_stats()
        torch.cuda.synchronize()
        
        result = func(*args, **kwargs)
        
        torch.cuda.synchronize()
        peak_mem = torch.cuda.max_memory_allocated() / 1e9
        print(f"峰值显存: {peak_mem:.2f} GB")
        return result
    return wrapper

@monitor_gpu
def train_epoch(model, dataloader):
    for x, y in dataloader:
        loss = model(x)
        loss.backward()

4.3 mem_get_info 详解

torch.cuda.mem_get_info() 返回当前GPU的空闲和总显存,是运行时监控最直接的方式。

Python
# 查看指定GPU的显存信息
for i in range(torch.cuda.device_count()):
    free, total = torch.cuda.mem_get_info(i)
    used = total - free
    print(f"GPU {i}: {used/1e9:.1f}/{total/1e9:.1f} GB "
          f"({used/total*100:.1f}%)")

五、CUDA编程基础

5.1 CUDA执行模型

CUDA采用SIMT(Single Instruction, Multiple Threads)执行模型。GPU由多个流多处理器(SM)组成,每个SM包含多个CUDA核心。理解线程层次结构是编写高效CUDA代码的基础。

GPU架构与CUDA线程层次 Grid(网格)— 所有线程的集合 Block (0,0) Block (1,0) Block (0,1) Block (1,1) ... Thread(0,0) Thread(1,0) Thread(0,1) ... 流多处理器(SM)—9216个CUDA核心 SM 0 Warp 0 (32线程) Warp 1 (32线程) 共享内存/L1缓存 寄存器文件 SM 1 Warp 0 (32线程) Warp 1 (32线程) 共享内存/L1缓存 寄存器文件 SM 2 Warp 0 (32线程) Warp 1 (32线程) 共享内存/L1缓存 寄存器文件 ... SM N

5.2 线程层次:Grid、Block、Thread

CUDA的线程组织为三层结构:Grid包含多个Block,Block包含多个Thread。每个线程有唯一的索引,通过 threadIdx、blockIdx、blockDim 和 gridDim 来定位。

层次变量说明典型大小
ThreadthreadIdx块内线程索引最多1024
BlockblockIdx, blockDim网格内块索引和块大小数百~数千
GridgridDim网格维度(总块数)由数据量决定
Warp—32个线程为一组执行固定32

5.3 共享内存

共享内存是每个线程块内的高速片上内存,延迟远低于全局内存。合理使用共享内存可以显著提升CUDA核函数性能。典型用途包括矩阵分块计算和前缀扫描。

CUDA C++
// 矩阵乘法中使用共享内存分块
__global__ void matmul_kernel(
    const float* A, const float* B, float* C,
    int N) {
    
    // 声明共享内存
    __shared__ float s_A[16][16];
    __shared__ float s_B[16][16];
    
    int tx = threadIdx.x;
    int ty = threadIdx.y;
    int row = blockIdx.y * 16 + ty;
    int col = blockIdx.x * 16 + tx;
    
    float sum = 0.0f;
    
    for (int ph = 0; ph < (N + 15) / 16; ph++) {
        // 加载数据到共享内存
        s_A[ty][tx] = (row < N && ph*16+tx < N) 
            ? A[row*N + ph*16+tx] : 0.0f;
        s_B[ty][tx] = (col < N && ph*16+ty < N) 
            ? B[(ph*16+ty)*N + col] : 0.0f;
        __syncthreads();  // 块内同步
        
        // 在共享内存中计算
        for (int k = 0; k < 16; k++) {
            sum += s_A[ty][k] * s_B[k][tx];
        }
        __syncthreads();
    }
    
    if (row < N && col < N) {
        C[row * N + col] = sum;
    }
}

六、自定义CUDA扩展

6.1 cpp_extension 模块

PyTorch提供了 torch.utils.cpp_extension 模块,允许用C++/CUDA编写自定义算子并编译为PyTorch扩展。这对于实现PyTorch原生不支持的高性能操作非常有用。

6.2 load_inline 快速编写CUDA kernel

load_inline 可以直接在Python代码中内联C++/CUDA代码并即时编译,无需单独的源文件。适合快速原型验证。

Python
from torch.utils.cpp_extension import load_inline

# CUDA核函数定义
cuda_source = """
__global__ void vector_add_kernel(const float* a, const float* b, 
                                   float* c, int n) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < n) {
        c[idx] = a[idx] + b[idx];
    }
}

torch::Tensor vector_add_cuda(torch::Tensor a, torch::Tensor b) {
    int n = a.size(0);
    auto c = torch::zeros_like(a);
    
    int threads = 256;
    int blocks = (n + threads - 1) / threads;
    
    vector_add_kernel<<>>(
        a.data_ptr(), b.data_ptr(), 
        c.data_ptr(), n
    );
    
    return c;
}
"""

cpp_source = """
torch::Tensor vector_add(torch::Tensor a, torch::Tensor b);
"""

# 编译并加载扩展
ext = load_inline(
    name='vector_add_ext',
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=['vector_add'],
    extra_cuda_cflags=['-O2']
)

# 使用自定义CUDA算子
a = torch.randn(1000000, device='cuda')
b = torch.randn(1000000, device='cuda')
c = ext.vector_add(a, b)  # 调用自定义CUDA核函数

6.3 带自动求导的CUDA扩展

要让自定义CUDA算子支持自动求导,需要分别实现前向和反向核函数,并通过 torch::autograd::Function 包装。

CUDA C++
// 自定义ReLU的前向和反向
__global__ void custom_relu_fwd(const float* x, float* y, int n) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < n) y[idx] = x[idx] > 0 ? x[idx] : 0;
}

__global__ void custom_relu_bwd(const float* x, const float* grad_y,
                                   float* grad_x, int n) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < n) grad_x[idx] = x[idx] > 0 ? grad_y[idx] : 0;
}

6.4 JIT编译与AOT编译

load_inline 使用JIT(即时编译),首次调用时编译,结果缓存。对于生产环境,推荐使用AOT(提前编译)通过 setup.py 预编译扩展,避免运行时编译延迟。

Python
# setup.py — AOT编译方式
from setuptools import setup
from torch.utils.cpp_extension import CUDAExtension, BuildExtension

setup(
    name='my_cuda_ext',
    ext_modules=[
        CUDAExtension(
            name='my_cuda_ext',
            sources=['my_ext.cpp', 'my_ext_kernel.cu'],
            extra_cuda_cflags=['-O2'],
        )
    ],
    cmdclass={'build_ext': BuildExtension}
)
# 运行: python setup.py install

七、性能考量与优化

7.1 数据传输开销(H2D/D2H)

CPU和GPU之间的数据传输(Host-to-Device和Device-to-Host)通过PCIe总线进行,带宽远低于GPU内部显存带宽。减少不必要的数据传输是GPU优化的首要原则。

Python
import time

# 测量H2D传输时间
data = torch.randn(10000, 10000)  # ~400MB on CPU

torch.cuda.synchronize()
t0 = time.time()
data_gpu = data.to('cuda')       # H2D传输
torch.cuda.synchronize()
t1 = time.time()
print(f"H2D传输: {(t1-t0)*1000:.1f} ms")

# 测量D2H传输时间
torch.cuda.synchronize()
t0 = time.time()
data_cpu = data_gpu.to('cpu')     # D2H传输
torch.cuda.synchronize()
t1 = time.time()
print(f"D2H传输: {(t1-t0)*1000:.1f} ms")

7.2 使用非阻塞传输优化

使用 pin_memory 的DataLoader和 non_blocking=True 可以实现异步数据传输,让数据传输与计算重叠。

Python
# DataLoader使用pin_memory加速H2D传输
dataloader = DataLoader(
    dataset, batch_size=64, 
    pin_memory=True,        # 锁页内存
    num_workers=4            # 多进程加载
)

# 训练循环中使用non_blocking
for x, y in dataloader:
    # 异步传输,与上一个batch的计算重叠
    x = x.to('cuda', non_blocking=True)
    y = y.to('cuda', non_blocking=True)
    loss = model(x)
    loss.backward()

7.3 Kernel Launch开销

每个CUDA核函数的启动都有一定开销(约5-10微秒)。对于大量小操作,kernel launch开销可能成为瓶颈。解决方案包括使用CUDA Graph、操作融合和减少不必要的同步。

Python
# 使用CUDA Graph减少kernel launch开销
# 适合固定计算图的重复执行
torch.cuda.synchronize()

# 捕获计算图
g = torch.cuda.CUDAGraph()
with torch.cuda.graph(g):
    output = model(static_input)

# 重放计算图(只需一次kernel launch)
for _ in range(1000):
    static_input.copy_(new_input)  # 更新输入
    g.replay()                      # 重放图
    result = output.clone()         # 获取结果

7.4 内存合并访问

当同一warp中的线程访问连续的内存地址时,GPU可以将这些访问合并为一次事务。非合并访问会导致显存带宽利用率大幅下降。在编写自定义CUDA核函数时,确保线程访问模式是合并的至关重要。

合并访问最佳实践
  • 让 threadIdx.x 对应连续的内存维度(最内层)
  • 避免跨步访问(stride > 1的访问模式)
  • 使用共享内存对非合并的全局访问进行重排
  • 确保数据起始地址对齐到128字节(cache line大小)

7.5 性能优化检查清单

优化项方法预期收益
减少H2D传输pin_memory + non_blocking10-30%加速
减少kernel launchCUDA Graph / 操作融合20-50%加速
合并内存访问调整线程索引映射2-10x带宽提升
减少同步避免不必要的synchronize5-15%加速
使用共享内存分块算法2-5x加速
减少分支分歧warp内统一执行路径10-30%加速

八、实战:完整的GPU训练管理器

8.1 封装GPU训练逻辑

将设备管理、显存监控、异常处理整合到一个训练管理器中,是工程化实践的良好范例。

Python
class GPUTrainer:
    def __init__(self, model, device=None):
        self.device = device or (
            torch.device('cuda') if torch.cuda.is_available()
            else torch.device('cpu')
        )
        self.model = model.to(self.device)
        print(f"使用设备: {self.device}")
        if self.device.type == 'cuda':
            print(f"GPU: {torch.cuda.get_device_name(self.device)}")
    
    def train_step(self, x, y, optimizer, criterion):
        x = x.to(self.device, non_blocking=True)
        y = y.to(self.device, non_blocking=True)
        
        optimizer.zero_grad()
        pred = self.model(x)
        loss = criterion(pred, y)
        loss.backward()
        optimizer.step()
        return loss.item()
    
    def get_memory_stats(self):
        if self.device.type != 'cuda':
            return {}
        return {
            'allocated': torch.cuda.memory_allocated() / 1e9,
            'reserved': torch.cuda.memory_reserved() / 1e9,
            'peak': torch.cuda.max_memory_allocated() / 1e9,
        }
    
    def cleanup(self):
        if self.device.type == 'cuda':
            torch.cuda.empty_cache()
            torch.cuda.reset_peak_memory_stats()

8.2 混合精度与梯度累积结合

在显存有限时,混合精度训练和梯度累积是两大关键策略。下面展示如何将它们整合到GPU训练流程中。

Python
scaler = torch.cuda.amp.GradScaler()
accumulation_steps = 4

model.train()
optimizer.zero_grad()

for step, (x, y) in enumerate(dataloader):
    x = x.to('cuda', non_blocking=True)
    y = y.to('cuda', non_blocking=True)
    
    # 混合精度前向
    with torch.cuda.amp.autocast():
        pred = model(x)
        loss = criterion(pred, y) / accumulation_steps
    
    # 梯度缩放反向
    scaler.scale(loss).backward()
    
    # 累积足够步数后更新
    if (step + 1) % accumulation_steps == 0:
        scaler.step(optimizer)
        scaler.update()
        optimizer.zero_grad()
类比理解

把GPU想象成一个拥有数千名工人(CUDA核心)的超级工厂。Grid是整个工厂的工单总表,Block是每个车间的工作组,Thread是每个工人。共享内存是车间内的工具箱(快但容量小),全局内存是中央仓库(大但慢)。好的CUDA编程就像高效的车间管理——让工人们同时干不同的活(并行),减少去仓库取料的次数(合并访问),充分利用工具箱(共享内存)。

九、常见问题与排错

9.1 "CUDA error: device-side assert"

这类错误通常由索引越界引起,如标签超出类别数。调试时设置 CUDA_LAUNCH_BLOCKING=1 环境变量可以让CUDA操作同步执行,从而精确定位错误。

Bash
# 同步执行CUDA操作以便调试
export CUDA_LAUNCH_BLOCKING=1
python train.py

# 调试完成后取消
unset CUDA_LAUNCH_BLOCKING

9.2 "CUDA error: out of memory"

系统化排查OOM:首先检查batch size和模型大小,然后使用 torch.cuda.memory_summary() 查看详细分配信息,最后考虑混合精度或梯度累积。

9.3 设备不一致错误

当模型在GPU但输入在CPU时,会报设备不匹配错误。最佳实践是在训练循环开始时统一迁移所有数据到模型所在设备。

Python
# 获取模型所在设备(自动推断)
model_device = next(model.parameters()).device

# 确保输入在同一设备
x = x.to(model_device)
y = y.to(model_device)

9.4 CUDA版本不匹配

当PyTorch编译时的CUDA版本与系统CUDA驱动不匹配时,可能出现各种奇怪错误。使用 torch.version.cuda 检查PyTorch的CUDA版本,确保与 nvidia-smi 显示的驱动支持的CUDA版本兼容。

Python
print(f"PyTorch CUDA版本: {torch.version.cuda}")
print(f"PyTorch版本: {torch.__version__}")
print(f"cuDNN版本: {torch.backends.cudnn.version()}")
print(f"NCCL版本: {torch.cuda.nccl.version()}")

本章小结

本章从设备管理基础出发,覆盖了多GPU并行策略(DP vs DDP)、CUDA内存管理与OOM处理、GPU监控诊断、CUDA编程基础(线程层次与共享内存)、自定义CUDA扩展编写,以及性能优化策略。掌握这些内容后,你能够:

下一章将深入可视化与调试技术,包括TensorBoard集成和torch.profiler性能分析。