# 教程：如何微调 gpt-oss

在本含截图的指南中，你将学习如何微调你自己的自定义 gpt-oss 模型，方式为 [本地](#local-gpt-oss-fine-tuning) 在你的机器上使用 [Unsloth](https://github.com/unslothai/unsloth) 或免费使用 [Google Colab](#colab-gpt-oss-fine-tuning)。我们将引导你完成从设置到运行并保存已训练模型的整个过程。

{% hint style="success" %}
[**8 月 28 日更新**](https://unsloth.ai/docs/zh/mo-xing/long-context-gpt-oss-training#introducing-unsloth-flex-attention-support)**:** 你现在可以将 QLoRA 微调的 gpt-oss 模型导出/保存为 llama.cpp、vLLM、HF 等格式。

我们还引入了 [Unsloth 弹性注意力（Flex Attention）](https://unsloth.ai/docs/zh/mo-xing/long-context-gpt-oss-training#introducing-unsloth-flex-attention-support) 它实现了 **超过 8 倍 更长的上下文长度**, **超过 50% 更少的显存使用** 以及 **超过 1.5 倍 更快的训练** 相较于所有实现。 [在此处阅读更多](https://unsloth.ai/docs/zh/mo-xing/long-context-gpt-oss-training#introducing-unsloth-flex-attention-support)
{% endhint %}

> **快速开始：** 使用我们的以下方式免费微调 gpt-oss-20b： [Colab 笔记本](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/gpt-oss-\(20B\)-Fine-tuning.ipynb)

与所有其他 FA2 实现相比，Unsloth 对 gpt-oss 的微调实现了 1.5× 的训练加速、70% 的显存减少以及 10 倍更长的上下文长度 —— 且无精度损失。

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

<a href="#local-gpt-oss-fine-tuning" class="button secondary">本地指南</a><a href="#colab-gpt-oss-fine-tuning" class="button secondary">Colab 指南</a>

## 🌐 Colab gpt-oss 微调

本节涵盖使用我们的 Google Colab 来微调 gpt-oss [笔记本](https://unsloth.ai/docs/zh/kai-shi-shi-yong/unsloth-notebooks)。你也可以将 gpt-oss 笔记本保存并在你喜欢的代码编辑器中使用，并按照我们的 [本地 gpt-oss 指南](#local-gpt-oss-fine-tuning).

{% stepper %}
{% step %}

#### 在 Colab 中安装 Unsloth

在 Colab 中，运行单元格 **从上到下**。使用 **全部运行** 作为首次运行。第一个单元格会安装 Unsloth（以及相关依赖）并打印 GPU/内存信息。如果单元格抛出错误，只需重新运行即可。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-b5e2d89ed2815aa5dd6be7e4d2424df454c46ca0%2Fchrome_wTbzfmSI21.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-bbea9a8316e670247b6e69ff62d45a0dea189f35%2Fchrome_yPnb553OGW.png?alt=media" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### 配置 gpt-oss 和推理强度

我们将加载 **`gpt-oss-20b`** 使用 Unsloth 的 [线性化版本](https://unsloth.ai/docs/zh/mo-xing/gpt-oss-how-to-run-and-fine-tune/..#making-efficient-gpt-oss-fine-tuning-work) （因为其他版本均无法工作）。

配置以下参数：

* `max_seq_length = 1024`
  * 推荐用于快速测试和初步实验。
* `load_in_4bit = True`
  * 使用 `False` 进行 LoRA 训练（注意：将此设置为 `False` 将至少需要 43GB 显存）。你 ***必须*** 同时设置 **`model_name = "unsloth/gpt-oss-20b-BF16"`**

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

你应该会看到类似下面的输出。注意：我们显式将 `数据类型（dtype）` 更改为 `float32` 以确保正确的训练行为。

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

{% step %}

#### 微调超参数（LoRA）

现在是调整训练超参数的时候了。想深入了解如何、何时以及调哪些参数，请查看我们的 [详细超参数指南](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide/lora-hyperparameters-guide).

{% hint style="info" %}
为避免 [过拟合](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide/lora-hyperparameters-guide#avoiding-overfitting-and-underfitting)，请监控你的训练损失并避免将这些值设置得过高。
{% endhint %}

此步骤为参数高效微调添加 LoRA 适配器。只有约 1% 的模型参数会被训练，这使得过程明显更高效。

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

{% step %}

#### 尝试推理

在笔记本中，有一个名为 *“推理强度”* 的部分，演示了 gpt-oss 在 Colab 中的推理运行。你可以跳过此步骤，但在微调完成后仍需要稍后运行模型。

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

{% step %}

#### 数据准备

在此示例中，我们将使用 [`HuggingFaceH4/Multilingual-Thinking`](https://huggingface.co/datasets/HuggingFaceH4/Multilingual-Thinking)。该数据集包含从用户问题中派生的连贯思路（chain-of-thought）推理示例，这些问题已从英语翻译成另外四种语言。

这是 OpenAI 微调手册中引用的相同数据集。

使用多语言数据集的目标是帮助模型学习并在多种语言之间泛化推理模式。

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

gpt-oss 引入了一个推理强度系统，用于控制模型执行多少推理。默认情况下，推理强度设置为 `低`，但你可以通过将 `reasoning_effort` 参数设置为 `低`, `中等` 或 `高`.

示例：

```python
tokenizer.apply_chat_template(
    text, 
    tokenize = False, 
    add_generation_prompt = False,
    reasoning_effort = "medium",
)
```

为格式化数据集，我们应用了 gpt-oss 提示的自定义版本：

```python
from unsloth.chat_templates import standardize_sharegpt
dataset = standardize_sharegpt(dataset)
dataset = dataset.map(formatting_prompts_func, batched = True,)
```

让我们通过打印第一个示例来查看数据集：

```notebook-python
print(dataset[0]['text'])
```

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

gpt-oss 的一个独特特性是它使用 [**OpenAI Harmony 格式**](https://github.com/openai/harmony)**,** ，该格式支持结构化对话、推理输出和工具调用。此格式包含诸如 `<|start|>` , `<|message|>` ，以及 `<|return|>` .

{% hint style="info" %}
🦥 Unsloth 修复了聊天模板以确保其正确性。有关我们模板修复的技术细节，请参阅这条 [推文](https://x.com/danielhanchen/status/1953901104150065544) 。
{% endhint %}

随意调整提示和结构以适应你自己的数据集或用例。有关更多指导，请参阅我们的 [数据集指南](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide/datasets-guide).
{% endstep %}

{% step %}

#### 训练模型

我们已预先选择了训练超参数以获得最佳结果。但是，你可以根据你的具体用例修改它们。参考我们的 [超参数指南](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide/lora-hyperparameters-guide).

在此示例中，为了加快流程我们训练 60 步。要进行完整训练，请设置 `num_train_epochs=1` 并通过设置 `max_steps=None`.

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-942bbba058a27b056cab8a21bed15d988e39fafc%2Fchrome_R85PmZRHMQ.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-5ace71760531cf39f14499baf9ca0f78d8018756%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### 在训练过程中，监控损失以确保其随时间下降。这可以确认训练过程正常运行。

推理：运行已训练的模型

现在是使用微调模型运行推理的时候了。你可以修改指令和输入，但将输出留空。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-85e0e0aac7ae30bf7108470795fbabf815176abe%2Fchrome_jbJmBTaY7B.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-0cb10ed022a5b451fe0bf4a4b9b35bef94364a5b%2Fchrome_ORco4bpZZ6.png?alt=media" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### 这应产生类似于以下的输出：

保存/导出你的模型 **要保存微调模型，你可以将微调后的模型导出为** bf16 格式， **使用我们的** 对 MXFP4 基线模型的按需反量化 `功能，使用`save\_method="merged\_16bit" **或以原生** MXFP4 `Safetensors 格式使用` .

save\_method="mxfp4" **或以原生** 原生合并格式与 **bf16 格式**相比提供显著的性能提升：它最多使用 75% 更少的磁盘空间，减少 50% 的显存消耗，加速合并 5-10 倍，并实现更快的转换为 **GGUF** 格式。

{% hint style="success" %}
新增：现在支持将 QLoRA 微调模型保存或合并为 GGUF，以便在其他框架中使用（例如 Hugging Face、带 GGUF 的 llama.cpp）。
{% endhint %}

微调你的 gpt-oss 模型后，你可以将其合并为 **或以原生** 格式，使用：

```python
model.save_pretrained_merged(save_directory, tokenizer, save_method="mxfp4)
```

如果你更愿意合并模型并直接推送到 hugging-face hub：

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

#### :sparkles: 保存到 Llama.cpp

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

   ```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.cp
   ```
2. 转换已 **或以原生** 合并的模型：

   ```bash
   python3 llama.cpp/convert_hf_to_gguf.py gpt-oss-finetuned-merged/ --outfile gpt-oss-finetuned-mxfp4.gguf
   ```
3. 在量化模型上运行推理：

   ```bash
   llama.cpp/llama-cli --model gpt-oss-finetuned-mxfp4.gguf \
       --jinja -ngl 99 --threads -1 --ctx-size 16384 \
       --temp 1.0 --top-p 1.0 --top-k 0 \
        -p "生命和宇宙的意义是"
   ```

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

## 🖥️ 本地 gpt-oss 微调

本章涵盖在本地设备上微调 gpt-oss。尽管 **gpt-oss-20b** 微调可以在仅 14GB 显存下运行，但我们建议至少有 16GB 显存以确保训练运行稳定可靠。

{% hint style="info" %}
我们建议下载或将我们的 Colab 元素整合到你的本地设置中以便更方便使用。 [笔记本](https://unsloth.ai/docs/zh/kai-shi-shi-yong/unsloth-notebooks) 将 Unsloth 安装到本地
{% endhint %}

{% stepper %}
{% step %}

#### 确保你的设备

与 Unsloth 兼容 [，你可以阅读我们的详细](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-for-beginners/unsloth-requirements) 安装指南 [你也可以使用我们的](https://unsloth.ai/docs/zh/kai-shi-shi-yong/install).

**Docker 镜像** [**来安装 Unsloth**](https://unsloth.ai/docs/models/qwen3-coder-next)**.**

注意， `pip install unsloth` 对于此设置不起作用，因为我们需要使用最新的 PyTorch、Triton 和相关包。请使用以下特定命令安装 Unsloth：

```python
# 我们正在安装最新的 Torch、Triton、OpenAI 的 Triton 内核、Transformers 和 Unsloth！
!pip install --upgrade -qqq uv
try: import numpy; install_numpy = f"numpy=={numpy.__version__}"
except: install_numpy = "numpy"
!uv pip install -qqq \
    "torch>=2.8.0" "triton>=3.4.0" {install_numpy} \
    "unsloth_zoo[base] @ git+https://github.com/unslothai/unsloth-zoo" \
    "unsloth[base] @ git+https://github.com/unslothai/unsloth" \
    torchvision bitsandbytes \
    git+https://github.com/huggingface/transformers \
    git+https://github.com/triton-lang/triton.git@05b2c186c1b6c9a08375389d5efe9cb4c401c075#subdirectory=python/triton_kernels
```

{% endstep %}

{% step %}

#### 配置 gpt-oss 和推理强度

我们将加载 **`gpt-oss-20b`** 使用 Unsloth 的 [线性化版本](https://unsloth.ai/docs/zh/mo-xing/gpt-oss-how-to-run-and-fine-tune/..#making-efficient-gpt-oss-fine-tuning-work) （因为其他版本无法用于 QLoRA 微调）。配置以下参数：

* `max_seq_length = 2048`
  * 推荐用于快速测试和初步实验。
* `load_in_4bit = True`
  * 使用 `False` 进行 LoRA 训练（注意：将此设置为 `False` 将至少需要 43GB 显存）。你 ***必须*** 同时设置 **`model_name = "unsloth/gpt-oss-20b-BF16"`**

<pre class="language-python"><code class="lang-python">from unsloth import FastLanguageModel
import torch
max_seq_length = 1024
dtype = None

# 我们支持的 4bit 预量化模型，可实现 4 倍更快的下载并避免 OOM。
fourbit_models = [
    "unsloth/gpt-oss-20b-unsloth-bnb-4bit", # 使用 bitsandbytes 4bit 量化的 20B 模型
<strong>    "unsloth/gpt-oss-120b-unsloth-bnb-4bit",
</strong>    "unsloth/gpt-oss-20b", # 使用 MXFP4 格式的 20B 模型
    "unsloth/gpt-oss-120b",
] # 更多模型见 https://huggingface.co/unsloth

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name = "unsloth/gpt-oss-20b",
    dtype = dtype, # None 表示自动检测
    max_seq_length = max_seq_length, # 为长上下文选择任意值！
    load_in_4bit = True,  # 4 位量化以减少内存
    full_finetuning = False, # [新！] 我们现在支持完全微调！
    # token = "hf_...", # 如果使用受限模型可使用
)
</code></pre>

你应该会看到类似下面的输出。注意：我们显式将 `数据类型（dtype）` 更改为 `float32` 以确保正确的训练行为。
{% endstep %}

{% step %}

#### 微调超参数（LoRA）

现在是调整训练超参数的时候了。想深入了解如何、何时以及调哪些参数，请查看我们的 [详细超参数指南](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide/lora-hyperparameters-guide).

{% hint style="info" %}
为避免 [过拟合](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide/lora-hyperparameters-guide#avoiding-overfitting-and-underfitting)，请监控你的训练损失并避免将这些值设置得过高。
{% endhint %}

此步骤为参数高效微调添加 LoRA 适配器。只有约 1% 的模型参数会被训练，这使得过程明显更高效。

```python
model = FastLanguageModel.get_peft_model(
    model,
    r = 8, # 选择任何大于 0 的数！建议 8、16、32、64、128
    target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
                      "gate_proj", "up_proj", "down_proj",],
    lora_alpha = 16,
    lora_dropout = 0, # 支持任意值，但 = 0 为优化设置
    bias = "none",    # 支持任意值，但 = "none" 为优化设置
    # [新] “unsloth” 使用 30% 更少的显存，可容纳 2 倍更大的批次！
    use_gradient_checkpointing = "unsloth", # 对于非常长的上下文可使用 True 或 "unsloth"
    random_state = 3407,
    use_rslora = False,  # 我们支持秩稳定化的 LoRA
    loftq_config = None, # 以及 LoftQ
)
```

{% endstep %}

{% step %}

#### 数据准备

在此示例中，我们将使用 [`HuggingFaceH4/Multilingual-Thinking`](https://huggingface.co/datasets/HuggingFaceH4/Multilingual-Thinking)。该数据集包含从用户问题中派生的连贯思路（chain-of-thought）推理示例，这些问题已从英语翻译成另外四种语言。

这是 OpenAI 微调手册中引用的相同数据集。使用多语言数据集的目标是帮助模型学习并在多种语言之间泛化推理模式。

```python
def formatting_prompts_func(examples):
    convos = examples["messages"]
    texts = [tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = False) for convo in convos]
    return { "text" : texts, }
pass

from datasets import load_dataset

dataset = load_dataset("HuggingFaceH4/Multilingual-Thinking", split="train")
dataset
```

gpt-oss 引入了一个推理强度系统，用于控制模型执行多少推理。默认情况下，推理强度设置为 `低`，但你可以通过将 `reasoning_effort` 参数设置为 `低`, `中等` 或 `高`.

示例：

```python
tokenizer.apply_chat_template(
    text, 
    tokenize = False, 
    add_generation_prompt = False,
    reasoning_effort = "medium",
)
```

为格式化数据集，我们应用了 gpt-oss 提示的自定义版本：

```python
from unsloth.chat_templates import standardize_sharegpt
dataset = standardize_sharegpt(dataset)
dataset = dataset.map(formatting_prompts_func, batched = True,)
```

让我们通过打印第一个示例来查看数据集：

```notebook-python
print(dataset[0]['text'])
```

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

gpt-oss 的一个独特特性是它使用 [**OpenAI Harmony 格式**](https://github.com/openai/harmony)**,** ，该格式支持结构化对话、推理输出和工具调用。此格式包含诸如 `<|start|>` , `<|message|>` ，以及 `<|return|>` .

{% hint style="info" %}
🦥 Unsloth 修复了聊天模板以确保其正确性。有关我们模板修复的技术细节，请参阅这条 [推文](https://x.com/danielhanchen/status/1953901104150065544) 。
{% endhint %}

随意调整提示和结构以适应你自己的数据集或用例。有关更多指导，请参阅我们的 [数据集指南](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide/datasets-guide).
{% endstep %}

{% step %}

#### 训练模型

我们已预先选择了训练超参数以获得最佳结果。但是，你可以根据你的具体用例修改它们。参考我们的 [超参数指南](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide/lora-hyperparameters-guide).

在此示例中，为了加快流程我们训练 60 步。要进行完整训练，请设置 `num_train_epochs=1` 并通过设置 `max_steps=None`.

```python
from trl import SFTConfig, SFTTrainer
trainer = SFTTrainer(
    model = model,
    tokenizer = tokenizer,
    train_dataset = dataset,
    args = SFTConfig(
        per_device_train_batch_size = 1,
        gradient_accumulation_steps = 4,
        warmup_steps = 5,
        # num_train_epochs = 1, # 为一次完整训练设置此项。
        max_steps = 30,
        learning_rate = 2e-4,
        logging_steps = 1,
        optim = "adamw_8bit",
        weight_decay = 0.01,
        lr_scheduler_type = "linear",
        seed = 3407,
        output_dir = "outputs",
        report_to = "none", # 用于 WandB 等时使用
    ),
)
```

来禁用步骤限制。

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

{% step %}

#### 推理：运行你的已训练模型

推理：运行已训练的模型

现在是使用微调模型运行推理的时候了。你可以修改指令和输入，但将输出留空。

```python
messages = [
    {"role": "system", "content": "reasoning language: French\n\nYou are a helpful assistant that can solve mathematical problems."},
    {"role": "user", "content": "Solve x^5 + 3x^4 - 10 = 3."},
]
inputs = tokenizer.apply_chat_template(
    messages,
    add_generation_prompt = True,
    return_tensors = "pt",
    return_dict = True,
    reasoning_effort = "medium",
).to(model.device)
from transformers import TextStreamer
_ = model.generate(**inputs, max_new_tokens = 2048, streamer = TextStreamer(tokenizer))
```

在此示例中，我们通过向系统提示添加特定指令来测试模型用法语进行推理的能力，遵循与我们数据集中相同的结构。

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

{% step %}

#### 保存并导出你的模型

要保存微调模型，它可以在 LoRA 合并过程中以 Safetensors 格式导出，配合我们的新 **使用我们的** 基线模型（例如 gpt-oss）。这使得可能 **将你的微调模型导出为 bf16 格式**.

{% hint style="success" %}
新增：现在支持将 QLoRA 微调模型保存或合并为 GGUF，以便在其他框架中使用（例如 Hugging Face、带 GGUF 的 llama.cpp）。
{% endhint %}

微调你的 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)
```

#### :sparkles: 保存到 Llama.cpp

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

   ```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.cp
   ```
2. 转换并量化合并模型：

   ```bash
   python3 llama.cpp/convert_hf_to_gguf.py gpt-oss-finetuned-merged/ --outfile gpt-oss-finetuned.gguf
   llama.cpp/llama-quantize gpt-oss-finetuned.gguf  gpt-oss-finetuned-Q8_0.gguf Q8_0
   ```
3. 在量化模型上运行推理：

   ```bash
   llama.cpp/llama-cli --model gpt-oss-finetuned-Q8_0.gguf \
       --jinja -ngl 99 --threads -1 --ctx-size 16384 \
       --temp 1.0 --top-p 1.0 --top-k 0 \
        -p "生命和宇宙的意义是"
   ```

{% endstep %}
{% endstepper %}

### 🏁 就是这样！

你已使用 Unsloth 微调了 gpt-oss。我们目前正在开发 RL 和 GRPO 的实现，以及改进的模型保存和运行功能，敬请期待。

一如既往，如果你需要任何帮助，欢迎随时来我们的 [Discord](https://discord.com/invite/unsloth) 或 [Reddit](https://www.reddit.com/r/unsloth/) 。

## ❓常见问题（FAQ）

#### 1. 我可以将模型导出以便稍后在 Hugging Face、llama.cpp GGUF 或 vLLM 中使用吗？

是的，你现在可以 [使用 Unsloth 的新更新保存/导出你微调的 gpt-oss](https://unsloth.ai/docs/zh/mo-xing/long-context-gpt-oss-training#new-saving-to-gguf-vllm-after-gpt-oss-training) 模型！

#### 2. 我可以对 gpt-oss 进行 fp4 或 MXFP4 训练吗？

不，目前没有框架支持 fp4 或 MXFP4 训练。不过 Unsloth 是唯一支持该模型的 QLoRA 4 位微调的框架，从而实现超过 4 倍更少的显存使用。

#### 3. 我可以在训练后将模型导出为 MXFP4 格式吗？

不，目前没有库或框架支持此操作。

#### 4. 我可以对 gpt-oss 进行强化学习（RL）或 GRPO 吗？

可以！Unsloth 现在支持带有 GRPO/GSPO 的 gpt-oss 强化学习。我们使其在免费的 Kaggle 笔记本上可运行，并实现了 RL 最快的推理速度。 [在此处阅读更多](https://unsloth.ai/docs/zh/mo-xing/gpt-oss-how-to-run-and-fine-tune/gpt-oss-reinforcement-learning)

***

***致谢：** 非常感谢* [*Eyera*](https://huggingface.co/Orenguteng) *为本指南做出的贡献！*


---

# 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/tutorial-how-to-fine-tune-gpt-oss.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.
