> 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/jp/ji-chu/unslothdenomoderuwosuru.md).

# Unslothで独自の決定モデルを学習する

QwenやGemmaのようなLLMをファインチューニングして、較正された確率で意思決定を行えるようにします。

今では、次のような独自の意思決定モデルを学習できます **Jev**, **Laya** と **Clef** Unslothを使って。ファインチューニングの方法を学びましょう [Qwen3.8](/docs/jp/moderu/qwen3.8.md) と [Gemma 4](/docs/jp/moderu/gemma-4.md) LLMをファインチューニングし、効果的なデータセット形式を設計し、それらを [意思決定](/docs/jp/moderu/decision-laya.md) する **意思決定を行う** テキストを生成するのではなく。ファインチューニングされたモデルは入力を読み取り、提示した選択肢を採点し、確率付きで選択結果を返します。

<a href="/docs/jp/ji-chu/unslothdenomoderuwosuru.md#train-in-unsloth" class="button secondary">学習ガイド</a><a href="/docs/jp/ji-chu/unslothdenomoderuwosuru.md#dataset-format" class="button secondary">データセットガイド</a><a href="/docs/jp/moderu/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を1エポックだけファインチューニングし、下流精度を30～37%（ほぼ偶然水準）から **最大78%まで向上させました**.

Training uses the same dataset format as Laya and Clef. Test sets were **汚染除去** されており、学習データと照合済みです。
{% endcolumn %}

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

**すべてのモデル** 同様に動作します。さらに **さらに** Laya / ClefのようなDecisionモデルを追加でファインチューニングすることもできます。

| モデル                | テスト精度 | VRAM   | 学習時間 |
| ------------------ | ----- | ------ | ---- |
| 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/jp/desktop.md)。対応環境は [macOS](/docs/jp/meru/install/mac.md), [Windows](/docs/jp/meru/install/windows-installation.md)、および [Linux](/docs/jp/meru/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 %}

#### **モデルとデータセットを選択**

Trainタブを開き、次のようなLLMを選択します `unsloth/Qwen3.5-4B`。次に **学習対象** を **意思決定モデル**。Unslothがうまく動作する設定を自動で入れます。結果を再現するには、epochを2、LoRAランクを16、学習率を2e-4に設定してください。

データセット形式でファイルをアップロードするか、Hugging Faceからデータセットを選択します。typed-decisionsでは、次を設定してください **サブセット** を `all`.

<figure><img src="https://735611837-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://735611837-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://735611837-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://735611837-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://735611837-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://735611837-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 %}

### 📒 無料ノートブックを使う

Google ColabまたはKaggleのノートブックを使って、完全無料で独自の意思決定モデルを学習できます。ColabとKaggleはいずれも、Googleアカウントがあれば寛大な無料GPU計算資源を提供しています。これらのノートブックには、順を追って進められるワークフローがあり、データ準備、実際のモデル（この場合はQwen3.5-4B）の学習、書き出し方法を示します。

* 無料ノートブックを使ってQwen3.5-4Bを意思決定モデルにファインチューニングします:

| [**Google Colab** ノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_5_\(4B\)-Decision.ipynb) | [**Kaggle** ノートブック](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ノートブックを使って、UIインターフェースで意思決定モデルを学習することもできます:

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

### 📈 データセットガイド

意思決定モデルのデータセットには、入力、その入力に関する質問、正解が含まれます。各行は3つのフィールドを使用します:

| フィールド       | 含まれる内容                         |
| ----------- | ------------------------------ |
| `state`     | 顧客メッセージなどの入力です。                |
| `questions` | モデルが判断すべき内容で、指示と利用可能な選択肢を含みます。 |
| `gold`      | 各質問に対する正解です。                   |

各行には複数の質問を含めることができます。 `questions` と `gold` Pythonの辞書またはJSONエンコードされた文字列にできます。

**質問タイプ**

| タイプ    | 機能                                | 正解                                        |
| ------ | --------------------------------- | ----------------------------------------- |
| `選択`   | 次から選択肢を選びます `criteria`.           | オプションキー。たとえば `"billing"`.                 |
| `noul` | はい/いいえで答えます。                      | `真` または `偽` Pythonでは; `真` または `偽` JSONでは。 |
| `スコア`  | 順序付けられた `criteria` リストからレベルを選びます。 | レベルのインデックス。開始は `0`.                       |

**例: サポートチケット**

この例では、次のサポートチケットの質問を使用しています。 [意思決定モデルのノートブック](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_5_%284B%29-Decision.ipynb)。学習ラベルと追加のサンプルチケット2件付きです。

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

各質問には、対応する回答が必要です `gold`。choiceの回答は、次の中のキーと一致する必要があります `criteria`。scoreのラベルは次から始まります `0`、したがって `"urgency": 2` は `"today"`.

入力は `state` 回答は `gold`。これらの行は形式を示しています。学習前に、あなたの用途を網羅する例を追加してください。

### 🎯 意思決定を行う

与える `予測` データセットと同じ形式で、入力と判断するための質問を与えます:

{% 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のオプションキーです `真` または `偽` noulでは、scoreではレベル番号です。各回答にはDecision APIの回答と同じフィールドも含まれます。

ラベル付きテストセットで精度を確認するには、次を使用します `評価`:

```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/jp/moderu/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は入力を1つのプロンプトにまとめ、その後にすべての質問とその選択肢を続けます。LLMはそれを1回だけ読みます。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, # 1回の完全な学習ランに使う設定です。
        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エポックを使用しました。データが少ない場合は3または4を試してください。
* 手早く試すなら、次を設定します `max_steps = 60`。Qwen3.5-4BはL4上で10分で76%に到達しました。
* メモリが足りなくなったら、バッチサイズを半分にし、勾配蓄積を2倍にしてください。
* `max_seq_length` は学習時の最長入力長を設定します。長い入力では質問と選択肢を維持し、収まるように入力末尾を切り詰めます。予測は最大16,384トークンまで読みます。


---

# 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/jp/ji-chu/unslothdenomoderuwosuru.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.
