TRL documentation

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

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v1.18.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

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

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

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

  • formatとは、データの構造を指し、通常はstandardまたはconversationalのいずれかに分類されます。
  • typeは、prompt-onlyやpreferenceなど、データセットが設計された特定のタスクに関連付けられています。各タイプは、そのタスクに応じて異なる列によって特徴付けられ、その詳細は以下の表に示されています。
型 \ 形式標準対話型
言語モデリング
{"text": "The sky is blue."}
{"messages": [{"role": "user", "content": "What color is the sky?"},
              {"role": "assistant", "content": "It is blue."}]}
プロンプトのみ
{"prompt": "The sky is"}
{"prompt": [{"role": "user", "content": "What color is the sky?"}]}
プロンプト-補完
{"prompt": "The sky is",
 "completion": " blue."}
{"prompt": [{"role": "user", "content": "What color is the sky?"}],
 "completion": [{"role": "assistant", "content": "It is blue."}]}
好み
{"prompt": "The sky is",
 "chosen": " blue.",
 "rejected": " green."}
または、プロンプトを省略して:
{"chosen": "The sky is blue.",
 "rejected": "The sky is green."}
{"prompt": [{"role": "user", "content": "What color is the sky?"}],
 "chosen": [{"role": "assistant", "content": "It is blue."}],
 "rejected": [{"role": "assistant", "content": "It is green."}]}
または、暗黙の prompt を使用する場合:
{"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."}]}
ペアなしの好み
{"prompt": "The sky is",
 "completion": " blue.",
 "label": True}
{"prompt": [{"role": "user", "content": "What color is the sky?"}],
 "completion": [{"role": "assistant", "content": "It is green."}],
 "label": False}

形式

標準

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

# 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(メッセージのテキスト)が割り当てられています。

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!"},
]

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

# 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"フィールドを出力できるようになり、モデルの会話機能が拡張されます。

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

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

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の関数シグネチャからこのスキーマを自動生成できます。

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)

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

{"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用の完全なデータセットエントリは、次のようになる可能性があります。

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

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

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([...]) を使用):

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

ツール呼び出しの詳細については、transformersドキュメントのTool Callingセクションおよびブログ記事Tool Use, Unifiedを参照してください。

Harmony

Harmony レスポンス形式は、OpenAI GPT OSS モデルとともに導入されました。この形式は、対話形式を拡張し、推論、関数呼び出し、およびモデルの動作に関するメタデータに対してより豊かな構造を追加します。主な機能は以下の通りです:

  • 開発者ロール – 高レベルの指示(システムプロンプトに類似)を提供し、利用可能なツールを列挙します。

  • チャンネル – アシスタントの出力を種類ごとに個別のストリームに分離します:

    • analysis – 内部の推論用。キー "thinking" から取得されます
    • final – ユーザー向けの回答。キー "content" から取得されます
    • commentary – ツール呼び出しやメタノート用
  • 推論の努力度 – モデルが示すべき思考の量を示します(例: "low"、"medium"、"high")。

  • モデルのアイデンティティ – アシスタントのペルソナを明示的に定義します。

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.",
    )
)

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

<|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のドキュメントを参照してください。

型

言語モデリング

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

# 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"の下に初期プロンプト(質問や部分文)のみが提供されます。トレーニングでは通常、このプロンプトに基づいて補完を生成し、モデルが与えられた入力を継続または補完することを学習します。

# 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を参照してください。

型と型は似ていますが、入力の処理方法が異なります。型では、プロンプトはモデルによる補完や継続を期待する部分入力を表し、型では、入力は完全な文またはシーケンスとして扱われます。TRLでは、これら2つの型は異なる方法で処理されます。以下は、各型におけるapply_chat_template関数の出力の違いを示す例です:

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"が含まれます。

# 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を参照してください。

好み

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

# 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を参照してください。

Hugging Face Hubのdpoタグで、いくつかの好みデータセットを見つけることができます。また、librarian-botsのDPOコレクションを探索して、好みデータセットを特定することもできます。

ペアなしの好み

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

# 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を参照してください。

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

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

Trainer期待されるデータセットの型
AsyncGRPOTrainerPromptのみ
DPOTrainer好み(明示的なプロンプトを推奨)
GRPOTrainerPromptのみ
KTOTrainer非ペアの好みまたは好み(明示的なプロンプトを推奨)
RewardTrainer好み(暗黙のプロンプトを推奨)
RLOOTrainerPromptのみ
SFTTrainer言語モデリングまたはPrompt-completion
experimental.cpo.CPOTrainer好み(明示的なプロンプトを推奨)
experimental.gkd.GKDTrainerプロンプト-補完
experimental.online_dpo.OnlineDPOTrainerPromptのみ
experimental.orpo.ORPOTrainer好み(明示的なプロンプトを推奨)

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

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

これを容易にするため、一般的なデータセット変換をカバーするサンプルスクリプトのセットを提供しています。

例: UltraFeedback データセット

UltraFeedback データセットを例に取ります。以下は、このデータセットのプレビューです。

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

提供されている変換スクリプト examples/datasets/ultrafeedback.py を使用すると、このデータセットをペアなしの好みタイプに変換し、Hub にプッシュできます。

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

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

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

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

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

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

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

From \ To言語モデリングプロンプト-補完プロンプトのみ暗黙のプロンプトによる選好好みペアなしの好み
言語モデリングN/AN/AN/AN/AN/AN/A
プロンプト-補完🔗N/A🔗N/AN/AN/A
プロンプトのみN/AN/AN/AN/AN/AN/A
暗黙のプロンプトによる選好🔗🔗🔗N/A🔗🔗
好み🔗🔗🔗🔗N/A🔗
ペアなしの好み🔗🔗🔗N/AN/AN/A

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

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

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"])
>>> dataset[0]
{'text': 'The sky is blue.'}

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

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

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")
>>> dataset[0]
{'prompt': 'The sky is'}

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

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

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")
>>> dataset[0]
{'text': 'The sky is blue.'}

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

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

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")
>>> dataset[0]
{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], 'completion': [{'role': 'assistant', 'content': 'It is blue.'}]}

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

暗黙的なプロンプトを含む選好データセットを、プロンプトのみのデータセットに変換するには、extract_prompt()でプロンプトを抽出し、rejectedとchosenを削除します。

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"])
>>> dataset[0]
{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}]}

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

暗黙的なプロンプトを含む選好データセットを、明示的なプロンプトを含む選好データセットに変換するには、extract_prompt()を使用してプロンプトを抽出します。

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)
>>> 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()でプロンプトを抽出し、unpair_preference_dataset()でデータセットをペアなしにします。

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)
>>> dataset[0]
{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}],
 'completion': [{'role': 'assistant', 'content': 'It is blue.'}],
 'label': True}

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

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

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

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"])
>>> dataset[0]
{'text': 'The sky is blue.'}

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

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

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")
>>> dataset[0]
{'prompt': 'The sky is', 'completion': ' blue.'}

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

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

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"])
>>> dataset[0]
{'prompt': 'The sky is'}

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

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

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")
>>> 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() を使用してデータセットを非ペア化します。

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)
>>> dataset[0]
{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}],
 'completion': [{'role': 'assistant', 'content': 'It is blue.'}],
 'label': True}

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

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

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

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"])
>>> dataset[0]
{'text': 'The sky is blue.'}

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

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

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"])
>>> dataset[0]
{'prompt': 'The sky is', 'completion': ' blue.'}

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

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

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"])
>>> dataset[0]
{'prompt': 'The sky is'}

ビジョンデータセット

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

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

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

例:

# 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があります。以下は、データセットのトレーニングデータの埋め込みビューです。直接探索できます:

データセットにテキストのみとビジョン言語のデータを混在させることは可能ですが、transformersのバージョン4.57.0以降が必要です。例:

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")],
        [],
    ],
})
Update on GitHub