Debian系统下PyTorch内存占用高的系统化优化
一 监控与定位
torch.cuda.memory_allocated()torch.cuda.memory_reserved()torch.cuda.max_memory_allocated()torch.cuda.memory_summary(device=None, abbreviated=False)nvidia-smi 实时监控显存,配合 htop 观察 CPU/RAM 压力,便于识别数据加载瓶颈或内存泄漏趋势。二 训练阶段的高效显存优化
with torch.cuda.amp.autocast(): 前向;scaler.scale(loss).backward();scaler.step(optimizer); scaler.update()。loss.backward(),每 accumulation_steps 步执行一次 optimizer.step() 与 optimizer.zero_grad()。torch.utils.checkpoint.checkpoint 包装计算密集或中间激活很大的子模块。optimizer.zero_grad(set_to_none=True) 替代默认置零,可降低梯度张量的显存占用。del x, y, output;必要时在块作用域末尾调用 torch.cuda.empty_cache() 清理缓存(注意其会引入短暂同步开销,勿频繁调用)。nn.ReLU(inplace=True) 可省显存,但可能破坏计算图或数值稳定性,确保不影响梯度与后续层行为再启用。三 数据与多卡配置优化
num_workers(如 4–8,视 CPU/IO 而定)与 pin_memory=True,减少数据拷贝与等待;避免每个 worker 复制不必要的大对象到显存。export PYTORCH_CUDA_ALLOC_CONF="garbage_collection_threshold:0.8,max_split_size_mb:128"(阈值与切分上限可按模型与显存大小调优)。四 快速检查清单与示例
memory_allocated/max_memory_allocated/reserved,确认增长是否异常。del + empty_cache()。num_workers 与 pin_memory,避免数据侧成为瓶颈。batch_size 或设置 PYTORCH_CUDA_ALLOC_CONF 缓解碎片。import torch, torch.nn as nn
from torch.cuda.amp import autocast, GradScaler
device = torch.device('cuda')
model = nn.Linear(1024, 1024).to(device)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
scaler = GradScaler()
accumulation_steps = 4
for i, (x, y) in enumerate(dataloader, 1):
x, y = x.to(device), y.to(device)
with autocast():
out = model(x)
loss = criterion(out, y) / accumulation_steps
scaler.scale(loss).backward()
if i % accumulation_steps == 0:
scaler.step(optimizer)
scaler.update()
optimizer.zero_grad(set_to_none=True) # 更省显存
如需进一步削减峰值,可对中间层使用 torch.utils.checkpoint.checkpoint 包装。