debian

如何在Debian上使用GPU加速PyTorch

小樊
32
2025-07-28 12:18:31
栏目: 智能运维

在Debian上使用GPU加速PyTorch,你需要确保你的系统已经安装了NVIDIA GPU驱动程序和CUDA工具包。以下是详细步骤:

1. 安装NVIDIA GPU驱动程序

  1. 检查GPU型号

    lspci | grep -i nvidia
    
  2. 添加NVIDIA驱动程序源

    sudo add-apt-repository ppa:graphics-drivers/ppa
    sudo apt update
    
  3. 安装推荐的驱动程序

    sudo ubuntu-drivers autoinstall
    
  4. 重启系统

    sudo reboot
    

2. 安装CUDA工具包

  1. 下载CUDA Toolkit: 访问NVIDIA CUDA Toolkit下载页面,选择适合Debian的版本并下载。

  2. 安装CUDA Toolkit

    sudo dpkg -i cuda-repo-<distro>_<version>_amd64.deb
    sudo apt-key adv --fetch-keys http://developer.download.nvidia.com/compute/cuda/repos/<distro>/x86_64/7fa2af80.pub
    sudo apt update
    sudo apt install cuda
    
  3. 设置环境变量: 编辑~/.bashrc文件,添加以下行:

    export PATH=/usr/local/cuda-<version>/bin${PATH:+:${PATH}}
    export LD_LIBRARY_PATH=/usr/local/cuda-<version>/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}
    

    然后运行:

    source ~/.bashrc
    

3. 安装cuDNN

  1. 下载cuDNN: 访问NVIDIA cuDNN下载页面,下载与你的CUDA版本兼容的cuDNN库。

  2. 安装cuDNN: 解压下载的文件并将文件复制到CUDA目录:

    tar -xzvf cudnn-<version>-linux-x64-v<version>.tgz
    sudo cp cuda/include/cudnn*.h /usr/local/cuda/include
    sudo cp cuda/lib64/libcudnn* /usr/local/cuda/lib64
    sudo chmod a+r /usr/local/cuda/include/cudnn*.h /usr/local/cuda/lib64/libcudnn*
    

4. 安装PyTorch

  1. 创建虚拟环境(可选但推荐):

    python3 -m venv pytorch-env
    source pytorch-env/bin/activate
    
  2. 安装PyTorch: 访问PyTorch官方网站,选择适合你的Debian版本和CUDA版本的命令进行安装。例如:

    pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu<version>
    

5. 验证安装

  1. 验证CUDA安装

    nvcc --version
    
  2. 验证PyTorch是否检测到GPU

    import torch
    print(torch.cuda.is_available())
    print(torch.cuda.current_device())
    print(torch.cuda.get_device_name(torch.cuda.current_device()))
    

如果一切顺利,你应该能够看到True以及你的GPU型号。

通过以上步骤,你应该能够在Debian上成功配置GPU加速的PyTorch环境。

0
看了该问题的人还看了