# gpt-oss：如何运行指南

OpenAI 发布“**gpt-oss-120b'** 和“**gpt-oss-20b'**”，这是两个采用 Apache 2.0 许可的 SOTA 开源语言模型。这两个 128k 上下文模型在推理、工具使用和智能体任务上都优于同等规模的开源模型。现在你可以使用 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) **使用我们的免费微调 gpt-oss-20b** [**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:gpt-oss 的 Unsloth 修复

{% 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>

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

```python
messages = [
    {"role" : "user", "content" : "What is 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` 类似于你可以添加的系统提示。
3. `model_identity` 最好保持不变——你可以编辑它，但我们不确定自定义内容是否会生效。

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

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

我们的 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 %}

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

我们还会将所有操作的精度（例如路由器）在 float16 机器上改为 float32。

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

以下是针对该模型 [20B](#run-gpt-oss-20b) 和 [120B](#run-gpt-oss-120b) 模型变体。

{% hint style="info" %}
任何小于 F16 的量化，包括 2-bit，精度损失都很小，因为只有一部分（例如注意力层）是低位宽，而大多数仍保持全精度。这就是为什么尺寸接近 F16 模型；例如，2-bit（11.5 GB）版本的表现几乎与完整 16-bit（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;">**Temperature 为 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
```

句末/生成结束 token：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 上运行该模型。见下文：

> **你可以使用我们的免费方式运行 gpt-oss-20b** [**Google Colab 笔记本**](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 的新网页界面。使用 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）
* [自动推理](/docs/zh/xin/studio.md#model-arena) 参数调优（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

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

然后前往 [Studio 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/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 的新网页界面。使用 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）
* [自动推理](/docs/zh/xin/studio.md#model-arena) 参数调优（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

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

然后前往 [Studio 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 缓存量化为 4bits** ，例如减少 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 倍，显存占用减少 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 %}

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

* 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 官方示例） | [内核生成笔记本](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 模型后，你现在可以将其合并为 16 位格式，并使用一个 **单个命令**:

```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 仅支持推理，但你仍然可以使用非推理的 [dataset](/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: 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:

```
GET https://unsloth.ai/docs/zh/mo-xing/gpt-oss-how-to-run-and-fine-tune.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
