# データセットの形式とタイプ

このガイドでは、TRLの各トレーナーがサポートするデータセットの形式と種類について概要を説明します。

## データセットの形式とタイプの概要

- *format*とは、データの構造を指し、通常は*standard*または*conversational*のいずれかに分類されます。
- *type*は、*prompt-only*や*preference*など、データセットが設計された特定のタスクに関連付けられています。各タイプは、そのタスクに応じて異なる列によって特徴付けられ、その詳細は以下の表に示されています。

  
    タイプ \ フォーマット 標準的な会話
  
  
    言語モデリング
    
      {"text": "空は青いです。"}
    
    
      {"messages": [{"role": "user", "content": "空は何色ですか？"}, {"role": "assistant", "content": "青です。"}]}
    
  
  
    プロンプトのみ
    
      {"prompt": "空は"}
    
    
      {"prompt": [{"role": "user", "content": "空は何色ですか？"}]}
    
  
  
    プロンプト-補完
    
      {"prompt": "空は", "completion": " 青い。"}
    
    
      {"prompt": [{"role": "user", "content": "空は何色ですか？"}], "completion": [{"role": "assistant", "content": "青です。"}]}
    
  
  
  
    好み
    
      {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."} or, with implicit prompt: {"chosen": "The sky is blue.", "rejected": "The sky is green."}
    
    
      {"prompt": [{"role": "user", "content": "空は何色ですか？"}], "chosen": [{"role": "assistant", "content": "青です。"}], "rejected": [{"role": "assistant", "content": "緑です。"}]} または、暗黙の prompt を使用する場合: {"chosen": [{"role": "user", "content": "空は何色ですか？"}, {"role": "assistant", "content": "青です。"}], "rejected": [{"role": "user", "content": "空は何色ですか？"}, {"role": "assistant", "content": "緑です。"}]}
    
  
    ペアなしの好み
    
      {"prompt": "空は", "completion": " 青い。", "label": True}
    
    
      {"prompt": [{"role": "user", "content": "空は何色ですか？"}], "completion": [{"role": "assistant", "content": "緑色です。"}], "label": False}
    
  

### 形式

#### 標準

標準的なデータセット形式は、通常プレーンテキストの文字列で構成されています。データセットの列はタスクによって異なります。これはTRLのトレーナーが期待する形式です。以下は、異なるタスクにおける標準的なデータセット形式の例です。

```python
# Language modeling
language_modeling_example = {"text": "The sky is blue."}
# Preference
preference_example = {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."}
# Unpaired preference
unpaired_preference_example = {"prompt": "The sky is", "completion": " blue.", "label": True}
```

#### 対話型

対話データセットは、ユーザーとアシスタント間の対話やチャットインタラクションを扱うタスクに使用されます。標準的なデータセット形式とは異なり、これらはメッセージのシーケンスを含み、各メッセージには`role`（例: `"user"`または`"assistant"`）と`content`（メッセージのテキスト）が割り当てられています。

```python
messages = [
    {"role": "user", "content": "Hello, how are you?"},
    {"role": "assistant", "content": "I'm doing great. How can I help you today?"},
    {"role": "user", "content": "I'd like to show off how chat templating works!"},
]
```

標準的なデータセットと同様に、会話型データセットの列はタスクによって異なります。以下は、異なるタスクにおける会話型データセットの形式の例です。

```python
# Prompt-completion
prompt_completion_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}],
                             "completion": [{"role": "assistant", "content": "It is blue."}]}
# Preference
preference_example = {
    "prompt": [{"role": "user", "content": "What color is the sky?"}],
    "chosen": [{"role": "assistant", "content": "It is blue."}],
    "rejected": [{"role": "assistant", "content": "It is green."}],
}
```

#### ツール呼び出し

一部のチャットテンプレートは*ツール呼び出し*をサポートしており、これによりモデルは生成中に外部関数（**ツール**）とやり取りできます。これにより、モデルがツールを呼び出すと判断した際に、標準的な`"content"`メッセージの代わりに`"tool_calls"`フィールドを出力できるようになり、モデルの会話機能が拡張されます。

アシスタントがツール呼び出しを開始すると、ツールが実行され、その出力が返されます。その後、アシスタントはこの出力を処理し、それに応じて会話を続行できます。

ツール呼び出しのインタラクションの簡単な例を以下に示します。

```python
messages = [
    {"role": "user", "content": "Turn on the living room lights."},
    {"role": "assistant", "tool_calls": [
        {"type": "function", "function": {
            "name": "control_light",
            "arguments": {"room": "living room", "state": "on"}
        }}]
    },
    {"role": "tool", "name": "control_light", "content": "The lights in the living room are now on."},
    {"role": "assistant", "content": "Done!"}
]
```

ツール呼び出しを伴うSupervised Fine-Tuning (SFT)用のデータセットを準備する際は、`tools`という名前の追加カラムをデータセットに含めることが重要です。このカラムには、モデルが利用可能なツールのリストが含まれており、通常、チャットテンプレートによってシステムプロンプトを構築するために使用されます。

ツールは、構造化されたJSONスキーマ形式で指定する必要があります。`get_json_schema`ユーティリティを使用して、Pythonの関数シグネチャからこのスキーマを自動生成できます。

```python
import json
from transformers.utils import get_json_schema

def control_light(room: str, state: str) -> str:
    """
    Controls the lights in a room.

    Args:
        room: The name of the room.
        state: The desired state of the light ("on" or "off").

    Returns:
        str: A message indicating the new state of the lights.
    """
    return f"The lights in {room} are now {state}."

# Generate JSON schema
json_schema = get_json_schema(control_light)
```

生成されるスキーマは次のようになります:

```python
{"type": "function", "function": {"name": "control_light", "description": "Controls the lights in a room.", "parameters": {"type": "object", "properties": {"room": {"type": "string", "description": "The name of the room."}, "state": {"type": "string", "description": "The desired state of the light (\"on\" or \"off\")."}}, "required": ["room", "state"]}, "return": {"type": "string", "description": "str: A message indicating the new state of the lights."}}}
```

SFT用の完全なデータセットエントリは、次のようになる可能性があります。

```python
{"messages": messages, "tools": [json_schema]}
```

`Dataset` を取得するには、ツール引数が固定のフィールドと型を持つ辞書ではなく、任意の JSON オブジェクトであるため、`Json()` 型を使用する必要があります。

```python
from datasets import Dataset

data = [
    {"messages": messages1, "tools": [json_schema1]},
    {"messages": messages2, "tools": [json_schema2]},
]
# auto-apply the Json() type
dataset = Dataset.from_list(data, on_mixed_types="use_json")

# or specify the features manually
from datasets import Features, Json, List, Value

features = Features(
    {
        "messages": List({"role": Value("string"), "content": Value("string"), "tool_calls": List(Json())}),
        "tools": List(Json()),
    }
)
dataset = Dataset.from_list(data, features=features)
```

`datasets` の旧バージョン（<4.7.0）には `Json()` 型がないため、`tools` は JSON 文字列（`str`）として保存する必要があります（`json.dumps([...])` を使用）：

```python
dataset = Dataset.from_list(
    [{"messages": messages1, "tools": json.dumps([json_schema1])},
     {"messages": messages2, "tools": json.dumps([json_schema2])}]
)
```

ツール呼び出しの詳細については、[`transformers`ドキュメントのTool Callingセクション](https://huggingface.co/docs/transformers/chat_extras#tools-and-rag)およびブログ記事[Tool Use, Unified](https://huggingface.co/blog/unified-tool-use)を参照してください。

### Harmony

[Harmony レスポンス形式](https://cookbook.openai.com/articles/openai-harmony)は、[OpenAI GPT OSS モデル](https://huggingface.co/collections/openai/gpt-oss-68911959590a1634ba11c7a4)とともに導入されました。この形式は、対話形式を拡張し、推論、関数呼び出し、およびモデルの動作に関するメタデータに対してより豊かな構造を追加します。主な機能は以下の通りです：

- **開発者ロール** – 高レベルの指示（システムプロンプトに類似）を提供し、利用可能なツールを列挙します。
- **チャンネル** – アシスタントの出力を種類ごとに個別のストリームに分離します:

  - `analysis` – 内部の推論用。キー `"thinking"` から取得されます
  - `final` – ユーザー向けの回答。キー `"content"` から取得されます
  - `commentary` – ツール呼び出しやメタノート用

- **推論の努力度** – モデルが示すべき思考の量を示します（例: `"low"`、`"medium"`、`"high"`）。
- **モデルのアイデンティティ** – アシスタントのペルソナを明示的に定義します。

```python
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("openai/gpt-oss-20b")

messages = [
    {"role": "developer", "content": "Use a friendly tone."},
    {"role": "user", "content": "What is the meaning of life?"},
    {"role": "assistant", "thinking": "Deep reflection...", "content": "The final answer is..."},
]

print(
    tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        reasoning_effort="low",
        model_identity="You are HuggingGPT, a large language model trained by Hugging Face.",
    )
)
```

これにより、以下が生成されます:

```txt
<|start|>system<|message|>You are HuggingGPT, a large language model trained by Hugging Face.
Knowledge cutoff: 2024-06
Current date: 2025-08-03

Reasoning: low

# Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions

Use a friendly tone.<|end|><|start|>user<|message|>What is the meaning of life?<|end|><|start|>assistant<|channel|>analysis<|message|>Deep reflection...<|end|><|start|>assistant<|channel|>final<|message|>The final answer is...<|return|>
```

メッセージ構造、サポートされているフィールド、および高度な使用方法の詳細については、[Harmonyのドキュメント](https://cookbook.openai.com/articles/openai-harmony)を参照してください。

### 型

#### 言語モデリング

言語モデリングのデータセットは、テキストの完全なシーケンスを含む `"text"`（会話型データセットの場合は `"messages"`）という列で構成されています。

```python
# Standard format
language_modeling_example = {"text": "The sky is blue."}
# Conversational format
language_modeling_example = {"messages": [
    {"role": "user", "content": "What color is the sky?"},
    {"role": "assistant", "content": "It is blue."}
]}
```

#### プロンプトのみ

プロンプトのみのデータセットでは、キー`"prompt"`の下に初期プロンプト（質問や部分文）のみが提供されます。トレーニングでは通常、このプロンプトに基づいて補完を生成し、モデルが与えられた入力を継続または補完することを学習します。

```python
# Standard format
prompt_only_example = {"prompt": "The sky is"}
# Conversational format
prompt_only_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}]}
```

プロンプトのみを含むデータセットの例については、[Prompt-only datasets collection](https://huggingface.co/collections/trl-lib/prompt-only-datasets-677ea25245d20252cea00368)を参照してください。

> [!TIP]
> 型と型は似ていますが、入力の処理方法が異なります。型では、プロンプトはモデルによる補完や継続を期待する部分入力を表し、型では、入力は完全な文またはシーケンスとして扱われます。TRLでは、これら2つの型は異なる方法で処理されます。以下は、各型における`apply_chat_template`関数の出力の違いを示す例です：
>
> ```python
> from transformers import AutoTokenizer
> from trl import apply_chat_template
>
> tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-128k-instruct")
>
> # Example for prompt-only type
> prompt_only_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}]}
> apply_chat_template(prompt_only_example, tokenizer)
> # Output: {'prompt': '<|user|>\nWhat color is the sky?<|end|>\n<|assistant|>\n'}
>
> # Example for language modeling type
> lm_example = {"messages": [{"role": "user", "content": "What color is the sky?"}]}
> apply_chat_template(lm_example, tokenizer)
> # Output: {'text': '<|user|>\nWhat color is the sky?<|end|>\n<|endoftext|>'}
> ```
>
> - プロンプトのみの出力には`'<|assistant|>\n'`が含まれ、アシスタントのターン開始を示し、モデルが補完を生成することを期待します。
- 一方、言語モデリングの出力は入力を完全なシーケンスとして扱い、`'<|endoftext|>'`で終了させ、テキストの終わりを示し、追加のコンテンツを期待しません。

#### プロンプト-補完

プロンプト-補完データセットには、`"prompt"`と`"completion"`が含まれます。

```python
# Standard format
prompt_completion_example = {"prompt": "The sky is", "completion": " blue."}
# Conversational format
prompt_completion_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}],
                             "completion": [{"role": "assistant", "content": "It is blue."}]}
```

プロンプト-補完データセットの例については、[Prompt-completion datasets collection](https://huggingface.co/collections/trl-lib/prompt-completion-datasets-677ea2bb20bbb6bdccada216)を参照してください。

#### 好み

好意データセットは、モデルが同じプロンプトに対する2つ以上の候補の補完から選択するよう学習されるタスクで使用されます。このデータセットには、`"prompt"`、`"chosen"`補完、`"rejected"`補完が含まれます。モデルは、`"rejected"`応答ではなく`"chosen"`応答を選択するよう学習されます。一部のデータセットには`"prompt"`カラムが含まれていない場合がありますが、その場合はプロンプトは暗黙のうちに`"chosen"`および`"rejected"`補完に直接含まれています。可能な限り明示的なプロンプトの使用を推奨します。

```python
# Standard format
## Explicit prompt (recommended)
preference_example = {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."}
# Implicit prompt
preference_example = {"chosen": "The sky is blue.", "rejected": "The sky is green."}

# Conversational format
## Explicit prompt (recommended)
preference_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}],
                      "chosen": [{"role": "assistant", "content": "It is blue."}],
                      "rejected": [{"role": "assistant", "content": "It is green."}]}
## Implicit prompt
preference_example = {"chosen": [{"role": "user", "content": "What color is the sky?"},
                                 {"role": "assistant", "content": "It is blue."}],
                      "rejected": [{"role": "user", "content": "What color is the sky?"},
                                   {"role": "assistant", "content": "It is green."}]}
```

好意データセットの例については、[Preference datasets collection](https://huggingface.co/collections/trl-lib/preference-datasets-677e99b581018fcad9abd82c)を参照してください。

[Hugging Face Hubの`dpo`タグ](https://huggingface.co/datasets?other=dpo)で、いくつかの好みデータセットを見つけることができます。また、[librarian-botsのDPOコレクション](https://huggingface.co/collections/librarian-bots/direct-preference-optimization-datasets-66964b12835f46289b6ef2fc)を探索して、好みデータセットを特定することもできます。

#### ペアなしの好み

ペアなしの好みデータセットは好みデータセットに似ていますが、同じプロンプトに対して`"chosen"`と`"rejected"`の補完を持つ代わりに、単一の`"completion"`と、その補完が好まれるかどうかを示す`"label"`を含みます。

```python
# Standard format
unpaired_preference_example = {"prompt": "The sky is", "completion": " blue.", "label": True}
# Conversational format
unpaired_preference_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}],
                               "completion": [{"role": "assistant", "content": "It is blue."}],
                               "label": True}
```

ペアなしの好意データセットの例については、[Unpaired preference datasets collection](https://huggingface.co/collections/trl-lib/unpaired-preference-datasets-677ea22bf5f528c125b0bcdf)を参照してください。

## どのデータセットタイプを使用しますか？

適切なデータセットの種類を選択するには、取り組んでいるタスクと、使用しているTRLトレーナーの具体的な要件を考慮する必要があります。以下は、各TRLトレーナーがサポートするデータセットの種類に関する簡単な概要です。

| Trainer | 期待されるデータセットの型 |
| --- | --- |
| [AsyncGRPOTrainer](/docs/trl/v1.19.0/ja/async_grpo_trainer#trl.AsyncGRPOTrainer) | [Promptのみ](#prompt-only) |
| [DistillationTrainer](/docs/trl/v1.19.0/ja/distillation_trainer#trl.DistillationTrainer) | [Promptのみ](#prompt-only) |
| [DPOTrainer](/docs/trl/v1.19.0/ja/bema_for_reference_model#trl.DPOTrainer) | [好み（明示的なプロンプトを推奨）](#preference) |
| [GRPOTrainer](/docs/trl/v1.19.0/ja/grpo_trainer#trl.GRPOTrainer) | [Promptのみ](#prompt-only) |
| [KTOTrainer](/docs/trl/v1.19.0/ja/kto_trainer#trl.KTOTrainer) | [非ペアの好み](#unpaired-preference)または[好み（明示的なプロンプトを推奨）](#preference) |
| [RewardTrainer](/docs/trl/v1.19.0/ja/reward_trainer#trl.RewardTrainer) | [好み（暗黙のプロンプトを推奨）](#preference) |
| [RLOOTrainer](/docs/trl/v1.19.0/ja/rloo_trainer#trl.RLOOTrainer) | [Promptのみ](#prompt-only) |
| [SFTTrainer](/docs/trl/v1.19.0/ja/sft_trainer#trl.SFTTrainer) | [言語モデリング](#language-modeling)または[Prompt-completion](#prompt-completion) |
| [experimental.cpo.CPOTrainer](/docs/trl/v1.19.0/ja/cpo_trainer#trl.experimental.cpo.CPOTrainer) | [好み（明示的なプロンプトを推奨）](#preference) |
| [experimental.gkd.GKDTrainer](/docs/trl/v1.19.0/ja/gkd_trainer#trl.experimental.gkd.GKDTrainer) | [プロンプト-補完](#prompt-completion) |
| [experimental.online_dpo.OnlineDPOTrainer](/docs/trl/v1.19.0/ja/online_dpo_trainer#trl.experimental.online_dpo.OnlineDPOTrainer) | [Promptのみ](#prompt-only) |
| [experimental.orpo.ORPOTrainer](/docs/trl/v1.19.0/ja/orpo_trainer#trl.experimental.orpo.ORPOTrainer) | [好み（明示的なプロンプトを推奨）](#preference) |

## TRLで任意のデータセットを使用する: 前処理と変換

多くのデータセットは特定のタスクに特化した形式で提供されており、TRLと直接互換性がない場合があります。TRLでそのようなデータセットを使用するには、前処理と必要な形式への変換を行う必要がある場合があります。

これを容易にするため、一般的なデータセット変換をカバーする[サンプルスクリプト](https://github.com/huggingface/trl/tree/main/examples/datasets)のセットを提供しています。

### 例: UltraFeedback データセット

[UltraFeedback データセット](https://huggingface.co/datasets/openbmb/UltraFeedback)を例に取ります。以下は、このデータセットのプレビューです。

<iframe src="https://huggingface.co/datasets/openbmb/UltraFeedback/embed/viewer/default/train" frameborder="0" width="100%" height="560px"
>

上記に示したように、データセットの形式は期待される構造と一致していません。会話形式になっておらず、列名が異なり、また結果は異なるモデル（例：Bard、GPT-4）や異なる側面（例："helpfulness"、"honesty"）に関するものです。

提供されている変換スクリプト [`examples/datasets/ultrafeedback.py`](https://github.com/huggingface/trl/tree/main/examples/datasets/ultrafeedback.py) を使用すると、このデータセットをペアなしの好みタイプに変換し、Hub にプッシュできます。

```sh
python examples/datasets/ultrafeedback.py --push_to_hub --repo_id trl-lib/ultrafeedback-gpt-3.5-turbo-helpfulness
```

変換後、データセットは次のようになります。

<iframe src="https://huggingface.co/datasets/trl-lib/ultrafeedback-gpt-3.5-turbo-helpfulness/embed/viewer/default/train?row=0" frameborder="0" width="100%" height="560px"
>

これで、このデータセットをTRLで使用できます!

提供されているスクリプトを適応させたり、独自のスクリプトを作成したりすることで、任意のデータセットをTRLと互換性のある形式に変換できます。

## データセット型の変換用ユーティリティ

このセクションでは、異なるデータセット形式間の相互変換を支援するためのサンプルコードを提供します。一部の形式変換は、チャットテンプレートの適用後（つまり、標準形式の状態）でも実行できますが、一貫して動作することを保証するために、チャットテンプレートを適用する前に変換を実行することをお勧めします。

簡便さのため、以下の一部の例ではこの推奨事項に従わず、標準形式を使用しています。ただし、変換は修正なしで会話形式に直接適用できます。

| From \ To | 言語モデリング | プロンプト-補完 | プロンプトのみ | 暗黙のプロンプトによる選好 | 好み | ペアなしの好み |
| --- | --- | --- | --- | --- | --- | --- |
| 言語モデリング | N/A | N/A | N/A | N/A | N/A | N/A |
| プロンプト-補完 | [🔗](#from-prompt-completion-to-language-modeling-dataset) | N/A | [🔗](#from-prompt-completion-to-prompt-only-dataset) | N/A | N/A | N/A |
| プロンプトのみ | N/A | N/A | N/A | N/A | N/A | N/A |
| 暗黙のプロンプトによる選好 | [🔗](#from-preference-with-implicit-prompt-to-language-modeling-dataset) | [🔗](#from-preference-with-implicit-prompt-to-prompt-completion-dataset) | [🔗](#from-preference-with-implicit-prompt-to-prompt-only-dataset) | N/A | [🔗](#from-implicit-to-explicit-prompt-preference-dataset) | [🔗](#from-preference-with-implicit-prompt-to-unpaired-preference-dataset) |
| 好み | [🔗](#from-preference-to-language-modeling-dataset) | [🔗](#from-preference-to-prompt-completion-dataset) | [🔗](#from-preference-to-prompt-only-dataset) | [🔗](#from-explicit-to-implicit-prompt-preference-dataset) | N/A | [🔗](#from-preference-to-unpaired-preference-dataset) |
| ペアなしの好み | [🔗](#from-unpaired-preference-to-language-modeling-dataset) | [🔗](#from-unpaired-preference-to-prompt-completion-dataset) | [🔗](#from-unpaired-preference-to-prompt-only-dataset) | N/A | N/A | N/A |

### プロンプト-補完から言語モデリングデータセットへ

プロンプトと補完のデータセットを言語モデリングのデータセットに変換するには、プロンプトと補完を連結します。

```python
from datasets import Dataset

dataset = Dataset.from_dict({
    "prompt": ["The sky is", "The sun is"],
    "completion": [" blue.", " in the sky."],
})

def concat_prompt_completion(example):
    return {"text": example["prompt"] + example["completion"]}

dataset = dataset.map(concat_prompt_completion, remove_columns=["prompt", "completion"])
```

```python
>>> dataset[0]
{'text': 'The sky is blue.'}
```

### プロンプト-補完からプロンプトのみのデータセットへ

プロンプトと補完のペアからなるデータセットを、プロンプトのみのデータセットに変換するには、補完を削除します。

```python
from datasets import Dataset

dataset = Dataset.from_dict({
    "prompt": ["The sky is", "The sun is"],
    "completion": [" blue.", " in the sky."],
})

dataset = dataset.remove_columns("completion")
```

```python
>>> dataset[0]
{'prompt': 'The sky is'}
```

### 暗黙のプロンプトを含む選好データから言語モデリング用データセットへ

暗黙のプロンプトを含む好みを言語モデリングデータセットに変換するには、拒否を削除し、`"chosen"` という列名を `"text"` に変更します。

```python
from datasets import Dataset

dataset = Dataset.from_dict({
    "chosen": ["The sky is blue.", "The sun is in the sky."],
    "rejected": ["The sky is green.", "The sun is in the sea."],
})

dataset = dataset.rename_column("chosen", "text").remove_columns("rejected")
```

```python
>>> dataset[0]
{'text': 'The sky is blue.'}
```

### 暗黙のプロンプト付きの選好データから、プロンプト-補完データセットへ

暗黙的なプロンプトを含む選好データセットを、プロンプトと補完のデータセットに変換するには、[extract_prompt()](/docs/trl/v1.19.0/ja/data_utils#trl.extract_prompt)でプロンプトを抽出し、rejectedを削除し、`"chosen"`列を`"completion"`に名前変更します。

```python
from datasets import Dataset
from trl import extract_prompt

dataset = Dataset.from_dict({
    "chosen": [
        [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}],
        [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}],
    ],
    "rejected": [
        [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}],
        [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}],
    ],
})
dataset = dataset.map(extract_prompt).remove_columns("rejected").rename_column("chosen", "completion")
```

```python
>>> dataset[0]
{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], 'completion': [{'role': 'assistant', 'content': 'It is blue.'}]}
```

### 暗黙のプロンプトを含む好意データセットから、プロンプトのみのデータセットへ

暗黙的なプロンプトを含む選好データセットを、プロンプトのみのデータセットに変換するには、[extract_prompt()](/docs/trl/v1.19.0/ja/data_utils#trl.extract_prompt)でプロンプトを抽出し、rejectedとchosenを削除します。

```python
from datasets import Dataset
from trl import extract_prompt

dataset = Dataset.from_dict({
    "chosen": [
        [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}],
        [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}],
    ],
    "rejected": [
        [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}],
        [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}],
    ],
})
dataset = dataset.map(extract_prompt).remove_columns(["chosen", "rejected"])
```

```python
>>> dataset[0]
{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}]}
```

### 暗黙的なプロンプト選好データセットから明示的なプロンプト選好データセットへ

暗黙的なプロンプトを含む選好データセットを、明示的なプロンプトを含む選好データセットに変換するには、[extract_prompt()](/docs/trl/v1.19.0/ja/data_utils#trl.extract_prompt)を使用してプロンプトを抽出します。

```python
from datasets import Dataset
from trl import extract_prompt

dataset = Dataset.from_dict({
    "chosen": [
        [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}],
        [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}],
    ],
    "rejected": [
        [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}],
        [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}],
    ],
})

dataset = dataset.map(extract_prompt)
```

```python
>>> dataset[0]
{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}],
 'chosen': [{'role': 'assistant', 'content': 'It is blue.'}],
 'rejected': [{'role': 'assistant', 'content': 'It is green.'}]}
```

### 暗黙のプロンプト付きの選好から非ペアの選好データセットへ

暗黙的なプロンプトを含む選好データセットをペアなしの選好データセットに変換するには、[extract_prompt()](/docs/trl/v1.19.0/ja/data_utils#trl.extract_prompt)でプロンプトを抽出し、[unpair_preference_dataset()](/docs/trl/v1.19.0/ja/data_utils#trl.unpair_preference_dataset)でデータセットをペアなしにします。

```python
from datasets import Dataset
from trl import extract_prompt, unpair_preference_dataset

dataset = Dataset.from_dict({
    "chosen": [
        [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}],
        [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}],
    ],
    "rejected": [
        [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}],
        [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}],
    ],
})

dataset = dataset.map(extract_prompt)
dataset = unpair_preference_dataset(dataset)
```

```python
>>> dataset[0]
{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}],
 'completion': [{'role': 'assistant', 'content': 'It is blue.'}],
 'label': True}
```

> [!WARNING]
> `"chosen"`と`"rejected"`の補完は、好みデータセットにおいてどちらも良いものでも悪いものでもあり得る点に注意してください。[unpair_preference_dataset()](/docs/trl/v1.19.0/ja/data_utils#trl.unpair_preference_dataset)を適用する前に、すべての`"chosen"`補完が「良い」とラベル付けでき、すべての`"rejected"`補完が「悪い」とラベル付けできることを確認してください。これは、報酬モデルなどから得られる各補完の絶対評価を確認することで保証できます。

### 嗜好データセットから言語モデリングデータセットへ

好意データセットを言語モデリングデータセットに変換するには、rejected を削除し、prompt と chosen を `"text"` 列に連結します。

```python
from datasets import Dataset

dataset = Dataset.from_dict({
    "prompt": ["The sky is", "The sun is"],
    "chosen": [" blue.", " in the sky."],
    "rejected": [" green.", " in the sea."],
})

def concat_prompt_chosen(example):
    return {"text": example["prompt"] + example["chosen"]}

dataset = dataset.map(concat_prompt_chosen, remove_columns=["prompt", "chosen", "rejected"])
```

```python
>>> dataset[0]
{'text': 'The sky is blue.'}
```

### からプロンプト-補完データセットへ

好意データセットをプロンプト-補完データセットに変換するには、拒否された列を削除し、`"chosen"` 列を `"completion"` に名前変更します。

```python
from datasets import Dataset

dataset = Dataset.from_dict({
    "prompt": ["The sky is", "The sun is"],
    "chosen": [" blue.", " in the sky."],
    "rejected": [" green.", " in the sea."],
})

dataset = dataset.remove_columns("rejected").rename_column("chosen", "completion")
```

```python
>>> dataset[0]
{'prompt': 'The sky is', 'completion': ' blue.'}
```

### からプロンプトのみのデータセットへ

好意データセットをプロンプトのみのデータセットに変換するには、拒否されたものと選択されたものを削除します。

```python
from datasets import Dataset

dataset = Dataset.from_dict({
    "prompt": ["The sky is", "The sun is"],
    "chosen": [" blue.", " in the sky."],
    "rejected": [" green.", " in the sea."],
})

dataset = dataset.remove_columns(["chosen", "rejected"])
```

```python
>>> dataset[0]
{'prompt': 'The sky is'}
```

### 明示的なプロンプト選好データセットから暗黙的なプロンプト選好データセットへ

明示的なプロンプトを含む選好データセットを、暗黙的なプロンプトを含む選好データセットに変換するには、プロンプトをchosenとrejectedの両方に連結し、プロンプトを削除します。

```python
from datasets import Dataset

dataset = Dataset.from_dict({
    "prompt": [
        [{"role": "user", "content": "What color is the sky?"}],
        [{"role": "user", "content": "Where is the sun?"}],
    ],
    "chosen": [
        [{"role": "assistant", "content": "It is blue."}],
        [{"role": "assistant", "content": "In the sky."}],
    ],
    "rejected": [
        [{"role": "assistant", "content": "It is green."}],
        [{"role": "assistant", "content": "In the sea."}],
    ],
})

def concat_prompt_to_completions(example):
    return {"chosen": example["prompt"] + example["chosen"], "rejected": example["prompt"] + example["rejected"]}

dataset = dataset.map(concat_prompt_to_completions, remove_columns="prompt")
```

```python
>>> dataset[0]
{'chosen': [{'role': 'user', 'content': 'What color is the sky?'}, {'role': 'assistant', 'content': 'It is blue.'}],
 'rejected': [{'role': 'user', 'content': 'What color is the sky?'}, {'role': 'assistant', 'content': 'It is green.'}]}
```

### 好みに基づくデータセットから非ペアの好みに基づくデータセットへ

データセットを非ペアの好みデータセットに変換するには、[unpair_preference_dataset()](/docs/trl/v1.19.0/ja/data_utils#trl.unpair_preference_dataset) を使用してデータセットを非ペア化します。

```python
from datasets import Dataset
from trl import unpair_preference_dataset

dataset = Dataset.from_dict({
    "prompt": [
        [{"role": "user", "content": "What color is the sky?"}],
        [{"role": "user", "content": "Where is the sun?"}],
    ],
    "chosen": [
        [{"role": "assistant", "content": "It is blue."}],
        [{"role": "assistant", "content": "In the sky."}],
    ],
    "rejected": [
        [{"role": "assistant", "content": "It is green."}],
        [{"role": "assistant", "content": "In the sea."}],
    ],
})

dataset = unpair_preference_dataset(dataset)
```

```python
>>> dataset[0]
{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}],
 'completion': [{'role': 'assistant', 'content': 'It is blue.'}],
 'label': True}
```

> [!WARNING]
> `"chosen"`と`"rejected"`の補完は、好みデータセットにおいてどちらも良いものでも悪いものでもあり得る点に注意してください。[unpair_preference_dataset()](/docs/trl/v1.19.0/ja/data_utils#trl.unpair_preference_dataset)を適用する前に、すべての`"chosen"`補完が「良い」とラベル付けでき、すべての`"rejected"`補完が「悪い」とラベル付けできることを確認してください。これは、報酬モデルなどから得られる各補完の絶対評価を確認することで保証できます。

### ペアなしの好みデータセットから言語モデリングデータセットへ

ペアなしの好みデータセットを言語モデリングデータセットに変換するには、プロンプトと良い補完を連結して`"text"`カラムに格納し、プロンプト、補完、ラベルのカラムを削除します。

```python
from datasets import Dataset

dataset = Dataset.from_dict({
    "prompt": ["The sky is", "The sun is", "The sky is", "The sun is"],
    "completion": [" blue.", " in the sky.", " green.", " in the sea."],
    "label": [True, True, False, False],
})

def concatenate_prompt_completion(example):
    return {"text": example["prompt"] + example["completion"]}

dataset = dataset.filter(lambda x: x["label"]).map(concatenate_prompt_completion).remove_columns(["prompt", "completion", "label"])
```

```python
>>> dataset[0]
{'text': 'The sky is blue.'}
```

### ペアなしの好みデータからプロンプト-補完データセットへ

ペアなしの好みデータセットをプロンプト-補完データセットに変換するには、良いラベルでフィルタリングし、その後ラベル列を削除します。

```python
from datasets import Dataset

dataset = Dataset.from_dict({
    "prompt": ["The sky is", "The sun is", "The sky is", "The sun is"],
    "completion": [" blue.", " in the sky.", " green.", " in the sea."],
    "label": [True, True, False, False],
})

dataset = dataset.filter(lambda x: x["label"]).remove_columns(["label"])
```

```python
>>> dataset[0]
{'prompt': 'The sky is', 'completion': ' blue.'}
```

### ペアなしの好みデータセットからプロンプトのみのデータセットへ

ペアなしの好みデータセットをプロンプトのみのデータセットに変換するには、completion列とlabel列を削除します。

```python
from datasets import Dataset

dataset = Dataset.from_dict({
    "prompt": ["The sky is", "The sun is", "The sky is", "The sun is"],
    "completion": [" blue.", " in the sky.", " green.", " in the sea."],
    "label": [True, True, False, False],
})

dataset = dataset.remove_columns(["completion", "label"])
```

```python
>>> dataset[0]
{'prompt': 'The sky is'}
```

## ビジョンデータセット

一部のトレーナーは、画像とテキストのペアを使用してビジョン言語モデル（VLM）のファインチューニングをサポートしています。このシナリオでは、各モデルがテキスト内の画像プレースホルダーを異なる方法で処理するため、会話形式の使用が推奨されます。

対話型ビジョンデータセットは、標準的な対話型データセットと2つの重要な点で異なります。

1. データセットには、画像データ（PIL画像のリスト）を含む`images`キー、または単一のPIL画像を含む`image`キーが含まれている必要があります。
2. メッセージ内の`"content"`フィールドは辞書のリストでなければならず、各辞書はデータの種類を指定します: `"image"`または`"text"`。

例:

```python
# Textual dataset:
"content": "What color is the sky?"

# Vision dataset:
"content": [
    {"type": "image"},
    {"type": "text", "text": "What color is the sky in the image?"}
]
```

対話型ビジョンデータセットの例として、[openbmb/RLAIF-V-Dataset](https://huggingface.co/datasets/openbmb/RLAIF-V-Dataset)があります。以下は、データセットのトレーニングデータの埋め込みビューです。直接探索できます:

<iframe src="https://huggingface.co/datasets/trl-lib/rlaif-v/embed/viewer/default/train" frameborder="0" width="100%" height="560px"
>

> [!NOTE]
> データセットにテキストのみとビジョン言語のデータを混在させることは可能ですが、`transformers`のバージョン4.57.0以降が必要です。例:
>
> ```python
> dataset = Dataset.from_dict({
>     "prompt": [
>         [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What color is the sky in the image?"}]}],
>         [{"role": "user", "content": [{"type": "text", "text": "What is the capital of France?"}]}],
>     ],
>     "completion": [
>         [{"role": "assistant", "content": [{"type": "text", "text": "It is blue."}]}],
>         [{"role": "assistant", "content": [{"type": "text", "text": "Paris."}]}],
>     ],
>     "images": [
>         [PIL.Image.open("path/to/sky_image1.png")],
>         [],
>     ],
> })
> ```

