使用 DirectML 的 PyTorch 可以在 适用于 Linux 的 Windows 子系统 (WSL) 中对支持 DirectX 12 的 GPU 进行训练和推理。 具有 DirectML 的 PyTorch 以公共预览版提供,适用于 WSL 2。
检查Windows的版本
WSL 2 中的 torch-directml 包需要 Windows 11(内部版本 22000 或更高版本)。 若要检查Windows版本和版本号,请选择Windows徽标键 + R,输入winver并选择“确定”。
安装 WSL 2
若要使用 WSL 2 安装默认 Linux 分发版,请在管理员模式下打开 PowerShell 或Windows命令提示符并运行:
wsl --install
出现提示时重启计算机。 有关分发选择和其他安装选项,请参阅使用 WSL 在 Windows上安装 Linux。
检查 GPU 驱动程序更新
通过 Windows 更新 或硬件制造商的网站安装 GPU 可用的最新Windows驱动程序。 Windows驱动程序在 WSL 中启用 GPU 加速;无需安装单独的 Linux 显示驱动程序。
设置 Python
在 WSL 分发版中安装Python环境。 例如,运行以下命令以安装 Miniconda:
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
然后创建并激活名为 pytorch-directml 的环境:
conda create --name pytorch-directml python=3.10
conda activate pytorch-directml
使用 DirectML 安装 PyTorch
安装 torch-directml 包:
pip install torch-directml
验证安装
启动 Python 并运行以下代码,在 DirectML 设备上将两个张量相加:
import torch
import torch_directml
dml = torch_directml.device()
tensor1 = torch.tensor([1]).to(dml)
tensor2 = torch.tensor([2]).to(dml)
dml_algebra = tensor1 + tensor2
print(dml_algebra.item())
预期输出:
3
示例和反馈
有关示例,请参阅 DirectML PyTorch 示例 。 若要报告包问题或请求功能,请使用 DirectML 问题跟踪器。