在 Linux 下调试 PyTorch 程序,常见方式和技巧如下,按使用频率和场景分类:
pdb(Python 自带)import pdb
pdb.set_trace()
运行后会进入交互式调试:
n:下一步s:进入函数c:继续l:查看代码p x:打印变量适合快速定位 Python 逻辑错误
breakpoint()(Python 3.7+)breakpoint()
等价于 pdb.set_trace(),更现代。
launch.json 配置 PyTorch 环境VS Code 示例:
{
"name": "Python: PyTorch",
"type": "python",
"request": "launch",
"program": "train.py",
"console": "integratedTerminal"
}
x.shape
x.dtype
x.device
torch.isnan(x).any()
torch.isinf(x).any()
import torch
torch.autograd.set_detect_anomaly(True)
with torch.autograd.detect_anomaly():
loss.backward()
nvidia-smi
torch.backends.cuda.matmul.allow_tf32 = False
torch.use_deterministic_algorithms(True)
CUDA_LAUNCH_BLOCKING=1 python train.py
会精确定位是哪一行 CUDA 出错(非常有用)
export CUDA_VISIBLE_DEVICES=0
python train.py
torchrun --nproc_per_node=1 train.py
print(f"rank {rank}: shape={x.shape}")
import time
t0 = time.time()
output = model(x)
print(time.time() - t0)
with torch.profiler.profile(
activities=[torch.profiler.ProfilerActivity.CPU,
torch.profiler.ProfilerActivity.CUDA]
) as prof:
model(x)
print(prof)
logging 而不是 printtry:
loss.backward()
except Exception as e:
print("ERROR:", e)
✅ 新手:VS Code + breakpoint
✅ CUDA 报错:CUDA_LAUNCH_BLOCKING=1
✅ NaN 问题:detect_anomaly
✅ 复杂模型:PyCharm 调试器
如果你有具体场景(如训练崩溃、NaN、DDP、自定义 CUDA),可以告诉我,我可以给你更针对性的调试方案。