Windows WSL2中使用 AMD 显卡的 GPU (ROCm) 加速运行 PyTorch 大模型 - radeon
环境准备
Windows 11 WSL2 (Ubuntu 22.04.5)AMD 显卡驱动 24.6.1及以上版本(本文以7900XTX为案例)科学上网(自行研究)
首先是根据 AMD官网进行安装ROCm
需要注意的是这里只能安装该版本的 amdgpu-install
sudo apt update
wget https://repo.radeon.com/amdgpu-install/6.2.3/ubuntu/jammy/amdgpu-install_6.2.60203-1_all.deb
sudo apt install ./amdgpu-install_6.2.60203-1_all.deb
进行ROCm安装, 如果上面安装的不是这个版本的amdgpu-install,这里则会安装ROCm失败
amdgpu-install -y --usecase=wsl,rocm --no-dkms
检测是否安装成功
#一般显示显卡的信息则是安装成功,如下图
rocminfo
安装PyTorch
接下来安装适合ROCm的 PyTorch
#安装python
sudo apt install python3-pip -y
pip3 install --upgrade pip wheel
#安装 torch
pip uninstall torch torchvision torchaudio -y
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm6.2
安装好检测下是否是结尾带rocm的版本
pip show torch
更新到与 WSL 兼容的运行时库
location=`pip show torch | grep Location | awk -F ": " '{print $2}'`
cd ${location}/torch/lib/
rm libhsa-runtime64.so*
cp /opt/rocm/lib/libhsa-runtime64.so.1.2 libhsa-runtime64.so
接下来可以检测下GPU是否可用
python3 -c 'import torch; print(torch.cuda.is_available())'
这里安装好后 torch就可以运行模型了,我这里使用它运行一个语言翻译模型
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
device = "cuda" if torch.cuda.is_available() else "cpu"
# 加载模型和分词器
# 千问
model_name = "hakutaku/qwen2.5-ja-zh"
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype="auto",
device_map="auto"
).to(device)
tokenizer = AutoTokenizer.from_pretrained(model_name)
# 输入日语文本
input_text = """彼は学生です。日本語を勉強しています。"""
prompt = f"请将以下日文翻译成中文:\n{input_text}"
print(prompt)
messages = [
{"role": "user", "content": prompt}
] 拼多多帮助力入口
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
model_inputs = tokenizer([text], return_tensors="pt").to(device)
generated_ids = model.generate(
model_inputs.input_ids,
max_new_tokens=128
)
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]
output_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
print(output_text)
如图我们已经成功使用gpu进行加速了
Windows WSL2中使用 AMD 显卡的 GPU (ROCm) 加速运行 PyTorch 大模型
精彩链接