# Định dạng và kiểu dữ liệu

Hướng dẫn này cung cấp cái nhìn tổng quan về các định dạng và kiểu dữ liệu được hỗ trợ bởi từng trainer trong TRL.

## Tổng quan về các định dạng và kiểu dữ liệu

- *Định dạng* của một tập dữ liệu đề cập đến cách dữ liệu được cấu trúc, thường được phân loại là *chuẩn* hoặc *đối thoại*.
- *type* liên quan đến nhiệm vụ cụ thể mà bộ dữ liệu được thiết kế cho, chẳng hạn như *prompt-only* hoặc *preference*. Mỗi type được đặc trưng bởi các cột của nó, thay đổi tùy theo nhiệm vụ, như được hiển thị trong bảng.

  
    Loại \ Định dạng Tiêu chuẩn Trò chuyện
  
  
    Mô hình hóa ngôn ngữ
    
      {"text": "Bầu trời màu xanh."}
    
    
      {"messages": [{"role": "user", "content": "Bầu trời màu gì?"}, {"role": "assistant", "content": "Nó màu xanh dương."}]}
    
  
  
    Chỉ prompt
    
      {"prompt": "Bầu trời là"}
    
    
      {"prompt": [{"role": "user", "content": "Bầu trời màu gì?"}]}
    
  
  
    Hoàn thành từ gợi ý
    
      {"prompt": "Bầu trời là", "completion": " xanh."}
    
    
      {"prompt": [{"role": "user", "content": "Trời màu gì?"}], "completion": [{"role": "assistant", "content": "Nó màu xanh."}]}
    
  
  
  
    Sở thích
    
      {"prompt": "Bầu trời là", "chosen": " màu xanh.", "rejected": " màu xanh lá."} hoặc, với prompt ngầm: {"chosen": "Bầu trời là màu xanh.", "rejected": "Bầu trời là màu xanh lá."}
    
    
      {"prompt": [{"role": "user", "content": "Bầu trời màu gì?"}], "chosen": [{"role": "assistant", "content": "Nó màu xanh dương."}], "rejected": [{"role": "assistant", "content": "Nó màu xanh lá."}]} hoặc, với prompt ngầm: {"chosen": [{"role": "user", "content": "Bầu trời màu gì?"}, {"role": "assistant", "content": "Nó màu xanh dương."}], "rejected": [{"role": "user", "content": "Bầu trời màu gì?"}, {"role": "assistant", "content": "Nó màu xanh lá."}]}
    
  
    Tùy chọn không ghép cặp
    
      {"prompt": "Bầu trời là", "completion": " xanh.", "label": True}
    
    
      {"prompt": [{"role": "user", "content": "Trời màu gì?"}], "completion": [{"role": "assistant", "content": "Nó màu xanh lá."}], "label": False}
    
  

### Định dạng

#### Tiêu chuẩn

Định dạng tập dữ liệu tiêu chuẩn thường bao gồm các chuỗi văn bản thuần túy. Các cột trong tập dữ liệu thay đổi tùy thuộc vào tác vụ. Đây là định dạng được các trình huấn luyện của TRL mong đợi. Dưới đây là các ví dụ về định dạng tập dữ liệu tiêu chuẩn cho các tác vụ khác nhau:

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

#### Đối thoại

Bộ dữ liệu hội thoại được sử dụng cho các tác vụ liên quan đến đối thoại hoặc tương tác trò chuyện giữa người dùng và trợ lý. Khác với định dạng bộ dữ liệu tiêu chuẩn, các bộ dữ liệu này chứa các chuỗi tin nhắn, trong đó mỗi tin nhắn có `role` (ví dụ: `"user"` hoặc `"assistant"`) và `content` (nội dung văn bản của tin nhắn).

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

Tương tự như các bộ dữ liệu tiêu chuẩn, các cột trong bộ dữ liệu hội thoại thay đổi tùy thuộc vào tác vụ. Dưới đây là các ví dụ về định dạng bộ dữ liệu hội thoại cho các tác vụ khác nhau:

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

#### Gọi công cụ

Một số chat template hỗ trợ *tool calling*, cho phép mô hình tương tác với các hàm bên ngoài—được gọi là **tools**—trong quá trình sinh. Điều này mở rộng khả năng hội thoại của mô hình bằng cách cho phép nó xuất ra trường `"tool_calls"` thay vì một tin nhắn `"content"` tiêu chuẩn bất cứ khi nào nó quyết định gọi một tool.

Sau khi trợ lý khởi tạo một cuộc gọi công cụ, công cụ sẽ thực thi và trả về kết quả. Trợ lý sau đó có thể xử lý kết quả này và tiếp tục cuộc trò chuyện theo cách phù hợp.

Dưới đây là một ví dụ đơn giản về tương tác gọi công cụ:

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

Khi chuẩn bị bộ dữ liệu cho Supervised Fine-Tuning (SFT) với tool calling, điều quan trọng là bộ dữ liệu của bạn phải bao gồm một cột bổ sung có tên là `tools`. Cột này chứa danh sách các công cụ khả dụng cho mô hình, thường được chat template sử dụng để xây dựng system prompt.

Các công cụ phải được chỉ định theo định dạng schema JSON có mã hóa. Bạn có thể tự động tạo schema này từ chữ ký hàm Python bằng tiện ích `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)
```

Sơ đồ được tạo ra sẽ có dạng:

```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."}}}
```

Một mục dữ liệu hoàn chỉnh cho SFT có thể trông như sau:

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

Để có được `Dataset`, bạn cần sử dụng kiểu `Json()` cho các đối số của công cụ vì chúng là các đối tượng JSON tùy ý, chứ không phải là các từ điển có các trường và kiểu cố định:

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

Trên các phiên bản cũ hơn của `datasets` (<4.7.0) không có kiểu `Json()`, bạn nên lưu trữ `tools` dưới dạng chuỗi JSON `str` (với `json.dumps([...])`):

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

Để biết thêm thông tin chi tiết về việc gọi công cụ, hãy tham khảo [mục Tool Calling trong tài liệu `transformers`](https://huggingface.co/docs/transformers/chat_extras#tools-and-rag) và bài viết trên blog [Tool Use, Unified](https://huggingface.co/blog/unified-tool-use).

### Harmony

Định dạng phản hồi [Harmony](https://cookbook.openai.com/articles/openai-harmony) được giới thiệu cùng với các [mô hình OpenAI GPT OSS](https://huggingface.co/collections/openai/gpt-oss-68911959590a1634ba11c7a4). Nó mở rộng định dạng hội thoại bằng cách thêm cấu trúc phong phú hơn cho suy luận, các cuộc gọi hàm và các siêu dữ liệu về hành vi của mô hình. Các tính năng chính bao gồm:

- **Vai trò nhà phát triển** – Cung cấp các chỉ dẫn cấp cao (tương tự như một prompt hệ thống) và liệt kê các công cụ khả dụng.
- **Kênh** – Tách các loại đầu ra của trợ lý thành các luồng riêng biệt:

  - `analysis` – cho suy luận nội bộ, từ khóa `"thinking"`
  - `final` – cho câu trả lời hướng đến người dùng, từ khóa `"content"`
  - `commentary` – dành cho các cuộc gọi công cụ hoặc ghi chú meta

- **Nỗ lực suy luận** – Chỉ báo mức độ suy nghĩ mà mô hình nên thể hiện (ví dụ: `"low"`, `"medium"`, `"high"`).
- **Định danh mô hình** – Xác định rõ ràng nhân vật của trợ lý.

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

Điều này tạo ra:

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

Để biết chi tiết đầy đủ về cấu trúc tin nhắn, các trường được hỗ trợ và cách sử dụng nâng cao, hãy xem [tài liệu Harmony](https://cookbook.openai.com/articles/openai-harmony).

### Các kiểu

#### Mô hình hóa ngôn ngữ

Bộ dữ liệu mô hình hóa ngôn ngữ bao gồm một cột `"text"` (hoặc `"messages"` đối với bộ dữ liệu hội thoại) chứa một chuỗi văn bản hoàn chỉnh.

```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."}
]}
```

#### Chỉ prompt

Trong một tập dữ liệu chỉ chứa prompt, chỉ có prompt ban đầu (câu hỏi hoặc câu chưa hoàn chỉnh) được cung cấp dưới khóa `"prompt"`. Việc huấn luyện thường bao gồm việc tạo ra phần hoàn thành dựa trên prompt này, trong đó mô hình học cách tiếp tục hoặc hoàn thành đầu vào đã cho.

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

Để xem các ví dụ về bộ dữ liệu chỉ chứa prompt, hãy tham khảo [bộ sưu tập các bộ dữ liệu chỉ chứa prompt](https://huggingface.co/collections/trl-lib/prompt-only-datasets-677ea25245d20252cea00368).

> [!TIP]
> Mặc dù cả hai loại prompt-only và language modeling đều tương tự nhau, chúng khác nhau ở cách xử lý đầu vào. Trong loại prompt-only, prompt đại diện cho một phần đầu vào, kỳ vọng mô hình sẽ hoàn thành hoặc tiếp tục, trong khi ở loại language modeling, đầu vào được coi là một câu hoặc chuỗi hoàn chỉnh. Hai loại này được TRL xử lý khác nhau. Dưới đây là một ví dụ minh họa sự khác biệt trong đầu ra của hàm `apply_chat_template` cho từng loại:
>
> ```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|>'}
> ```
>
> - Đầu ra chỉ gồm prompt bao gồm `'<|assistant|>\n'`, đánh dấu sự bắt đầu của lượt trả lời của trợ lý và kỳ vọng mô hình sẽ tạo ra phần hoàn thành. - Ngược lại, đầu ra của mô hình ngôn ngữ coi đầu vào là một chuỗi hoàn chỉnh và kết thúc nó bằng `'<|endoftext|>'`, báo hiệu kết thúc văn bản và không kỳ vọng thêm nội dung nào khác.

#### Hoàn thành từ gợi ý

Bộ dữ liệu prompt-completion bao gồm một `"prompt"` và một `"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."}]}
```

Để xem các ví dụ về bộ dữ liệu prompt-completion, hãy tham khảo [bộ sưu tập bộ dữ liệu prompt-completion](https://huggingface.co/collections/trl-lib/prompt-completion-datasets-677ea2bb20bbb6bdccada216).

#### Sở thích

Bộ dữ liệu ưu tiên được sử dụng cho các tác vụ mà mô hình được huấn luyện để chọn giữa hai hoặc nhiều hơn các phần hoàn thành có thể cho cùng một prompt. Bộ dữ liệu này bao gồm một `"prompt"`, một phần hoàn thành `"chosen"` và một phần hoàn thành `"rejected"`. Mô hình được huấn luyện để chọn phản hồi `"chosen"` thay vì phản hồi `"rejected"`. Một số bộ dữ liệu có thể không bao gồm cột `"prompt"`, trong trường hợp đó prompt là ngầm định và được bao gồm trực tiếp trong các phần hoàn thành `"chosen"` và `"rejected"`. Chúng tôi khuyến nghị sử dụng prompt rõ ràng bất cứ khi nào có thể.

```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."}]}
```

Để xem các ví dụ về bộ dữ liệu ưu tiên, hãy tham khảo [bộ sưu tập bộ dữ liệu ưu tiên](https://huggingface.co/collections/trl-lib/preference-datasets-677e99b581018fcad9abd82c).

Một số bộ dữ liệu ưu tiên có thể được tìm thấy với [thẻ `dpo` trên Hugging Face Hub](https://huggingface.co/datasets?other=dpo). Bạn cũng có thể khám phá [Các bộ sưu tập DPO của librarian-bots](https://huggingface.co/collections/librarian-bots/direct-preference-optimization-datasets-66964b12835f46289b6ef2fc) để xác định các bộ dữ liệu ưu tiên.

#### Tùy chọn không ghép cặp

Bộ dữ liệu ưu thích không ghép cặp tương tự như bộ dữ liệu ưu thích, nhưng thay vì có các phần hoàn thành `"chosen"` và `"rejected"` cho cùng một prompt, nó bao gồm một `"completion"` duy nhất và một `"label"` cho biết phần hoàn thành đó có được ưu thích hay không.

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

Để xem các ví dụ về bộ dữ liệu ưu tiên không ghép cặp, hãy tham khảo [bộ sưu tập bộ dữ liệu ưu tiên không ghép cặp](https://huggingface.co/collections/trl-lib/unpaired-preference-datasets-677ea22bf5f528c125b0bcdf).

## Nên sử dụng loại tập dữ liệu nào?

Việc chọn đúng loại dataset phụ thuộc vào tác vụ bạn đang thực hiện và các yêu cầu cụ thể của TRL trainer bạn đang sử dụng. Dưới đây là tổng quan ngắn gọn về các loại dataset được hỗ trợ bởi từng TRL trainer.

| Trainer | Kiểu dữ liệu tập dữ liệu dự kiến |
| --- | --- |
| [AsyncGRPOTrainer](/docs/trl/v1.18.2/vi/async_grpo_trainer#trl.AsyncGRPOTrainer) | [Chỉ prompt](#prompt-only) |
| [DPOTrainer](/docs/trl/v1.18.2/vi/dpo_trainer#trl.DPOTrainer) | [Ưu tiên (khuyến nghị dùng prompt rõ ràng)](#preference) |
| [GRPOTrainer](/docs/trl/v1.18.2/vi/grpo_trainer#trl.GRPOTrainer) | [Chỉ prompt](#prompt-only) |
| [KTOTrainer](/docs/trl/v1.18.2/vi/kto_trainer#trl.KTOTrainer) | [Ưu tiên không ghép cặp](#unpaired-preference) hoặc [Ưu tiên (khuyến nghị dùng prompt rõ ràng)](#preference) |
| [RewardTrainer](/docs/trl/v1.18.2/vi/reward_trainer#trl.RewardTrainer) | [Ưu tiên (khuyến nghị dùng prompt ẩn)](#preference) |
| [RLOOTrainer](/docs/trl/v1.18.2/vi/rloo_trainer#trl.RLOOTrainer) | [Chỉ prompt](#prompt-only) |
| [SFTTrainer](/docs/trl/v1.18.2/vi/sft_trainer#trl.SFTTrainer) | [Mô hình hóa ngôn ngữ](#language-modeling) hoặc [Hoàn thành prompt](#prompt-completion) |
| [experimental.cpo.CPOTrainer](/docs/trl/v1.18.2/vi/cpo_trainer#trl.experimental.cpo.CPOTrainer) | [Ưu tiên (khuyến nghị dùng prompt rõ ràng)](#preference) |
| [experimental.gkd.GKDTrainer](/docs/trl/v1.18.2/vi/gkd_trainer#trl.experimental.gkd.GKDTrainer) | [Hoàn thành prompt](#prompt-completion) |
| [experimental.online_dpo.OnlineDPOTrainer](/docs/trl/v1.18.2/vi/online_dpo_trainer#trl.experimental.online_dpo.OnlineDPOTrainer) | [Chỉ prompt](#prompt-only) |
| [experimental.orpo.ORPOTrainer](/docs/trl/v1.18.2/vi/orpo_trainer#trl.experimental.orpo.ORPOTrainer) | [Ưu tiên (khuyến nghị dùng prompt rõ ràng)](#preference) |

## Sử dụng bất kỳ bộ dữ liệu nào với TRL: tiền xử lý và chuyển đổi

Nhiều bộ dữ liệu có định dạng được thiết kế riêng cho các tác vụ cụ thể, có thể không tương thích trực tiếp với TRL. Để sử dụng các bộ dữ liệu này với TRL, bạn có thể cần tiền xử lý và chuyển đổi chúng sang định dạng yêu cầu.

Để việc này dễ dàng hơn, chúng tôi cung cấp một bộ [script mẫu](https://github.com/huggingface/trl/tree/main/examples/datasets) bao phủ các phép chuyển đổi tập dữ liệu phổ biến.

### Ví dụ: bộ dữ liệu UltraFeedback

Hãy lấy [dataset UltraFeedback](https://huggingface.co/datasets/openbmb/UltraFeedback) làm ví dụ. Dưới đây là bản xem trước của dataset:

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

Như đã trình bày ở trên, định dạng bộ dữ liệu không khớp với cấu trúc mong đợi. Dữ liệu không ở định dạng hội thoại, tên các cột khác nhau, và các kết quả liên quan đến các mô hình khác nhau (ví dụ: Bard, GPT-4) và các khía cạnh khác nhau (ví dụ: "helpfulness", "honesty").

Bằng cách sử dụng script chuyển đổi được cung cấp [`examples/datasets/ultrafeedback.py`](https://github.com/huggingface/trl/tree/main/examples/datasets/ultrafeedback.py), bạn có thể biến đổi dataset này thành dạng preference không ghép cặp, và đẩy nó lên Hub:

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

Sau khi chuyển đổi, bộ dữ liệu sẽ có dạng như sau:

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

Bây giờ, bạn có thể sử dụng bộ dữ liệu này với TRL!

Bằng cách điều chỉnh các script được cung cấp hoặc tự tạo script riêng, bạn có thể chuyển đổi bất kỳ dataset nào sang định dạng tương thích với TRL.

## Công cụ để chuyển đổi các kiểu dữ liệu

Phần này cung cấp mã mẫu để giúp bạn chuyển đổi giữa các kiểu dữ liệu khác nhau. Mặc dù một số phép chuyển đổi có thể được thực hiện sau khi áp dụng chat template (tức là ở định dạng chuẩn), chúng tôi khuyến nghị thực hiện chuyển đổi trước khi áp dụng chat template để đảm bảo tính nhất quán.

Để đơn giản hóa, một số ví dụ bên dưới không tuân theo khuyến nghị này và sử dụng định dạng chuẩn. Tuy nhiên, các phép chuyển đổi có thể được áp dụng trực tiếp lên định dạng hội thoại mà không cần chỉnh sửa.

| Từ \ Đến | Mô hình hóa ngôn ngữ | Hoàn thành từ gợi ý | Chỉ prompt | Tùy chọn với lời nhắc ẩn | Sở thích | Tùy chọn không ghép cặp |
| --- | --- | --- | --- | --- | --- | --- |
| Mô hình hóa ngôn ngữ | N/A | N/A | N/A | N/A | N/A | N/A |
| Hoàn thành từ gợi ý | [🔗](#from-prompt-completion-to-language-modeling-dataset) | N/A | [🔗](#from-prompt-completion-to-prompt-only-dataset) | N/A | N/A | N/A |
| Chỉ prompt | N/A | N/A | N/A | N/A | N/A | N/A |
| Tùy chọn với lời nhắc ẩn | [🔗](#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) |
| Sở thích | [🔗](#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) |
| Tùy chọn không ghép cặp | [🔗](#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 |

### Từ prompt-completion sang tập dữ liệu mô hình hóa ngôn ngữ

Để chuyển đổi một tập dữ liệu prompt-completion thành tập dữ liệu mô hình hóa ngôn ngữ, hãy nối prompt và completion lại với nhau.

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

### Từ tập dữ liệu prompt-completion sang tập dữ liệu chỉ có prompt

Để chuyển đổi một tập dữ liệu prompt-completion thành tập dữ liệu chỉ có prompt, hãy xóa phần completion.

```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'}
```

### Từ dữ liệu ưu tiên với prompt ẩn sang tập dữ liệu mô hình hóa ngôn ngữ

Để chuyển đổi một tập dữ liệu ưu tiên có prompt ngầm thành tập dữ liệu mô hình hóa ngôn ngữ, hãy xóa các phần bị từ chối và đổi tên cột `"chosen"` thành `"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.'}
```

### Từ dữ liệu ưu tiên có prompt ngầm sang tập dữ liệu prompt-completion

Để chuyển đổi bộ dữ liệu sở thích có prompt ẩn thành bộ dữ liệu prompt-completion, hãy trích xuất prompt bằng [extract_prompt()](/docs/trl/v1.18.2/vi/data_utils#trl.extract_prompt), loại bỏ các phần bị từ chối và đổi tên cột `"chosen"` thành `"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.'}]}
```

### Từ tập dữ liệu có prompt ẩn đến tập dữ liệu chỉ có prompt

Để chuyển đổi bộ dữ liệu sở thích có prompt ẩn thành bộ dữ liệu chỉ chứa prompt, hãy trích xuất prompt bằng [extract_prompt()](/docs/trl/v1.18.2/vi/data_utils#trl.extract_prompt) và loại bỏ các phần bị từ chối và được chọn.

```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?'}]}
```

### Từ tập dữ liệu ưu tiên prompt ẩn sang tập dữ liệu ưu tiên prompt tường minh

Để chuyển đổi bộ dữ liệu ưu tiên có prompt ẩn thành bộ dữ liệu ưu tiên có prompt rõ ràng, hãy trích xuất prompt bằng [extract_prompt()](/docs/trl/v1.18.2/vi/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.'}]}
```

### Từ sở thích có prompt ẩn sang tập dữ liệu sở thích không ghép cặp

Để chuyển đổi một tập dữ liệu sở thích có prompt ẩn thành một tập dữ liệu sở thích không ghép cặp, hãy trích xuất prompt bằng [extract_prompt()](/docs/trl/v1.18.2/vi/data_utils#trl.extract_prompt) và tách cặp tập dữ liệu bằng [unpair_preference_dataset()](/docs/trl/v1.18.2/vi/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]
> Hãy lưu ý rằng các completion `"chosen"` và `"rejected"` trong một tập dữ liệu preference có thể đều tốt hoặc đều xấu. Trước khi áp dụng [unpair_preference_dataset()](/docs/trl/v1.18.2/vi/data_utils#trl.unpair_preference_dataset), hãy đảm bảo rằng tất cả các completion `"chosen"` có thể được gán nhãn là tốt và tất cả các completion `"rejected"` là xấu. Điều này có thể được đảm bảo bằng cách kiểm tra đánh giá tuyệt đối của từng completion, ví dụ từ một reward model.

### Từ tập dữ liệu ưu tiên sang tập dữ liệu mô hình hóa ngôn ngữ

Để chuyển đổi một tập dữ liệu ưu tiên thành tập dữ liệu mô hình hóa ngôn ngữ, hãy xóa các phần bị từ chối, nối prompt và phần được chọn vào cột `"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.'}
```

### Từ tập dữ liệu ưu tiên sang tập dữ liệu hoàn thành prompt

Để chuyển đổi một tập dữ liệu ưu tiên thành tập dữ liệu prompt-completion, hãy xóa các phần bị từ chối và đổi tên cột `"chosen"` thành `"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.'}
```

### Từ dữ liệu tập hợp theo sở thích sang tập hợp chỉ có prompt

Để chuyển đổi một tập dữ liệu ưu tiên thành tập dữ liệu chỉ chứa prompt, hãy loại bỏ các phần bị từ chối và được chọn.

```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'}
```

### Từ bộ dữ liệu ưu tiên prompt tường minh sang bộ dữ liệu ưu tiên prompt ẩn

Để chuyển đổi một tập dữ liệu ưu tiên có prompt rõ ràng thành một tập dữ liệu ưu tiên có prompt ngầm, hãy nối prompt vào cả phần được chọn và phần bị từ chối, sau đó xóa prompt.

```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.'}]}
```

### Từ dữ liệu ưu tiên sang tập dữ liệu ưu tiên không ghép cặp

Để chuyển đổi dataset thành một dataset preference không ghép cặp, hãy tách dataset bằng [unpair_preference_dataset()](/docs/trl/v1.18.2/vi/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]
> Hãy lưu ý rằng các completion `"chosen"` và `"rejected"` trong một tập dữ liệu preference có thể đều tốt hoặc đều xấu. Trước khi áp dụng [unpair_preference_dataset()](/docs/trl/v1.18.2/vi/data_utils#trl.unpair_preference_dataset), hãy đảm bảo rằng tất cả các completion `"chosen"` có thể được gán nhãn là tốt và tất cả các completion `"rejected"` là xấu. Điều này có thể được đảm bảo bằng cách kiểm tra đánh giá tuyệt đối của từng completion, ví dụ từ một reward model.

### Từ tập dữ liệu ưu thích không ghép cặp sang tập dữ liệu mô hình hóa ngôn ngữ

Để chuyển đổi một bộ dữ liệu ưu tiên không ghép cặp thành một bộ dữ liệu mô hình hóa ngôn ngữ, hãy nối các prompt với các completion tốt vào cột `"text"`, và xóa các cột prompt, completion và 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],
})

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

### Từ tập dữ liệu ưu thích không ghép cặp sang tập dữ liệu prompt-completion

Để chuyển đổi một bộ dữ liệu ưu tiên không ghép cặp thành một bộ dữ liệu prompt-completion, hãy lọc các nhãn tốt, sau đó xóa các cột nhãn.

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

### Từ tập dữ liệu ưu thích không ghép cặp sang tập dữ liệu chỉ có prompt

Để chuyển đổi một bộ dữ liệu ưu tiên không ghép cặp thành một bộ dữ liệu chỉ chứa prompt, hãy xóa các cột completion và 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'}
```

## Bộ dữ liệu thị giác

Một số trình huấn luyện cũng hỗ trợ tinh chỉnh các mô hình thị giác-ngôn ngữ (VLM) bằng cách sử dụng các cặp hình ảnh-văn bản. Trong kịch bản này, việc sử dụng định dạng hội thoại được khuyến nghị, vì mỗi mô hình xử lý các vị trí chèn hình ảnh trong văn bản theo những cách khác nhau.

Một tập dữ liệu thị giác hội thoại khác với một tập dữ liệu hội thoại tiêu chuẩn ở hai điểm chính:

1. Bộ dữ liệu phải chứa khóa `images` với dữ liệu hình ảnh (dưới dạng danh sách các hình ảnh PIL) hoặc `image` với một hình ảnh PIL duy nhất.
2. Trường `"content"` trong messages phải là một danh sách các từ điển, trong đó mỗi từ điển chỉ định loại dữ liệu: `"image"` hoặc `"text"`.

Ví dụ:

```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?"}
]
```

Một ví dụ về tập dữ liệu thị giác hội thoại là [openbmb/RLAIF-V-Dataset](https://huggingface.co/datasets/openbmb/RLAIF-V-Dataset). Dưới đây là khung nhúng hiển thị dữ liệu huấn luyện của tập dữ liệu, cho phép bạn khám phá trực tiếp:

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

> [!NOTE]
> Việc trộn lẫn dữ liệu chỉ có văn bản và dữ liệu thị giác-ngôn ngữ trong tập dữ liệu là khả thi, nhưng yêu cầu phiên bản `transformers` 4.57.0 trở lên. Ví dụ:
>
> ```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")],
>         [],
>     ],
> })
> ```

