# 데이터셋 형식 및 유형

이 가이드는 TRL의 각 trainer가 지원하는 데이터셋 형식과 유형에 대한 개요를 제공합니다.

## 데이터셋 형식 및 유형 개요

- 데이터셋의 *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": "What color is the sky?"}], "chosen": [{"role": "assistant", "content": "It is blue."}], "rejected": [{"role": "assistant", "content": "It is green."}]} or, with implicit 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": "하늘은", "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."}],
}
```

#### Tool Calling

일부 채팅 템플릿은 *tool calling*을 지원하며, 이를 통해 모델은 생성 과정에서 외부 함수, 즉 **tools**와 상호작용할 수 있습니다. 이는 모델이 도구를 호출하기로 결정할 때마다 표준 `"content"` 메시지 대신 `"tool_calls"` 필드를 출력하도록 하여 모델의 대화 기능을 확장합니다.

assistant가 도구 호출을 시작하면, 도구가 실행되어 출력을 반환합니다. 이후 assistant는 이 출력을 처리하고 그에 따라 대화를 계속 진행할 수 있습니다.

도구 호출 상호작용의 간단한 예시입니다:

```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.dumps([...])`를 사용하여 JSON `str`으로 저장해야 합니다:

```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"` 키 아래에 제공됩니다. 학습은 일반적으로 이 프롬프트를 기반으로 completion을 생성하는 과정을 포함하며, 모델은 주어진 입력을 계속하거나 완성하는 방법을 학습합니다.

```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]
> prompt-only 유형과 language modeling 유형은 유사하지만, 입력을 처리하는 방식에서 차이가 있습니다. prompt-only 유형에서는 프롬프트가 모델이 완성하거나 이어서 생성하기를 기대하는 부분 입력을 나타내지만, language modeling 유형에서는 입력이 완전한 문장 또는 시퀀스로 취급됩니다. TRL은 이 두 유형을 서로 다른 방식으로 처리합니다. 아래는 각 유형에 대해 `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|>'}
> ```
>
> - prompt-only 출력에는 `'<|assistant|>\n'`가 포함되어 있으며, 이는 어시스턴트의 턴 시작을 나타내고 모델이 completion을 생성하도록 기대합니다. - 반면, language modeling 출력은 입력을 완전한 시퀀스로 취급하여 `'<|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)을 참조하세요.

#### 선호

선호 데이터셋은 동일한 프롬프트에 대한 두 개 이상의 가능한 완성안 중에서 선택하도록 모델을 학습하는 작업에 사용됩니다. 이 데이터셋에는 `"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 Collections](https://huggingface.co/collections/librarian-bots/direct-preference-optimization-datasets-66964b12835f46289b6ef2fc)를 탐색하여 선호 데이터셋을 식별할 수도 있습니다.

#### 비대칭 선호

비쌍(pair) 선호 데이터셋은 선호 데이터셋과 유사하지만, 동일한 프롬프트에 대해 `"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 trainer의 특정 요구 사항에 따라 달라집니다. 아래는 각 TRL trainer가 지원하는 데이터셋 유형에 대한 간략한 개요입니다.

| Trainer | 기대되는 데이터셋 유형 |
| --- | --- |
| [AsyncGRPOTrainer](/docs/trl/v1.18.0/ko/async_grpo_trainer#trl.AsyncGRPOTrainer) | [프롬프트 전용](#prompt-only) |
| [DPOTrainer](/docs/trl/v1.18.0/ko/dpo_trainer#trl.DPOTrainer) | [선호도 (명시적 프롬프트 권장)](#preference) |
| [GRPOTrainer](/docs/trl/v1.18.0/ko/grpo_trainer#trl.GRPOTrainer) | [프롬프트 전용](#prompt-only) |
| [KTOTrainer](/docs/trl/v1.18.0/ko/kto_trainer#trl.KTOTrainer) | [비쌍 선호](#unpaired-preference) 또는 [선호(명시적 프롬프트 권장)](#preference) |
| [RewardTrainer](/docs/trl/v1.18.0/ko/reward_trainer#trl.RewardTrainer) | [선호도 (암시 프롬프트 권장)](#preference) |
| [RLOOTrainer](/docs/trl/v1.18.0/ko/rloo_trainer#trl.RLOOTrainer) | [프롬프트 전용](#prompt-only) |
| [SFTTrainer](/docs/trl/v1.18.0/ko/sft_trainer#trl.SFTTrainer) | [언어 모델링](#language-modeling) 또는 [Prompt-completion](#prompt-completion) |
| [experimental.cpo.CPOTrainer](/docs/trl/v1.18.0/ko/cpo_trainer#trl.experimental.cpo.CPOTrainer) | [선호도 (명시적 프롬프트 권장)](#preference) |
| [experimental.gkd.GKDTrainer](/docs/trl/v1.18.0/ko/gkd_trainer#trl.experimental.gkd.GKDTrainer) | [프롬프트-완성](#prompt-completion) |
| [experimental.online_dpo.OnlineDPOTrainer](/docs/trl/v1.18.0/ko/online_dpo_trainer#trl.experimental.online_dpo.OnlineDPOTrainer) | [프롬프트 전용](#prompt-only) |
| [experimental.orpo.ORPOTrainer](/docs/trl/v1.18.0/ko/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)를 사용하면 이 데이터셋을 unpaired preference 유형으로 변환하여 Hub에 push할 수 있습니다:

```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과 호환되는 형식으로 변환할 수 있습니다.

## 데이터셋 유형 변환 유틸리티

이 섹션에서는 서로 다른 데이터셋 유형 간 변환을 돕기 위한 예제 코드를 제공합니다. 일부 변환은 채팅 템플릿 적용 후(즉, 표준 형식에서) 수행할 수 있지만, 일관되게 작동하도록 보장하기 위해 채팅 템플릿 적용 전에 변환을 수행하는 것을 권장합니다.

간단함을 위해 아래 예시 중 일부는 이 권장 사항을 따르지 않고 표준 형식을 사용합니다. 그러나 변환은 수정 없이 대화 형식에 직접 적용할 수 있습니다.

| \에서 \로 | 언어 모델링 | 프롬프트-완성 | 프롬프트 전용 | 암시적 프롬프트를 사용한 선호도 | 선호 | 비대칭 선호 |
| --- | --- | --- | --- | --- | --- | --- |
| 언어 모델링 | 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.18.0/ko/data_utils#trl.extract_prompt)로 프롬프트를 추출하고, 거부 항목을 제거한 뒤 `"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.18.0/ko/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.18.0/ko/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.18.0/ko/data_utils#trl.extract_prompt)로 프롬프트를 추출하고, [unpair_preference_dataset()](/docs/trl/v1.18.0/ko/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.18.0/ko/data_utils#trl.unpair_preference_dataset)를 적용하기 전에, 모든 `"chosen"` 완료본이 양호하고 모든 `"rejected"` 완료본이 불량으로 분류될 수 있는지 확인하세요. 이는 각 완료본의 절대 평가 점수를 확인함으로써 보장할 수 있으며, 예를 들어 보상 모델로부터의 점수를 사용할 수 있습니다.

### Preference에서 언어 모델링 데이터셋으로

선호 데이터셋을 언어 모델링 데이터셋으로 변환하려면, 거부 항목을 제거하고 프롬프트와 선택 항목을 `"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.'}
```

### 선호도에서 프롬프트-완성 데이터셋으로

선호 데이터셋을 프롬프트-완성 데이터셋으로 변환하려면 rejected를 제거하고 `"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.'}
```

### Preference에서 prompt-only 데이터셋으로

prompt-only 데이터셋으로 변환하려면, 거부(rejected)와 선택(chosen)을 제거합니다.

```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.18.0/ko/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.18.0/ko/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.'}
```

### 미페어링된 선호도에서 프롬프트-완성 데이터셋으로

unpaired 선호 데이터셋을 prompt-completion 데이터셋으로 변환하려면, 좋은 라벨을 필터링한 후 라벨 컬럼을 제거합니다.

```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)의 파인튜닝을 지원합니다. 이 시나리오에서는 각 모델이 텍스트 내 이미지 플레이스홀더를 처리하는 방식이 다르므로 대화형 형식을 사용하는 것이 권장됩니다.

대화형 비전 데이터셋은 표준 대화형 데이터셋과 두 가지 핵심적인 점에서 다릅니다:

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")],
>         [],
>     ],
> })
> ```

