以下是Ubuntu系統下調試PyTorch的實用技巧,涵蓋環境配置、調試工具及優化方法:
基礎環境搭建
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
conda create -n pytorch_env python=3.8
conda activate pytorch_env
conda install pytorch torchvision torchaudio pytorch-cuda11.7 -c pytorch -c nvidia
import torch
print(torch.__version__, torch.cuda.is_available()) # 檢查版本及GPU可用性
GPU環境檢查
nvcc --version # 查看CUDA版本
nvidia-smi # 查看GPU狀態及驅動信息
交互式調試
import pdb; pdb.set_trace() # pdb斷點
# 或使用ipdb(需安裝):import ipdb; ipdb.set_trace()
執行后可通過n
(下一步)、s
(進入函數)、c
(繼續)等命令控制流程。IDE集成調試
Debug
按鈕啟動調試會話。launch.json
后,在斷點處點擊Start Debugging
。日志與異常檢測
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug(f"Variable x: {x}")
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter('runs/experiment')
writer.add_scalar('Loss/train', loss.item(), epoch)
# 終端運行:tensorboard --logdir=runs
性能分析與優化
torch.autograd.set_detect_anomaly(True) # 檢測梯度計算錯誤
from torch.autograd import profiler
with profiler.profile(record_shapes=True) as prof:
output = model(input)
print(prof.key_averages().table(sort_by="cuda_time_total"))
單元測試與代碼審查
unittest
或pytest
編寫測試用例,驗證模型各模塊功能。pylint
或flake8
檢查代碼規范,提前發現潛在問題。batch_size
或使用梯度累積。torch.cuda.amp
)減少顯存占用。torch.nn.DataParallel
或DistributedDataParallel
時,確保數據正確分配到各GPU。通過以上工具和方法,可高效定位和解決PyTorch代碼中的問題,提升開發效率。