> 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/mo-xing/gpt-oss-how-to-run-and-fine-tune.md).

# gpt-oss：运行指南

OpenAI 发布了‘**gpt-oss-120b’** 和‘**gpt-oss-20b’**，两个在 Apache 2.0 许可下的 SOTA 开源语言模型。两个 128k 上下文模型在推理、工具使用和 agentic 任务上都优于同等规模的开源模型。现在你可以使用 Unsloth 在本地运行并微调它们！

<a href="#run-gpt-oss-20b" class="button secondary">运行 gpt-oss-20b</a><a href="#run-gpt-oss-120b" class="button secondary">运行 gpt-oss-120b</a><a href="#fine-tuning-gpt-oss-with-unsloth" class="button primary">微调 gpt-oss</a>

> [**微调**](#fine-tuning-gpt-oss-with-unsloth) **使用我们的** [**Colab 笔记本**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/gpt-oss-\(20B\)-Fine-tuning.ipynb)

采用 [RL](/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide.md), **gpt-oss-120b** 可与 o4-mini 相媲美，并且 **gpt-oss-20b** 可与 o3-mini 相媲美。两者在函数调用和 CoT 推理方面都很出色，超越了 o1 和 GPT-4o。

为了获得最佳性能，请确保你的可用总内存（统一内存 + VRAM + 系统内存）大于你正在下载的量化模型文件的大小。否则，llama.cpp 仍可通过 SSD/HDD 卸载运行，但推理会更慢。

#### **gpt-oss - Unsloth GGUF：**

{% hint style="success" %}
**包含 Unsloth 的** [**聊天模板修复**](#unsloth-fixes-for-gpt-oss)**。为了获得最佳效果，请使用我们的上传版本并使用 Unsloth 训练！**
{% endhint %}

* 20B： [gpt-oss-**20B**](https://huggingface.co/unsloth/gpt-oss-20b-GGUF)
* 120B： [gpt-oss-**120B**](https://huggingface.co/unsloth/gpt-oss-120b-GGUF)

## :scroll:Unsloth 对 gpt-oss 的修复

{% hint style="info" %}
我们的一些修复已上游合并到 OpenAI 在 Hugging Face 上的官方模型中。 [参见](https://huggingface.co/openai/gpt-oss-20b/discussions/94/files)
{% endhint %}

OpenAI 发布了一个独立的解析和分词库，名为 [Harmony](https://github.com/openai/harmony) ，它允许将对话分词为 OpenAI 为 gpt-oss 首选的格式。

推理引擎通常改用 jinja 聊天模板，而不是 Harmony 包。我们在与 Harmony 直接比较后发现了一些问题。如下所示，上方是来自 Harmony 的正确渲染形式。下方是当前 jinja 聊天模板渲染的结果。两者差异相当多！

<div data-with-frame="true"><figure><img src="/files/5e8e082f8496e0f67b29c94a4b487e9c8ff4032c" alt="" width="563"><figcaption></figcaption></figure></div>

如果你愿意，我们还制作了一些函数，使你可以直接使用 OpenAI 的 Harmony 库，而无需 jinja 聊天模板——你只需像下面这样解析普通对话：

```python
messages = [
    {"role" : "user", "content" : "1+1 等于多少？"},
    {"role" : "assistant", "content" : "2"},
    {"role": "user",  "content": "现在旧金山的气温是多少？明天呢？今天的日期是 2024-09-30。"},
    {"role": "assistant",  "content": "用户问：'旧金山的天气怎么样？' 我们需要使用 get_current_temperature 工具。", "thinking" : ""},
    {"role": "assistant", "content": "", "tool_calls": [{"name": "get_current_temperature", "arguments": '{"location": "旧金山，加利福尼亚州，美国", "unit": "celsius"}'}]},
    {"role": "tool", "name": "get_current_temperature", "content": '{"temperature": 19.9, "location": "旧金山，加利福尼亚州，美国", "unit": "celsius"}'},
]
```

然后使用 `encode_conversations_with_harmony` 来自 Unsloth 的函数：

```python
from unsloth_zoo import encode_conversations_with_harmony

def encode_conversations_with_harmony(
    messages,
    reasoning_effort = "medium",
    add_generation_prompt = True,
    tool_calls = None,
    developer_instructions = None,
    model_identity = "你是 ChatGPT，一个由 OpenAI 训练的大型语言模型。",
)
```

Harmony 格式包含多个有趣的内容：

1. `reasoning_effort = "medium"` 你可以选择 low、medium 或 high，这会改变 gpt-oss 的推理预算——通常越高，模型准确率越好。
2. `developer_instructions` 就像你可以添加的 system 提示词。
3. `model_identity` 最好保持不变——你可以编辑它，但我们不确定自定义内容是否会起作用。

我们发现当前的 jinja 聊天模板存在多个问题（生态中有多种实现）：

1. 函数和工具调用会使用 `tojson`渲染，这本身没问题，因为它是一个字典，但如果它是字符串，双引号和其他 **符号会被转义加反斜杠**.
2. 在 **某些边界上** ，jinja 模板中会多出一些换行。
3. 模型的工具调用思考应当使用 **`analysis` 标签，而不是 `final` 标签**.
4. 其他聊天模板似乎根本没有使用 `<|channel|>final` ——应当将其用于最终的 assistant 消息。你不应将其用于思维链或工具调用。

我们的 GGUF、BnB 和 BF16 上传版本以及所有版本的聊天模板都已修复！例如，当比较我们的格式与 Harmony 的格式时，不会出现不同字符：

<div data-with-frame="true"><figure><img src="/files/fa08d482b295df9f3b504bbdccf9220f71efc68a" alt="" width="563"><figcaption></figcaption></figure></div>

### :1234: 精度问题

我们在 Tesla T4 和 float16 机器上发现了多个精度问题，主要是因为模型使用 BF16 训练，因此存在离群值和溢出。MXFP4 实际上不支持 Ampere 及更旧的 GPU，因此 Triton 提供 `tl.dot_scaled` 用于 MXFP4 矩阵乘法。它会在运行时内部将矩阵即时上转换为 BF16。

我们也制作了一个 [MXFP4 推理笔记本](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/GPT_OSS_MXFP4_\(20B\)-Inference.ipynb) ，并已放在 Tesla T4 的 Colab 中！

{% hint style="info" %}
[软件仿真](https://triton-lang.org/main/python-api/generated/triton.language.dot_scaled.html) 使得能够面向不原生支持微缩放操作的硬件架构。目前这种情况下，微缩放的 lhs/rhs 会在点积计算之前上转换为 `bf16` 元素类型，
{% endhint %}

我们发现，如果你在混合精度 autocast 中使用 float16 作为数据类型，过一段时间后就会出现无穷大。为了解决这个问题，我们发现先用 bfloat16 执行 MoE，然后将其保持为 bfloat16 或 float32 精度。如果更旧的 GPU 甚至不支持 bfloat16（如 T4），则使用 float32。

我们还将所有操作（例如路由器）的精度都改为 float32，以适配 float16 机器。

## 🖥️ **运行 gpt-oss**

下面是 [20B](#run-gpt-oss-20b) 和 [120B](#run-gpt-oss-120b) 这些模型变体的指南。

{% hint style="info" %}
任何小于 F16 的量化，包括 2 位，准确率损失都很小，因为只有部分（例如注意力层）是低比特，其余大多保持全精度。这就是为什么尺寸接近 F16 模型；例如，2 位（11.5 GB）版本的表现几乎与完整 16 位（14 GB）版本相同。一旦 llama.cpp 为这些模型支持更好的量化，我们会尽快上传。
{% endhint %}

该 `gpt-oss` OpenAI 的模型包含一个功能，允许用户调整模型的“推理力度”。这使你能够控制模型性能与响应速度（延迟）之间的权衡，这取决于模型用于思考的 token 数量。

该 `gpt-oss` 这些模型提供三个不同级别的推理力度供你选择：

* **低**：针对需要极快响应且不需要复杂多步推理的任务进行了优化。
* **中**：在性能和速度之间取得平衡。
* **高**：为需要它的任务提供最强的推理性能，不过这会带来更高的延迟。

### :gear: 推荐设置

OpenAI 建议这两个模型使用以下推理设置：

`temperature=1.0`, `top_p=1.0`, `top_k=0`

* <mark style="background-color:green;">**温度为 1.0**</mark>
* Top\_K = 0（或者试试 100，可能效果更好）
* Top\_P = 1.0
* 建议最小上下文：16,384
* 最大上下文长度窗口：131,072

**聊天模板：**

```
<|start|>system<|message|>你是 ChatGPT，一个由 OpenAI 训练的大型语言模型。\n知识截止时间：2024-06\n当前日期：2025-08-05\n\n推理：中\n\n# 有效通道：analysis, commentary, final。每条消息都必须包含通道。<|end|><|start|>user<|message|>你好<|end|><|start|>assistant<|channel|>final<|message|>你好！<|end|><|start|>user<|message|>1+1 等于多少？<|end|><|start|>assistant
```

句子/生成结束标记：EOS 是 `<|return|>`

### 运行 gpt-oss-20B

<figure><img src="/files/23ef7c8efdc5bbe981661eb2c4c3d93939e25ebd" alt=""><figcaption></figcaption></figure>

为了让我们的动态 4-bit 量化达到每秒 6+ token 的推理速度，至少需要 **14GB 的统一内存** （VRAM 和 RAM 合计）或 **14GB 的系统内存** 。经验法则是，你可用的内存应当等于或大于你正在使用的模型大小。GGUF 链接： [unsloth/gpt-oss-20b-GGUF](https://huggingface.co/unsloth/gpt-oss-20b-GGUF)

**注意：** 模型可以在低于其总大小的内存上运行，但这会减慢推理速度。只有为了最快速度才需要最大内存。

{% hint style="info" %}
遵循 [**上面的最佳实践**](#recommended-settings)。它们与 120B 模型相同。
{% endhint %}

你现在可以在 Google Colab、Docker、LM Studio 或 llama.cpp 上运行该模型。见下文：

> **你可以使用我们的** [**Google Colab 笔记本免费运行 gpt-oss-20b**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/GPT_OSS_MXFP4_\(20B\)-Inference.ipynb)

#### 🦥 Unsloth Studio 指南

在本教程中，我们将使用 [Unsloth Studio](/docs/zh/xin/studio.md)，这是我们用于运行和训练 LLM 的新网页 UI。使用 Unsloth Studio，你可以在以下平台本地运行模型： **Mac、Windows**和 Linux，并且：

{% columns %}
{% column %}

* 搜索、下载、 [运行 GGUF](/docs/zh/xin/studio.md#run-models-locally) 和 safetensor 模型
* **对比** 模型 **并排**
* [**自我修复** 工具调用](/docs/zh/xin/studio.md#execute-code--heal-tool-calling) + **网页搜索**
* [**代码执行**](/docs/zh/xin/studio.md#run-models-locally) （Python、Bash）
* [自动推理](https://unsloth.ai/docs/desktop#feature-deep-dive) 参数调优（temp、top-p 等）
* [训练 LLM](/docs/zh/xin/studio.md#no-code-training) 速度快 2 倍，VRAM 占用减少 70%
  {% endcolumn %}

{% column %}

<div data-with-frame="true"><figure><img src="/files/5af4df407c8134f1ff75a4d7535569361c049e51" alt=""><figcaption></figcaption></figure></div>
{% endcolumn %}
{% endcolumns %}

{% stepper %}
{% step %}

#### 安装 Unsloth

在终端中运行：

**MacOS、Linux、WSL：**

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

**Windows PowerShell：**

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

{% endstep %}

{% step %}

#### 启动 Unsloth

**MacOS、Linux、WSL、Windows：**

```bash
unsloth studio -H 0.0.0.0 -p 8888
```

<div data-with-frame="true"><figure><img src="/files/7fd4b2ed7fb55df6d31b4dd1ce1181d57613709b" alt="" width="375"><figcaption></figcaption></figure></div>

**然后打开 `http://localhost:8888` 在你的浏览器中。**
{% endstep %}

{% step %}

#### 搜索并下载 gpt-oss-20b

首次启动时，你需要创建密码以保护你的账户，并在之后重新登录。随后你会看到一个简短的引导向导，用于选择模型、数据集和基本设置。你可以随时跳过。

然后前往 [Unsloth Chat](/docs/zh/xin/studio/chat.md) 标签页，在搜索栏中搜索 gpt-oss，然后下载你想要的模型和量化版本。

<div data-with-frame="true"><figure><img src="/files/d5a19e2c7b60840abde31887a1b0ff9d6778c86d" alt="" width="375"><figcaption></figcaption></figure></div>
{% endstep %}

{% step %}

#### 运行 gpt-oss-20b

在使用 Unsloth Studio 时，推理参数应会自动设置，不过你仍然可以手动更改。你也可以编辑上下文长度、聊天模板和其他设置。

更多信息请查看我们的 [Unsloth Studio 推理指南](/docs/zh/xin/studio/chat.md).

<div data-with-frame="true"><figure><img src="/files/6273055e6bbde016134838582519f00de2201635" alt="" width="563"><figcaption></figcaption></figure></div>
{% endstep %}
{% endstepper %}

#### 🐋 Docker：运行 gpt-oss-20b 教程

如果你已经安装了 Docker desktop，只需运行下面的命令即可：

```bash
docker model run hf.co/unsloth/gpt-oss-20b-GGUF:F16
```

#### :sparkles: Llama.cpp：运行 gpt-oss-20b 教程

1. 获取最新的 `llama.cpp` 在 [GitHub 这里](https://github.com/ggml-org/llama.cpp)。你也可以按照下面的构建说明操作。将 `-DGGML_CUDA=ON` 改为 `-DGGML_CUDA=OFF` 如果你没有 GPU，或者只想进行 CPU 推理。 **对于 Apple Mac / Metal 设备**，设置 `-DGGML_CUDA=OFF` 然后按常规继续——Metal 支持默认开启。

```bash
apt-get update
apt-get install pciutils build-essential cmake curl libcurl4-openssl-dev -y
git clone https://github.com/ggml-org/llama.cpp
cmake llama.cpp -B llama.cpp/build \
    -DBUILD_SHARED_LIBS=OFF -DGGML_CUDA=ON -DLLAMA_CURL=ON
cmake --build llama.cpp/build --config Release -j --clean-first --target llama-cli llama-gguf-split
cp llama.cpp/build/bin/llama-* llama.cpp
```

2. 你可以通过以下方式直接从 Hugging Face 拉取：

   ```bash
   ./llama.cpp/llama-cli \
       -hf unsloth/gpt-oss-20b-GGUF:F16 \\
       --jinja -ngl 99 --ctx-size 16384 \\
       --temp 1.0 --top-p 1.0 --top-k 0
   ```
3. 通过以下方式下载模型（在安装 `pip install huggingface_hub hf_transfer` ）。如果下载卡住，请参见 [Hugging Face Hub、XET 调试](/docs/zh/ji-chu-zhi-shi/troubleshooting-and-faqs/hugging-face-hub-xet-debugging.md)

```python
# !pip install huggingface_hub hf_transfer
import os
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
from huggingface_hub import snapshot_download
snapshot_download(
    repo_id = "unsloth/gpt-oss-20b-GGUF",
    local_dir = "unsloth/gpt-oss-20b-GGUF",
    allow_patterns = ["*F16*"],
)
```

### 运行 gpt-oss-120b：

<figure><img src="/files/45f395de6fdc2450938cfc54d7f786b07fff7500" alt=""><figcaption></figcaption></figure>

为了让我们的 1-bit 量化达到每秒 6+ token 的推理速度，我们建议至少 **66GB 的统一内存** （VRAM 和 RAM 合计）或 **66GB 的系统内存** 。经验法则是，你可用的内存应当等于或大于你正在使用的模型大小。GGUF 链接： [unsloth/gpt-oss-120b-GGUF](https://huggingface.co/unsloth/gpt-oss-120b-GGUF)

**注意：** 模型可以在低于其总大小的内存上运行，但这会减慢推理速度。只有为了最快速度才需要最大内存。

{% hint style="info" %}
遵循 [**上面的最佳实践**](#recommended-settings)。它们与 20B 模型相同。
{% endhint %}

#### 🦥 Unsloth Studio 指南

在本教程中，我们将使用 [Unsloth Studio](/docs/zh/xin/studio.md)，这是我们用于运行和训练 LLM 的新网页 UI。使用 Unsloth Studio，你可以在以下平台本地运行模型： **Mac、Windows**和 Linux，并且：

{% columns %}
{% column %}

* 搜索、下载、 [运行 GGUF](/docs/zh/xin/studio.md#run-models-locally) 和 safetensor 模型
* **对比** 模型 **并排**
* [**自我修复** 工具调用](/docs/zh/xin/studio.md#execute-code--heal-tool-calling) + **网页搜索**
* [**代码执行**](/docs/zh/xin/studio.md#run-models-locally) （Python、Bash）
* [自动推理](https://unsloth.ai/docs/desktop#feature-deep-dive) 参数调优（temp、top-p 等）
* [训练 LLM](/docs/zh/xin/studio.md#no-code-training) 速度快 2 倍，VRAM 占用减少 70%
  {% endcolumn %}

{% column %}

<div data-with-frame="true"><figure><img src="/files/5af4df407c8134f1ff75a4d7535569361c049e51" alt=""><figcaption></figcaption></figure></div>
{% endcolumn %}
{% endcolumns %}

{% stepper %}
{% step %}

#### 安装 Unsloth

**MacOS、Linux、WSL：**

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

**Windows PowerShell：**

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

{% endstep %}

{% step %}

#### 设置 Unsloth Studio（一次性）

设置会自动安装 Node.js（通过 nvm）、构建前端、安装所有 Python 依赖，并构建启用 CUDA 支持的 llama.cpp。

{% hint style="info" %}
**WSL 用户：** 系统会提示你输入 `sudo` 密码，以安装构建依赖项（`cmake`, `git`, `libcurl4-openssl-dev`).
{% endhint %}
{% endstep %}

{% step %}

#### 启动 Unsloth

**MacOS、Linux、WSL：**

```bash
source unsloth_studio/bin/activate
unsloth studio -H 0.0.0.0 -p 8888
```

**Windows Powershell：**

```bash
& .\unsloth_studio\Scripts\unsloth.exe studio -H 0.0.0.0 -p 8888
```

<div data-with-frame="true"><figure><img src="/files/7fd4b2ed7fb55df6d31b4dd1ce1181d57613709b" alt="" width="375"><figcaption></figcaption></figure></div>

**然后打开 `http://localhost:8888` 在你的浏览器中。**
{% endstep %}

{% step %}

#### 搜索并下载 gpt-oss-120b

首次启动时，你需要创建密码以保护你的账户，并在之后重新登录。随后你会看到一个简短的引导向导，用于选择模型、数据集和基本设置。你可以随时跳过。

然后前往 [Unsloth Chat](/docs/zh/xin/studio/chat.md) 标签页，在搜索栏中搜索 gpt-oss，然后下载你想要的模型和量化版本。

<div data-with-frame="true"><figure><img src="/files/f32409ba1816e2e09cb2aed69cd25259ca2ceefa" alt="" width="375"><figcaption></figcaption></figure></div>
{% endstep %}

{% step %}

#### 运行 gpt-oss-120b

在使用 Unsloth Studio 时，推理参数应会自动设置，不过你仍然可以手动更改。你也可以编辑上下文长度、聊天模板和其他设置。

更多信息请查看我们的 [Unsloth Studio 推理指南](/docs/zh/xin/studio/chat.md).

<div data-with-frame="true"><figure><img src="/files/6273055e6bbde016134838582519f00de2201635" alt="" width="563"><figcaption></figcaption></figure></div>
{% endstep %}
{% endstepper %}

#### 📖 Llama.cpp：运行 gpt-oss-120b 教程

对于 gpt-oss-120b，我们将专门使用 Llama.cpp 进行优化推理。

{% hint style="success" %}
如果你想要 **完整精度的未量化版本**，请使用我们的 `F16` 版本！
{% endhint %}

1. 获取最新的 `llama.cpp` 在 [GitHub 这里](https://github.com/ggml-org/llama.cpp)。你也可以按照下面的构建说明操作。将 `-DGGML_CUDA=ON` 改为 `-DGGML_CUDA=OFF` 如果你没有 GPU，或者只想进行 CPU 推理。

   ```bash
   apt-get update
   apt-get install pciutils build-essential cmake curl libcurl4-openssl-dev -y
   git clone https://github.com/ggml-org/llama.cpp
   cmake llama.cpp -B llama.cpp/build \
       -DBUILD_SHARED_LIBS=OFF -DGGML_CUDA=ON -DLLAMA_CURL=ON
   cmake --build llama.cpp/build --config Release -j --clean-first --target llama-cli llama-gguf-split
   cp llama.cpp/build/bin/llama-* llama.cpp
   ```
2. 你可以直接使用 llama.cpp 下载模型，但我通常建议使用 `huggingface_hub` 要直接使用 llama.cpp，请执行：

   ```bash
   ./llama.cpp/llama-cli \
       -hf unsloth/gpt-oss-120b-GGUF:F16 \\
       --ctx-size 16384 \\
       --n-gpu-layers 99 \\
       -ot ".ffn_.*_exps.=CPU" \\
       --temp 1.0 \
       --min-p 0.0 \\
       --top-p 1.0 \
       --top-k 0 \\
   ```
3. 或者，通过以下方式下载模型（安装后 `pip install huggingface_hub hf_transfer` ）。你可以选择 UD-Q2\_K\_XL，或其他量化版本。

   ```python
   # !pip install huggingface_hub hf_transfer
   import os
   os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "0" # 有时会触发速率限制，因此设置为 0 以禁用
   from huggingface_hub import snapshot_download
   snapshot_download(
       repo_id = "unsloth/gpt-oss-120b-GGUF",
       local_dir = "unsloth/gpt-oss-120b-GGUF",
       allow_patterns = ["*F16*"],
   )
   ```
4. 在对话模式下运行模型并尝试任何提示词。
5. 编辑 `--threads -1` 以设置 CPU 线程数， `--ctx-size` 262114 用于上下文长度， `--n-gpu-layers 99` 以设置 GPU 负载到多少层。如果你的 GPU 内存不足，请尝试调整它。如果你只进行 CPU 推理，也请将其移除。

{% hint style="success" %}
使用 `-ot ".ffn_.*_exps.=CPU"` 以将所有 MoE 层卸载到 CPU！这样实际上可以让你把所有非 MoE 层放到 1 张 GPU 上，从而提高生成速度。如果你的 GPU 容量更大，你可以自定义正则表达式以容纳更多层。更多选项请参见 [这里](#improving-generation-speed).
{% endhint %}

{% code overflow="wrap" %}

```bash
./llama.cpp/llama-cli \
    --model unsloth/gpt-oss-120b-GGUF/gpt-oss-120b-F16.gguf \\
    --ctx-size 16384 \\
    --n-gpu-layers 99 \\
    -ot ".ffn_.*_exps.=CPU" \\
    --temp 1.0 \
    --min-p 0.0 \\
    --top-p 1.0 \
    --top-k 0 \\
```

{% endcode %}

### :tools: 提升生成速度

如果你有更多 VRAM，可以尝试卸载更多 MoE 层，或者直接卸载整层。

通常， `-ot ".ffn_.*_exps.=CPU"` 会将所有 MoE 层卸载到 CPU！这样实际上可以让你把所有非 MoE 层放到 1 张 GPU 上，从而提高生成速度。如果你的 GPU 容量更大，你可以自定义正则表达式以容纳更多层。

如果你有更多一点的 GPU 内存，试试 `-ot ".ffn_(up|down)_exps.=CPU"` 这会卸载上投影和下投影 MoE 层。

试试 `-ot ".ffn_(up)_exps.=CPU"` 如果你有更多 GPU 内存。这会只卸载上投影 MoE 层。

你也可以自定义正则表达式，例如 `-ot "\.(6|7|8|9|[0-9][0-9]|[0-9][0-9][0-9])\.ffn_(gate|up|down)_exps.=CPU"` 表示只从第 6 层开始卸载 gate、up 和 down MoE 层。

该 [最新的 llama.cpp 版本](https://github.com/ggml-org/llama.cpp/pull/14363) 还引入了高吞吐模式。使用 `llama-parallel`。阅读更多 [这里](https://github.com/ggml-org/llama.cpp/tree/master/examples/parallel)。你还可以 **将 KV cache 量化为 4bit** ，例如以减少 VRAM/RAM 传输，这也能让生成过程更快。

## 🦥 使用 Unsloth 微调 gpt-oss

{% hint style="success" %}
[**8 月 28 日更新**](/docs/zh/mo-xing/gpt-oss-how-to-run-and-fine-tune/long-context-gpt-oss-training.md#new-saving-to-gguf-vllm-after-gpt-oss-training)**:** 你现在可以将通过 QLoRA 微调后的 gpt-oss 模型导出/保存到 llama.cpp、vLLM、HF 等。

我们还推出了 [Unsloth Flex Attention](/docs/zh/mo-xing/gpt-oss-how-to-run-and-fine-tune/long-context-gpt-oss-training.md#introducing-unsloth-flex-attention-support) ，它可以实现 **>8× 更长的上下文长度**, **>50% 更少的 VRAM 占用** 和 **>1.5× 更快的训练** ，相较于所有实现。 [在此阅读更多](/docs/zh/mo-xing/gpt-oss-how-to-run-and-fine-tune/long-context-gpt-oss-training.md#introducing-unsloth-flex-attention-support)
{% endhint %}

Unsloth gpt-oss 微调速度快 1.5 倍，VRAM 占用减少 70%，并支持 10 倍更长的上下文长度。gpt-oss-20b 的 QLoRA 训练可在 14GB VRAM 上运行，而 gpt-oss-120b 可在 65GB VRAM 上运行。

* **QLoRA 要求：** gpt-oss-20b = 14GB VRAM • gpt-oss-120b = 65GB VRAM。
* **BF16 LoRA 要求：** gpt-oss-20b = 44GB VRAM • gpt-oss-120b = 210GB VRAM。

阅读我们关于微调 gpt-oss 的分步教程：

{% content-ref url="/pages/0148694a359883dd63c310577df8161407074855" %}
[教程：如何微调 gpt-oss](/docs/zh/mo-xing/gpt-oss-how-to-run-and-fine-tune/tutorial-how-to-fine-tune-gpt-oss.md)
{% endcontent-ref %}

{% hint style="success" %}
你现在可以将通过 QLoRA 微调后的 gpt-oss 模型导出/保存到 llama.cpp、vLLM、HF 等。
{% endhint %}

可免费使用的 Unsloth 笔记本，用于微调 gpt-oss：

* gpt-oss-20b [推理 + 对话笔记本](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/gpt-oss-\(20B\)-Fine-tuning.ipynb)

### 强化学习（GRPO）

Unsloth 现在支持 gpt-oss 的 RL！我们制作了两个笔记本，更多细节请阅读我们专门关于 gpt-oss RL 的博客： [gpt-oss RL](/docs/zh/mo-xing/gpt-oss-how-to-run-and-fine-tune/gpt-oss-reinforcement-learning.md)

| [2048 笔记本](https://colab.research.google.com/github/openai/gpt-oss/blob/main/examples/reinforcement-fine-tuning.ipynb) （OpenAI 官方示例） | [Kernel 生成笔记本](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/gpt-oss-\(20B\)-GRPO.ipynb) |
| ------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |

### 💾**新功能：在 gpt-oss 训练后保存到 GGUF、vLLM**

你现在可以对 gpt-oss 进行 QLoRA 微调，并直接将模型保存、导出或合并到 **llama.cpp**, **vLLM**，或 **HF** ——不只是 Unsloth。我们希望很快发布一个免费笔记本。

此前，任何经过 QLoRA 微调的 gpt-oss 模型都只能在 Unsloth 中运行。我们通过引入 **MXFP4 的按需反量化** 基础模型（如 gpt-oss）在 LoRA 合并过程中，移除了这一限制。这使得可以 **将你微调后的模型导出为 bf16 格式**.

在微调完 gpt-oss 模型后，你现在可以使用一个 **单条命令**:

```python
model.save_pretrained_merged(save_directory, tokenizer)
```

如果你更希望直接合并模型并推送到 Hugging Face Hub，也可以使用：

```python
model.push_to_hub_merged(repo_name, tokenizer=tokenizer, token=hf_token)
```

### 💡让高效的 gpt-oss 微调真正可用

我们发现，虽然 MXFP4 效率很高，但它并不原生支持在 gpt-oss 上训练。为了克服这一限制，我们通过模拟 `Bitsandbytes` NF4 量化，为 MXFP4 层实现了自定义训练函数。

我们直接利用了 OpenAI 的 Triton Kernels 库来支持 MXFP4 推理。然而，对于微调/训练，MXFP4 内核目前还不支持训练，因为反向传播尚未实现。我们正在积极用 Triton 实现它！有一个名为 `W_TRANSPOSE` 的标志，如前所述 [这里](https://github.com/triton-lang/triton/blob/main/python/triton_kernels/triton_kernels/matmul_ogs_details/_matmul_ogs.py#L39)，它应该被实现。导数可以通过权重矩阵的转置来计算，因此我们必须实现转置操作。

如果你想使用除 Unsloth 之外的任何库来训练 gpt-oss，那么你需要在训练前将权重上转换为 bf16。不过，这种方法 **会显著增加** VRAM 占用和训练时间，最高可达 **内存占用增加 300%**! <mark style="background-color:green;">**所有其他训练方法训练 20b 模型至少需要 65GB VRAM，而 Unsloth 仅需 14GB VRAM（-80%）。**</mark>

由于两个模型都使用 MoE 架构，20B 模型每个 token 从 32 个专家中选择 4 个，而 120B 模型每个 token 从 128 个中选择 4 个。在训练和发布期间，权重以 MXFP4 格式存储为 `nn.Parameter` 对象，而不是 `nn.Linear` 层，这使量化变得复杂，尤其是因为 MoE/MLP 专家大约占 20B 参数中的 19B。

为了启用 `BitsandBytes` 量化和节省内存的微调，我们将这些参数转换为 `nn.Linear` 层。尽管这会略微降低操作速度，但它使得可以在显存有限的 GPU 上进行微调，这是一个值得的权衡。

### 数据集微调指南

虽然 gpt-oss 只支持推理，你仍然可以使用非推理 [数据集](/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide/datasets-guide.md)来微调它，但这可能会影响其推理能力。如果你希望保持其推理能力（可选），你可以使用直接答案和思维链示例的混合。你的数据集中至少应使用 <mark style="background-color:green;">75% 推理</mark> 和 <mark style="background-color:green;">25% 非推理</mark> ，以使模型保留其推理能力。

我们的 gpt-oss-20b 对话笔记本使用了 OpenAI 的示例，即 Hugging Face 的 Multilingual-Thinking 数据集。使用该数据集的目的是让模型学习并发展这四种不同语言中的推理能力。

<figure><img src="/files/26eb2ab9552829819809859094141e67eac385e6" alt=""><figcaption></figcaption></figure>


---

# 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/mo-xing/gpt-oss-how-to-run-and-fine-tune.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.
