PyTorch在Debian上的使用技巧
sudo apt update && sudo apt upgrade -y),安裝Python 3.6+及pip(sudo apt install python3 python3-pip),建議通過venv或conda創建虛擬環境,隔離項目依賴。pip install torch torchvision torchaudio);pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu117);conda create -n pytorch_env python=3.9創建環境,再用conda install pytorch torchvision torchaudio cudatoolkit=11.7 -c pytorch安裝。import torch; print(torch.__version__); print(torch.cuda.is_available())),確保安裝正確。torch.utils.data.DataLoader時,設置num_workers>0(建議4*num_GPU)啟用多進程加載,開啟pin_memory=True加速CPU到GPU的數據傳輸。torch.cuda.amp模塊實現,使用torch.cuda.amp.autocast()自動選擇計算精度,torch.cuda.amp.GradScaler()縮放梯度,減少顯存占用并提升速度。torch.nn.parallel.DistributedDataParallel(DDP),每個GPU獨立處理數據分片,比DataParallel更高效;大模型可考慮模型并行(將模型拆分到不同GPU)。backward()調用后執行optimizer.step(),模擬大批次訓練,減少顯存占用;cuda:0)創建張量,避免CPU-GPU來回傳輸;del model, tensor),調用torch.cuda.empty_cache()清理顯存。net.core.somaxconn、vm.swappiness),優化系統性能。.item()、.cpu()、.numpy()等操作,如需獲取標量值,可使用loss.item()但避免在循環中頻繁調用;清除計算圖用detach()而非轉移設備。torch.tensor([1,2], device='cuda:0')),避免先創建CPU張量再轉移,減少開銷。torch.autograd.profiler分析計算圖性能,nvprof工具分析GPU利用率,找出代碼瓶頸(如數據加載慢、計算密集部分)。torch.save(model.state_dict(), 'model.pth')保存模型參數(而非整個模型),加載時通過model.load_state_dict(torch.load('model.pth'))恢復,避免版本兼容問題。