温馨提示×

怎样在ubuntu测pytorch

小樊
32
2026-10-19 11:19:37
栏目: 智能运维

在 Ubuntu 上“测 PyTorch”通常指安装后验证是否能正常运行(尤其是 GPU)。下面按常见场景一步一步说明。


一、确认系统环境

lsb_release -a
python3 --version

建议:

  • Python 3.8–3.11
  • 已安装 pip

二、创建虚拟环境(推荐)

python3 -m venv pytorch-env
source pytorch-env/bin/activate

三、安装 PyTorch

1️⃣ 仅 CPU 版本

pip install torch torchvision torchaudio

2️⃣ 使用 NVIDIA GPU(CUDA)

先确认驱动:

nvidia-smi

然后去官网选命令,例如 CUDA 12.1:

pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121

四、测试 PyTorch 是否可用

✅ 基础测试

python -c "import torch; print(torch.__version__)"

✅ CPU 测试

python -c "import torch; print(torch.rand(3,3))"

✅ GPU 测试(关键)

python -c "import torch; print(torch.cuda.is_available())"

如果输出:

  • True → GPU 可用
  • False → 驱动 / CUDA / 安装版本不匹配

✅ 完整测试脚本

import torch

print("PyTorch version:", torch.__version__)
print("CUDA available:", torch.cuda.is_available())

if torch.cuda.is_available():
    print("GPU:", torch.cuda.get_device_name(0))
    x = torch.randn(3,3).cuda()
    print(x)

五、常见问题排查

❌ torch.cuda.is_available() 为 False

检查:

nvidia-smi
nvcc --version

可能原因:

  • 没装 NVIDIA 驱动
  • PyTorch CPU 版
  • CUDA 版本不匹配

❌ 找不到 pip

sudo apt install python3-pip

六、快速一键检测(推荐)

python -c "import torch; assert torch.cuda.is_available(); print('OK')"

如果你愿意,可以告诉我:

  • ✅ 是否有 GPU
  • ✅ Ubuntu 版本
  • ✅ 是否已装驱动

我可以直接给你精确安装命令。

0 踩