温馨提示×

centos pytorch如何测试

小樊
43
2026-09-24 16:24:25
栏目: 智能运维

在 CentOS 上测试 PyTorch 是否安装成功、能否正常使用(尤其是 GPU 是否可用),可以按下面步骤来。


一、确认 Python 环境

先确认你用的是哪个 Python(建议用虚拟环境):

which python
python --version

如果是 conda 环境:

conda activate your_env

二、进入 Python 测试 PyTorch

1️⃣ 基本导入测试

python

在 Python 交互环境中输入:

import torch
print(torch.__version__)

✅ 能正常输出版本号说明安装成功。


2️⃣ CPU 测试

x = torch.randn(3, 3)
print(x)

3️⃣ GPU(CUDA)测试(非常重要)

print(torch.cuda.is_available())
  • True → CUDA 可用(GPU 正常)
  • False → 可能是:
    • 没装 GPU 版 PyTorch
    • 驱动/CUDA 不匹配
    • CentOS 没装 NVIDIA 驱动

4️⃣ 查看 GPU 信息

print(torch.cuda.current_device())
print(torch.cuda.get_device_name(0))

5️⃣ 简单 GPU 运算测试

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x = torch.randn(1000, 1000).to(device)
y = torch.randn(1000, 1000).to(device)
z = x @ y
print(z.device)

三、CentOS 常见问题排查

❌ torch.cuda.is_available() 为 False

1. 检查 NVIDIA 驱动

nvidia-smi
  • 看不到显卡 → 驱动没装
  • 报错 → 驱动异常

2. 检查 CUDA 版本

nvcc --version

PyTorch 版本要和 CUDA 匹配(如 CUDA 11.8 / 12.1)

3. 确认安装的是 GPU 版 PyTorch

pip list | grep torch

GPU 版一般包含 cu11x


四、快速一键测试脚本(推荐)

新建 test_torch.py:

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))

运行:

python test_torch.py

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

  • ✅ CentOS 版本(7 / 8 / Stream)
  • ✅ 是否用 conda / pip
  • ✅ 是否有 NVIDIA 显卡

我可以直接给你对应的安装 + 测试命令。

0 踩