前言

搞 AI 开发,第一道门槛往往是环境——CUDA 装不上、PyTorch 版本不对、显存不够报 OOM、各种依赖冲突。

这篇文章把安装步骤和常见坑一次性说清楚。


一、Python 环境管理

推荐用 Miniconda 做 Python 版本管理和虚拟环境隔离,比系统 Python 省心很多。

安装 Miniconda

1
2
3
4
5
6
7
8
9
10
11
# Linux
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh

# macOS (Intel)
curl -O https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh
bash Miniconda3-latest-MacOSX-x86_64.sh

# macOS (Apple Silicon)
curl -O https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-arm64.sh
bash Miniconda3-latest-MacOSX-arm64.sh

创建和管理虚拟环境

1
2
3
4
5
conda create -n ai python=3.11 -y    # 创建名为 ai 的环境
conda activate ai # 激活环境
conda deactivate # 退出环境
conda env list # 查看所有环境
conda remove -n ai --all # 删除环境

为什么用 3.11 而不是 3.12 或 3.13?

AI 生态对最新 Python 的支持有延迟。2025 年初,Python 3.11 兼容性最好,几乎所有主流库都有预编译的 wheel。3.12 大部分能用了,3.13 还不能保证全兼容。

pip 换源

1
2
3
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
# 或阿里源
# pip config set global.index-url https://mirrors.aliyun.com/pypi/simple

二、CUDA 与显卡驱动

先确认你的显卡

1
2
3
4
5
# Linux
nvidia-smi
# 输出会显示驱动版本、CUDA 版本、GPU 型号和显存

# 如果提示 nvidia-smi 找不到,说明还没装驱动
1
2
3
4
5
6
7
8
9
nvidia-smi
# +-----------------------------------------------------------------------------+
# | NVIDIA-SMI 550.54.15 Driver Version: 550.54.15 CUDA Version: 12.4 |
# |-------------------------------+----------------------+----------------------+
# | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
# | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
# | 0 NVIDIA GeForce RTX 4070 | 00000000:01:00.0 On | N/A |
# | 30% 45C P8 15W / 200W | 1200MiB / 12282MiB | 5% Default |
# +-------------------------------+----------------------+----------------------+

上面这行 CUDA Version: 12.4 不是说你装了 CUDA Toolkit,而是说你的驱动最高支持 CUDA 12.4。

CUDA Toolkit 到底要不要装?

大多数情况不需要。

PyTorch 的 conda/pip 包里已经自带 CUDA 运行时。只有当你要用 C++ 写 CUDA 程序或者编译某些底层库(如 llama.cpp、bitsandbytes)时才需要装完整的 CUDA Toolkit。

如果需要装(比如要编译 flash-attention),去 NVIDIA CUDA 下载页 选择对应系统。Ubuntu 22.04 举例:

1
2
3
wget https://developer.download.nvidia.com/compute/cuda/12.4.0/local_installers/cuda_12.4.0_550.54.15_linux.run
sudo sh cuda_12.4.0_550.54.15_linux.run
# 安装时不选 Driver(你已经装过了),只选 CUDA Toolkit

安装后在 ~/.bashrc 末尾加:

1
2
export PATH=/usr/local/cuda-12.4/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda-12.4/lib64:$LD_LIBRARY_PATH

三、PyTorch 安装

1
2
3
4
5
6
7
conda activate ai

# 推荐用 conda 安装(自动匹配 CUDA 版本)
conda install pytorch torchvision torchaudio pytorch-cuda=12.4 -c pytorch -c nvidia

# 或者用 pip(注意在 pytorch.org 确认对应你系统的命令)
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124

验证:

1
2
3
4
5
6
7
import torch
print(f"PyTorch 版本: {torch.__version__}")
print(f"CUDA 可用: {torch.cuda.is_available()}")
print(f"CUDA 版本: {torch.version.cuda}")
print(f"GPU 数量: {torch.cuda.device_count()}")
print(f"当前 GPU: {torch.cuda.get_device_name(0)}")
print(f"显存总量: {torch.cuda.get_device_properties(0).total_mem / 1e9:.1f} GB")

输出:

1
2
3
4
5
6
PyTorch 版本: 2.5.1+cu124
CUDA 可用: True
CUDA 版本: 12.4
GPU 数量: 1
当前 GPU: NVIDIA GeForce RTX 4070
显存总量: 12.0 GB

四、AI 开发常用库

1
2
3
4
5
6
7
pip install transformers accelerate datasets peft    # HuggingFace 全家桶
pip install bitsandbytes sentencepiece # 量化和分词
pip install einops timm # 模型工具
pip install openai anthropic # API 调用
pip install langchain chromadb # RAG 开发
pip install ultralytics opencv-python # YOLO
pip install jupyterlab ipywidgets # Notebook

五、HuggingFace 镜像加速

从 HuggingFace 下载模型在国内很慢,用镜像:

1
2
3
4
5
6
# 方法一:环境变量(推荐)
export HF_ENDPOINT=https://hf-mirror.com

# 方法二:在 Python 代码中设置
import os
os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"

如果用的是 huggingface_hub 下载模型,也可以用 hf_transfer 加速:

1
2
pip install hf-transfer
export HF_HUB_ENABLE_HF_TRANSFER=1

六、Jupyter Lab 配置

1
2
pip install jupyterlab
jupyter lab --ip 0.0.0.0 --port 8888 --no-browser

远程服务器上跑 Jupyter 时,推荐配个 Nginx 反向代理 + SSL,或者直接用 VS Code 的 Remote SSH 连上去用 Notebook。


七、常用工具速查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 查看哪些进程在占用 GPU
nvidia-smi
fuser -v /dev/nvidia*

# 查看 Python 包版本
pip list | grep torch
conda list | grep torch

# 清理 conda 缓存(释放磁盘空间)
conda clean --all -y

# 导出/还原环境
pip freeze > requirements.txt
pip install -r requirements.txt

# 手动杀死占用 GPU 的僵尸进程
kill -9 $(nvidia-smi | grep 'python' | awk '{print $5}')

八、常见报错与解决

报错 原因 解决
CUDA out of memory 显存不够 减小 batch_size,用 gradient checkpointing,换更小模型
torch.cuda.is_available() 返回 False PyTorch 装的 CPU 版本 重新装 CUDA 版:pip install torch --index-url https://download.pytorch.org/whl/cu124
NVIDIA driver too old 驱动版本太低 sudo apt update && sudo apt install nvidia-driver-550
libcudnn.so.8 not found 缺少 cudnn conda install cudnnsudo apt install libcudnn8
symbol not found in flat namespace Intel Mac 装了 ARM 版 PyTorch 确保 pip 装的是 x86_64 版本

环境搭好之后基本不用动,后续开发都在这个基础上进行。