> 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/ji-chu-zhi-shi/shi-yong-unsloth-xun-lian-ni-zi-ji-de-jue-ce-mo-xing.md).

# 使用 Unsloth 训练你自己的决策模型

微调像 Qwen 和 Gemma 这样的 LLM，用经过校准的概率来做决策。

你现在可以训练你自己的决策模型，例如 **Jev**, **Laya** 和 **Clef** 使用 Unsloth。了解如何微调 [Qwen3.8](/docs/zh/mo-xing/qwen3.8.md) 和 [Gemma 4](/docs/zh/mo-xing/gemma-4.md) LLM，设计高效的数据集格式，并将它们转化为 [决策](/docs/zh/mo-xing/decision-laya.md) 模型，能够 **做出决策** 而不是生成文本。微调后的模型会读取你的输入，对你提供的选项进行评分，并返回一个带概率的选择。

<a href="/docs/zh/ji-chu-zhi-shi/shi-yong-unsloth-xun-lian-ni-zi-ji-de-jue-ce-mo-xing.md#train-in-unsloth" class="button secondary">训练指南</a><a href="/docs/zh/ji-chu-zhi-shi/shi-yong-unsloth-xun-lian-ni-zi-ji-de-jue-ce-mo-xing.md#dataset-format" class="button secondary">数据集指南</a><a href="/docs/zh/mo-xing/decision-laya.md" class="button secondary">Decisions API + 部署指南</a>

训练后的基准结果见下表：

| 模型           | typed-decisions | BANKING77     | CLINC150       | 留出集准确率 |
| ------------ | --------------- | ------------- | -------------- | ------ |
| Qwen3.5-0.8B | 36% -> **73%**  | 7% -> **74%** | 19% -> **76%** | 78%    |
| Qwen3.5-2B   | 33% -> **78%**  | 1% -> 58%     | 1% -> 62%      | 81%    |

{% columns %}
{% column %}
我们使用 LoRA（r=64）和 Clef 头对 LLM 仅微调了一个 epoch，使下游准确率从 30–37%（大致相当于随机水平）提升到 **高达 78%**.

训练使用与 Laya 和 Clef 相同的数据集格式。测试集已 **去污染** 以避免与训练数据重叠。
{% endcolumn %}

{% column %}
{% embed url="<https://github.com/user-attachments/assets/92959172-d2a2-450b-a5bf-6369a1e5ae16>" %}
{% endcolumn %}
{% endcolumns %}

**所有模型** 效果也一样好——而且你还可以 **进一步** 像 Laya / Clef 这样的决策模型进行微调。

| 模型           | 测试准确率 | 显存     | 训练时间  |
| ------------ | ----- | ------ | ----- |
| Qwen3.5-0.8B | 78%   | 4GB    | 42 分钟 |
| Qwen3.5-2B   | 81%   | 8GB    | 40 分钟 |
| Llama 3.2 3B | 79%   | 4.1GB  | 30 分钟 |
| Gemma 4 E4B  | 77%   | 14.4GB | 49 分钟 |
| Laya（微调后）    | 77%   | 2.5GB  | 10 分钟 |

我们混合使用了 **12 个来源**，以及 `typed-decisions`: `ag_news`, `arc`, `banking77`, `boolq`, `clinc150`, `commonsense_qa`, `mmlu`, `mnli`, `prompt_injections`, `snli`, `sst5` 和 `wanli`. 其中 **测试集包含 3,000 行**：其中 typed-decisions 2,000 行，BANKING77 500 行，CLINC150 500 行。

### 🦥 在 Unsloth 中训练

{% stepper %}
{% step %}

#### **设置 Unsloth**

最简单的入门方式是下载 [Unsloth 桌面应用](/docs/zh/desktop.md)。适用于 [macOS](/docs/zh/kuai-su-kai-shi/install/mac.md), [Windows](/docs/zh/kuai-su-kai-shi/install/windows-installation.md)，以及 [Linux](/docs/zh/kuai-su-kai-shi/install/linux.md).

<a href="https://unsloth.ai/download" class="button primary" data-icon="down-to-bracket">下载 Unsloth</a>

或者，如果你更喜欢手动安装：

MacOS、Linux、WSL：

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

Windows PowerShell：

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

{% endstep %}

{% step %}

#### **选择你的模型和数据集**

打开训练选项卡并选择一个 LLM，例如 `unsloth/Qwen3.5-4B`。然后设置 **训练为** 为 **决策模型**。Unsloth 会自动填入效果较好的设置。若要匹配我们的结果，请将 epochs 设为 2，LoRA rank 设为 16，学习率设为 2e-4。

以上传文件或从 Hugging Face 中选择一个数据集，格式需符合数据集规范。对于 typed-decisions，请设置 **子集** 为 `全部`.

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FYL0pJRBFmFO0U1kjhv25%2F1-train-as-decision-model.png?alt=media&amp;token=bace6a9c-4c15-4794-b4ab-b2997014d5b6" alt="" width="375"><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%2Fcj5kfa0UJdty3SCM27dM%2F2-training-finished.png?alt=media&amp;token=4c1891e0-904a-4ca6-a9b4-7f2f5f059d35" alt=""><figcaption></figcaption></figure>

点击 **开始训练**。Unsloth 会报告训练前后在留出决策上的准确率，并校准模型的置信度。
{% endstep %}

{% step %}

#### **在 Decision API 中运行**

点击 **在 Decision API 中使用**。使用 `laya`, `default` 或 `jev-latest` 现在会转到你的模型。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FvzeWCbrxYPdTJFKI6dYg%2Fimage.png?alt=media&amp;token=5fd18788-4d63-4515-bd25-c0b8ebad75de" alt=""><figcaption></figcaption></figure>

你的模型也会以运行名称显示在 Settings → API 中，位于 Decision API → Model 下。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FHR6LKi4f1NiVvClJTtc7%2F4-settings-api-model.png?alt=media&amp;token=bcc74621-c635-4feb-bfb3-50a45f411b4d" alt="" width="563"><figcaption></figcaption></figure>
{% endstep %}

{% step %}
你还可以通过 Decision API 中的“Try It”选项来体验已训练的决策模型：

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FqYXH1FE3U5feaT7QLUjA%2Fimage.png?alt=media&amp;token=37f1ee77-9a66-4821-86aa-7aa0da123d91" alt="" width="563"><figcaption></figcaption></figure>

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FWvV5wGT1mqZaW4Ylbu0R%2Fimage.png?alt=media&amp;token=52500d48-0707-426d-bca9-a314bc9e29d3" alt="" width="563"><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

### 📒 使用我们的免费 notebook

你可以完全免费地使用我们的 Google Colab 或 Kaggle notebook 训练自己的决策模型。只要你有 Google 账户，Colab 和 Kaggle 都提供相当慷慨的免费 GPU 计算资源。在这些 notebook 中，你可以按照逐步流程操作，我们会演示如何进行数据准备、训练实际模型（此处为 Qwen3.5-4B）并导出它。

* 通过我们的免费 notebook 将 Qwen3.5-4B 微调为决策模型：

| [**Google Colab** notebook](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_5_\(4B\)-Decision.ipynb) | [**Kaggle** notebook](https://www.kaggle.com/notebooks/welcome?src=https://github.com/unslothai/notebooks/blob/main/nb/Kaggle-Qwen3_5_\(4B\)-Decision.ipynb\&accelerator=nvidiaTeslaT4) |
| ------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

你也可以使用我们免费的 Unsloth Studio notebook，通过 UI 界面训练决策模型：

{% embed url="<https://colab.research.google.com/github/unslothai/unsloth/blob/main/studio/Unsloth_Studio_Colab.ipynb>" %}

### 📈 数据集指南

决策模型数据集包含输入、关于该输入的问题以及正确答案。每一行使用三个字段：

| 字段     | 包含内容                |
| ------ | ------------------- |
| `状态`   | 输入，例如客户消息。          |
| `问题`   | 模型应做出的决定，包括说明和可用选项。 |
| `标准答案` | 每个问题的正确答案。          |

每一行可以包含多个问题。 `问题` 和 `标准答案` 可以是 Python 字典或 JSON 编码字符串。

**问题类型**

| 类型       | 作用                        | 标准答案                                                    |
| -------- | ------------------------- | ------------------------------------------------------- |
| `choice` | 从以下内容中选择一个选项： `criteria`. | 选项键，例如 `"billing"`.                                     |
| `noul`   | 回答是或否。                    | `True` 或 `False` 在 Python 中； `true` 或 `false` 在 JSON 中。 |
| `score`  | 从有序 `criteria` 列表中选择一个级别。 | 级别的索引，从 `0`.                                            |

**示例：支持工单**

此示例使用了我们 [决策模型 notebook 中的支持工单问题](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_5_%284B%29-Decision.ipynb)，包含训练标签和另外两个示例工单。

{% code expandable="true" %}

```python
questions = {
    "team": {
        "type": "choice",
        "instructions": "应该由哪个团队处理这个问题？",
        "criteria": {
            "billing": "发票、付款、退款",
            "technical": "漏洞、故障、中断",
            "sales": "定价、新方案",
        },
    },
    "refund": {
        "type": "noul",
        "instructions": "客户是否要求退款？",
    },
    "urgency": {
        "type": "score",
        "instructions": "这件事有多紧急？",
        "criteria": ["不紧急", "很快", "今天"],
    },
}

rows = [
    {
        "state": "你好，我在发票 #4411 上被重复收费了。请在今天退还多扣的金额。",
        "questions": questions,
        "gold": {"team": "billing", "refund": True, "urgency": 2},
    },
    {
        "state": "我导出报告时，仪表板显示错误。请在接下来的几天内帮忙处理。",
        "questions": questions,
        "gold": {"team": "technical", "refund": False, "urgency": 1},
    },
    {
        "state": "你能否发送你们商业方案的价格信息？我们是在为明年做调研，不着急。",
        "questions": questions,
        "gold": {"team": "sales", "refund": False, "urgency": 0},
    },
]
```

{% endcode %}

每个问题都需要在 `标准答案`. 选择类答案必须与其中一个键匹配 `criteria`. 评分标签从 `0`，因此 `"urgency": 2` 表示 `"今天"`.

将输入保留在 `状态` 并将答案保留在 `标准答案`。这些行仅展示格式；在训练前请添加更多覆盖你使用场景的示例。

### 🎯 做出决策

给出 `predict` 一个输入和需要做出决策的问题，格式与您的数据集相同：

{% code expandable="true" %}

```python
FastDecisionModel.for_inference(model)
answers = FastDecisionModel.predict(
    model,
    tokenizer,
    "你好，我在发票 #4411 上被重复收费了。请在今天退还多扣的金额。",
    {
        "team": {
            "type": "choice",
            "instructions": "应该由哪个团队处理这个问题？",
            "criteria": {
                "billing": "发票、付款、退款",
                "technical": "漏洞、故障、中断",
                "sales": "定价、新方案",
            },
        },
        "refund": {"type": "noul", "instructions": "客户是否要求退款？"},
        "urgency": {
            "type": "score",
            "instructions": "这件事有多紧急？",
            "criteria": ["不紧急", "很快", "今天"],
        },
    },
)
for name, result in answers.items():
    print(name, result["answer"], {k: round(v, 3) for k, v in result["probabilities"].items()})
```

{% endcode %}

`答案` 是 choice 的选项键， `True` 或 `False` 对于 noul，以及 score 的级别编号。每个答案还具有与 Decision API 答案相同的字段。

要检查带标签测试集上的准确率，请使用 `evaluate`:

```python
test = load_dataset("LocalLLaMA/typed-decisions", "all", split = "test")
test_items, _ = FastDecisionModel.build_dataset(test, tokenizer, model)
print(FastDecisionModel.evaluate(model, tokenizer, test_items))
```

### 在 Decision API 中使用它

你可以 [阅读我们的详细指南](/docs/zh/mo-xing/decision-laya.md) 关于部署/运行决策模型的内容，请阅读我们的详细指南；否则可继续阅读下方的简要说明。你在 Unsloth 中训练的模型会显示在 Settings → API 中。对于你用代码训练的模型，请使用你保存的合并文件夹启动 Unsloth：

```bash
UNSLOTH_SYSTEMONE_MODEL=/path/to/qwen-decisions-merged unsloth studio -H 0.0.0.0 -p 8888
```

在 Settings → API 中开启 Decision API。使用 `laya`, `default` 或 `jev-latest` 现在会转到你的模型，且答案格式与 Laya 的相同。该模型需要 GPU，并会在首次请求时加载，这可能需要几分钟。当某次训练运行占用 GPU 时，Decision API 会等待，并在运行结束后重新开始响应。

#### 工作原理

Unsloth 会将你的输入放入一个 prompt，后面跟着每个问题及其选项。LLM 只读取一次。一个小头部——设计与 Cloudflare 的 Clef 相同——会查看 LLM 针对每个问题和选项的输出，对每个选项打分，并一次性决定所有问题。它不会生成文本，因此不会把内存花在 LLM 的词预测上。

### 🐍 用代码训练

使用以下命令安装或更新 Unsloth： `pip install --upgrade unsloth`，并使用以下代码训练你自己的决策模型。

{% code expandable="true" %}

```python
from unsloth import FastDecisionModel, DecisionTrainer, is_bfloat16_supported
from datasets import load_dataset
from transformers import TrainingArguments

model, tokenizer = FastDecisionModel.from_pretrained(
    model_name = "unsloth/Qwen3.5-4B",
    max_seq_length = 2048,
    load_in_4bit = True,
)

model = FastDecisionModel.get_peft_model(
    model,
    r = 16,
    lora_alpha = 16,
    lora_dropout = 0,
    use_gradient_checkpointing = "unsloth",
    random_state = 3407,
)

dataset = load_dataset("LocalLLaMA/typed-decisions", "all", split = "train")
items, report = FastDecisionModel.build_dataset(dataset, tokenizer, model)
print(f"跳过了 {report['skipped']} / {report['total']} 个决策")

train_items, eval_items = FastDecisionModel.split_holdout(items, seed = 3407)
print(f"{len(train_items)} 行训练数据，{len(eval_items)} 行留出数据")

from transformers import TrainingArguments

trainer = DecisionTrainer(
    model = model,
    processing_class = tokenizer,
    train_dataset = train_items,
    eval_dataset = eval_items,
    args = TrainingArguments(
        per_device_train_batch_size = 2,
        gradient_accumulation_steps = 4, # 使用 GA 来模拟批次大小！
        warmup_steps = 10,
        # num_train_epochs = 2, # 如需一次完整训练可在此设置。
        max_steps = 240,
        learning_rate = 2e-5,
        lr_scheduler_type = "cosine",
        weight_decay = 0.01,
        bf16 = is_bfloat16_supported(),
        fp16 = not is_bfloat16_supported(),
        eval_strategy = "epoch",
        logging_steps = 1,
        output_dir = "outputs",
        report_to = "none", # 使用 TrackIO/WandB 等
        seed = 3407,
    ),
)
trainer_stats = trainer.train()
```

{% endcode %}

如需使用 Llama 或 Gemma 4，请修改 `model_name` 为 `unsloth/Llama-3.2-3B-Instruct` 或 `unsloth/gemma-4-E4B-it`。Unsloth 能微调的其他 LLM 也应同样适用。

对于你自己的数据，请参见数据集格式。每一行都有一个 state、需要做出决定的问题以及标准答案。

#### 校准并保存

在这些行上进行校准 `split_holdout` 留出的数据上进行，因此模型的概率与其正确频率相匹配：

```python
metrics = FastDecisionModel.calibrate(model, tokenizer, eval_items)
print(metrics) # 留出集准确率、校准误差（ece）和损失
```

然后保存。 `save_pretrained` 会保存 LoRA 适配器和头部。 `save_pretrained_merged` 会保存一个完整的 16 位模型：

```python
model.save_pretrained("qwen-decisions")
model.save_pretrained_merged("qwen-decisions-merged")
# model.push_to_hub("hf_username/qwen-decisions", token = "hf_...")
```

用加载基础模型的相同方式再次加载它：

```python
model, tokenizer = FastDecisionModel.from_pretrained("qwen-decisions", load_in_4bit = True)
```

### ⚙️ 推荐设置

* 从 rank 为 16、学习率为 2e-4 的 4-bit LoRA 开始。新的头部默认以 1e-4 训练。你可以通过以下方式更改： `head_learning_rate` 在 `DecisionTrainer`.
* 我们在 typed-decisions 上使用了 2 个 epoch。若数据更少，可尝试 3 或 4 个。
* 若想快速试用，请设置 `max_steps = 60`。Qwen3.5-4B 在 L4 上 10 分钟内达到了 76%。
* 如果显存不足，请将 batch size 减半，并将梯度累积加倍。
* `max_seq_length` 用于设置训练期间允许的最长输入。长输入会保留问题和选项，并截断输入末尾以适配。预测最多读取 16,384 个 token。


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://unsloth.ai/docs/zh/ji-chu-zhi-shi/shi-yong-unsloth-xun-lian-ni-zi-ji-de-jue-ce-mo-xing.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
