Ubuntu下PyTorch常见问题及解决方法
解决方法:使用国内镜像源加速安装。例如,通过pip安装时添加清华镜像源:
pip install torch torchvision torchaudio -i https://pypi.tuna.tsinghua.edu.cn/simple;
通过conda安装时,添加清华镜像源并设置:
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --set show_channel_urls yes。
问题表现:安装或运行时报错“Unsupported Python version”(不支持的Python版本)。
解决方法:PyTorch建议使用Python 3.8-3.11版本,不支持Python 3.12。通过python3 --version检查版本,若版本过高,可通过sudo apt install python3.8安装指定版本,并创建虚拟环境使用。
问题表现:运行torch.cuda.is_available()返回False,或报错“RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same”(输入与权重类型不匹配)。
解决方法:
nvcc --version查看已安装的CUDA版本;pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu118;~/.bashrc中添加export PATH=/usr/local/cuda/bin:$PATH和export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH,并执行source ~/.bashrc)。问题表现:运行时出现“ImportError: libcudnn.so.X: cannot open shared object file”(无法打开共享库文件)或性能低下。
解决方法:
sudo apt install libcudnn8安装;cudatoolkit版本(如conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia),conda会自动处理cuDNN依赖。问题表现:系统黑屏、无法使用GPU,或报错“NVIDIA driver version is insufficient for CUDA runtime version”(驱动版本不足)。
解决方法:
ubuntu-drivers devices;sudo apt install nvidia-driver-版本号(如nvidia-driver-535);nvidia-smi验证驱动是否正常。问题表现:安装时报错“Missing dependencies: xxx”(缺少依赖库),或运行时出现“ImportError: No module named ‘xxx’”(缺少模块)。
解决方法:
pandas:conda install pandas或pip install pandas;sudo apt install libssl-dev libffi-dev build-essential(部分PyTorch功能需要这些库)。问题表现:训练或推理时报错“CUDA out of memory”(CUDA显存耗尽)。
解决方法:
torch.cuda.empty_cache()释放未使用的显存。问题表现:在VSCode/PyCharm中无法切换PyTorch环境,或报错“ModuleNotFoundError: No module named ‘torch’”。
解决方法:
Ctrl+Shift+P,选择“Python: Select Interpreter”,指向虚拟环境中的Python(如~/miniconda3/envs/pytorch_env/bin/python);conda create -n pytorch_env python=3.9),并在激活环境后安装PyTorch。