debian

Debian系统如何解决PyTorch内存不足问题

小樊
35
2025-12-28 22:45:19
栏目: 智能运维

Debian系统下PyTorch内存不足的排查与优化

一 快速定位与系统层面检查

二 训练侧最有效的显存优化

三 环境与资源层面的配置

四 推理与服务场景的实用做法

五 最小可用代码示例

import torch, gc
from torch.cuda.amp import autocast, GradScaler

model.train()
optimizer.zero_grad()
scaler = GradScaler()
accum_steps = 4

for i, (inputs, targets) in enumerate(dataloader):
    inputs, targets = inputs.cuda(), targets.cuda()

    with autocast():
        outputs = model(inputs)
        loss = criterion(outputs, targets) / accum_steps  # 梯度缩放

    scaler.scale(loss).backward()

    if (i + 1) % accum_steps == 0:
        scaler.step(optimizer)
        scaler.update()
        optimizer.zero_grad()

    # 可选:每若干步清理缓存与垃圾
    if i % 100 == 0:
        torch.cuda.empty_cache()
        gc.collect()
# 碎片优化
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
# 或限制显存占用比例
# export PYTORCH_CUDA_ALLOC_CONF=memory_fraction:0.9
nvidia-smi -l 1
python - <<'PY'
import torch
print(torch.cuda.memory_summary(device=None, abbreviated=False))
print(f"Allocated: {torch.cuda.memory_allocated()/1024**2:.2f} MB")
print(f"Max allocated: {torch.cuda.max_memory_allocated()/1024**2:.2f} MB")
PY

上述组合能在多数Debian+PyTorch环境中稳定降低显存占用并提升稳定性。

0
看了该问题的人还看了