> For the complete documentation index, see [llms.txt](https://unsloth.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://unsloth.ai/docs/zh/kai-shi-shi-yong/install/amd.md).

# 使用 Unsloth 指南在 AMD GPU 上微调 LLM

了解如何使用 Unsloth 在 AMD GPU 上微调大型语言模型（LLM）。

在 AMD 硬件上微调 LLM，速度最高快 2 倍、显存占用约减少 70%，无需 NVIDIA。Unsloth 支持 Windows 和 Linux 上的 AMD Radeon RDNA 3/3.5/4（RX 6000–9000 系列），以及包括 MI300X（192GB）在内的数据中心 GPU。

{% stepper %}
{% step %}

#### **一行安装器**

要在 AMD 上安装 Unsloth，最简单的方法是下载我们的 [桌面应用](/docs/zh/desktop.md).

<a href="https://unsloth.ai/download/windows" class="button secondary" data-icon="windows">下载 Windows 版</a><a href="https://unsloth.ai/download/windows" class="button secondary" data-icon="linux">下载 Linux 版</a>\
\
对于手动安装：

**Linux：**

```bash
curl -fsSL https://unsloth.ai/install.sh | sh
```

**Windows（PowerShell）：**

```powershell
irm https://unsloth.ai/install.ps1 | iex
```

下面的手动步骤适用于想在 AMD 上安装 Unsloth Python 库并包含所需依赖项的用户。
{% endstep %}

{% step %}

#### **新建一个隔离环境（可选）**

为了不破坏任何系统包，你可以创建一个隔离的 pip 环境。提醒：检查你使用的 Python 版本！它可能是 `pip3`, `pip3.13`, `python3`, `python.3.13` 等等。

**Linux：** 示例显示的是 3.13；任何 3.11-3.13 都可以在各处使用（3.10 适用于手动安装

{% code overflow="wrap" %}

```bash
# Linux — 将 3.13 替换为你拥有的 3.10-3.13 版本中的任意一个
apt update && apt install python3.13-venv -y
python3.13 -m venv unsloth_env
source unsloth_env/bin/activate
pip install uv
```

{% endcode %}

**Windows（PowerShell）：**&#x20;

示例显示的是 3.13；如果安装 unsloth\[rocm72-torch291] 额外包，请使用 3.12

```shellscript
py -3.13 -m venv unsloth_env
unsloth_env\Scripts\Activate.ps1
pip install uv
```

{% endstep %}

{% step %}

#### **安装 PyTorch**

计划使用 AMD 额外包安装 Unsloth（`unsloth[rocm72-torch291]` 等，见下一节）？这些包已捆绑匹配的 PyTorch，所以你可以 **跳过本节**。只有在你想自己管理它，或你的 ROCm 版本未被某个额外包覆盖时，才在这里安装 PyTorch。

**Linux：** \
从 PyTorch 索引安装支持 ROCm 的 PyTorch。通过以下方式检查你的 ROCm 版本： `amd-smi version` （查找 `ROCm version：` 这一行），然后将 `https://download.pytorch.org/whl/rocm7.1` 替换为对应版本。需要 ROCm 6.0 或更新版本。

{% code overflow="wrap" %}

```bash
uv pip install "torch>=2.4,<2.11.0" "torchvision<0.26.0" "torchaudio<2.11.0" \
    --index-url https://download.pytorch.org/whl/rocm7.1 --upgrade --force-reinstall
```

{% endcode %}

ROCm 7.2 提供了更新的 wheels（torch 2.11），因此在 ROCm 7.2 上请改用此命令：

```bash
uv pip install "torch>=2.11.0,<2.12.0" torchvision torchaudio \
    --index-url https://download.pytorch.org/whl/rocm7.2 --upgrade --force-reinstall
```

可用的索引标签有 `rocm6.0`, `rocm6.1`, `rocm6.2`, `rocm6.3`, `rocm6.4`, `rocm7.0`, `rocm7.1`，以及 `rocm7.2`。ROCm 6.5-6.9 没有专用 wheels（使用 `rocm6.4`），而 ROCm 7.3+ 使用 `rocm7.2`.

*这些版本上限可防止意外拉取 torch 2.11+，因为它只提供 ROCm 7.2 wheels，且会导致问题。像之前一样，把 `rocm7.1` 改为与你检测到的版本匹配。*

我们还编写了一条单行终端命令，如果有帮助的话，可以提取正确的 ROCM 版本。

```bash
ROCM_TAG="$({ command -v amd-smi >/dev/null 2>&1 && amd-smi version 2>/dev/null | awk -F'ROCm version: ' 'NF>1{split($2,a,"."); print "rocm"a[1]"."a[2]; ok=1; exit} END{exit !ok}'; } || { [ -r /opt/rocm/.info/version ] && awk -F. '{print "rocm"$1"."$2; exit}' /opt/rocm/.info/version; } || { command -v hipconfig >/dev/null 2>&1 && hipconfig --version 2>/dev/null | awk -F': *' '/HIP version/{split($2,a,"."); print "rocm"a[1]"."a[2]; ok=1; exit} END{exit !ok}'; } || { command -v dpkg-query >/dev/null 2>&1 && ver="$(dpkg-query -W -f="${Version}\n" rocm-core 2>/dev/null)" && [ -n "$ver" ] && awk -F'[.-]' '{print "rocm"$1"."$2; exit}' <<<"$ver"; } || { command -v rpm >/dev/null 2>&1 && ver="$(rpm -q --qf '%{VERSION}\n' rocm-core 2>/dev/null)" && [ -n "$ver" ] && awk -F'[.-]' '{print "rocm"$1"."$2; exit}' <<<"$ver"; })"; [ -n "$ROCM_TAG" ] && uv pip install "torch>=2.4,<2.11.0" "torchvision<0.26.0" "torchaudio<2.11.0" --index-url "https://download.pytorch.org/whl/$ROCM_TAG" --upgrade --force-reinstall
```

*注意：如果你的 ROCm 版本是 7.2 或更高，请把 `$ROCM_TAG` 在上面的命令中替换为 `rocm7.1，` 目前还没有适用于 7.2+ 的 PyTorch wheels。*

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FTVWdHJi4m8thLmCwOocd%2Fimage.png?alt=media&amp;token=c3c2dc1d-a405-4998-96ec-8dc320e3e4ce" alt="" width="563"><figcaption></figcaption></figure></div>
{% endstep %}

{% step %}

#### **安装 Unsloth**

使用 AMD 额外包安装 Unsloth：

{% code overflow="wrap" %}

```bash
uv pip install unsloth[amd]
```

{% endcode %}

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fe0HmhIq3WvgX4hMh5B8N%2Fimage.png?alt=media&amp;token=8376914f-e8b8-4a84-bee9-83c80ed5ad92" alt="" width="547"><figcaption></figcaption></figure></div>

⚠️ AMD 必需：安装兼容 ROCm 的 bitsandbytes\
所有 ROCm 系统都需要一个预发布的 bitsandbytes 构建版本，版本 ≤ 0.49.2 在所有 AMD GPU 上都有 4 位解码 NaN bug。注意：此步骤请使用 `pip` 而不是 `uv` ， `uv` 因为它会由于文件名中的版本不匹配而拒绝这个预发布 wheel。

{% code overflow="wrap" %}

```bash
# x86_64 系统：
pip install --force-reinstall --no-cache-dir --no-deps \
    "https://github.com/bitsandbytes-foundation/bitsandbytes/releases/download/continuous-release_main/bitsandbytes-1.33.7.preview-py3-none-manylinux_2_24_x86_64.whl"

# aarch64 系统：将上面 URL 中的 x86_64 替换为 aarch64

# 如果 URL 无法访问，则回退：
# pip install --force-reinstall --no-cache-dir --no-deps "bitsandbytes>=0.49.1"
```

{% endcode %}

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FG8j6PTQaLqgWK0gWfi5d%2Fimage.png?alt=media&amp;token=3c25056f-932f-4373-be25-485423f94b4d" alt="" width="563"><figcaption></figcaption></figure></div>
{% endstep %}

{% step %}

#### **开始使用 Unsloth 进行微调！**

就这样。试试我们 [**Unsloth 笔记本**](/docs/zh/kai-shi-shi-yong/unsloth-notebooks.md) 页面！

你可以查看我们专门的 [微调](/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide.md) 或 [强化学习](/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide.md) 指南。下面也有一个简短示例：

**1. 设置环境变量**

{% code overflow="wrap" %}

```bash
export HSA_OVERRIDE_GFX_VERSION=9.4.2  # AMD MI300X 所需
export HF_HUB_DISABLE_XET=1            # 修复 AMD 上的 HuggingFace 下载问题
```

{% endcode %}

***注意：*** *`HSA_OVERRIDE_GFX_VERSION=9.4.2` 告诉 ROCm 将你的 GPU 视为 gfx942（MI300X）。没有这个设置，某些内核可能无法编译或运行。*

**2. 加载并配置模型**

{% code overflow="wrap" %}

```python
from unsloth import FastModel

model, tokenizer = FastModel.from_pretrained(
    model_name = "unsloth/gemma-4-26b-a4b-it",
    max_seq_length = 2048,
    load_in_4bit = True,
)

model = FastModel.get_peft_model(
    model,
    r = 16,
    lora_alpha = 16,
    target_modules = ["q_proj", "k_proj", "v_proj", "o_proj"],
)
```

{% endcode %}

**3. 训练**

{% code overflow="wrap" %}

```python
from trl import SFTTrainer, SFTConfig

trainer = SFTTrainer(
    model = model,
    tokenizer = tokenizer,
    train_dataset = dataset,
    formatting_func = formatting_func,
    args = SFTConfig(
        per_device_train_batch_size = 1,
        gradient_accumulation_steps = 4,
        max_steps = 60,
        output_dir = "outputs",
        report_to = "none",
    ),
)

trainer_stats = trainer.train()
```

{% endcode %}

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FwIcg0yj5i1hSyHDLyMYG%2Fimage.png?alt=media&amp;token=a6cbe0c7-fdbf-4feb-ad7b-7ac55ba91872" alt="" width="375"><figcaption></figcaption></figure></div>

***注意：** 在 AMD GPU 上，Flash Attention 2 不可用。Unsloth 会自动回退到 Xformers，它在 ROCm 上提供等效性能。该警告可以安全忽略。*
{% endstep %}
{% endstepper %}

### :1234: AMD GPU 上的强化学习

你可以使用我们的 :ledger:[gpt-oss RL 自动赢 2048](https://github.com/unslothai/notebooks/blob/main/nb/AMD-gpt_oss_\(20B\)_Reinforcement_Learning_2048_Game_BF16.ipynb) 示例，在 MI300X（192GB）GPU 上运行。目标是自动玩 2048 游戏，并通过 RL 赢得它。LLM（gpt-oss 20b）会自动制定赢得 2048 游戏的策略，我们会对获胜策略给予高奖励，对失败策略给予低奖励。

{% columns %}
{% column %}

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-2bc5a2e25a51781fd945ab9e87e73821ed4eb6c9%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>
{% endcolumn %}

{% column %}
大约 300 步之后，随时间推移的奖励开始上升了！

RL 的目标是最大化平均奖励，以赢得 2048 游戏。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-8d7ea897fd57156a796e4f74aa2e3b60afe9d405%2F2048%20Auto%20Win%20Game%20Reward.png?alt=media" alt=""><figcaption></figcaption></figure>
{% endcolumn %}
{% endcolumns %}

我们使用一台 AMD MI300X 机器（192GB）运行了 Unsloth 的 2048 RL 示例，并且效果很好！

<div><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-174890aa5f63632ebe6f3f212f1ced0d0e8dc381%2FScreenshot%202025-10-17%20052504.png?alt=media" alt=""><figcaption></figcaption></figure> <figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-f907ba596705496515fdfb39b49d649697317ca7%2FScreenshot%202025-10-17%20052641.png?alt=media" alt=""><figcaption></figcaption></figure></div>

你也可以使用我们的 :ledger:[自动内核生成 RL 笔记本](https://github.com/unslothai/notebooks/blob/main/nb/AMD-gpt_oss_\(20B\)_GRPO_BF16.ipynb) ，同样使用 gpt-oss 在 Python 中自动创建矩阵乘法内核。该笔记本还设计了多种方法来对抗奖励作弊。

{% columns %}
{% column width="50%" %}
我们用于自动创建这些内核的提示词是：

{% code overflow="wrap" %}

````
仅使用原生 Python 代码创建一个新的快速矩阵乘法函数。
你会得到一个数字列表的列表。
请按照下面的格式，用反引号输出你的新函数：
```
python
def matmul(A, B):
    return ...
```
````

{% endcode %}
{% endcolumn %}

{% column width="50%" %}
例如，这个 RL 过程会学习如何在 Python 中应用 Strassen 算法来加速矩阵乘法。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-ddb993e5d2c986794ede1f2b0d08897469b78506%2Fimage%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt="" width="375"><figcaption></figcaption></figure>
{% endcolumn %}
{% endcolumns %}

### :books:AMD 免费一键笔记本

AMD 通过他们的 Dev Cloud 提供配备 **免费 192GB 显存 MI300X GPU** 的一键笔记本。完全免费训练大型模型（无需注册或信用卡）：

* [Qwen3（32B）](https://amd-ai-academy.com/github/unslothai/notebooks/blob/main/nb/Qwen3_\(32B\)_A100-Reasoning-Conversational.ipynb)
* [Llama 3.3（70B）](https://amd-ai-academy.com/github/unslothai/notebooks/blob/main/nb/AMD-Llama3.3_\(70B\)_A100-Conversational.ipynb)
* [Qwen3（14B）](https://amd-ai-academy.com/github/unslothai/notebooks/blob/main/nb/AMD-Qwen3_\(14B\)-Reasoning-Conversational.ipynb)
* [Mistral v0.3（7B）](https://amd-ai-academy.com/github/unslothai/notebooks/blob/main/nb/AMD-Mistral_v0.3_\(7B\)-Alpaca.ipynb)
* [GPT OSS MXFP4（20B）](https://amd-ai-academy.com/github/unslothai/notebooks/blob/main/nb/AMD-GPT_OSS_MXFP4_\(20B\)-Inference.ipynb) - 推理
* [Gemma4（E2B）](https://amd-ai-academy.com/github/unslothai/notebooks/blob/main/nb/Gemma4_\(E2B\)_Reinforcement_Learning_Sudoku_Game.ipynb) - RL 数独
* Unsloth Studio

{% embed url="<https://oneclickamd.ai/github/unslothai/notebooks/blob/main/nb/gpt_oss_(20B)_Reinforcement_Learning_2048_Game_BF16.ipynb>" %}

你可以通过在前面加上 <https://amd-ai-academy.com/github/unslothai/notebooks/blob/main/nb> 中的 [Unsloth 笔记本](/docs/zh/kai-shi-shi-yong/unsloth-notebooks.md) 并将链接从 <https://github.com/unslothai/notebooks/blob/main/nb/AMD-gpt_oss_(20B)_Reinforcement_Learning_2048_Game_BF16.ipynb>\
更改为 <https://amd-ai-academy.com/github/unslothai/notebooks/blob/main/nb/AMD-Gemma4_(E2B)_Reinforcement_Learning_Sudoku_Game.ipynb>

{% columns %}
{% column width="33.33333333333333%" %}

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F7NNi4jLKvmZoRnLel9Kg%2Fimage.png?alt=media&amp;token=0379eda9-569c-4614-afb5-ffec463a7676" alt=""><figcaption></figcaption></figure>
{% endcolumn %}

{% column width="66.66666666666667%" %}

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FRfKS1GAW7BqL9lGNTcxh%2Fimage.png?alt=media&amp;token=3a8aeb01-62a7-4d55-89a9-98526052e305" alt=""><figcaption></figcaption></figure>
{% endcolumn %}
{% endcolumns %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://unsloth.ai/docs/zh/kai-shi-shi-yong/install/amd.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
