温馨提示×

linux pytorch怎样调试

小樊
47
2026-10-16 04:16:27
栏目: 智能运维

在 Linux 下调试 PyTorch 程序,常见方式和技巧如下,按使用频率和场景分类:


一、最常用:Python 层调试(推荐)

1. 使用 pdb(Python 自带)

import pdb
pdb.set_trace()

运行后会进入交互式调试:

  • n:下一步
  • s:进入函数
  • c:继续
  • l:查看代码
  • p x:打印变量

适合快速定位 Python 逻辑错误


2. 使用 breakpoint()(Python 3.7+)

breakpoint()

等价于 pdb.set_trace(),更现代。


3. 使用 IDE 调试(强烈推荐)

  • PyCharm
    • 直接断点
    • 可查看 Tensor 形状、值
  • VS Code
    • 安装 Python 插件
    • launch.json 配置 PyTorch 环境

VS Code 示例:

{
  "name": "Python: PyTorch",
  "type": "python",
  "request": "launch",
  "program": "train.py",
  "console": "integratedTerminal"
}

二、PyTorch 特有调试技巧

1. 检查 Tensor

x.shape
x.dtype
x.device
torch.isnan(x).any()
torch.isinf(x).any()

2. 打开异常详细堆栈

import torch
torch.autograd.set_detect_anomaly(True)

3. 捕获 NaN / Inf

with torch.autograd.detect_anomaly():
    loss.backward()

三、CUDA / GPU 调试

1. 查看 GPU 状态

nvidia-smi

2. CUDA 错误调试

torch.backends.cuda.matmul.allow_tf32 = False
torch.use_deterministic_algorithms(True)

3. CUDA 崩溃定位

CUDA_LAUNCH_BLOCKING=1 python train.py

会精确定位是哪一行 CUDA 出错(非常有用)


四、多进程 / 分布式调试

1. 单进程先调通

export CUDA_VISIBLE_DEVICES=0
python train.py

2. DDP 调试

torchrun --nproc_per_node=1 train.py

3. 打印 rank

print(f"rank {rank}: shape={x.shape}")

五、性能调试(不是 bug,但很重要)

1. 时间分析

import time
t0 = time.time()
output = model(x)
print(time.time() - t0)

2. PyTorch Profiler

with torch.profiler.profile(
    activities=[torch.profiler.ProfilerActivity.CPU,
                torch.profiler.ProfilerActivity.CUDA]
) as prof:
    model(x)
print(prof)

六、日志与报错定位技巧

  • 使用 logging 而不是 print
  • 捕获异常:
try:
    loss.backward()
except Exception as e:
    print("ERROR:", e)

七、推荐组合(实战经验)

✅ 新手:VS Code + breakpoint
✅ CUDA 报错:CUDA_LAUNCH_BLOCKING=1
✅ NaN 问题:detect_anomaly
✅ 复杂模型:PyCharm 调试器


如果你有具体场景(如训练崩溃、NaN、DDP、自定义 CUDA),可以告诉我,我可以给你更针对性的调试方案。

0 踩