> 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/shii/train-your-own-decision-model-with-unsloth.md).

# 独自のDecision Modelを学習する

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) そうして **意思決定を行う** テキストを生成する代わりに。ファインチューニングしたモデルは入力を読み取り、あなたが用意した選択肢をスコア化し、確率付きで選択結果を返します。学習後のベンチマークは表を参照してください:

| モデル          | 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%まで**.

学習にはLayaとClefと同じデータセット形式を使用します。テストセットは **汚染除去されました** 学習データに対して。
{% endcolumn %}

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

**すべてのモデル** 同様に動作します。さらに、 **さらに** Laya / Clefのような意思決定モデルをさらにファインチューニングできます。

| モデル                | テスト精度 | 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から2000件、BANKING77から500件、CLINC150から500件。

### 🦥 Unslothで学習

{% stepper %}
{% step %}

#### **Unsloth のセットアップ**

始める最も簡単な方法は、 [Unsloth Desktopアプリ](/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がうまく動作する設定を自動で入力します。結果を合わせるには、エポック数を2、LoRAランクを16、学習率を2e-4に設定してください。

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

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

### 🐍 コードで学習

Unslothをインストールまたは更新するには `pip install --upgrade unsloth`を実行し、以下のコードで独自の意思決定モデルを学習します。

```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"Skipped {report['skipped']} of {report['total']} decisions")

train_items, eval_items = FastDecisionModel.split_holdout(items, seed = 3407)
print(f"{len(train_items)} training rows, {len(eval_items)} held out")

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()
```

LlamaまたはGemma 4を使うには、 `model_name` を `unsloth/Llama-3.2-3B-Instruct` に渡すことで有効にできます。 `unsloth/gemma-4-E4B-it`。Unslothでファインチューニングできる他のLLMでも同様に動作するはずです。

独自データについては、データセット形式を参照してください。各行には状態、判定する質問、そして正解ラベルがあります。

#### 較正して保存

行に対して較正する `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)
```

### 🎯 意思決定を行う

与える `predict` データセットと同じ形式で、入力と判定する質問を与えます:

```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()})
```

`回答` は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/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はそれを一度だけ読みます。CloudflareのClefと同じ設計の小さなヘッドが、各質問と選択肢ごとのLLM出力を見てすべての選択肢をスコア化し、すべての質問をまとめて判定します。テキストは一切生成しないため、LLMの単語予測にメモリを使いません。

### ⚙️ 推奨設定

* まずは4ビットLoRA、ランク16、学習率2e-4から始めてください。新しいヘッドはデフォルトで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/shii/train-your-own-decision-model-with-unsloth.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.
