Linux搭建PyTorch开发环境
一 准备与规划
nvidia-smi(右上角显示 CUDA Version)。如需安装或升级 NVIDIA 驱动,请先关闭图形界面,禁用 nouveau,再运行官方驱动安装包,完成后用 cat /proc/driver/nvidia/version 验证。若不使用GPU,可直接安装 CPU 版本。build-essential cmake git wget unzip yasm pkg-config libopenblas-dev liblapack-dev libjpeg-dev libpng-dev 等,便于后续扩展与多媒体数据处理。二 安装与配置环境
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh && bash Miniconda3-latest-Linux-x86_64.sh,按提示完成安装。conda create -n pytorch python=3.10 -y && conda activate pytorch。conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia;CPU 版:conda install pytorch torchvision torchaudio cpuonly -c pytorch。python3 -m venv ~/venvs/pytorch && source ~/venvs/pytorch/bin/activate。pip install -U pip。pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121;CPU 版:pip install torch torchvision torchaudio。conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/conda config --set show_channel_urls yespip install -i https://pypi.tuna.tsinghua.edu.cn/simple torch torchvision torchaudio。三 验证安装与常见问题
python - <<'PY' import torch, torchvision, torchaudio print("torch:", torch.__version__, "torchvision:", torchvision.__version__, "torchaudio:", torchaudio.__version__) print("cuda available:", torch.cuda.is_available()) print("device count:", torch.cuda.device_count()) if torch.cuda.is_available(): print("current device:", torch.cuda.current_device(), torch.cuda.get_device_name()) PYcuda available: True(GPU版),并显示设备数量与名称。torch.cuda.is_available() 为 False:检查 nvidia-smi 是否正常、驱动与 CUDA 版本匹配、是否误装了 CPU 版本、Conda 是否混用 pip 导致冲突。pip install -U numpy 后重试。-no-opengl-files 参数规避。四 开发工具与后续配置
pip install jupyter 或 conda install jupyter,然后 jupyter notebook 启动。pip install numpy pandas matplotlib scikit-learn;深度学习训练常用:pip install tqdm tensorboard。conda env export > environment.yml;复现:conda env create -f environment.yml。pip freeze > requirements.txt;复现:pip install -r requirements.txt。CUDA_HOME, PATH, LD_LIBRARY_PATH)。