[ { "chunk_id": 0, "text": "# TRL - Transformers Reinforcement Learning\n\nTRL is a full stack library where we provide a set of tools to train transformer language models with methods like Supervised Fine-Tuning (SFT), Group Relative Policy Optimization (GRPO), Direct Preference Optimization (DPO), Reward Modeling, and more.\nThe library is integrated with \ud83e\udd17 [transformers](https://github.com/huggingface/transformers).", "source_file": "trl/index.md", "section_heading": "TRL - Transformers Reinforcement Learning", "char_start": 0, "char_end": 391, "token_estimate": 97, "prev_chunk_id": null, "next_chunk_id": 1, "url": "https://huggingface.co/docs/trl/index", "doc_title": "TRL - Transformers Reinforcement Learning" }, { "chunk_id": 1, "text": "## \ud83c\udf89 What's New\n\n**TRL v1:** We released TRL v1 \u2014 a major milestone that marks a real shift in what TRL is. Read the [blog post](https://huggingface.co/blog/trl-v1) to learn more.", "source_file": "trl/index.md", "section_heading": "\ud83c\udf89 What's New", "char_start": 393, "char_end": 572, "token_estimate": 44, "prev_chunk_id": 0, "next_chunk_id": 2, "url": "https://huggingface.co/docs/trl/index", "doc_title": "TRL - Transformers Reinforcement Learning" }, { "chunk_id": 2, "text": "## Taxonomy\n\nBelow is the current list of TRL trainers, organized by method type (\u26a1\ufe0f = vLLM support; \ud83e\uddea = experimental).", "source_file": "trl/index.md", "section_heading": "Taxonomy", "char_start": 574, "char_end": 693, "token_estimate": 29, "prev_chunk_id": 1, "next_chunk_id": 3, "url": "https://huggingface.co/docs/trl/index", "doc_title": "TRL - Transformers Reinforcement Learning" }, { "chunk_id": 3, "text": "### Online methods\n\n- [`GRPOTrainer`](grpo_trainer) \u26a1\ufe0f\n- [`RLOOTrainer`](rloo_trainer) \u26a1\ufe0f\n- [`OnlineDPOTrainer`](online_dpo_trainer) \ud83e\uddea \u26a1\ufe0f\n- [`NashMDTrainer`](nash_md_trainer) \ud83e\uddea \u26a1\ufe0f\n- [`PPOTrainer`](ppo_trainer) \ud83e\uddea\n- [`XPOTrainer`](xpo_trainer) \ud83e\uddea \u26a1\ufe0f", "source_file": "trl/index.md", "section_heading": "Online methods", "char_start": 695, "char_end": 941, "token_estimate": 61, "prev_chunk_id": 2, "next_chunk_id": 4, "url": "https://huggingface.co/docs/trl/index", "doc_title": "TRL - Transformers Reinforcement Learning" }, { "chunk_id": 4, "text": "### Reward modeling\n\n- [`RewardTrainer`](reward_trainer)\n- [`PRMTrainer`](prm_trainer) \ud83e\uddea", "source_file": "trl/index.md", "section_heading": "Reward modeling", "char_start": 943, "char_end": 1031, "token_estimate": 22, "prev_chunk_id": 3, "next_chunk_id": 5, "url": "https://huggingface.co/docs/trl/index", "doc_title": "TRL - Transformers Reinforcement Learning" }, { "chunk_id": 5, "text": "### Offline methods\n\n- [`SFTTrainer`](sft_trainer)\n- [`DPOTrainer`](dpo_trainer)\n- [`BCOTrainer`](bco_trainer) \ud83e\uddea\n- [`CPOTrainer`](cpo_trainer) \ud83e\uddea\n- [`KTOTrainer`](kto_trainer) \ud83e\uddea\n- [`ORPOTrainer`](orpo_trainer) \ud83e\uddea", "source_file": "trl/index.md", "section_heading": "Offline methods", "char_start": 1033, "char_end": 1243, "token_estimate": 52, "prev_chunk_id": 4, "next_chunk_id": 6, "url": "https://huggingface.co/docs/trl/index", "doc_title": "TRL - Transformers Reinforcement Learning" }, { "chunk_id": 6, "text": "### Knowledge distillation\n\n- [`GKDTrainer`](gkd_trainer) \ud83e\uddea\n- [`MiniLLMTrainer`](minillm_trainer) \ud83e\uddea\n\nYou can also explore TRL-related models, datasets, and demos in the [TRL Hugging Face organization](https://huggingface.co/trl-lib).", "source_file": "trl/index.md", "section_heading": "Knowledge distillation", "char_start": 1245, "char_end": 1478, "token_estimate": 58, "prev_chunk_id": 5, "next_chunk_id": 7, "url": "https://huggingface.co/docs/trl/index", "doc_title": "TRL - Transformers Reinforcement Learning" }, { "chunk_id": 7, "text": "## Learn\n\nLearn post-training with TRL and other libraries in \ud83e\udd17 [smol course](https://github.com/huggingface/smol-course).", "source_file": "trl/index.md", "section_heading": "Learn", "char_start": 1480, "char_end": 1602, "token_estimate": 30, "prev_chunk_id": 6, "next_chunk_id": 8, "url": "https://huggingface.co/docs/trl/index", "doc_title": "TRL - Transformers Reinforcement Learning" }, { "chunk_id": 8, "text": "## Contents\n\nThe documentation is organized into the following sections:\n\n- **Getting Started**: installation and quickstart guide.\n- **Conceptual Guides**: dataset formats, training FAQ, and understanding logs.\n- **How-to Guides**: reducing memory usage, speeding up training, distributing training, etc.\n- **Integrations**: DeepSpeed, Liger Kernel, PEFT, etc.\n- **Examples**: example overview, community tutorials, etc.\n- **API**: trainers, utils, etc.", "source_file": "trl/index.md", "section_heading": "Contents", "char_start": 1604, "char_end": 2058, "token_estimate": 113, "prev_chunk_id": 7, "next_chunk_id": 9, "url": "https://huggingface.co/docs/trl/index", "doc_title": "TRL - Transformers Reinforcement Learning" }, { "chunk_id": 9, "text": "## Blog posts", "source_file": "trl/index.md", "section_heading": "Blog posts", "char_start": 2060, "char_end": 2073, "token_estimate": 3, "prev_chunk_id": 8, "next_chunk_id": 10, "url": "https://huggingface.co/docs/trl/index", "doc_title": "TRL - Transformers Reinforcement Learning" }, { "chunk_id": 10, "text": "Published March 27, 2026\n TRL v1: Post-Training Library That Holds When the Field Invalidates Its Own Assumptions\n \n \n \n Published October 23, 2025\n Building the Open Agent Ecosystem Together: Introducing OpenEnv\n \n \n \n Published on August 7, 2025\n Vision Language Model Alignment in TRL \u26a1\ufe0f\n \n \n \n Published on June 3, 2025\n NO GPU left behind: Unlocking Efficiency with Co-located vLLM in TRL\n \n \n \n Published on May 25, 2025\n \ud83d\udc2f Liger GRPO meets TRL\n \n \n \n Published on January 28, 2025\n Open-R1: a fully open reproduction of DeepSeek-R1\n \n \n \n Published on July 10, 2024\n Preference Optimization for Vision Language Models with TRL\n \n \n \n Published on June 12, 2024\n Putting RL back in RLHF\n \n \n \n Published on September 29, 2023\n Finetune Stable Diffusion Models with DDPO via TRL\n \n \n \n Published on August 8, 2023\n Fine-tune Llama 2 with DPO\n \n \n \n Published on April 5, 2023\n StackLLaMA: A hands-on guide to train LLaMA with RLHF\n \n \n \n Published on March 9, 2023\n Fine-tuning 20B LLMs with RLHF on a 24GB consumer GPU\n \n \n \n Published on December 9, 2022\n Illustrating Reinforcement Learning from Human Feedback", "source_file": "trl/index.md", "section_heading": "Blog posts", "char_start": 2096, "char_end": 3470, "token_estimate": 348, "prev_chunk_id": 9, "next_chunk_id": 11, "url": "https://huggingface.co/docs/trl/index", "doc_title": "TRL - Transformers Reinforcement Learning" }, { "chunk_id": 11, "text": "## Talks\n\n \n \n \n Talk given on October 30, 2025\n Fine tuning with TRL", "source_file": "trl/index.md", "section_heading": "Talks", "char_start": 3480, "char_end": 3568, "token_estimate": 22, "prev_chunk_id": 10, "next_chunk_id": null, "url": "https://huggingface.co/docs/trl/index", "doc_title": "TRL - Transformers Reinforcement Learning" }, { "chunk_id": 12, "text": "# SFT Trainer\n\n[![All_models-SFT-blue](https://img.shields.io/badge/All_models-SFT-blue)](https://huggingface.co/models?other=sft,trl) [![smol_course-Chapter_1-yellow](https://img.shields.io/badge/smol_course-Chapter_1-yellow)](https://github.com/huggingface/smol-course/tree/main/1_instruction_tuning)", "source_file": "trl/sft_trainer.md", "section_heading": "SFT Trainer", "char_start": 0, "char_end": 302, "token_estimate": 75, "prev_chunk_id": null, "next_chunk_id": 13, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 13, "text": "## Overview\n\nTRL supports the Supervised Fine-Tuning (SFT) Trainer for training language models.\n\nThis post-training method was contributed by [Younes Belkada](https://huggingface.co/ybelkada).", "source_file": "trl/sft_trainer.md", "section_heading": "Overview", "char_start": 304, "char_end": 497, "token_estimate": 48, "prev_chunk_id": 12, "next_chunk_id": 14, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 14, "text": "## Quick start\n\nThis example demonstrates how to train a language model using the [SFTTrainer](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTTrainer) from TRL. We train a [Qwen 3 0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) model on the [Capybara dataset](https://huggingface.co/datasets/trl-lib/Capybara), a compact, diverse multi-turn dataset to benchmark reasoning and generalization.\n\n```python\nfrom trl import SFTTrainer\nfrom datasets import load_dataset\n\ntrainer = SFTTrainer(\n model=\"Qwen/Qwen3-0.6B\",\n train_dataset=load_dataset(\"trl-lib/Capybara\", split=\"train\"),\n)\ntrainer.train()\n```", "source_file": "trl/sft_trainer.md", "section_heading": "Quick start", "char_start": 499, "char_end": 1093, "token_estimate": 148, "prev_chunk_id": 13, "next_chunk_id": 15, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 15, "text": "## Expected dataset type and format\n\nSFT supports both [language modeling](dataset_formats#language-modeling) and [prompt-completion](dataset_formats#prompt-completion) datasets. The [SFTTrainer](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTTrainer) is compatible with both [standard](dataset_formats#standard) and [conversational](dataset_formats#conversational) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset.\n\n```python", "source_file": "trl/sft_trainer.md", "section_heading": "Expected dataset type and format", "char_start": 1095, "char_end": 1596, "token_estimate": 125, "prev_chunk_id": 14, "next_chunk_id": 16, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 16, "text": "# Standard language modeling\n{\"text\": \"The sky is blue.\"}", "source_file": "trl/sft_trainer.md", "section_heading": "Standard language modeling", "char_start": 1597, "char_end": 1654, "token_estimate": 14, "prev_chunk_id": 15, "next_chunk_id": 17, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 17, "text": "# Conversational language modeling\n{\"messages\": [{\"role\": \"user\", \"content\": \"What color is the sky?\"},\n {\"role\": \"assistant\", \"content\": \"It is blue.\"}]}", "source_file": "trl/sft_trainer.md", "section_heading": "Conversational language modeling", "char_start": 1656, "char_end": 1823, "token_estimate": 41, "prev_chunk_id": 16, "next_chunk_id": 18, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 18, "text": "# Standard prompt-completion\n{\"prompt\": \"The sky is\",\n \"completion\": \" blue.\"}", "source_file": "trl/sft_trainer.md", "section_heading": "Standard prompt-completion", "char_start": 1825, "char_end": 1903, "token_estimate": 19, "prev_chunk_id": 17, "next_chunk_id": 19, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 19, "text": "# Conversational prompt-completion\n{\"prompt\": [{\"role\": \"user\", \"content\": \"What color is the sky?\"}],\n \"completion\": [{\"role\": \"assistant\", \"content\": \"It is blue.\"}]}\n```\n\nIf your dataset is not in one of these formats, you can preprocess it to convert it into the expected format. Here is an example with the [FreedomIntelligence/medical-o1-reasoning-SFT](https://huggingface.co/datasets/FreedomIntelligence/medical-o1-reasoning-SFT) dataset:\n\n```python\nfrom datasets import load_dataset\n\ndataset = load_dataset(\"FreedomIntelligence/medical-o1-reasoning-SFT\", \"en\")\n\ndef preprocess_function(example):\n return {\n \"prompt\": [{\"role\": \"user\", \"content\": example[\"Question\"]}],\n \"completion\": [\n {\"role\": \"assistant\", \"content\": f\"{example['Complex_CoT']}{example['Response']}\"}\n ],\n }", "source_file": "trl/sft_trainer.md", "section_heading": "Conversational prompt-completion", "char_start": 1905, "char_end": 2727, "token_estimate": 205, "prev_chunk_id": 18, "next_chunk_id": 20, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 20, "text": "dataset = dataset.map(preprocess_function, remove_columns=[\"Question\", \"Response\", \"Complex_CoT\"])\nprint(next(iter(dataset[\"train\"])))\n```\n\n```json\n{\n \"prompt\": [\n {\n \"content\": \"Given the symptoms of sudden weakness in the left arm and leg, recent long-distance travel, and the presence of swollen and tender right lower leg, what specific cardiac abnormality is most likely to be found upon further evaluation that could explain these findings?\",\n \"role\": \"user\",\n }\n ],\n \"completion\": [\n {\n \"content\": \"Okay, let's see what's going on here. We've got sudden weakness [...] clicks into place!The specific cardiac abnormality most likely to be found in [...] the presence of a PFO facilitating a paradoxical embolism.\",\n \"role\": \"assistant\",\n }\n ],\n}\n```", "source_file": "trl/sft_trainer.md", "section_heading": "Conversational prompt-completion", "char_start": 2729, "char_end": 3568, "token_estimate": 209, "prev_chunk_id": 19, "next_chunk_id": 21, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 21, "text": "## Looking deeper into the SFT method\n\nSupervised Fine-Tuning (SFT) is the simplest and most commonly used method to adapt a language model to a target dataset. The model is trained in a fully supervised fashion using pairs of input and output sequences. The goal is to minimize the negative log-likelihood (NLL) of the target sequence, conditioning on the input.\n\nThis section breaks down how SFT works in practice, covering the key steps: **preprocessing**, **tokenization** and **loss computation**.", "source_file": "trl/sft_trainer.md", "section_heading": "Looking deeper into the SFT method", "char_start": 3570, "char_end": 4072, "token_estimate": 125, "prev_chunk_id": 20, "next_chunk_id": 22, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 22, "text": "### Preprocessing and tokenization\n\nDuring training, each example is expected to contain a **text field** or a **(prompt, completion)** pair, depending on the dataset format. For more details on the expected formats, see [Dataset formats](dataset_formats).\nThe [SFTTrainer](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTTrainer) tokenizes each input using the model's tokenizer. If both prompt and completion are provided separately, they are concatenated before tokenization.", "source_file": "trl/sft_trainer.md", "section_heading": "Preprocessing and tokenization", "char_start": 4074, "char_end": 4543, "token_estimate": 117, "prev_chunk_id": 21, "next_chunk_id": 23, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 23, "text": "### Computing the loss\n\n![sft_figure](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/sft_figure.png)\n\nThe loss used in SFT is the **token-level cross-entropy loss**, defined as:\n\n$$\n\\mathcal{L}_{\\text{SFT}}(\\theta) = - \\sum_{t=1}^{T} \\log p_\\theta(y_t \\mid y_{ [!TIP]\n> The paper [On the Generalization of SFT: A Reinforcement Learning Perspective with Reward Rectification](https://huggingface.co/papers/2508.05629) proposes an alternative loss function, called **Dynamic Fine-Tuning (DFT)**, which aims to improve generalization by rectifying the reward signal. This method can be enabled by setting `loss_type=\"dft\"` in the [SFTConfig](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTConfig). For more details, see [Paper Index - Dynamic Fine-Tuning](paper_index#on-the-generalization-of-sft-a-reinforcement-learning-perspective-with-reward-rectification).", "source_file": "trl/sft_trainer.md", "section_heading": "Computing the loss", "char_start": 4545, "char_end": 5422, "token_estimate": 219, "prev_chunk_id": 22, "next_chunk_id": 24, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 24, "text": "### Label shifting and masking\n\nDuring training, the loss is computed using a **one-token shift**: the model is trained to predict each token in the sequence based on all previous tokens. Specifically, the input sequence is shifted right by one position to form the target labels.\nPadding tokens (if present) are ignored in the loss computation by applying an ignore index (default: `-100`) to the corresponding positions. This ensures that the loss focuses only on meaningful, non-padding tokens.", "source_file": "trl/sft_trainer.md", "section_heading": "Label shifting and masking", "char_start": 5424, "char_end": 5921, "token_estimate": 124, "prev_chunk_id": 23, "next_chunk_id": 25, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 25, "text": "## Logged metrics\n\nWhile training and evaluating we record the following reward metrics:\n\n* `global_step`: The total number of optimizer steps taken so far.\n* `epoch`: The current epoch number, based on dataset iteration.\n* `num_tokens`: The total number of tokens processed so far.\n* `loss`: The average cross-entropy loss computed over non-masked tokens in the current logging interval.\n* `entropy`: The average entropy of the model's predicted token distribution over non-masked tokens.\n* `mean_token_accuracy`: The proportion of non-masked tokens for which the model\u2019s top-1 prediction matches the ground truth token.\n* `learning_rate`: The current learning rate, which may change dynamically if a scheduler is used.\n* `grad_norm`: The L2 norm of the gradients, computed before gradient clipping.", "source_file": "trl/sft_trainer.md", "section_heading": "Logged metrics", "char_start": 5923, "char_end": 6723, "token_estimate": 200, "prev_chunk_id": 24, "next_chunk_id": 26, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 26, "text": "## Customization", "source_file": "trl/sft_trainer.md", "section_heading": "Customization", "char_start": 6725, "char_end": 6741, "token_estimate": 4, "prev_chunk_id": 25, "next_chunk_id": 27, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 27, "text": "### Model initialization\n\nYou can directly pass the kwargs of the `from_pretrained()` method to the [SFTConfig](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTConfig). For example, if you want to load a model in a different precision, analogous to\n\n```python\nmodel = AutoModelForCausalLM.from_pretrained(\"Qwen/Qwen3-0.6B\", dtype=torch.bfloat16)\n```\n\nyou can do so by passing the `model_init_kwargs={\"dtype\": torch.bfloat16}` argument to the [SFTConfig](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTConfig).\n\n```python\nfrom trl import SFTConfig\n\ntraining_args = SFTConfig(\n model_init_kwargs={\"dtype\": torch.bfloat16},\n)\n```\n\nNote that all keyword arguments of `from_pretrained()` are supported.", "source_file": "trl/sft_trainer.md", "section_heading": "Model initialization", "char_start": 6743, "char_end": 7426, "token_estimate": 170, "prev_chunk_id": 26, "next_chunk_id": 28, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 28, "text": "### Packing\n\n[SFTTrainer](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTTrainer) supports _example packing_, where multiple examples are packed in the same input sequence to increase training efficiency. To enable packing, simply pass `packing=True` to the [SFTConfig](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTConfig) constructor.\n\n```python\ntraining_args = SFTConfig(packing=True)\n```\n\nFor more details on packing, see [Packing](reducing_memory_usage#packing).", "source_file": "trl/sft_trainer.md", "section_heading": "Packing", "char_start": 7428, "char_end": 7880, "token_estimate": 113, "prev_chunk_id": 27, "next_chunk_id": 29, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 29, "text": "### Train on assistant messages only\n\nTo train on assistant messages only, use a [conversational](dataset_formats#conversational) dataset and set `assistant_only_loss=True` in the [SFTConfig](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTConfig). This setting ensures that loss is computed **only** on the assistant responses, ignoring user or system messages.\n\n```python\ntraining_args = SFTConfig(assistant_only_loss=True)\n```\n\n![train_on_assistant](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/train_on_assistant.png)\n\n> [!WARNING]\n> This functionality requires the chat template to include `{% generation %}` and `{% endgeneration %}` keywords. For known model families (e.g. Qwen3), TRL automatically patches the template when `assistant_only_loss=True`. For other models, check that your chat template includes these keywords \u2014 see [HuggingFaceTB/SmolLM3-3B](https://huggingface.co/HuggingFaceTB/SmolLM3-3B/blob/main/chat_template.jinja#L76-L82) for an example.", "source_file": "trl/sft_trainer.md", "section_heading": "Train on assistant messages only", "char_start": 7882, "char_end": 8890, "token_estimate": 252, "prev_chunk_id": 28, "next_chunk_id": 30, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 30, "text": "### Train on completion only\n\nTo train on completion only, use a [prompt-completion](dataset_formats#prompt-completion) dataset. By default, the trainer computes the loss on the completion tokens only, ignoring the prompt tokens. If you want to train on the full sequence, set `completion_only_loss=False` in the [SFTConfig](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTConfig).\n\n```python\nfrom trl import SFTConfig, SFTTrainer\nfrom datasets import load_dataset", "source_file": "trl/sft_trainer.md", "section_heading": "Train on completion only", "char_start": 8892, "char_end": 9347, "token_estimate": 113, "prev_chunk_id": 29, "next_chunk_id": 31, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 31, "text": "# Load a prompt-completion dataset; loss is computed on the completion only by default\ndataset = load_dataset(\"trl-lib/kto-mix-14k\", split=\"train\")\n\ntrainer = SFTTrainer(\n model=\"Qwen/Qwen2.5-0.5B-Instruct\",\n args=SFTConfig(completion_only_loss=True), # True by default for prompt-completion datasets\n train_dataset=dataset,\n)\ntrainer.train()\n```\n\n![train_on_completion](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/train_on_completion.png)\n\n> [!TIP]\n> Training on completion only is compatible with training on assistant messages only. In this case, use a [conversational](dataset_formats#conversational) [prompt-completion](dataset_formats#prompt-completion) dataset and set `assistant_only_loss=True` in the [SFTConfig](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTConfig).", "source_file": "trl/sft_trainer.md", "section_heading": "Load a prompt-completion dataset; loss is computed on the completion only by default", "char_start": 9349, "char_end": 10158, "token_estimate": 202, "prev_chunk_id": 30, "next_chunk_id": 32, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 32, "text": "### Train adapters with PEFT\n\nWe support tight integration with \ud83e\udd17 PEFT library, allowing any user to conveniently train adapters and share them on the Hub, rather than training the entire model.\n\n```python\nfrom datasets import load_dataset\nfrom trl import SFTTrainer\nfrom peft import LoraConfig\n\ndataset = load_dataset(\"trl-lib/Capybara\", split=\"train\")\n\ntrainer = SFTTrainer(\n \"Qwen/Qwen3-0.6B\",\n train_dataset=dataset,\n peft_config=LoraConfig(),\n)\n\ntrainer.train()\n```\n\nYou can also continue training your `PeftModel`. For that, first load a `PeftModel` outside [SFTTrainer](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTTrainer) and pass it directly to the trainer without the `peft_config` argument being passed.", "source_file": "trl/sft_trainer.md", "section_heading": "Train adapters with PEFT", "char_start": 10160, "char_end": 10878, "token_estimate": 179, "prev_chunk_id": 31, "next_chunk_id": 33, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 33, "text": "```python\nfrom datasets import load_dataset\nfrom trl import SFTTrainer\nfrom peft import AutoPeftModelForCausalLM\n\nmodel = AutoPeftModelForCausalLM.from_pretrained(\"trl-lib/Qwen3-4B-LoRA\", is_trainable=True)\ndataset = load_dataset(\"trl-lib/Capybara\", split=\"train\")\n\ntrainer = SFTTrainer(\n model=model,\n train_dataset=dataset,\n)\n\ntrainer.train()\n```\n\n> [!TIP]\n> When training adapters, you typically use a higher learning rate (\u22481e\u20114) since only new parameters are being learned.\n>\n> ```python\n> SFTConfig(learning_rate=1e-4, ...)\n> ```", "source_file": "trl/sft_trainer.md", "section_heading": "Train adapters with PEFT", "char_start": 10880, "char_end": 11421, "token_estimate": 135, "prev_chunk_id": 32, "next_chunk_id": 34, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 34, "text": "### Train with Liger Kernel\n\nLiger Kernel is a collection of Triton kernels for LLM training that boosts multi-GPU throughput by 20%, cuts memory use by 60% (enabling up to 4\u00d7 longer context), and works seamlessly with tools like FlashAttention, PyTorch FSDP, and DeepSpeed. For more information, see [Liger Kernel Integration](liger_kernel_integration).", "source_file": "trl/sft_trainer.md", "section_heading": "Train with Liger Kernel", "char_start": 11423, "char_end": 11777, "token_estimate": 88, "prev_chunk_id": 33, "next_chunk_id": 35, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 35, "text": "### Rapid Experimentation for SFT\n\nRapidFire AI is an open-source experimentation engine that sits on top of TRL and lets you launch multiple SFT configurations at once, even on a single GPU. Instead of trying configurations sequentially, RapidFire lets you **see all their learning curves earlier, stop underperforming runs, and clone promising ones with new settings in flight** without restarting. For more information, see [RapidFire AI Integration](rapidfire_integration).", "source_file": "trl/sft_trainer.md", "section_heading": "Rapid Experimentation for SFT", "char_start": 11779, "char_end": 12256, "token_estimate": 119, "prev_chunk_id": 34, "next_chunk_id": 36, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 36, "text": "### Train with Unsloth\n\nUnsloth is an open\u2011source framework for fine\u2011tuning and reinforcement learning that trains LLMs (like Llama, Mistral, Gemma, DeepSeek, and more) up to 2\u00d7 faster with up to 70% less VRAM, while providing a streamlined, Hugging Face\u2013compatible workflow for training, evaluation, and deployment. For more information, see [Unsloth Integration](unsloth_integration).", "source_file": "trl/sft_trainer.md", "section_heading": "Train with Unsloth", "char_start": 12258, "char_end": 12644, "token_estimate": 96, "prev_chunk_id": 35, "next_chunk_id": 37, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 37, "text": "## Instruction tuning example\n\n**Instruction tuning** teaches a base language model to follow user instructions and engage in conversations. This requires:\n\n1. **Chat template**: Defines how to structure conversations into text sequences, including role markers (user/assistant), special tokens, and turn boundaries. Read more about chat templates in [Chat templates](https://huggingface.co/docs/transformers/chat_templating#templates).\n2. **Conversational dataset**: Contains instruction-response pairs\n\nThis example shows how to transform the [Qwen 3 0.6B Base](https://huggingface.co/Qwen/Qwen3-0.6B-Base) model into an instruction-following model using the [Capybara dataset](https://huggingface.co/datasets/trl-lib/Capybara) and a chat template from [HuggingFaceTB/SmolLM3-3B](https://huggingface.co/HuggingFaceTB/SmolLM3-3B). The SFT Trainer automatically handles tokenizer updates and special token configuration.", "source_file": "trl/sft_trainer.md", "section_heading": "Instruction tuning example", "char_start": 12646, "char_end": 13566, "token_estimate": 230, "prev_chunk_id": 36, "next_chunk_id": 38, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 38, "text": "```python\nfrom trl import SFTConfig, SFTTrainer\nfrom datasets import load_dataset\n\ntrainer = SFTTrainer(\n model=\"Qwen/Qwen3-0.6B-Base\",\n args=SFTConfig(\n output_dir=\"Qwen3-0.6B-Instruct\",\n chat_template_path=\"HuggingFaceTB/SmolLM3-3B\",\n ),\n train_dataset=load_dataset(\"trl-lib/Capybara\", split=\"train\"),\n)\ntrainer.train()\n```\n\n> [!WARNING]\n> Some base models, like those from Qwen, have a predefined chat template in the model's tokenizer. In these cases, it is not necessary to apply `clone_chat_template()`, as the tokenizer already handles the formatting. However, it is necessary to align the EOS token with the chat template to ensure the model's responses terminate correctly. In these cases, specify `eos_token` in [SFTConfig](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTConfig); for example, for `Qwen/Qwen2.5-1.5B`, one should set `eos_token=\"\"`.\n\nOnce trained, your model can now follow instructions and engage in conversations using its new chat template.", "source_file": "trl/sft_trainer.md", "section_heading": "Instruction tuning example", "char_start": 13568, "char_end": 14555, "token_estimate": 246, "prev_chunk_id": 37, "next_chunk_id": 39, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 39, "text": "```python\n>>> from transformers import pipeline\n>>> pipe = pipeline(\"text-generation\", model=\"Qwen3-0.6B-Instruct/checkpoint-5000\")\n>>> prompt = \"user\\nWhat is the capital of France? Answer in one word.\\nassistant\\n\"\n>>> response = pipe(prompt)\n>>> response[0][\"generated_text\"]\n'user\\nWhat is the capital of France? Answer in one word.\\nassistant\\nThe capital of France is Paris.'\n```\n\nAlternatively, use the structured conversation format (recommended):\n\n```python\n>>> prompt = [{\"role\": \"user\", \"content\": \"What is the capital of France? Answer in one word.\"}]\n>>> response = pipe(prompt)\n>>> response[0][\"generated_text\"]\n[{'role': 'user', 'content': 'What is the capital of France? Answer in one word.'}, {'role': 'assistant', 'content': 'The capital of France is Paris.'}]\n```", "source_file": "trl/sft_trainer.md", "section_heading": "Instruction tuning example", "char_start": 14557, "char_end": 15339, "token_estimate": 195, "prev_chunk_id": 38, "next_chunk_id": 40, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 40, "text": "## Tool Calling with SFT\n\nThe [SFTTrainer](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTTrainer) fully supports fine-tuning models with _tool calling_ capabilities. In this case, each dataset example should include:\n\n* The conversation messages, including any tool calls (`tool_calls`) and tool responses (`tool` role messages)\n* The list of available tools in the `tools` column, typically provided as JSON schemas\n\nFor details on the expected dataset structure, see the [Dataset Format \u2014 Tool Calling](dataset_formats#tool-calling) section.", "source_file": "trl/sft_trainer.md", "section_heading": "Tool Calling with SFT", "char_start": 15341, "char_end": 15877, "token_estimate": 134, "prev_chunk_id": 39, "next_chunk_id": 41, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 41, "text": "## Training Vision Language Models\n\n[SFTTrainer](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTTrainer) fully supports training Vision-Language Models (VLMs). To train a VLM, provide a dataset with either an `image` column (single image per sample) or an `images` column (list of images per sample). For more information on the expected dataset structure, see the [Dataset Format \u2014 Vision Dataset](dataset_formats#vision-dataset) section.\nAn example of such a dataset is the [LLaVA Instruct Mix](https://huggingface.co/datasets/trl-lib/llava-instruct-mix).\n\n```python\nfrom trl import SFTConfig, SFTTrainer\nfrom datasets import load_dataset\n\ntrainer = SFTTrainer(\n model=\"Qwen/Qwen2.5-VL-3B-Instruct\",\n args=SFTConfig(max_length=None),\n train_dataset=load_dataset(\"trl-lib/llava-instruct-mix\", split=\"train\"),\n)\ntrainer.train()\n```", "source_file": "trl/sft_trainer.md", "section_heading": "Training Vision Language Models", "char_start": 15879, "char_end": 16711, "token_estimate": 208, "prev_chunk_id": 40, "next_chunk_id": 42, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 42, "text": "> [!TIP]\n> For VLMs, truncating may remove image tokens, leading to errors during training. To avoid this, set `max_length=None` in the [SFTConfig](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTConfig). This allows the model to process the full sequence length without truncating image tokens.\n>\n> ```python\n> SFTConfig(max_length=None, ...)\n> ```\n>\n> Only use `max_length` when you've verified that truncation won't remove image tokens for the entire dataset.", "source_file": "trl/sft_trainer.md", "section_heading": "Training Vision Language Models", "char_start": 16713, "char_end": 17166, "token_estimate": 113, "prev_chunk_id": 41, "next_chunk_id": 43, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 43, "text": "## SFTTrainer[[trl.SFTTrainer]]", "source_file": "trl/sft_trainer.md", "section_heading": "SFTTrainer[[trl.SFTTrainer]]", "char_start": 17168, "char_end": 17199, "token_estimate": 7, "prev_chunk_id": 42, "next_chunk_id": 44, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 44, "text": "#### trl.SFTTrainer[[trl.SFTTrainer]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/trainer/sft_trainer.py#L543)\n\nTrainer for Supervised Fine-Tuning (SFT) method.\n\nThis class is a wrapper around the [Trainer](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer) class and inherits all of its attributes and methods.\n\nExample:\n\n```python\nfrom trl import SFTTrainer\nfrom datasets import load_dataset\n\ndataset = load_dataset(\"roneneldan/TinyStories\", split=\"train[:1%]\")\n\ntrainer = SFTTrainer(\n model=\"Qwen/Qwen2.5-0.5B-Instruct\",\n train_dataset=dataset,\n)\ntrainer.train()\n```", "source_file": "trl/sft_trainer.md", "section_heading": "trl.SFTTrainer[[trl.SFTTrainer]]", "char_start": 17201, "char_end": 17836, "token_estimate": 158, "prev_chunk_id": 43, "next_chunk_id": 45, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 45, "text": "traintrl.SFTTrainer.trainhttps://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L1323[{\"name\": \"resume_from_checkpoint\", \"val\": \": str | bool | None = None\"}, {\"name\": \"trial\", \"val\": \": optuna.Trial | dict[str, Any] | None = None\"}, {\"name\": \"ignore_keys_for_eval\", \"val\": \": list[str] | None = None\"}]- **resume_from_checkpoint** (`str` or `bool`, *optional*) --\n If a `str`, local path to a saved checkpoint as saved by a previous instance of `Trainer`. If a\n `bool` and equals `True`, load the last checkpoint in *args.output_dir* as saved by a previous instance\n of `Trainer`. If present, training will resume from the model/optimizer/scheduler states loaded here.\n- **trial** (`optuna.Trial` or `dict[str, Any]`, *optional*) --\n The trial run or the hyperparameter dictionary for hyperparameter search.\n- **ignore_keys_for_eval** (`list[str]`, *optional*) --\n A list of keys in the output of your model (if it is a dictionary) that should be ignored when\n gathering predictions for evaluation during the training.0`~trainer_utils.TrainOutput`Object containing the global step count, training loss, and metrics.", "source_file": "trl/sft_trainer.md", "section_heading": "trl.SFTTrainer[[trl.SFTTrainer]]", "char_start": 17838, "char_end": 18976, "token_estimate": 284, "prev_chunk_id": 44, "next_chunk_id": 46, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 46, "text": "Main training entry point.\n\n**Parameters:**", "source_file": "trl/sft_trainer.md", "section_heading": "trl.SFTTrainer[[trl.SFTTrainer]]", "char_start": 18978, "char_end": 19021, "token_estimate": 10, "prev_chunk_id": 45, "next_chunk_id": 47, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 47, "text": "model (`str` or [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) or `PeftModel`) : Model to be trained. Can be either: - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a path to a *directory* containing model weights saved using [save_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.save_pretrained), e.g., `'./my_model_directory/'`. The model is loaded using `.from_pretrained` (where `` is derived from the model config) with the keyword arguments in `args.model_init_kwargs`. - A [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) object. Only causal language models are supported. - A `PeftModel` object. Only causal language models are supported. If you're training a model with an MoE architecture and want to include the load balancing/auxiliary loss as a part of the final loss, remember to set the `output_router_logits` config of the model to `True`.", "source_file": "trl/sft_trainer.md", "section_heading": "trl.SFTTrainer[[trl.SFTTrainer]]", "char_start": 19023, "char_end": 20138, "token_estimate": 278, "prev_chunk_id": 46, "next_chunk_id": 48, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 48, "text": "args ([SFTConfig](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTConfig), *optional*) : Configuration for this trainer. If `None`, a default configuration is used.\n\ndata_collator (`DataCollator`, *optional*) : Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`. Will default to `DataCollatorForLanguageModeling` if the model is a language model and `DataCollatorForVisionLanguageModeling` if the model is a vision-language model. Custom collators must truncate sequences before padding; the trainer does not apply post-collation truncation.", "source_file": "trl/sft_trainer.md", "section_heading": "trl.SFTTrainer[[trl.SFTTrainer]]", "char_start": 20140, "char_end": 20728, "token_estimate": 147, "prev_chunk_id": 47, "next_chunk_id": 49, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 49, "text": "train_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) or [IterableDataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset)) : Dataset to use for training. This trainer supports both [language modeling](#language-modeling) type and [prompt-completion](#prompt-completion) type. The format of the samples can be either: - [Standard](dataset_formats#standard): Each sample contains plain text. - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role and content). The trainer also supports processed datasets (tokenized) as long as they contain an `input_ids` field.", "source_file": "trl/sft_trainer.md", "section_heading": "trl.SFTTrainer[[trl.SFTTrainer]]", "char_start": 20730, "char_end": 21467, "token_estimate": 184, "prev_chunk_id": 48, "next_chunk_id": 50, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 50, "text": "eval_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset), [IterableDataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) or `dict[str, Dataset | IterableDataset]`) : Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.", "source_file": "trl/sft_trainer.md", "section_heading": "trl.SFTTrainer[[trl.SFTTrainer]]", "char_start": 21469, "char_end": 21842, "token_estimate": 93, "prev_chunk_id": 49, "next_chunk_id": 51, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 51, "text": "processing_class ([PreTrainedTokenizerBase](https://huggingface.co/docs/transformers/v5.5.4/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase), [ProcessorMixin](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/processors#transformers.ProcessorMixin), *optional*) : Processing class used to process the data. If `None`, the processing class is loaded from the model's name with [from_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/model_doc/auto#transformers.AutoProcessor.from_pretrained). A padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, `tokenizer.eos_token` will be used as the default.", "source_file": "trl/sft_trainer.md", "section_heading": "trl.SFTTrainer[[trl.SFTTrainer]]", "char_start": 21844, "char_end": 22539, "token_estimate": 173, "prev_chunk_id": 50, "next_chunk_id": 52, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 52, "text": "compute_loss_func (`Callable`, *optional*) : A function that accepts the raw model outputs, labels, and the number of items in the entire accumulated batch (batch_size * gradient_accumulation_steps) and returns the loss. For example, see the default [loss function](https://github.com/huggingface/transformers/blob/052e652d6d53c2b26ffde87e039b723949a53493/src/transformers/trainer.py#L3618) used by `Trainer`.", "source_file": "trl/sft_trainer.md", "section_heading": "trl.SFTTrainer[[trl.SFTTrainer]]", "char_start": 22541, "char_end": 22950, "token_estimate": 102, "prev_chunk_id": 51, "next_chunk_id": 53, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 53, "text": "compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*) : The function that will be used to compute metrics at evaluation. Must take a [EvalPrediction](https://huggingface.co/docs/transformers/v5.5.4/en/internal/trainer_utils#transformers.EvalPrediction) and return a dictionary string to metric values. When passing [SFTConfig](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTConfig) with `batch_eval_metrics` set to `True`, your `compute_metrics` function must take a boolean `compute_result` argument. This will be triggered after the last eval batch to signal that the function needs to calculate and return the global summary statistics rather than accumulating the batch-level statistics.", "source_file": "trl/sft_trainer.md", "section_heading": "trl.SFTTrainer[[trl.SFTTrainer]]", "char_start": 22952, "char_end": 23646, "token_estimate": 173, "prev_chunk_id": 52, "next_chunk_id": 54, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 54, "text": "callbacks (list of [TrainerCallback](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/callback#transformers.TrainerCallback), *optional*) : List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed in [here](https://huggingface.co/docs/transformers/main_classes/callback). If you want to remove one of the default callbacks used, use the [remove_callback](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer.remove_callback) method.\n\noptimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`) : A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your model and a scheduler given by [get_linear_schedule_with_warmup](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/optimizer_schedules#transformers.get_linear_schedule_with_warmup) controlled by `args`.", "source_file": "trl/sft_trainer.md", "section_heading": "trl.SFTTrainer[[trl.SFTTrainer]]", "char_start": 23648, "char_end": 24645, "token_estimate": 249, "prev_chunk_id": 53, "next_chunk_id": 55, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 55, "text": "optimizer_cls_and_kwargs (`tuple[Type[torch.optim.Optimizer], Dict[str, Any]]`, *optional*) : A tuple containing the optimizer class and keyword arguments to use. Overrides `optim` and `optim_args` in `args`. Incompatible with the `optimizers` argument. Unlike `optimizers`, this argument avoids the need to place model parameters on the correct devices before initializing the Trainer.\n\npreprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*) : A function that preprocess the logits right before caching them at each evaluation step. Must take two tensors, the logits and the labels, and return the logits once processed as desired. The modifications made by this function will be reflected in the predictions received by `compute_metrics`. Note that the labels (second parameter) will be `None` if the dataset does not have them.\n\npeft_config (`PeftConfig`, *optional*) : PEFT configuration used to wrap the model. If `None`, the model is not wrapped.", "source_file": "trl/sft_trainer.md", "section_heading": "trl.SFTTrainer[[trl.SFTTrainer]]", "char_start": 24647, "char_end": 25645, "token_estimate": 249, "prev_chunk_id": 54, "next_chunk_id": 56, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 56, "text": "formatting_func (`Callable`, *optional*) : Formatting function applied to the dataset before tokenization. Applying the formatting function explicitly converts the dataset into a [language modeling](#language-modeling) type.\n\n**Returns:**\n\n``~trainer_utils.TrainOutput``\n\nObject containing the global step count, training loss, and metrics.", "source_file": "trl/sft_trainer.md", "section_heading": "trl.SFTTrainer[[trl.SFTTrainer]]", "char_start": 25647, "char_end": 25987, "token_estimate": 85, "prev_chunk_id": 55, "next_chunk_id": 57, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 57, "text": "#### save_model[[trl.SFTTrainer.save_model]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L3746)\n\nWill save the model, so you can reload it using `from_pretrained()`.\n\nWill only save from the main process.", "source_file": "trl/sft_trainer.md", "section_heading": "save_model[[trl.SFTTrainer.save_model]]", "char_start": 25988, "char_end": 26229, "token_estimate": 60, "prev_chunk_id": 56, "next_chunk_id": 58, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 58, "text": "#### push_to_hub[[trl.SFTTrainer.push_to_hub]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L3993)\n\nUpload `self.model` and `self.processing_class` to the \ud83e\udd17 model hub on the repo `self.args.hub_model_id`.\n\n**Parameters:**\n\ncommit_message (`str`, *optional*, defaults to `\"End of training\"`) : Message to commit while pushing.\n\nblocking (`bool`, *optional*, defaults to `True`) : Whether the function should return only when the `git push` has finished.\n\ntoken (`str`, *optional*, defaults to `None`) : Token with write permission to overwrite Trainer's original args.\n\nrevision (`str`, *optional*) : The git revision to commit from. Defaults to the head of the \"main\" branch.\n\nkwargs (`dict[str, Any]`, *optional*) : Additional keyword arguments passed along to `~Trainer.create_model_card`.\n\n**Returns:**\n\nThe URL of the repository where the model was pushed if `blocking=False`, or a `Future` object tracking the\nprogress of the commit if `blocking=True`.", "source_file": "trl/sft_trainer.md", "section_heading": "push_to_hub[[trl.SFTTrainer.push_to_hub]]", "char_start": 26230, "char_end": 27223, "token_estimate": 248, "prev_chunk_id": 57, "next_chunk_id": 59, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 59, "text": "## SFTConfig[[trl.SFTConfig]]", "source_file": "trl/sft_trainer.md", "section_heading": "SFTConfig[[trl.SFTConfig]]", "char_start": 27225, "char_end": 27254, "token_estimate": 7, "prev_chunk_id": 58, "next_chunk_id": 60, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 60, "text": "#### trl.SFTConfig[[trl.SFTConfig]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/trainer/sft_config.py#L23)\n\nConfiguration class for the [SFTTrainer](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTTrainer).\n\nThis class includes only the parameters that are specific to SFT training. For a full list of training arguments,\nplease refer to the [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments) documentation. Note that default values in this class may\ndiffer from those in [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments).\n\nUsing [HfArgumentParser](https://huggingface.co/docs/transformers/v5.5.4/en/internal/trainer_utils#transformers.HfArgumentParser) we can turn this class into\n[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the\ncommand line.", "source_file": "trl/sft_trainer.md", "section_heading": "trl.SFTConfig[[trl.SFTConfig]]", "char_start": 27256, "char_end": 28216, "token_estimate": 240, "prev_chunk_id": 59, "next_chunk_id": 61, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 61, "text": "> [!NOTE]\n> These parameters have default values different from [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments):\n> - `logging_steps`: Defaults to `10` instead of `500`.\n> - `gradient_checkpointing`: Defaults to `True` instead of `False`.\n> - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.\n> - `learning_rate`: Defaults to `2e-5` instead of `5e-5`.", "source_file": "trl/sft_trainer.md", "section_heading": "trl.SFTConfig[[trl.SFTConfig]]", "char_start": 28218, "char_end": 28663, "token_estimate": 111, "prev_chunk_id": 60, "next_chunk_id": null, "url": "https://huggingface.co/docs/trl/sft_trainer", "doc_title": "SFT Trainer" }, { "chunk_id": 62, "text": "# DPO Trainer\n\n[![All_models-DPO-blue](https://img.shields.io/badge/All_models-DPO-blue)](https://huggingface.co/models?other=dpo,trl) [![smol_course-Chapter_2-yellow](https://img.shields.io/badge/smol_course-Chapter_2-yellow)](https://github.com/huggingface/smol-course/tree/main/2_preference_alignment)", "source_file": "trl/dpo_trainer.md", "section_heading": "DPO Trainer", "char_start": 0, "char_end": 304, "token_estimate": 76, "prev_chunk_id": null, "next_chunk_id": 63, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 63, "text": "## Overview\n\nTRL supports the Direct Preference Optimization (DPO) Trainer for training language models, as described in the paper [Direct Preference Optimization: Your Language Model is Secretly a Reward Model](https://huggingface.co/papers/2305.18290) by [Rafael Rafailov](https://huggingface.co/rmrafailov), Archit Sharma, Eric Mitchell, [Stefano Ermon](https://huggingface.co/ermonste), [Christopher D. Manning](https://huggingface.co/manning), [Chelsea Finn](https://huggingface.co/cbfinn).\n\nThe abstract from the paper is the following:", "source_file": "trl/dpo_trainer.md", "section_heading": "Overview", "char_start": 306, "char_end": 848, "token_estimate": 135, "prev_chunk_id": 62, "next_chunk_id": 64, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 64, "text": "> While large-scale unsupervised language models (LMs) learn broad world knowledge and some reasoning skills, achieving precise control of their behavior is difficult due to the completely unsupervised nature of their training. Existing methods for gaining such steerability collect human labels of the relative quality of model generations and fine-tune the unsupervised LM to align with these preferences, often with reinforcement learning from human feedback (RLHF). However, RLHF is a complex and often unstable procedure, first fitting a reward model that reflects the human preferences, and then fine-tuning the large unsupervised LM using reinforcement learning to maximize this estimated reward without drifting too far from the original model. In this paper we introduce a new parameterization of the reward model in RLHF that enables extraction of the corresponding optimal policy in closed form, allowing us to solve the standard RLHF problem with only a simple classification loss. The resulting algorithm, which we call Direct Preference Optimization (DPO), is stable, performant, and computationally lightweight, eliminating the need for sampling from the LM during fine-tuning or performing significant hyperparameter tuning. Our experiments show that DPO can fine-tune LMs to align with human preferences as well as or better than existing methods. Notably, fine-tuning with DPO exceeds PPO-based RLHF in ability to control sentiment of generations, and matches or improves response quality in summarization and single-turn dialogue while being substantially simpler to implement and train.", "source_file": "trl/dpo_trainer.md", "section_heading": "Overview", "char_start": 850, "char_end": 2456, "token_estimate": 401, "prev_chunk_id": 63, "next_chunk_id": 65, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 65, "text": "This post-training method was contributed by [Kashif Rasul](https://huggingface.co/kashif) and later refactored by [Quentin Gallou\u00e9dec](https://huggingface.co/qgallouedec).", "source_file": "trl/dpo_trainer.md", "section_heading": "Overview", "char_start": 2458, "char_end": 2630, "token_estimate": 43, "prev_chunk_id": 64, "next_chunk_id": 66, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 66, "text": "## Quick start\n\nThis example demonstrates how to train a language model using the [DPOTrainer](/docs/trl/v1.2.0/en/bema_for_reference_model#trl.DPOTrainer) from TRL. We train a [Qwen 3 0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) model on the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback).\n\n```python\nfrom trl import DPOTrainer\nfrom datasets import load_dataset\n\ntrainer = DPOTrainer(\n model=\"Qwen/Qwen3-0.6B\",\n train_dataset=load_dataset(\"trl-lib/ultrafeedback_binarized\", split=\"train\"),\n)\ntrainer.train()\n```", "source_file": "trl/dpo_trainer.md", "section_heading": "Quick start", "char_start": 2632, "char_end": 3183, "token_estimate": 137, "prev_chunk_id": 65, "next_chunk_id": 67, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 67, "text": "## Expected dataset type and format\n\nDPO requires a [preference](dataset_formats#preference) dataset. The [DPOTrainer](/docs/trl/v1.2.0/en/bema_for_reference_model#trl.DPOTrainer) is compatible with both [standard](dataset_formats#standard) and [conversational](dataset_formats#conversational) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset.\n\n```python", "source_file": "trl/dpo_trainer.md", "section_heading": "Expected dataset type and format", "char_start": 3185, "char_end": 3622, "token_estimate": 109, "prev_chunk_id": 66, "next_chunk_id": 68, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 68, "text": "# Standard format", "source_file": "trl/dpo_trainer.md", "section_heading": "Standard format", "char_start": 3623, "char_end": 3640, "token_estimate": 4, "prev_chunk_id": 67, "next_chunk_id": 69, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 69, "text": "## Explicit prompt (recommended)\npreference_example = {\"prompt\": \"The sky is\", \"chosen\": \" blue.\", \"rejected\": \" green.\"}", "source_file": "trl/dpo_trainer.md", "section_heading": "Explicit prompt (recommended)", "char_start": 3641, "char_end": 3762, "token_estimate": 30, "prev_chunk_id": 68, "next_chunk_id": 70, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 70, "text": "# Implicit prompt\npreference_example = {\"chosen\": \"The sky is blue.\", \"rejected\": \"The sky is green.\"}", "source_file": "trl/dpo_trainer.md", "section_heading": "Implicit prompt", "char_start": 3763, "char_end": 3865, "token_estimate": 25, "prev_chunk_id": 69, "next_chunk_id": 71, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 71, "text": "# Conversational format", "source_file": "trl/dpo_trainer.md", "section_heading": "Conversational format", "char_start": 3867, "char_end": 3890, "token_estimate": 5, "prev_chunk_id": 70, "next_chunk_id": 72, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 72, "text": "## Explicit prompt (recommended)\npreference_example = {\"prompt\": [{\"role\": \"user\", \"content\": \"What color is the sky?\"}],\n \"chosen\": [{\"role\": \"assistant\", \"content\": \"It is blue.\"}],\n \"rejected\": [{\"role\": \"assistant\", \"content\": \"It is green.\"}]}", "source_file": "trl/dpo_trainer.md", "section_heading": "Explicit prompt (recommended)", "char_start": 3891, "char_end": 4181, "token_estimate": 72, "prev_chunk_id": 71, "next_chunk_id": 73, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 73, "text": "## Implicit prompt\npreference_example = {\"chosen\": [{\"role\": \"user\", \"content\": \"What color is the sky?\"},\n {\"role\": \"assistant\", \"content\": \"It is blue.\"}],\n \"rejected\": [{\"role\": \"user\", \"content\": \"What color is the sky?\"},\n {\"role\": \"assistant\", \"content\": \"It is green.\"}]}\n```\n\nIf your dataset is not in one of these formats, you can preprocess it to convert it into the expected format. Here is an example with the [Vezora/Code-Preference-Pairs](https://huggingface.co/datasets/Vezora/Code-Preference-Pairs) dataset:\n\n```python\nfrom datasets import load_dataset\n\ndataset = load_dataset(\"Vezora/Code-Preference-Pairs\")\n\ndef preprocess_function(example):\n return {\n \"prompt\": [{\"role\": \"user\", \"content\": example[\"input\"]}],\n \"chosen\": [{\"role\": \"assistant\", \"content\": example[\"accepted\"]}],\n \"rejected\": [{\"role\": \"assistant\", \"content\": example[\"rejected\"]}],\n }", "source_file": "trl/dpo_trainer.md", "section_heading": "Implicit prompt", "char_start": 4182, "char_end": 5166, "token_estimate": 246, "prev_chunk_id": 72, "next_chunk_id": 74, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 74, "text": "dataset = dataset.map(preprocess_function, remove_columns=[\"instruction\", \"input\", \"accepted\", \"ID\"])\nprint(next(iter(dataset[\"train\"])))\n```\n\n```json\n{\n \"prompt\": [{\"role\": \"user\", \"content\": \"Create a nested loop to print every combination of numbers [...]\"}],\n \"chosen\": [{\"role\": \"assistant\", \"content\": \"Here is an example of a nested loop in Python [...]\"}],\n \"rejected\": [{\"role\": \"assistant\", \"content\": \"Here is an example of a nested loop in Python [...]\"}],\n}\n```", "source_file": "trl/dpo_trainer.md", "section_heading": "Implicit prompt", "char_start": 5168, "char_end": 5651, "token_estimate": 120, "prev_chunk_id": 73, "next_chunk_id": 75, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 75, "text": "## Looking deeper into the DPO method\n\nDirect Preference Optimization (DPO) is a training method designed to align a language model with preference data. Instead of supervised input\u2013output pairs, the model is trained on pairs of completions to the same prompt, where one completion is preferred over the other. The objective directly optimizes the model to widen the margin between the log-likelihoods of preferred and dispreferred completions, relative to a reference model, without requiring an explicit reward model. In practice, this is typically achieved by suppressing the likelihood of dispreferred completions rather than by increasing the likelihood of preferred ones.\n\nThis section breaks down how DPO works in practice, covering the key steps: **preprocessing** and **loss computation**.", "source_file": "trl/dpo_trainer.md", "section_heading": "Looking deeper into the DPO method", "char_start": 5653, "char_end": 6451, "token_estimate": 199, "prev_chunk_id": 74, "next_chunk_id": 76, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 76, "text": "### Preprocessing and tokenization\n\nDuring training, each example is expected to contain a prompt along with a preferred (`chosen`) and a dispreferred (`rejected`) completion. For more details on the expected formats, see [Dataset formats](dataset_formats).\nThe [DPOTrainer](/docs/trl/v1.2.0/en/bema_for_reference_model#trl.DPOTrainer) tokenizes each input using the model's tokenizer.", "source_file": "trl/dpo_trainer.md", "section_heading": "Preprocessing and tokenization", "char_start": 6453, "char_end": 6838, "token_estimate": 96, "prev_chunk_id": 75, "next_chunk_id": 77, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 77, "text": "### Computing the loss\n\n![dpo_figure](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/dpo_figure.png)\n\nThe loss used in DPO is defined as follows:\n$$\n\\mathcal{L}_{\\mathrm{DPO}}(\\theta) = -\\mathbb{E}_{(x,y^{+},y^{-})}\\!\\left[\\log \\sigma\\!\\left(\\beta\\Big(\\log\\frac{\\pi_{\\theta}(y^{+}\\!\\mid x)}{\\pi_{\\mathrm{ref}}(y^{+}\\!\\mid x)}-\\log \\frac{\\pi_{\\theta}(y^{-}\\!\\mid x)}{\\pi_{\\mathrm{ref}}(y^{-}\\!\\mid x)}\\Big)\\right)\\right]\n$$\n \nwhere \\\\( x \\\\) is the prompt, \\\\( y^+ \\\\) is the preferred completion and \\\\( y^- \\\\) is the dispreferred completion. \\\\( \\pi_{\\theta} \\\\) is the policy model being trained, \\\\( \\pi_{\\mathrm{ref}} \\\\) is the reference model, \\\\( \\sigma \\\\) is the sigmoid function, and \\\\( \\beta > 0 \\\\) is a hyperparameter that controls the strength of the preference signal.", "source_file": "trl/dpo_trainer.md", "section_heading": "Computing the loss", "char_start": 6840, "char_end": 7666, "token_estimate": 206, "prev_chunk_id": 76, "next_chunk_id": 78, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 78, "text": "#### Loss Types\n\nSeveral formulations of the objective have been proposed in the literature. Initially, the objective of DPO was defined as presented above.", "source_file": "trl/dpo_trainer.md", "section_heading": "Loss Types", "char_start": 7668, "char_end": 7824, "token_estimate": 39, "prev_chunk_id": 77, "next_chunk_id": 79, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 79, "text": "| `loss_type=` | Description |\n| --- | --- |\n| `\"sigmoid\"` (default) | Given the preference data, we can fit a binary classifier according to the Bradley-Terry model and in fact the [DPO](https://huggingface.co/papers/2305.18290) authors propose the sigmoid loss on the normalized likelihood via the `logsigmoid` to fit a logistic regression. |\n| `\"hinge\"` | The [RSO](https://huggingface.co/papers/2309.06657) authors propose to use a hinge loss on the normalized likelihood from the [SLiC](https://huggingface.co/papers/2305.10425) paper. In this case, the `beta` is the reciprocal of the margin. |\n| `\"ipo\"` | The [IPO](https://huggingface.co/papers/2310.12036) authors argue the logit transform can overfit and propose the identity transform to optimize preferences directly; TRL exposes this as `loss_type=\"ipo\"`. |\n| `\"exo_pair\"` | The [EXO](https://huggingface.co/papers/2402.00856) authors propose reverse-KL preference optimization. `label_smoothing` must be strictly greater than `0.0`; a recommended value is `1e-3` (see Eq. 16 for the simplified pairwise variant). The full method uses `K>2` SFT completions and approaches PPO as `K` grows. |\n| `\"nca_pair\"` | The [NCA](https://huggingface.co/papers/2402.05369) authors shows that NCA optimizes the absolute likelihood for each response rather than the relative likelihood. |\n| `\"robust\"` | The [Robust DPO](https://huggingface.co/papers/2403.00409) authors propose an unbiased DPO loss under noisy preferences. Use `label_smoothing` in [DPOConfig](/docs/trl/v1.2.0/en/dpo_trainer#trl.DPOConfig) to model label-flip probability; valid values are in the range `[0.0, 0.5)`. |\n| `\"bco_pair\"` | The [BCO](https://huggingface.co/papers/2404.04656) authors train a binary classifier whose logit serves as a reward so that the classifier maps {prompt, chosen completion} pairs to 1 and {prompt, rejected completion} pairs to 0. For unpaired data, we recommend the dedicated [experimental.bco.BCOTrainer](/docs/trl/v1.2.0/en/bco_trainer#trl.experimental.bco.BCOTrainer). |\n| `\"sppo_hard\"` | The [SPPO](https://huggingface.co/papers/2405.00675) authors claim that SPPO is capable of solving the Nash equilibrium iteratively by pushing the chosen rewards to be as large as 1/2 and the rejected rewards to be as small as -1/2 and can alleviate data sparsity issues. The implementation approximates this algorithm by employing hard label probabilities, assigning 1 to the winner and 0 to the loser. |\n| `\"aot\"` or `loss_type=\"aot_unpaired\"` | The [AOT](https://huggingface.co/papers/2406.05882) authors propose Distributional Preference Alignment via Optimal Transport. `loss_type=\"aot\"` is for paired data; `loss_type=\"aot_unpaired\"` is for unpaired data. Both enforce stochastic dominance via sorted quantiles; larger per-GPU batch sizes help. |\n| `\"apo_zero\"` or `loss_type=\"apo_down\"` | The [APO](https://huggingface.co/papers/2408.06266) method introduces an anchored objective. `apo_zero` boosts winners and downweights losers (useful when the model underperforms the winners). `apo_down` downweights both, with stronger pressure on losers (useful when the model already outperforms winners). |\n| `\"discopop\"` | The [DiscoPOP](https://huggingface.co/papers/2406.08414) paper uses LLMs to discover more efficient offline preference optimization losses. In the paper the proposed DiscoPOP loss (which is a log-ratio modulated loss) outperformed other optimization losses on different tasks (IMDb positive text generation, Reddit TLDR summarization, and Alpaca Eval 2.0). |\n| `\"sft\"` | SFT (Supervised Fine-Tuning) loss is the negative log likelihood loss, used to train the model to generate preferred responses. |", "source_file": "trl/dpo_trainer.md", "section_heading": "Loss Types", "char_start": 7826, "char_end": 11496, "token_estimate": 917, "prev_chunk_id": 78, "next_chunk_id": 80, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 80, "text": "## Logged metrics\n\nWhile training and evaluating we record the following reward metrics:", "source_file": "trl/dpo_trainer.md", "section_heading": "Logged metrics", "char_start": 11498, "char_end": 11586, "token_estimate": 22, "prev_chunk_id": 79, "next_chunk_id": 81, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 81, "text": "* `global_step`: The total number of optimizer steps taken so far.\n* `epoch`: The current epoch number, based on dataset iteration.\n* `num_tokens`: The total number of tokens processed so far.\n* `loss`: The average cross-entropy loss computed over non-masked tokens in the current logging interval.\n* `entropy`: The average entropy of the model's predicted token distribution over non-masked tokens.\n* `mean_token_accuracy`: The proportion of non-masked tokens for which the model\u2019s top-1 prediction matches the token from the chosen completion.\n* `learning_rate`: The current learning rate, which may change dynamically if a scheduler is used.\n* `grad_norm`: The L2 norm of the gradients, computed before gradient clipping.\n* `logits/chosen`: The average logit values assigned by the model to the tokens in the chosen completion.\n* `logits/rejected`: The average logit values assigned by the model to the tokens in the rejected completion.\n* `logps/chosen`: The average log-probability assigned by the model to the tokens in the chosen completion.\n* `logps/rejected`: The average log-probability assigned by the model to the tokens in the rejected completion.\n* `rewards/chosen`: The average implicit reward computed for the chosen completion, computed as \\\\( \\beta \\log \\frac{\\pi_{\\theta}(y^{+}\\!\\mid x)}{\\pi_{\\mathrm{ref}}(y^{+}\\!\\mid x)} \\\\).\n* `rewards/rejected`: The average implicit reward computed for the rejected completion, computed as \\\\( \\beta \\log \\frac{\\pi_{\\theta}(y^{-}\\!\\mid x)}{\\pi_{\\mathrm{ref}}(y^{-}\\!\\mid x)} \\\\).\n* `rewards/margins`: The average implicit reward margin between the chosen and rejected completions.\n* `rewards/accuracies`: The proportion of examples where the implicit reward for the chosen completion is higher than that for the rejected completion.", "source_file": "trl/dpo_trainer.md", "section_heading": "Logged metrics", "char_start": 11588, "char_end": 13379, "token_estimate": 447, "prev_chunk_id": 80, "next_chunk_id": 82, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 82, "text": "## Customization", "source_file": "trl/dpo_trainer.md", "section_heading": "Customization", "char_start": 13381, "char_end": 13397, "token_estimate": 4, "prev_chunk_id": 81, "next_chunk_id": 83, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 83, "text": "### Compatibility and constraints\n\nSome argument combinations are intentionally restricted in the current [DPOTrainer](/docs/trl/v1.2.0/en/bema_for_reference_model#trl.DPOTrainer) implementation:\n\n* `use_weighting=True` is not supported with `loss_type=\"aot\"` or `loss_type=\"aot_unpaired\"`.\n* With `use_liger_kernel=True`:\n * only a single `loss_type` is supported,\n * `compute_metrics` is not supported,\n * `precompute_ref_log_probs=True` is not supported.\n* `sync_ref_model=True` is not supported when training with PEFT models that do not keep a standalone `ref_model`.\n* `sync_ref_model=True` cannot be combined with `precompute_ref_log_probs=True`.\n* `precompute_ref_log_probs=True` is not supported with `IterableDataset` (train or eval).", "source_file": "trl/dpo_trainer.md", "section_heading": "Compatibility and constraints", "char_start": 13399, "char_end": 14146, "token_estimate": 186, "prev_chunk_id": 82, "next_chunk_id": 84, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 84, "text": "### Multi-loss combinations\n\nThe DPO trainer supports combining multiple loss functions with different weights, enabling more sophisticated optimization strategies. This is particularly useful for implementing algorithms like MPO (Mixed Preference Optimization). MPO is a training approach that combines multiple optimization objectives, as described in the paper [Enhancing the Reasoning Ability of Multimodal Large Language Models via Mixed Preference Optimization](https://huggingface.co/papers/2411.10442).\n\nTo combine multiple losses, specify the loss types and corresponding weights as lists:\n\n```python", "source_file": "trl/dpo_trainer.md", "section_heading": "Multi-loss combinations", "char_start": 14148, "char_end": 14757, "token_estimate": 152, "prev_chunk_id": 83, "next_chunk_id": 85, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 85, "text": "# MPO: Combines DPO (sigmoid) for preference and BCO (bco_pair) for quality\ntraining_args = DPOConfig(\n loss_type=[\"sigmoid\", \"bco_pair\", \"sft\"], # loss types to combine\n loss_weights=[0.8, 0.2, 1.0] # corresponding weights, as used in the MPO paper\n)\n```", "source_file": "trl/dpo_trainer.md", "section_heading": "MPO: Combines DPO (sigmoid) for preference and BCO (bco_pair) for quality", "char_start": 14758, "char_end": 15021, "token_estimate": 65, "prev_chunk_id": 84, "next_chunk_id": 86, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 86, "text": "### Model initialization\n\nYou can directly pass the kwargs of the `from_pretrained()` method to the [DPOConfig](/docs/trl/v1.2.0/en/dpo_trainer#trl.DPOConfig). For example, if you want to load a model in a different precision, analogous to\n\n```python\nmodel = AutoModelForCausalLM.from_pretrained(\"Qwen/Qwen3-0.6B\", dtype=torch.bfloat16)\n```\n\nyou can do so by passing the `model_init_kwargs={\"dtype\": torch.bfloat16}` argument to the [DPOConfig](/docs/trl/v1.2.0/en/dpo_trainer#trl.DPOConfig).\n\n```python\nfrom trl import DPOConfig\n\ntraining_args = DPOConfig(\n model_init_kwargs={\"dtype\": torch.bfloat16},\n)\n```\n\nNote that all keyword arguments of `from_pretrained()` are supported.", "source_file": "trl/dpo_trainer.md", "section_heading": "Model initialization", "char_start": 15023, "char_end": 15706, "token_estimate": 170, "prev_chunk_id": 85, "next_chunk_id": 87, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 87, "text": "### Train adapters with PEFT\n\nWe support tight integration with \ud83e\udd17 PEFT library, allowing any user to conveniently train adapters and share them on the Hub, rather than training the entire model.\n\n```python\nfrom datasets import load_dataset\nfrom trl import DPOTrainer\nfrom peft import LoraConfig\n\ndataset = load_dataset(\"trl-lib/ultrafeedback_binarized\", split=\"train\")\n\ntrainer = DPOTrainer(\n \"Qwen/Qwen3-0.6B\",\n train_dataset=dataset,\n peft_config=LoraConfig(),\n)\n\ntrainer.train()\n```\n\nYou can also continue training your `PeftModel`. For that, first load a `PeftModel` outside [DPOTrainer](/docs/trl/v1.2.0/en/bema_for_reference_model#trl.DPOTrainer) and pass it directly to the trainer without the `peft_config` argument being passed.", "source_file": "trl/dpo_trainer.md", "section_heading": "Train adapters with PEFT", "char_start": 15708, "char_end": 16454, "token_estimate": 186, "prev_chunk_id": 86, "next_chunk_id": 88, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 88, "text": "```python\nfrom datasets import load_dataset\nfrom trl import DPOTrainer\nfrom peft import AutoPeftModelForCausalLM\n\nmodel = AutoPeftModelForCausalLM.from_pretrained(\"trl-lib/Qwen3-4B-LoRA\", is_trainable=True)\ndataset = load_dataset(\"trl-lib/ultrafeedback_binarized\", split=\"train\")\n\ntrainer = DPOTrainer(\n model=model,\n train_dataset=dataset,\n)\n\ntrainer.train()\n```\n\n> [!TIP]\n> When training adapters, you typically use a higher learning rate (\u22481e\u20115) than full fine-tuning since only new parameters are being learned.\n>\n> ```python\n> DPOConfig(learning_rate=1e-5, ...)\n> ```", "source_file": "trl/dpo_trainer.md", "section_heading": "Train adapters with PEFT", "char_start": 16456, "char_end": 17034, "token_estimate": 144, "prev_chunk_id": 87, "next_chunk_id": 89, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 89, "text": "### Train with Liger Kernel\n\nLiger Kernel is a collection of Triton kernels for LLM training that boosts multi-GPU throughput by 20%, cuts memory use by 60% (enabling up to 4\u00d7 longer context), and works seamlessly with tools like FlashAttention, PyTorch FSDP, and DeepSpeed. For more information, see [Liger Kernel Integration](liger_kernel_integration).", "source_file": "trl/dpo_trainer.md", "section_heading": "Train with Liger Kernel", "char_start": 17036, "char_end": 17390, "token_estimate": 88, "prev_chunk_id": 88, "next_chunk_id": 90, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 90, "text": "### Rapid Experimentation for DPO\n\nRapidFire AI is an open-source experimentation engine that sits on top of TRL and lets you launch multiple DPO configurations at once, even on a single GPU. Instead of trying configurations sequentially, RapidFire lets you **see all their learning curves earlier, stop underperforming runs, and clone promising ones with new settings in flight** without restarting. For more information, see [RapidFire AI Integration](rapidfire_integration).", "source_file": "trl/dpo_trainer.md", "section_heading": "Rapid Experimentation for DPO", "char_start": 17392, "char_end": 17869, "token_estimate": 119, "prev_chunk_id": 89, "next_chunk_id": 91, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 91, "text": "### Train with Unsloth\n\nUnsloth is an open\u2011source framework for fine\u2011tuning and reinforcement learning that trains LLMs (like Llama, Mistral, Gemma, DeepSeek, and more) up to 2\u00d7 faster with up to 70% less VRAM, while providing a streamlined, Hugging Face\u2013compatible workflow for training, evaluation, and deployment. For more information, see [Unsloth Integration](unsloth_integration).", "source_file": "trl/dpo_trainer.md", "section_heading": "Train with Unsloth", "char_start": 17871, "char_end": 18257, "token_estimate": 96, "prev_chunk_id": 90, "next_chunk_id": 92, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 92, "text": "## Tool Calling with DPO\n\nThe [DPOTrainer](/docs/trl/v1.2.0/en/bema_for_reference_model#trl.DPOTrainer) fully supports fine-tuning models with _tool calling_ capabilities. In this case, each dataset example should include:\n\n* The conversation messages (prompt, chosen and rejected), including any tool calls (`tool_calls`) and tool responses (`tool` role messages)\n* The list of available tools in the `tools` column, typically provided as JSON schemas\n\nFor details on the expected dataset structure, see the [Dataset Format \u2014 Tool Calling](dataset_formats#tool-calling) section.", "source_file": "trl/dpo_trainer.md", "section_heading": "Tool Calling with DPO", "char_start": 18259, "char_end": 18838, "token_estimate": 144, "prev_chunk_id": 91, "next_chunk_id": 93, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 93, "text": "## Training Vision Language Models\n\n[DPOTrainer](/docs/trl/v1.2.0/en/bema_for_reference_model#trl.DPOTrainer) fully supports training Vision-Language Models (VLMs). To train a VLM, provide a dataset with either an `image` column (single image per sample) or an `images` column (list of images per sample). For more information on the expected dataset structure, see the [Dataset Format \u2014 Vision Dataset](dataset_formats#vision-dataset) section.\nAn example of such a dataset is the [RLAIF-V Dataset](https://huggingface.co/datasets/HuggingFaceH4/rlaif-v_formatted) dataset.\n\n```python\nfrom trl import DPOConfig, DPOTrainer\nfrom datasets import load_dataset\n\ntrainer = DPOTrainer(\n model=\"Qwen/Qwen2.5-VL-3B-Instruct\",\n args=DPOConfig(max_length=None),\n train_dataset=load_dataset(\"HuggingFaceH4/rlaif-v_formatted\", split=\"train\"),\n)\ntrainer.train()\n```", "source_file": "trl/dpo_trainer.md", "section_heading": "Training Vision Language Models", "char_start": 18840, "char_end": 19700, "token_estimate": 215, "prev_chunk_id": 92, "next_chunk_id": 94, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 94, "text": "> [!TIP]\n> For VLMs, truncating may remove image tokens, leading to errors during training. To avoid this, set `max_length=None` in the [DPOConfig](/docs/trl/v1.2.0/en/dpo_trainer#trl.DPOConfig). This allows the model to process the full sequence length without truncating image tokens.\n>\n> ```python\n> DPOConfig(max_length=None, ...)\n> ```\n>\n> Only use `max_length` when you've verified that truncation won't remove image tokens for the entire dataset.", "source_file": "trl/dpo_trainer.md", "section_heading": "Training Vision Language Models", "char_start": 19702, "char_end": 20155, "token_estimate": 113, "prev_chunk_id": 93, "next_chunk_id": 95, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 95, "text": "## DPOTrainer[[trl.DPOTrainer]]", "source_file": "trl/dpo_trainer.md", "section_heading": "DPOTrainer[[trl.DPOTrainer]]", "char_start": 20157, "char_end": 20188, "token_estimate": 7, "prev_chunk_id": 94, "next_chunk_id": 96, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 96, "text": "#### trl.DPOTrainer[[trl.DPOTrainer]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/trainer/dpo_trainer.py#L406)\n\nTrainer for Direct Preference Optimization (DPO) method. This algorithm was initially proposed in the paper [Direct\nPreference Optimization: Your Language Model is Secretly a Reward Model](https://huggingface.co/papers/2305.18290).\nThis class is a wrapper around the [Trainer](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer) class and inherits all of its attributes and methods.\n\nExample:\n\n```python\nfrom trl import DPOTrainer\nfrom datasets import load_dataset\n\ndataset = load_dataset(\"trl-lib/ultrafeedback_binarized\", split=\"train\")\n\ntrainer = DPOTrainer(\n model=\"Qwen/Qwen2.5-0.5B-Instruct\",\n train_dataset=dataset,\n)\ntrainer.train()\n```", "source_file": "trl/dpo_trainer.md", "section_heading": "trl.DPOTrainer[[trl.DPOTrainer]]", "char_start": 20190, "char_end": 21011, "token_estimate": 205, "prev_chunk_id": 95, "next_chunk_id": 97, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 97, "text": "traintrl.DPOTrainer.trainhttps://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L1323[{\"name\": \"resume_from_checkpoint\", \"val\": \": str | bool | None = None\"}, {\"name\": \"trial\", \"val\": \": optuna.Trial | dict[str, Any] | None = None\"}, {\"name\": \"ignore_keys_for_eval\", \"val\": \": list[str] | None = None\"}]- **resume_from_checkpoint** (`str` or `bool`, *optional*) --\n If a `str`, local path to a saved checkpoint as saved by a previous instance of `Trainer`. If a\n `bool` and equals `True`, load the last checkpoint in *args.output_dir* as saved by a previous instance\n of `Trainer`. If present, training will resume from the model/optimizer/scheduler states loaded here.\n- **trial** (`optuna.Trial` or `dict[str, Any]`, *optional*) --\n The trial run or the hyperparameter dictionary for hyperparameter search.\n- **ignore_keys_for_eval** (`list[str]`, *optional*) --\n A list of keys in the output of your model (if it is a dictionary) that should be ignored when\n gathering predictions for evaluation during the training.0`~trainer_utils.TrainOutput`Object containing the global step count, training loss, and metrics.", "source_file": "trl/dpo_trainer.md", "section_heading": "trl.DPOTrainer[[trl.DPOTrainer]]", "char_start": 21013, "char_end": 22151, "token_estimate": 284, "prev_chunk_id": 96, "next_chunk_id": 98, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 98, "text": "Main training entry point.\n\n**Parameters:**\n\nmodel (`str` or [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) or `PeftModel`) : Model to be trained. Can be either: - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a path to a *directory* containing model weights saved using [save_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.save_pretrained), e.g., `'./my_model_directory/'`. The model is loaded using `.from_pretrained` (where `` is derived from the model config) with the keyword arguments in `args.model_init_kwargs`. - A [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) object. Only causal language models are supported. - A `PeftModel` object. Only causal language models are supported.", "source_file": "trl/dpo_trainer.md", "section_heading": "trl.DPOTrainer[[trl.DPOTrainer]]", "char_start": 22153, "char_end": 23104, "token_estimate": 237, "prev_chunk_id": 97, "next_chunk_id": 99, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 99, "text": "ref_model ([PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel), *optional*) : Reference model used to compute the reference log probabilities. - If provided, this model is used directly as the reference policy. - If `None`, the trainer will automatically use the initial policy corresponding to `model`, i.e. the model state before DPO training starts.\n\nargs ([DPOConfig](/docs/trl/v1.2.0/en/dpo_trainer#trl.DPOConfig), *optional*) : Configuration for this trainer. If `None`, a default configuration is used.\n\ndata_collator (`DataCollator`, *optional*) : Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`. Will default to `DataCollatorForPreference` if the model is a language model and `DataCollatorForVisionPreference` if the model is a vision-language model. Custom collators must truncate sequences before padding; the trainer does not apply post-collation truncation.", "source_file": "trl/dpo_trainer.md", "section_heading": "trl.DPOTrainer[[trl.DPOTrainer]]", "char_start": 23106, "char_end": 24103, "token_estimate": 249, "prev_chunk_id": 98, "next_chunk_id": 100, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 100, "text": "train_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) or [IterableDataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset)) : Dataset to use for training. This trainer supports both [language modeling](#language-modeling) type and [prompt-completion](#prompt-completion) type. The format of the samples can be either: - [Standard](dataset_formats#standard): Each sample contains plain text. - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role and content).\n\neval_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset), [IterableDataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) or `dict[str, Dataset | IterableDataset]`) : Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.", "source_file": "trl/dpo_trainer.md", "section_heading": "trl.DPOTrainer[[trl.DPOTrainer]]", "char_start": 24105, "char_end": 25113, "token_estimate": 252, "prev_chunk_id": 99, "next_chunk_id": 101, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 101, "text": "processing_class ([PreTrainedTokenizerBase](https://huggingface.co/docs/transformers/v5.5.4/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase), [ProcessorMixin](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/processors#transformers.ProcessorMixin), *optional*) : Processing class used to process the data. The padding side must be set to \"left\". If `None`, the processing class is loaded from the model's name with [from_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/model_doc/auto#transformers.AutoProcessor.from_pretrained). A padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, `tokenizer.eos_token` will be used as the default.", "source_file": "trl/dpo_trainer.md", "section_heading": "trl.DPOTrainer[[trl.DPOTrainer]]", "char_start": 25115, "char_end": 25850, "token_estimate": 183, "prev_chunk_id": 100, "next_chunk_id": 102, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 102, "text": "compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*) : The function that will be used to compute metrics at evaluation. Must take a [EvalPrediction](https://huggingface.co/docs/transformers/v5.5.4/en/internal/trainer_utils#transformers.EvalPrediction) and return a dictionary string to metric values. When passing [SFTConfig](/docs/trl/v1.2.0/en/sft_trainer#trl.SFTConfig) with `batch_eval_metrics` set to `True`, your `compute_metrics` function must take a boolean `compute_result` argument. This will be triggered after the last eval batch to signal that the function needs to calculate and return the global summary statistics rather than accumulating the batch-level statistics.", "source_file": "trl/dpo_trainer.md", "section_heading": "trl.DPOTrainer[[trl.DPOTrainer]]", "char_start": 25852, "char_end": 26546, "token_estimate": 173, "prev_chunk_id": 101, "next_chunk_id": 103, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 103, "text": "callbacks (list of [TrainerCallback](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/callback#transformers.TrainerCallback), *optional*) : List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed in [here](https://huggingface.co/docs/transformers/main_classes/callback). If you want to remove one of the default callbacks used, use the [remove_callback](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer.remove_callback) method.\n\noptimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`) : A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your model and a scheduler given by [get_linear_schedule_with_warmup](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/optimizer_schedules#transformers.get_linear_schedule_with_warmup) controlled by `args`.", "source_file": "trl/dpo_trainer.md", "section_heading": "trl.DPOTrainer[[trl.DPOTrainer]]", "char_start": 26548, "char_end": 27545, "token_estimate": 249, "prev_chunk_id": 102, "next_chunk_id": 104, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 104, "text": "peft_config (`PeftConfig`, *optional*) : PEFT configuration used to wrap the model. If `None`, the model is not wrapped.\n\n**Returns:**\n\n``~trainer_utils.TrainOutput``\n\nObject containing the global step count, training loss, and metrics.", "source_file": "trl/dpo_trainer.md", "section_heading": "trl.DPOTrainer[[trl.DPOTrainer]]", "char_start": 27547, "char_end": 27783, "token_estimate": 59, "prev_chunk_id": 103, "next_chunk_id": 105, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 105, "text": "#### save_model[[trl.DPOTrainer.save_model]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L3746)\n\nWill save the model, so you can reload it using `from_pretrained()`.\n\nWill only save from the main process.", "source_file": "trl/dpo_trainer.md", "section_heading": "save_model[[trl.DPOTrainer.save_model]]", "char_start": 27784, "char_end": 28025, "token_estimate": 60, "prev_chunk_id": 104, "next_chunk_id": 106, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 106, "text": "#### push_to_hub[[trl.DPOTrainer.push_to_hub]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L3993)\n\nUpload `self.model` and `self.processing_class` to the \ud83e\udd17 model hub on the repo `self.args.hub_model_id`.\n\n**Parameters:**\n\ncommit_message (`str`, *optional*, defaults to `\"End of training\"`) : Message to commit while pushing.\n\nblocking (`bool`, *optional*, defaults to `True`) : Whether the function should return only when the `git push` has finished.\n\ntoken (`str`, *optional*, defaults to `None`) : Token with write permission to overwrite Trainer's original args.\n\nrevision (`str`, *optional*) : The git revision to commit from. Defaults to the head of the \"main\" branch.\n\nkwargs (`dict[str, Any]`, *optional*) : Additional keyword arguments passed along to `~Trainer.create_model_card`.\n\n**Returns:**\n\nThe URL of the repository where the model was pushed if `blocking=False`, or a `Future` object tracking the\nprogress of the commit if `blocking=True`.", "source_file": "trl/dpo_trainer.md", "section_heading": "push_to_hub[[trl.DPOTrainer.push_to_hub]]", "char_start": 28026, "char_end": 29019, "token_estimate": 248, "prev_chunk_id": 105, "next_chunk_id": 107, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 107, "text": "## DPOConfig[[trl.DPOConfig]]", "source_file": "trl/dpo_trainer.md", "section_heading": "DPOConfig[[trl.DPOConfig]]", "char_start": 29021, "char_end": 29050, "token_estimate": 7, "prev_chunk_id": 106, "next_chunk_id": 108, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 108, "text": "#### trl.DPOConfig[[trl.DPOConfig]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/trainer/dpo_config.py#L23)\n\nConfiguration class for the [DPOTrainer](/docs/trl/v1.2.0/en/bema_for_reference_model#trl.DPOTrainer).\n\nThis class includes only the parameters that are specific to DPO training. For a full list of training arguments,\nplease refer to the [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments) documentation. Note that default values in this class may\ndiffer from those in [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments).\n\nUsing [HfArgumentParser](https://huggingface.co/docs/transformers/v5.5.4/en/internal/trainer_utils#transformers.HfArgumentParser) we can turn this class into\n[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the\ncommand line.", "source_file": "trl/dpo_trainer.md", "section_heading": "trl.DPOConfig[[trl.DPOConfig]]", "char_start": 29052, "char_end": 30025, "token_estimate": 243, "prev_chunk_id": 107, "next_chunk_id": 109, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 109, "text": "> [!NOTE]\n> These parameters have default values different from [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments):\n> - `logging_steps`: Defaults to `10` instead of `500`.\n> - `gradient_checkpointing`: Defaults to `True` instead of `False`.\n> - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.\n> - `learning_rate`: Defaults to `1e-6` instead of `5e-5`.", "source_file": "trl/dpo_trainer.md", "section_heading": "trl.DPOConfig[[trl.DPOConfig]]", "char_start": 30027, "char_end": 30472, "token_estimate": 111, "prev_chunk_id": 108, "next_chunk_id": null, "url": "https://huggingface.co/docs/trl/dpo_trainer", "doc_title": "DPO Trainer" }, { "chunk_id": 110, "text": "# GRPO Trainer\n\n[![model badge](https://img.shields.io/badge/All_models-GRPO-blue)](https://huggingface.co/models?other=grpo,trl)", "source_file": "trl/grpo_trainer.md", "section_heading": "GRPO Trainer", "char_start": 0, "char_end": 129, "token_estimate": 32, "prev_chunk_id": null, "next_chunk_id": 111, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 111, "text": "## Overview\n\nTRL supports the GRPO Trainer for training language models, as described in the paper [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://huggingface.co/papers/2402.03300) by [Zhihong Shao](https://huggingface.co/syhia), [Peiyi Wang](https://huggingface.co/peiyiwang89), [Qihao Zhu](https://huggingface.co/zqh11), Runxin Xu, [Junxiao Song](https://huggingface.co/haha-point), Mingchuan Zhang, Y. K. Li, Y. Wu, [Daya Guo](https://huggingface.co/guoday).\n\nThe abstract from the paper is the following:", "source_file": "trl/grpo_trainer.md", "section_heading": "Overview", "char_start": 131, "char_end": 684, "token_estimate": 138, "prev_chunk_id": 110, "next_chunk_id": 112, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 112, "text": "> Mathematical reasoning poses a significant challenge for language models due to its complex and structured nature. In this paper, we introduce DeepSeekMath 7B, which continues pre-training DeepSeek-Coder-Base-v1.5 7B with 120B math-related tokens sourced from Common Crawl, together with natural language and code data. DeepSeekMath 7B has achieved an impressive score of 51.7% on the competition-level MATH benchmark without relying on external toolkits and voting techniques, approaching the performance level of Gemini-Ultra and GPT-4. Self-consistency over 64 samples from DeepSeekMath 7B achieves 60.9% on MATH. The mathematical reasoning capability of DeepSeekMath is attributed to two key factors: First, we harness the significant potential of publicly available web data through a meticulously engineered data selection pipeline. Second, we introduce Group Relative Policy Optimization (GRPO), a variant of Proximal Policy Optimization (PPO), that enhances mathematical reasoning abilities while concurrently optimizing the memory usage of PPO.", "source_file": "trl/grpo_trainer.md", "section_heading": "Overview", "char_start": 686, "char_end": 1741, "token_estimate": 263, "prev_chunk_id": 111, "next_chunk_id": 113, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 113, "text": "This post-training method was contributed by [Quentin Gallou\u00e9dec](https://huggingface.co/qgallouedec).", "source_file": "trl/grpo_trainer.md", "section_heading": "Overview", "char_start": 1743, "char_end": 1845, "token_estimate": 25, "prev_chunk_id": 112, "next_chunk_id": 114, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 114, "text": "## Quick start\n\nThis example demonstrates how to train a model using the GRPO method. We train a [Qwen 0.5B Instruct model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) with the prompts from the [DeepMath-103K dataset](https://huggingface.co/datasets/trl-lib/DeepMath-103K). You can view the data in the dataset here:\n\nBelow is the script to train the model.\n\n```python", "source_file": "trl/grpo_trainer.md", "section_heading": "Quick start", "char_start": 1847, "char_end": 2220, "token_estimate": 93, "prev_chunk_id": 113, "next_chunk_id": 115, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 115, "text": "# train_grpo.py\nfrom datasets import load_dataset\nfrom trl import GRPOTrainer\nfrom trl.rewards import accuracy_reward\n\ndataset = load_dataset(\"trl-lib/DeepMath-103K\", split=\"train\")\n\ntrainer = GRPOTrainer(\n model=\"Qwen/Qwen2-0.5B-Instruct\",\n reward_funcs=accuracy_reward,\n train_dataset=dataset,\n)\ntrainer.train()\n```\n\nExecute the script using the following command:\n\n```bash\naccelerate launch train_grpo.py\n```\n\nDistributed across 8 GPUs, the training takes approximately 1 day.\n\n![GRPO curves](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/grpo_curves.png)", "source_file": "trl/grpo_trainer.md", "section_heading": "train_grpo.py", "char_start": 2221, "char_end": 2816, "token_estimate": 148, "prev_chunk_id": 114, "next_chunk_id": 116, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 116, "text": "## Looking deeper into the GRPO method\n\nGRPO is an online learning algorithm, meaning it improves iteratively by using the data generated by the trained model itself during training. The intuition behind GRPO objective is to maximize the advantage of the generated completions, while ensuring that the model remains close to the reference policy. To understand how GRPO works, it can be broken down into four main steps: **Generating completions**, **computing the advantage**, **estimating the KL divergence**, and **computing the loss**.\n\n![GRPO visual](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/grpo_visual.png)", "source_file": "trl/grpo_trainer.md", "section_heading": "Looking deeper into the GRPO method", "char_start": 2818, "char_end": 3464, "token_estimate": 161, "prev_chunk_id": 115, "next_chunk_id": 117, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 117, "text": "### Generating completions\n\nAt each training step, we sample a batch of prompts and generate a set of \\\\( G \\\\) completions for each prompt (denoted as \\\\( o_i \\\\)).", "source_file": "trl/grpo_trainer.md", "section_heading": "Generating completions", "char_start": 3466, "char_end": 3633, "token_estimate": 41, "prev_chunk_id": 116, "next_chunk_id": 118, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 118, "text": "### Computing the advantage\n\nFor each of the \\\\( G \\\\) sequences, we compute the reward using a reward model or reward function. To align with the comparative nature of reward models\u2014typically trained on datasets of comparisons between outputs for the same question\u2014the advantage is calculated to reflect these relative comparisons. It is normalized as follows:\n\n$$\\hat{A}_{i,t} = \\frac{r_i - \\text{mean}(\\mathbf{r})}{\\text{std}(\\mathbf{r})}$$\n\nThis approach gives the method its name: **Group Relative Policy Optimization (GRPO)**.", "source_file": "trl/grpo_trainer.md", "section_heading": "Computing the advantage", "char_start": 3635, "char_end": 4168, "token_estimate": 133, "prev_chunk_id": 117, "next_chunk_id": 119, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 119, "text": "> [!TIP]\n> It was shown in the paper [Understanding R1-Zero-Like Training: A Critical Perspective](https://huggingface.co/papers/2503.20783) that scaling by \\\\( \\text{std}(\\mathbf{r}) \\\\) may cause a question-level difficulty bias. You can disable this scaling by setting `scale_rewards=False` in [GRPOConfig](/docs/trl/v1.2.0/en/grpo_trainer#trl.GRPOConfig).\n> Note that turning off std-based scaling also removes variance normalization, so update magnitudes depend directly on the raw reward scale and batch composition.\n\n> [!TIP]\n> As shown in [Part I: Tricks or Traps? A Deep Dive into RL for LLM Reasoning (Lite PPO)](https://huggingface.co/papers/2508.08221), calculating the mean at the local (group) level and the standard deviation at the global (batch) level enables more robust reward shaping. You can use this scaling strategy by setting `scale_rewards=\"batch\"` in [GRPOConfig](/docs/trl/v1.2.0/en/grpo_trainer#trl.GRPOConfig).", "source_file": "trl/grpo_trainer.md", "section_heading": "Computing the advantage", "char_start": 4170, "char_end": 5110, "token_estimate": 235, "prev_chunk_id": 118, "next_chunk_id": 120, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 120, "text": "### Estimating the KL divergence\n\nKL divergence is estimated using the approximator introduced by [Schulman et al. (2020)](http://joschu.net/blog/kl-approx.html). The approximator is defined as follows:\n\n$$\\mathbb{D}_{\\text{KL}}\\left[\\pi_\\theta \\|\\pi_{\\text{ref}}\\right] = \\frac{\\pi_{\\text{ref}}(o_{i,t} \\mid q, o_{i, [!TIP]\n> Note that compared to the original formulation in [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://huggingface.co/papers/2402.03300), we don't scale by \\\\( \\frac{1}{|o_i|} \\\\) because it was shown in the paper [Understanding R1-Zero-Like Training: A Critical Perspective](https://huggingface.co/papers/2503.20783) that this introduces a response-level length bias. More details in [loss types](#loss-types).", "source_file": "trl/grpo_trainer.md", "section_heading": "Estimating the KL divergence", "char_start": 5112, "char_end": 5891, "token_estimate": 194, "prev_chunk_id": 119, "next_chunk_id": 121, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 121, "text": "> [!TIP]\n> Note that compared to the original formulation in [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://huggingface.co/papers/2402.03300), we use \\\\( \\beta = 0.0 \\\\) by default, meaning that the KL divergence term is not used. This choice is motivated by several recent studies (e.g., [Open-Reasoner-Zero: An Open Source Approach to Scaling Up Reinforcement Learning on the Base Model](https://huggingface.co/papers/2503.24290)) which have shown that the KL divergence term is not essential for training with GRPO. As a result, it has become common practice to exclude it (e.g. [Understanding R1-Zero-Like Training: A Critical Perspective](https://huggingface.co/papers/2503.20783), [DAPO: An Open-Source LLM Reinforcement Learning System at Scale](https://huggingface.co/papers/2503.14476)). If you wish to include the KL divergence term, you can set `beta` in [GRPOConfig](/docs/trl/v1.2.0/en/grpo_trainer#trl.GRPOConfig) to a non-zero value.", "source_file": "trl/grpo_trainer.md", "section_heading": "Estimating the KL divergence", "char_start": 5893, "char_end": 6888, "token_estimate": 248, "prev_chunk_id": 120, "next_chunk_id": 122, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 122, "text": "In the original paper, this formulation is generalized to account for multiple updates after each generation (denoted \\\\( \\mu \\\\), can be set with `num_iterations` in [GRPOConfig](/docs/trl/v1.2.0/en/grpo_trainer#trl.GRPOConfig)) by leveraging the **clipped surrogate objective**:\n\n$$\n\\mathcal{L}_{\\text{GRPO}}(\\theta) = - \\frac{1}{\\sum_{i=1}^G |o_i|} \\sum_{i=1}^G \\sum_{t=1}^{|o_i|} \\left[ \\min \\left( \\frac{\\pi_\\theta(o_{i,t} \\mid q, o_{i, 0 \\\\\n\\tau_{\\text{neg}}, & \\text{otherwise}\n\\end{cases}\n$$\n\nThey recommend using asymmetric temperatures, \\\\( \\tau_{\\text{neg}} > \\tau_{\\text{pos}} \\\\) (defaults are \\\\( \\tau_{\\text{pos}}=1.0, \\tau_{\\text{neg}}=1.05 \\\\) ). This ensures that the model is penalized more strictly for \"bad\" actions to prevent instability, while being more permissive with \"good\" actions.\n\nTo use this formulation, set `loss_type=\"sapo\"` in the [GRPOConfig](/docs/trl/v1.2.0/en/grpo_trainer#trl.GRPOConfig).", "source_file": "trl/grpo_trainer.md", "section_heading": "Estimating the KL divergence", "char_start": 6890, "char_end": 7821, "token_estimate": 232, "prev_chunk_id": 121, "next_chunk_id": 123, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 123, "text": "## Logged metrics\n\nWhile training and evaluating, we record the following reward metrics:", "source_file": "trl/grpo_trainer.md", "section_heading": "Logged metrics", "char_start": 7823, "char_end": 7912, "token_estimate": 22, "prev_chunk_id": 122, "next_chunk_id": 124, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 124, "text": "- `num_tokens`: The total number of tokens processed so far, including both prompts and completions. When using tools, only non-tool tokens are counted.\n- `step_time`: The average time (in seconds) taken per training step (including generation).\n- `completions/mean_length`: The average length of generated completions. When using tools, only non-tool tokens are counted.\n- `completions/min_length`: The minimum length of generated completions. When using tools, only non-tool tokens are counted.\n- `completions/max_length`: The maximum length of generated completions. When using tools, only non-tool tokens are counted.\n- `completions/mean_terminated_length`: The average length of generated completions that terminate with EOS. When using tools, only non-tool tokens are counted.\n- `completions/min_terminated_length`: The minimum length of generated completions that terminate with EOS. When using tools, only non-tool tokens are counted.\n- `completions/max_terminated_length`: The maximum length of generated completions that terminate with EOS. When using tools, only non-tool tokens are counted.\n- `completions/clipped_ratio`: The ratio of truncated (clipped) completions.\n- `reward/{reward_func_name}/mean`: The average reward from a specific reward function.\n- `reward/{reward_func_name}/std`: The standard deviation of the reward from a specific reward function.\n- `reward`: The overall average reward after summing rewards across functions (weighted by `reward_weights`).\n- `reward_std`: The standard deviation of summed rewards across functions (weighted by `reward_weights`), computed over the full batch.\n- `frac_reward_zero_std`: The fraction of samples in the generation batch with a reward std of zero, implying there is little diversity for that prompt (all answers are correct or incorrect).\n- `entropy`: Average entropy of token predictions across generated completions. (If `mask_truncated_completions=True`, masked sequences tokens are excluded.)\n- `kl`: The average KL divergence between the model and the reference model, calculated over generated completions. Logged only if `beta` is nonzero.\n- `clip_ratio/region_mean`: The ratio of token (or sequence, if `importance_sampling_level=\"sequence\"`) probabilities where the GRPO objective is clipped to stay within the trust region: \\\\( \\text{clip}\\left( r_{i,t}(\\theta), 1 - \\epsilon_\\mathrm{low}, 1 + \\epsilon_\\mathrm{high} \\right)\\,, \\quad r_{i,t}(\\theta) = \\frac{\\pi_\\theta(o_{i,t} \\mid q, o_{i, 1 + \\epsilon_\\mathrm{high}\\\\).\n- `clip_ratio/high_max`: The maximum ratio of token (or sequence, if `importance_sampling_level=\"sequence\"`) probabilities that were clipped on the upper bound of the trust region: \\\\(r_{i,t}(\\theta) > 1 + \\epsilon_\\mathrm{high}\\\\).", "source_file": "trl/grpo_trainer.md", "section_heading": "Logged metrics", "char_start": 7914, "char_end": 10652, "token_estimate": 684, "prev_chunk_id": 123, "next_chunk_id": 125, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 125, "text": "## Customization", "source_file": "trl/grpo_trainer.md", "section_heading": "Customization", "char_start": 10654, "char_end": 10670, "token_estimate": 4, "prev_chunk_id": 124, "next_chunk_id": 126, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 126, "text": "### Speed up training with vLLM-powered generation\n\nGeneration is often the main bottleneck when training with online methods. To accelerate generation, you can use [vLLM](https://github.com/vllm-project/vllm), a high-throughput, low-latency inference engine for LLMs. To enable it, first install the package with\n\n```shell\npip install trl[vllm]\n```\n\nWe support two ways of using vLLM during training: **server mode** and **colocate mode**.\n\n> [!TIP]\n> By default, Truncated Importance Sampling is activated for vLLM generation to address the generation-training mismatch that occurs when using different frameworks. This can be turned off by setting `vllm_importance_sampling_correction=False`. For more information, see [Truncated Importance Sampling](paper_index#truncated-importance-sampling)", "source_file": "trl/grpo_trainer.md", "section_heading": "Speed up training with vLLM-powered generation", "char_start": 10672, "char_end": 11468, "token_estimate": 199, "prev_chunk_id": 125, "next_chunk_id": 127, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 127, "text": "#### Option 1: Colocate mode\n\nIn this mode, vLLM runs inside the trainer process and shares GPU memory with the training model. This avoids launching a separate server and can improve GPU utilization, but may lead to memory contention on the training GPUs. This is the default mode.\n\n```python\nfrom trl import GRPOConfig\n\ntraining_args = GRPOConfig(\n ...,\n use_vllm=True, # vllm_mode=\"colocate\" by default\n)\n```", "source_file": "trl/grpo_trainer.md", "section_heading": "Option 1: Colocate mode", "char_start": 11470, "char_end": 11888, "token_estimate": 104, "prev_chunk_id": 126, "next_chunk_id": 128, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 128, "text": "#### Option 2: Server mode\n\nIn this mode, vLLM runs in a separate process (and using separate GPUs) and communicates with the trainer via HTTP. This is ideal if you have dedicated GPUs for inference.\n\n1. **Start the vLLM server**:\n\n ```bash\n trl vllm-serve --model \n ```\n\n2. **Enable server mode in your training script**:\n\n ```python\n from trl import GRPOConfig\n\n training_args = GRPOConfig(\n ...,\n use_vllm=True,\n vllm_mode=\"server\",\n )\n ```\n\n> [!WARNING]\n> Make sure that the server is using different GPUs than the trainer, otherwise you may run into NCCL errors. You can specify the GPUs to use with the `CUDA_VISIBLE_DEVICES` environment variable.", "source_file": "trl/grpo_trainer.md", "section_heading": "Option 2: Server mode", "char_start": 11890, "char_end": 12577, "token_estimate": 171, "prev_chunk_id": 127, "next_chunk_id": 129, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 129, "text": "> [!TIP]\n> Depending on the model size and the overall GPU memory requirements for training, you may need to adjust the `vllm_gpu_memory_utilization` parameter in [GRPOConfig](/docs/trl/v1.2.0/en/grpo_trainer#trl.GRPOConfig) to avoid underutilization or out-of-memory errors.\n>\n> We provide a [HF Space](https://huggingface.co/spaces/trl-lib/recommend-vllm-memory) to help estimate the recommended GPU memory utilization based on your model configuration and experiment settings. Simply use it as follows to get `vllm_gpu_memory_utilization` recommendation:\n>\n> \n>\n> If the recommended value does not work in your environment, we suggest adding a small buffer (e.g., +0.05 or +0.1) to the recommended value to ensure stability.\n>\n> If you still find you are getting out-of-memory errors set `vllm_enable_sleep_mode` to True and the vllm parameters and cache will be offloaded during the optimization step. For more information, see [Reducing Memory Usage with vLLM Sleep Mode](reducing_memory_usage#vllm-sleep-mode).", "source_file": "trl/grpo_trainer.md", "section_heading": "Option 2: Server mode", "char_start": 12579, "char_end": 13595, "token_estimate": 254, "prev_chunk_id": 128, "next_chunk_id": 130, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 130, "text": "> [!TIP]\n> By default, GRPO uses `MASTER_ADDR=localhost` and `MASTER_PORT=12345` for vLLM, but you can override these values by setting the environment variables accordingly.\n\nFor more information, see [Speeding up training with vLLM](speeding_up_training#vllm-for-fast-generation-in-online-methods).", "source_file": "trl/grpo_trainer.md", "section_heading": "Option 2: Server mode", "char_start": 13597, "char_end": 13897, "token_estimate": 75, "prev_chunk_id": 129, "next_chunk_id": 131, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 131, "text": "#### Dealing with the Training-Inference Mismatch\nWhile vLLM greatly accelerates inference, it also decouples the inference engine from the training engine. In theory these engines are mathematically identical, in practice however they can produce different outputs due to precision effects and hardware specific optimizations. This divergence reflects the different optimization objectives of the two systems. This divergence reflects the distinct optimization goals of the two systems. Inference engines aim to maximize sampling throughput, typically measured in tokens per second, while maintaining acceptable sampling fidelity. Training frameworks instead focus on numerical stability and precision for gradient computation, often using higher precision formats like FP32 for master weights and optimizer states. These differing priorities and constraints introduce an inevitable, albeit subtle, mismatch between training and inference.", "source_file": "trl/grpo_trainer.md", "section_heading": "Dealing with the Training-Inference Mismatch", "char_start": 13899, "char_end": 14839, "token_estimate": 235, "prev_chunk_id": 130, "next_chunk_id": 132, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 132, "text": "This mismatch leads to a biased gradient update which has been observed to destabilize training ([[1]](https://fengyao.notion.site/off-policy-rl)[[2]](https://yingru.notion.site/When-Speed-Kills-Stability-Demystifying-RL-Collapse-from-the-Training-Inference-Mismatch-271211a558b7808d8b12d403fd15edda)[[3]](https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/#true-on-policy-rl)[[4]](https://huggingface.co/papers/2510.26788)[[5]](https://huggingface.co/papers/2510.18855)). For simplicity, consider the REINFORCE policy gradient:\n\n$$\n\\nabla_\\theta \\mathcal{J}(x,\\theta)\n= \\mathbb{E}_{y \\sim \\pi^\\text{train}(\\cdot \\mid x,\\theta)}\n\\left[ \\nabla_\\theta \\log \\pi^\\text{train}(y \\mid x,\\theta) \\cdot R(x,y) \\right]\n$$\n\nHere \\\\( x \\\\) denotes prompts sampled from some data distribution, and \\\\( \\pi^\\text{train} \\\\) is the policy implemented by the training engine. With vLLM in the loop we obtain a separate inference policy \\\\( \\pi^\\text{inference} \\\\), so the effective policy gradient becomes", "source_file": "trl/grpo_trainer.md", "section_heading": "Dealing with the Training-Inference Mismatch", "char_start": 14841, "char_end": 15859, "token_estimate": 254, "prev_chunk_id": 131, "next_chunk_id": 133, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 133, "text": "$$\n\\nabla_\\theta \\mathcal{J}_{\\text{biased}}(x,\\theta)\n= \\mathbb{E}_{y \\sim \\pi^\\text{inference}(\\cdot \\mid x,\\theta)}\n\\left[ \\nabla_\\theta \\log \\pi^\\text{train}(y \\mid x,\\theta) \\cdot R(x,y) \\right].\n$$\n\nThis turns an otherwise on policy RL problem into an off policy one.\n\nThe standard way to correct for this distribution shift is **importance sampling (IS)**. We provide two IS variants: [Truncated Importance Sampling (TIS)](paper_index#truncated-importance-sampling) and [Masked Importance Sampling (MIS)](paper_index#masked-importance-sampling). Both variants can be applied either at the token level or at the sequence level.Let \\\\( \\rho \\\\) denote the importance weight, for example \\\\( \\rho_t \\\\) per token or \\\\( \\rho_{\\text{seq}} \\\\) per sequence. Under TIS, ratios larger than `vllm_importance_sampling_cap` are clipped,\n\n$$\n\\rho \\leftarrow \\min(\\rho, C).\n$$", "source_file": "trl/grpo_trainer.md", "section_heading": "Dealing with the Training-Inference Mismatch", "char_start": 15861, "char_end": 16735, "token_estimate": 218, "prev_chunk_id": 132, "next_chunk_id": 134, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 134, "text": "Under MIS, ratios larger than `vllm_importance_sampling_cap` are set to zero, so those samples do not contribute to the gradient. In other words, large ratio samples are downweighted under TIS and discarded under MIS. The configuration flag `vllm_importance_sampling_mode` chooses both the IS variant (masking or truncation) and the granularity (token level or sequence level).", "source_file": "trl/grpo_trainer.md", "section_heading": "Dealing with the Training-Inference Mismatch", "char_start": 16737, "char_end": 17114, "token_estimate": 94, "prev_chunk_id": 133, "next_chunk_id": 135, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 135, "text": "Importance sampling is the principled algorithmic response to the training\u2013inference mismatch. However, there are also more direct approaches that attempt to reduce the mismatch between the two engines themselves. Most of these are engineering solutions. For example, [MiniMax M1 uses an FP32 language model head](https://huggingface.co/papers/2506.13585) in the inference engine. Thinking Machines has explored [deterministic inference kernels](https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/), although this comes with a significant efficiency cost. vLLM has shown [bitwise consistent policies](https://blog.vllm.ai/2025/11/10/bitwise-consistent-train-inference.html) by building on the batch invariant deterministic kernels from Thinking Machines, but as of November 2025 there remains a substantial throughput penalty relative to standard vLLM inference.", "source_file": "trl/grpo_trainer.md", "section_heading": "Dealing with the Training-Inference Mismatch", "char_start": 17116, "char_end": 18002, "token_estimate": 221, "prev_chunk_id": 134, "next_chunk_id": 136, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 136, "text": "### GRPO at scale: train a 70B+ Model on multiple nodes\n\nWhen training large models like **Qwen2.5-72B**, you need several key optimizations to make the training efficient and scalable across multiple GPUs and nodes. These include:", "source_file": "trl/grpo_trainer.md", "section_heading": "GRPO at scale: train a 70B+ Model on multiple nodes", "char_start": 18004, "char_end": 18235, "token_estimate": 57, "prev_chunk_id": 135, "next_chunk_id": 137, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 137, "text": "- **DeepSpeed ZeRO Stage 3**: ZeRO leverages data parallelism to distribute model states (weights, gradients, optimizer states) across multiple GPUs and CPUs, reducing memory and compute requirements on each device. Since large models cannot fit on a single GPU, using ZeRO Stage 3 is required for training such models. For more details, see [DeepSpeed Integration](deepspeed_integration).\n- **Accelerate**: Accelerate is a library that simplifies distributed training across multiple GPUs and nodes. It provides a simple API to launch distributed training and handles the complexities of distributed training, such as data parallelism, gradient accumulation, and distributed data loading. For more details, see [Distributing Training](distributing_training).\n- **vLLM**: See the previous section on how to use vLLM to speed up generation.\n\nBelow is an example SLURM script to train a 70B model with GRPO on multiple nodes. This script trains a model on 4 nodes and uses the 5th node for vLLM-powered generation.", "source_file": "trl/grpo_trainer.md", "section_heading": "GRPO at scale: train a 70B+ Model on multiple nodes", "char_start": 18237, "char_end": 19249, "token_estimate": 253, "prev_chunk_id": 136, "next_chunk_id": 138, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 138, "text": "```sh\n#!/bin/bash\n#SBATCH --nodes=5\n#SBATCH --gres=gpu:8", "source_file": "trl/grpo_trainer.md", "section_heading": "GRPO at scale: train a 70B+ Model on multiple nodes", "char_start": 19251, "char_end": 19307, "token_estimate": 14, "prev_chunk_id": 137, "next_chunk_id": 139, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 139, "text": "# Get the list of allocated nodes\nNODELIST=($(scontrol show hostnames $SLURM_JOB_NODELIST))", "source_file": "trl/grpo_trainer.md", "section_heading": "Get the list of allocated nodes", "char_start": 19309, "char_end": 19400, "token_estimate": 22, "prev_chunk_id": 138, "next_chunk_id": 140, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 140, "text": "# Assign the first 4 nodes for training and the 5th node for vLLM\nTRAIN_NODES=\"${NODELIST[@]:0:4}\" # Nodes 0, 1, 2, 3 for training\nVLLM_NODE=\"${NODELIST[4]}\" # Node 4 for vLLM", "source_file": "trl/grpo_trainer.md", "section_heading": "Assign the first 4 nodes for training and the 5th node for vLLM", "char_start": 19402, "char_end": 19579, "token_estimate": 44, "prev_chunk_id": 139, "next_chunk_id": 141, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 141, "text": "# Run training on the first 4 nodes (Group 1)\nsrun --nodes=4 --ntasks=4 --nodelist=\"${NODELIST[@]:0:4}\" accelerate launch \\\n --config_file examples/accelerate_configs/deepspeed_zero3.yaml \\\n --num_processes 32 \\\n --num_machines 4 \\\n --main_process_ip ${NODELIST[0]} \\\n --machine_rank $SLURM_PROCID \\\n --rdzv_backend c10d \\\n train_grpo.py \\\n --server_ip $VLLM_NODE &", "source_file": "trl/grpo_trainer.md", "section_heading": "Run training on the first 4 nodes (Group 1)", "char_start": 19581, "char_end": 19978, "token_estimate": 99, "prev_chunk_id": 140, "next_chunk_id": 142, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 142, "text": "# Run vLLM server on the 5th node (Group 2)\nsrun --nodes=1 --ntasks=1 --nodelist=\"${NODELIST[4]}\" trl vllm-serve --model Qwen/Qwen2.5-72B --tensor_parallel_size 8 &\n\nwait\n```\n\n```python\nimport argparse\n\nfrom datasets import load_dataset\nfrom trl import GRPOTrainer, GRPOConfig\nfrom trl.rewards import accuracy_reward\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--vllm_server_host\", type=str, default=\"\", help=\"The server IP\")\n args = parser.parse_args()\n\n dataset = load_dataset(\"trl-lib/DeepMath-103K\", split=\"train\")\n\n training_args = GRPOConfig(\n per_device_train_batch_size=4,\n use_vllm=True,\n vllm_mode=\"server\",\n vllm_server_host=args.vllm_server_host.replace(\"ip-\", \"\").replace(\"-\", \".\"), # from ip-X-X-X-X to X.X.X.X\n )\n\n trainer = GRPOTrainer(\n model=\"Qwen/Qwen2.5-72B\",\n args=training_args,\n reward_funcs=accuracy_reward,\n train_dataset=dataset\n )\n trainer.train()\n\nif __name__==\"__main__\":\n main()\n```", "source_file": "trl/grpo_trainer.md", "section_heading": "Run vLLM server on the 5th node (Group 2)", "char_start": 19980, "char_end": 21006, "token_estimate": 256, "prev_chunk_id": 141, "next_chunk_id": 143, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 143, "text": "### Using a custom reward function\n\nThe [GRPOTrainer](/docs/trl/v1.2.0/en/gspo_token#trl.GRPOTrainer) supports using custom reward functions instead of dense reward models. To ensure compatibility, your reward function must satisfy the following requirements:\n\nReward functions can be either synchronous Python callables or asynchronous `async def` coroutines. When you provide multiple asynchronous reward functions, they are awaited concurrently (run in parallel via `asyncio.gather`) so their latency overlaps.", "source_file": "trl/grpo_trainer.md", "section_heading": "Using a custom reward function", "char_start": 21008, "char_end": 21521, "token_estimate": 128, "prev_chunk_id": 142, "next_chunk_id": 144, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 144, "text": "1. **Input arguments**:\n - The function must accept the following as keyword arguments:\n - `prompts` (contains the prompts),\n - `completions` (contains the generated completions),\n - `completion_ids` (contains the tokenized completions),\n - `trainer_state` ([TrainerState](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/callback#transformers.TrainerState)): The current state of the trainer. This can be used to implement dynamic reward functions, such as curriculum learning, where the reward is adjusted based on the training progress.\n - `log_extra`: a callable `log_extra(column: str, values: list)` to add extra columns to the completions table. See Example 6. In distributed training, it's important that all processes log the same set of keys.\n - `log_metric`: a callable `log_metric(name: str, value: float)` to log scalar metrics as plots alongside `kl`, `entropy`, etc. See Example 6. In distributed training, it's important that all processes log the same set of keys.\n - `environments`: a list of environment instances, one per completion. Only present when `environment_factory` is provided. Use this to read state accumulated during the episode (e.g., `env.reward`).\n - All column names (but `prompt`) that the dataset may have. For example, if the dataset contains a column named `ground_truth`, the function will be called with `ground_truth` as a keyword argument.", "source_file": "trl/grpo_trainer.md", "section_heading": "Using a custom reward function", "char_start": 21523, "char_end": 22955, "token_estimate": 358, "prev_chunk_id": 143, "next_chunk_id": 145, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 145, "text": "The easiest way to comply with this requirement is to use `**kwargs` in the function signature.\n - Depending on the dataset format, the input will vary:\n - For [standard format](dataset_formats#standard), `prompts` and `completions` will be lists of strings.\n - For [conversational format](dataset_formats#conversational), `prompts` and `completions` will be lists of message dictionaries.\n\n2. **Return value**: The function must return a list of floats. Each float represents the reward corresponding to a single completion.", "source_file": "trl/grpo_trainer.md", "section_heading": "Using a custom reward function", "char_start": 22962, "char_end": 23497, "token_estimate": 133, "prev_chunk_id": 144, "next_chunk_id": 146, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 146, "text": "#### Example 1: Reward longer completions\n\nBelow is an example of a reward function for a standard format that rewards longer completions:\n\n```python\ndef reward_func(completion_ids, **kwargs):\n \"\"\"Reward function that assigns higher scores to longer completions (in terms of token count).\"\"\"\n return [float(len(ids)) for ids in completion_ids]\n```\n\nYou can test it as follows:\n\n```python\n>>> prompts = [\"The sky is\", \"The sun is\"] # not used in the reward function, but the trainer will pass it\n>>> completions = [\" blue.\", \" in the sky.\"] # not used in the reward function, but the trainer will pass it\n>>> completion_ids = [[6303, 13], [304, 279, 12884, 13]]\n>>> reward_func(prompts=prompts, completions=completions, completion_ids=completion_ids)\n[2.0, 4.0]\n```", "source_file": "trl/grpo_trainer.md", "section_heading": "Example 1: Reward longer completions", "char_start": 23499, "char_end": 24271, "token_estimate": 193, "prev_chunk_id": 145, "next_chunk_id": 147, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 147, "text": "#### Example 1.1: Reward longer completions (based on the number of characters)\n\nSame as the previous example, but this time the reward function is based on the number of characters instead of tokens.\n\n```python\ndef reward_func(completions, **kwargs):\n \"\"\"Reward function that assigns higher scores to longer completions (in terms of character count).\"\"\"\n return [float(len(completion)) for completion in completions]\n```\n\nYou can test it as follows:\n\n```python\n>>> prompts = [\"The sky is\", \"The sun is\"]\n>>> completions = [\" blue.\", \" in the sky.\"]\n>>> completion_ids = [[6303, 13], [304, 279, 12884, 13]] # not used in the reward function, but the trainer will pass it\n>>> reward_func(prompts=prompts, completions=completions, completion_ids=completion_ids)\n[6.0, 12.0]\n```", "source_file": "trl/grpo_trainer.md", "section_heading": "Example 1.1: Reward longer completions (based on the number of characters)", "char_start": 24273, "char_end": 25055, "token_estimate": 195, "prev_chunk_id": 146, "next_chunk_id": 148, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 148, "text": "#### Example 2: Reward completions with a specific format\n\nBelow is an example of a reward function that checks if the completion has a specific format. This example is inspired by the _format reward_ function used in the paper [DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning](https://huggingface.co/papers/2501.12948).\nIt is designed for a conversational format, where prompts and completions consist of structured messages.\n\n```python\nimport re\n\ndef format_reward_func(completions, **kwargs):\n \"\"\"Reward function that checks if the completion has a specific format.\"\"\"\n pattern = r\"^.*?.*?$\"\n completion_contents = [completion[0][\"content\"] for completion in completions]\n matches = [re.match(pattern, content) for content in completion_contents]\n return [1.0 if match else 0.0 for match in matches]\n```\n\nYou can test this function as follows:", "source_file": "trl/grpo_trainer.md", "section_heading": "Example 2: Reward completions with a specific format", "char_start": 25057, "char_end": 25953, "token_estimate": 224, "prev_chunk_id": 147, "next_chunk_id": 149, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 149, "text": "```python\n>>> prompts = [\n... [{\"role\": \"assistant\", \"content\": \"What is the result of (1 + 2) * 4?\"}],\n... [{\"role\": \"assistant\", \"content\": \"What is the result of (3 + 1) * 2?\"}],\n... ]\n>>> completions = [\n... [{\"role\": \"assistant\", \"content\": \"The sum of 1 and 2 is 3, which we multiply by 4 to get 12.(1 + 2) * 4 = 12\"}],\n... [{\"role\": \"assistant\", \"content\": \"The sum of 3 and 1 is 4, which we multiply by 2 to get 8. So (3 + 1) * 2 = 8.\"}],\n... ]\n>>> format_reward_func(prompts=prompts, completions=completions)\n[1.0, 0.0]\n```", "source_file": "trl/grpo_trainer.md", "section_heading": "Example 2: Reward completions with a specific format", "char_start": 25955, "char_end": 26503, "token_estimate": 137, "prev_chunk_id": 148, "next_chunk_id": 150, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 150, "text": "#### Example 3: Reward completions based on a reference\n\nBelow is an example of a reward function that checks if the completion is correct. This example is inspired by the _accuracy reward_ function used in the paper [DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning](https://huggingface.co/papers/2501.12948).\nThis example is designed for [standard format](dataset_formats#standard), where the dataset contains a column named `ground_truth`.\n\n```python\nimport re\n\ndef reward_func(completions, ground_truth, **kwargs):\n # Regular expression to capture content inside \\boxed{}\n matches = [re.search(r\"\\\\boxed\\{(.*?)\\}\", completion) for completion in completions]\n contents = [match.group(1) if match else \"\" for match in matches]\n # Reward 1 if the content is the same as the ground truth, 0 otherwise\n return [1.0 if c == gt else 0.0 for c, gt in zip(contents, ground_truth)]\n```\n\nYou can test this function as follows:", "source_file": "trl/grpo_trainer.md", "section_heading": "Example 3: Reward completions based on a reference", "char_start": 26505, "char_end": 27473, "token_estimate": 242, "prev_chunk_id": 149, "next_chunk_id": 151, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 151, "text": "```python\n>>> prompts = [\"Problem: Solve the equation $2x + 3 = 7$. Solution:\", \"Problem: Solve the equation $3x - 5 = 10$.\"]\n>>> completions = [r\" The solution is \\boxed{2}.\", r\" The solution is \\boxed{6}.\"]\n>>> ground_truth = [\"2\", \"5\"]\n>>> reward_func(prompts=prompts, completions=completions, ground_truth=ground_truth)\n[1.0, 0.0]\n```", "source_file": "trl/grpo_trainer.md", "section_heading": "Example 3: Reward completions based on a reference", "char_start": 27475, "char_end": 27813, "token_estimate": 84, "prev_chunk_id": 150, "next_chunk_id": 152, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 152, "text": "#### Example 4: Multi-task reward functions\n\nBelow is an example of using multiple reward functions in the [GRPOTrainer](/docs/trl/v1.2.0/en/gspo_token#trl.GRPOTrainer). In this example, we define two task-specific reward functions: `math_reward_func` and `coding_reward_func`. The `math_reward_func` rewards math problems based on their correctness, while the `coding_reward_func` rewards coding problems based on whether the solution works.\n\n```python\nfrom datasets import Dataset\nfrom trl import GRPOTrainer", "source_file": "trl/grpo_trainer.md", "section_heading": "Example 4: Multi-task reward functions", "char_start": 27815, "char_end": 28325, "token_estimate": 127, "prev_chunk_id": 151, "next_chunk_id": 153, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 153, "text": "# Define a dataset that contains both math and coding problems\ndataset = Dataset.from_list(\n [\n {\"prompt\": \"What is 2+2?\", \"task\": \"math\"},\n {\"prompt\": \"Write a function that returns the sum of two numbers.\", \"task\": \"code\"},\n {\"prompt\": \"What is 3*4?\", \"task\": \"math\"},\n {\"prompt\": \"Write a function that returns the product of two numbers.\", \"task\": \"code\"},\n ]\n)", "source_file": "trl/grpo_trainer.md", "section_heading": "Define a dataset that contains both math and coding problems", "char_start": 28327, "char_end": 28726, "token_estimate": 99, "prev_chunk_id": 152, "next_chunk_id": 154, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 154, "text": "# Math-specific reward function\ndef math_reward_func(prompts, completions, task, **kwargs):\n rewards = []\n for prompt, completion, t in zip(prompts, completions, task):\n if t == \"math\":\n # Calculate math-specific reward\n correct = check_math_solution(prompt, completion)\n reward = 1.0 if correct else -1.0\n rewards.append(reward)\n else:\n # Return None for non-math tasks\n rewards.append(None)\n return rewards", "source_file": "trl/grpo_trainer.md", "section_heading": "Math-specific reward function", "char_start": 28728, "char_end": 29225, "token_estimate": 124, "prev_chunk_id": 153, "next_chunk_id": 155, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 155, "text": "# Coding-specific reward function\ndef coding_reward_func(prompts, completions, task, **kwargs):\n rewards = []\n for prompt, completion, t in zip(prompts, completions, task):\n if t == \"coding\":\n # Calculate coding-specific reward\n works = test_code_solution(prompt, completion)\n reward = 1.0 if works else -1.0\n rewards.append(reward)\n else:\n # Return None for non-coding tasks\n rewards.append(None)\n return rewards", "source_file": "trl/grpo_trainer.md", "section_heading": "Coding-specific reward function", "char_start": 29227, "char_end": 29729, "token_estimate": 125, "prev_chunk_id": 154, "next_chunk_id": 156, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 156, "text": "# Use both task-specific reward functions\ntrainer = GRPOTrainer(\n model=\"Qwen/Qwen2-0.5B-Instruct\",\n reward_funcs=[math_reward_func, coding_reward_func],\n train_dataset=dataset,\n)\n\ntrainer.train()\n```\n\nIn this example, the `math_reward_func` and `coding_reward_func` are designed to work with a mixed dataset that contains both math and coding problems. The `task` column in the dataset is used to determine which reward function to apply to each problem. If there is no relevant reward function for a sample in the dataset, the reward function will return `None`, and the [GRPOTrainer](/docs/trl/v1.2.0/en/gspo_token#trl.GRPOTrainer) will continue with the valid functions and tasks. This allows the [GRPOTrainer](/docs/trl/v1.2.0/en/gspo_token#trl.GRPOTrainer) to handle multiple reward functions with different applicability.", "source_file": "trl/grpo_trainer.md", "section_heading": "Use both task-specific reward functions", "char_start": 29731, "char_end": 30568, "token_estimate": 209, "prev_chunk_id": 155, "next_chunk_id": 157, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 157, "text": "Note that the [GRPOTrainer](/docs/trl/v1.2.0/en/gspo_token#trl.GRPOTrainer) will ignore the `None` rewards returned by the reward functions and only consider the rewards returned by the relevant functions. This ensures that the model is trained on the relevant tasks and ignores the tasks for which there is no relevant reward function.", "source_file": "trl/grpo_trainer.md", "section_heading": "Use both task-specific reward functions", "char_start": 30570, "char_end": 30906, "token_estimate": 84, "prev_chunk_id": 156, "next_chunk_id": 158, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 158, "text": "#### Example 5: Asynchronous reward functions\n\nCustom reward functions can also be defined as `async def` coroutines. This is useful if your reward depends on slow I/O (for example, calling a remote service). When you pass multiple async reward functions, [GRPOTrainer](/docs/trl/v1.2.0/en/gspo_token#trl.GRPOTrainer) executes them concurrently so their latency overlaps.\n\nBelow is a minimal example of an async reward function that simulates an I/O-bound operation:\n\n```python\nimport asyncio\n\nasync def async_reward_func(prompts, completions, **kwargs):\n # Simulate an I/O-bound call (e.g., HTTP request, database lookup)\n await asyncio.sleep(0.01)\n # Simple toy reward: 1.0 if the completion is non-empty, else 0.0\n return [1.0 if completion else 0.0 for completion in completions]\n```", "source_file": "trl/grpo_trainer.md", "section_heading": "Example 5: Asynchronous reward functions", "char_start": 30908, "char_end": 31707, "token_estimate": 199, "prev_chunk_id": 157, "next_chunk_id": 159, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 159, "text": "#### Example 6: Logging extra columns and metrics\n\nBelow is an example of a reward function that logs extra columns to the completions table and scalar metrics as plots.\n\n```python\nimport re\n\ndef reward_func(completions, ground_truth, log_extra=None, log_metric=None, **kwargs):\n extracted = [re.search(r\"\\\\boxed\\{(.*?)\\}\", c) for c in completions]\n extracted = [m.group(1) if m else None for m in extracted]\n rewards = [1.0 if e == gt else 0.0 for e, gt in zip(extracted, ground_truth)]\n\n if log_extra:\n log_extra(\"golden_answer\", list(ground_truth))\n log_extra(\"extracted_answer\", [e or \"[none]\" for e in extracted])\n\n if log_metric:\n log_metric(\"accuracy\", sum(rewards) / len(rewards))\n\n return rewards\n```", "source_file": "trl/grpo_trainer.md", "section_heading": "Example 6: Logging extra columns and metrics", "char_start": 31709, "char_end": 32457, "token_estimate": 187, "prev_chunk_id": 158, "next_chunk_id": 160, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 160, "text": "#### Passing the reward function to the trainer\n\nTo use your custom reward function, pass it to the [GRPOTrainer](/docs/trl/v1.2.0/en/gspo_token#trl.GRPOTrainer) as follows:\n\n```python\nfrom trl import GRPOTrainer\n\ntrainer = GRPOTrainer(\n reward_funcs=reward_func,\n ...,\n)\n```\n\nYou can pass several reward functions as a list; this list may include both synchronous and asynchronous functions:\n\n```python\nfrom trl import GRPOTrainer\n\ntrainer = GRPOTrainer(\n reward_funcs=[reward_func, async_reward_func1, async_reward_func2],\n ...,\n)\n```\n\nand the reward will be computed as the sum of the rewards from each function, or the weighted sum if `reward_weights` is provided in the config.\n\nNote that [GRPOTrainer](/docs/trl/v1.2.0/en/gspo_token#trl.GRPOTrainer) supports multiple reward functions of different types. See the parameters documentation for more details.", "source_file": "trl/grpo_trainer.md", "section_heading": "Passing the reward function to the trainer", "char_start": 32459, "char_end": 33332, "token_estimate": 218, "prev_chunk_id": 159, "next_chunk_id": 161, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 161, "text": "### Rapid Experimentation for GRPO\n\nRapidFire AI is an open-source experimentation engine that sits on top of TRL and lets you launch multiple GRPO configurations at once, even on a single GPU. Instead of trying configurations sequentially, RapidFire lets you **see all their learning curves earlier, stop underperforming runs, and clone promising ones with new settings in flight** without restarting. For more information, see [RapidFire AI Integration](rapidfire_integration).", "source_file": "trl/grpo_trainer.md", "section_heading": "Rapid Experimentation for GRPO", "char_start": 33334, "char_end": 33813, "token_estimate": 119, "prev_chunk_id": 160, "next_chunk_id": 162, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 162, "text": "## Agent Training\n\nGRPO supports **agent training** through the `tools` argument in [GRPOTrainer](/docs/trl/v1.2.0/en/gspo_token#trl.GRPOTrainer).\nThis parameter expects a list of Python functions (sync or async) that define the tools available to the agent:\n\n```python\nfrom trl import GRPOTrainer\n\ntrainer = GRPOTrainer(\n tools=[tool1, tool2],\n ...,\n)\n```\n\nEach tool must be a standard Python function with **type-hinted arguments and return types**, along with a **Google-style docstring** describing its purpose, arguments, and return value.\nFor more details, see the [Passing tools guide](https://huggingface.co/docs/transformers/en/chat_extras#passing-tools).\n\nExample:", "source_file": "trl/grpo_trainer.md", "section_heading": "Agent Training", "char_start": 33815, "char_end": 34495, "token_estimate": 170, "prev_chunk_id": 161, "next_chunk_id": 163, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 163, "text": "```python\nfrom trl import GRPOTrainer\n\ndef multiply(a: int, b: int) -> int:\n \"\"\"\n Multiplies two integers.\n\n Args:\n a: The first integer.\n b: The second integer.\n\n Returns:\n The product of the two integers.\n \"\"\"\n return a * b\n\nasync def async_add(a: int, b: int) -> int:\n \"\"\"\n Asynchronously adds two integers.\n\n Args:\n a: The first integer.\n b: The second integer.\n\n Returns:\n The sum of the two integers.\n \"\"\"\n return a + b\n\ntrainer = GRPOTrainer(\n tools=[multiply, async_add],\n ...,\n)\n```\n\nYou can also provide tools through `environment_factory`. In this mode, [GRPOTrainer](/docs/trl/v1.2.0/en/gspo_token#trl.GRPOTrainer) creates one environment instance per rollout and exposes the environment's public methods as tools.\n\n> [!IMPORTANT]\n> `environment_factory` requires `transformers>=5.2.0`.", "source_file": "trl/grpo_trainer.md", "section_heading": "Agent Training", "char_start": 34497, "char_end": 35379, "token_estimate": 220, "prev_chunk_id": 162, "next_chunk_id": 164, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 164, "text": "The following is a minimal example of using `environment_factory` to define a simple environment with an `increment` method, which is exposed as a tool to the agent:", "source_file": "trl/grpo_trainer.md", "section_heading": "Agent Training", "char_start": 35381, "char_end": 35546, "token_estimate": 41, "prev_chunk_id": 163, "next_chunk_id": 165, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 165, "text": "```python\nfrom datasets import Dataset\nfrom trl import GRPOConfig, GRPOTrainer\n\ninstructions = [f\"Increment the counter by {i}.\" for i in range(1, 7)]\ndataset = Dataset.from_dict({\"prompt\": [[{\"role\": \"user\", \"content\": instruction}] for instruction in instructions]})\n\ndef reward_func(environments, **kwargs): # dummy reward: the reward is the current value of the counter\n return [environment.counter for environment in environments]\n\nclass IncrementEnv:\n def reset(self, **kwargs) -> str | None: # required; receives sampled row fields as kwargs (e.g., `prompt`)\n self.counter = 0\n return \"Counter reset to 0.\\n\"\n\n def increment(self, step: int) -> int: # the other public methods of the environment are exposed as tools\n \"\"\"\n Increment the internal counter.\n\n Args:\n step: Value to add to the counter.\n\n Returns:\n The updated counter value.\n \"\"\"\n self.counter += step\n return self.counter\n\ntrainer = GRPOTrainer(\n model=\"Qwen/Qwen3-0.6B\",\n args=GRPOConfig(chat_template_kwargs={\"enable_thinking\": False}),\n train_dataset=dataset,\n reward_funcs=reward_func,\n environment_factory=IncrementEnv,\n)\ntrainer.train()\n```", "source_file": "trl/grpo_trainer.md", "section_heading": "Agent Training", "char_start": 35548, "char_end": 36777, "token_estimate": 307, "prev_chunk_id": 164, "next_chunk_id": 166, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 166, "text": "`reset` can return either `None` or a string. In GRPO, when it returns a string, that string is appended to the last user message before generation.", "source_file": "trl/grpo_trainer.md", "section_heading": "Agent Training", "char_start": 36779, "char_end": 36927, "token_estimate": 37, "prev_chunk_id": 165, "next_chunk_id": 167, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 167, "text": "### Multimodal Tool Responses\n\nTools can return images alongside text by returning a list of content blocks. This is useful for VLM agent training where the tool provides visual feedback (e.g., screenshots, plots, camera captures).\n\n```python\nfrom PIL import Image\n\ndef take_screenshot() -> list:\n \"\"\"\n Takes a screenshot of the current screen.\n\n Returns:\n The screenshot image with a description.\n \"\"\"\n img = Image.open(\"screenshot.png\")\n return [{\"type\": \"image\", \"image\": img}, {\"type\": \"text\", \"text\": \"Here is the screenshot.\"}]\n```\n\nThe returned images are automatically injected into the conversation and passed to the VLM for subsequent generation turns.", "source_file": "trl/grpo_trainer.md", "section_heading": "Multimodal Tool Responses", "char_start": 36929, "char_end": 37616, "token_estimate": 171, "prev_chunk_id": 166, "next_chunk_id": 168, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 168, "text": "### Supported Models\n\nTested with:\n\n- [**Gemma4**](https://huggingface.co/collections/google/gemma-4) \u2014 e.g., `google/gemma-4-E2B-it`\n- **GLM-4-MoE** ([4.5](https://huggingface.co/collections/zai-org/glm-45), [4.6](https://huggingface.co/collections/zai-org/glm-46) or [4.7](https://huggingface.co/collections/zai-org/glm-47)) \u2014 e.g., `zai-org/GLM-4.7`\n- [**GPT-OSS**](https://huggingface.co/collections/openai/gpt-oss) \u2014 e.g., `openai/gpt-oss-20b`\n- [**Llama 3.1**](https://huggingface.co/collections/meta-llama/llama-31) \u2014 e.g., `meta-llama/Llama-3.1-8B-Instruct`\n- [**Llama 3.2**](https://huggingface.co/collections/meta-llama/llama-32) \u2014 e.g., `meta-llama/Llama-3.2-3B-Instruct`\n- [**Qwen3**](https://huggingface.co/collections/Qwen/qwen3) \u2014 e.g., `Qwen/Qwen3-0.6B`\n- [**Qwen3-VL**](https://huggingface.co/collections/Qwen/qwen3-vl) \u2014 e.g., `Qwen/Qwen3-VL-2B-Instruct`\n- [**Qwen3.5**](https://huggingface.co/collections/Qwen/qwen35) \u2014 e.g., `Qwen/Qwen3.5-2B`", "source_file": "trl/grpo_trainer.md", "section_heading": "Supported Models", "char_start": 37618, "char_end": 38580, "token_estimate": 240, "prev_chunk_id": 167, "next_chunk_id": 169, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 169, "text": "> [!TIP]\n> Compatibility with all LLMs is not guaranteed. If you believe a model should be supported, feel free to open an issue on GitHub \u2014 or better yet, submit a pull request with the required changes.", "source_file": "trl/grpo_trainer.md", "section_heading": "Supported Models", "char_start": 38582, "char_end": 38786, "token_estimate": 51, "prev_chunk_id": 168, "next_chunk_id": 170, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 170, "text": "### Quick Start\n\nUse [grpo\\_agent.py](https://github.com/huggingface/trl/blob/main/examples/scripts/grpo_agent.py) to fine-tune a LLM for agentic workflows.\n\n```bash\naccelerate launch \\\n --config_file=examples/accelerate_configs/deepspeed_zero3.yaml \\\n examples/scripts/grpo_agent.py \\\n --model_name_or_path Qwen/Qwen3-0.6B\n ...\n```", "source_file": "trl/grpo_trainer.md", "section_heading": "Quick Start", "char_start": 38788, "char_end": 39124, "token_estimate": 84, "prev_chunk_id": 169, "next_chunk_id": 171, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 171, "text": "## Vision-Language Model (VLM) Training\n\nGRPO supports training Vision-Language Models (VLMs) on multimodal datasets containing both text and images.", "source_file": "trl/grpo_trainer.md", "section_heading": "Vision-Language Model (VLM) Training", "char_start": 39126, "char_end": 39275, "token_estimate": 37, "prev_chunk_id": 170, "next_chunk_id": 172, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 172, "text": "### Supported Models\n\nTested with:\n\n- **Gemma3** \u2014 e.g., `google/gemma-3-4b-it`\n- **LLaVA-NeXT** \u2014 e.g., `llava-hf/llava-v1.6-mistral-7b-hf`\n- **Qwen2-VL** \u2014 e.g., `Qwen/Qwen2-VL-2B-Instruct`\n- **Qwen2.5-VL** \u2014 e.g., `Qwen/Qwen2.5-VL-3B-Instruct`\n- **SmolVLM2** \u2014 e.g., `HuggingFaceTB/SmolVLM2-2.2B-Instruct`\n \n> [!TIP]\n> Compatibility with all VLMs is not guaranteed. If you believe a model should be supported, feel free to open an issue on GitHub \u2014 or better yet, submit a pull request with the required changes.", "source_file": "trl/grpo_trainer.md", "section_heading": "Supported Models", "char_start": 39277, "char_end": 39793, "token_estimate": 129, "prev_chunk_id": 171, "next_chunk_id": 173, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 173, "text": "### Quick Start\n\nUse [grpo\\_vlm.py](https://github.com/huggingface/trl/blob/main/examples/scripts/grpo_vlm.py) to fine-tune a VLM. Example command for training on [`lmms-lab/multimodal-open-r1-8k-verified`](https://huggingface.co/datasets/lmms-lab/multimodal-open-r1-8k-verified):\n\n```bash\naccelerate launch \\\n --config_file=examples/accelerate_configs/deepspeed_zero3.yaml \\\n examples/scripts/grpo_vlm.py \\\n --model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \\\n --output_dir grpo-Qwen2.5-VL-3B-Instruct \\\n --learning_rate 1e-5 \\\n --dtype bfloat16 \\\n --max_completion_length 1024 \\\n --use_vllm \\\n --vllm_mode colocate \\\n --use_peft \\\n --lora_target_modules \"q_proj\", \"v_proj\" \\\n --log_completions\n```", "source_file": "trl/grpo_trainer.md", "section_heading": "Quick Start", "char_start": 39795, "char_end": 40505, "token_estimate": 177, "prev_chunk_id": 172, "next_chunk_id": 174, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 174, "text": "### Configuration Tips\n\n- Use LoRA on vision-language projection layers\n- Enable 4-bit quantization to reduce memory usage\n- VLMs are memory-intensive \u2014 start with smaller batch sizes\n- Most models are compatible with vLLM (`server` and `colocate` modes)", "source_file": "trl/grpo_trainer.md", "section_heading": "Configuration Tips", "char_start": 40507, "char_end": 40761, "token_estimate": 63, "prev_chunk_id": 173, "next_chunk_id": 175, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 175, "text": "### Dataset Format\n\nEach training sample should include:\n\n- `prompt`: Text formatted via the processor's chat template\n- `image`/`images`: PIL Image or list of PIL Images\n\nThe trainer automatically handles image-to-tensor conversion via the model\u2019s image processor.", "source_file": "trl/grpo_trainer.md", "section_heading": "Dataset Format", "char_start": 40763, "char_end": 41028, "token_estimate": 66, "prev_chunk_id": 174, "next_chunk_id": 176, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 176, "text": "## GRPOTrainer[[trl.GRPOTrainer]]", "source_file": "trl/grpo_trainer.md", "section_heading": "GRPOTrainer[[trl.GRPOTrainer]]", "char_start": 41030, "char_end": 41063, "token_estimate": 8, "prev_chunk_id": 175, "next_chunk_id": 177, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 177, "text": "#### trl.GRPOTrainer[[trl.GRPOTrainer]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/trainer/grpo_trainer.py#L133)\n\nTrainer for the Group Relative Policy Optimization (GRPO) method. This algorithm was initially proposed in the\npaper [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language\nModels](https://huggingface.co/papers/2402.03300).\n\nExample:\n\n```python\nfrom trl import GRPOTrainer\nfrom trl.rewards import accuracy_reward\nfrom datasets import load_dataset\n\ndataset = load_dataset(\"trl-lib/DeepMath-103K\", split=\"train\")\n\ntrainer = GRPOTrainer(\n model=\"Qwen/Qwen2.5-0.5B-Instruct\",\n reward_funcs=accuracy_reward,\n train_dataset=dataset,\n)\ntrainer.train()\n```", "source_file": "trl/grpo_trainer.md", "section_heading": "trl.GRPOTrainer[[trl.GRPOTrainer]]", "char_start": 41065, "char_end": 41775, "token_estimate": 177, "prev_chunk_id": 176, "next_chunk_id": 178, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 178, "text": "traintrl.GRPOTrainer.trainhttps://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L1323[{\"name\": \"resume_from_checkpoint\", \"val\": \": str | bool | None = None\"}, {\"name\": \"trial\", \"val\": \": optuna.Trial | dict[str, Any] | None = None\"}, {\"name\": \"ignore_keys_for_eval\", \"val\": \": list[str] | None = None\"}]- **resume_from_checkpoint** (`str` or `bool`, *optional*) --\n If a `str`, local path to a saved checkpoint as saved by a previous instance of `Trainer`. If a\n `bool` and equals `True`, load the last checkpoint in *args.output_dir* as saved by a previous instance\n of `Trainer`. If present, training will resume from the model/optimizer/scheduler states loaded here.\n- **trial** (`optuna.Trial` or `dict[str, Any]`, *optional*) --\n The trial run or the hyperparameter dictionary for hyperparameter search.\n- **ignore_keys_for_eval** (`list[str]`, *optional*) --\n A list of keys in the output of your model (if it is a dictionary) that should be ignored when\n gathering predictions for evaluation during the training.0`~trainer_utils.TrainOutput`Object containing the global step count, training loss, and metrics.", "source_file": "trl/grpo_trainer.md", "section_heading": "trl.GRPOTrainer[[trl.GRPOTrainer]]", "char_start": 41777, "char_end": 42916, "token_estimate": 284, "prev_chunk_id": 177, "next_chunk_id": 179, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 179, "text": "Main training entry point.\n\n**Parameters:**\n\nmodel (`str` or [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) or `PeftModel`) : Model to be trained. Can be either: - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a path to a *directory* containing model weights saved using [save_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.save_pretrained), e.g., `'./my_model_directory/'`. The model is loaded using `.from_pretrained` (where `` is derived from the model config) with the keyword arguments in `args.model_init_kwargs`. - A [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) object. Only causal language models are supported. - A `PeftModel` object. Only causal language models are supported.", "source_file": "trl/grpo_trainer.md", "section_heading": "trl.GRPOTrainer[[trl.GRPOTrainer]]", "char_start": 42918, "char_end": 43869, "token_estimate": 237, "prev_chunk_id": 178, "next_chunk_id": 180, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 180, "text": "reward_funcs (`RewardFunc | list[RewardFunc]`) : Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward functions with the prompts and completions and sum the rewards. Can be either: - A single reward function, such as: - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a path to a *directory* containing model weights saved using [save_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.save_pretrained), e.g., `'./my_model_directory/'`. The model is loaded using [from_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/model_doc/auto#transformers.AutoModelForSequenceClassification.from_pretrained) with `num_labels=1` and the keyword arguments in `args.model_init_kwargs`. - A [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) object: Only sequence classification models are supported. - A custom reward function: The function is provided with the prompts and the generated completions, plus any additional columns in the dataset. It should return a list of rewards. Custom reward functions can be either synchronous or asynchronous and can also return `None` when the reward is not applicable to those samples. This is useful for multi-task training where different reward functions apply to different types of samples. When a reward function returns `None` for a sample, that reward function is excluded from the reward calculation for that sample. For more details, see [Using a custom reward function](#using-a-custom-reward-function). The trainer's state is also passed to the reward function. The trainer's state is an instance of [TrainerState](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/callback#transformers.TrainerState) and can be accessed by accessing the `trainer_state` argument to the reward function's signature. - A list of reward functions, where each item can independently be any of the above types. Mixing different types within the list (e.g., a string model ID and a custom reward function) is allowed.", "source_file": "trl/grpo_trainer.md", "section_heading": "trl.GRPOTrainer[[trl.GRPOTrainer]]", "char_start": 43871, "char_end": 46058, "token_estimate": 546, "prev_chunk_id": 179, "next_chunk_id": 181, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 181, "text": "args ([GRPOConfig](/docs/trl/v1.2.0/en/grpo_trainer#trl.GRPOConfig), *optional*) : Configuration for this trainer. If `None`, a default configuration is used.\n\ntrain_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) or [IterableDataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset)) : Dataset to use for training. It must include a column `\"prompt\"`. Any additional columns in the dataset is ignored. The format of the samples can be either: - [Standard](dataset_formats#standard): Each sample contains plain text. - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role and content).", "source_file": "trl/grpo_trainer.md", "section_heading": "trl.GRPOTrainer[[trl.GRPOTrainer]]", "char_start": 46060, "char_end": 46818, "token_estimate": 189, "prev_chunk_id": 180, "next_chunk_id": 182, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 182, "text": "eval_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset), [IterableDataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) or `dict[str, Dataset | IterableDataset]`) : Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.", "source_file": "trl/grpo_trainer.md", "section_heading": "trl.GRPOTrainer[[trl.GRPOTrainer]]", "char_start": 46820, "char_end": 47193, "token_estimate": 93, "prev_chunk_id": 181, "next_chunk_id": 183, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 183, "text": "processing_class ([PreTrainedTokenizerBase](https://huggingface.co/docs/transformers/v5.5.4/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase), [ProcessorMixin](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/processors#transformers.ProcessorMixin), *optional*) : Processing class used to process the data. The padding side must be set to \"left\". If `None`, the processing class is loaded from the model's name with [from_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/model_doc/auto#transformers.AutoProcessor.from_pretrained). A padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token, `tokenizer.eos_token` will be used as the default.", "source_file": "trl/grpo_trainer.md", "section_heading": "trl.GRPOTrainer[[trl.GRPOTrainer]]", "char_start": 47195, "char_end": 47930, "token_estimate": 183, "prev_chunk_id": 182, "next_chunk_id": 184, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 184, "text": "reward_processing_classes ([PreTrainedTokenizerBase](https://huggingface.co/docs/transformers/v5.5.4/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase) or `list[PreTrainedTokenizerBase]`, *optional*) : Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either: - A single processing class: Used when `reward_funcs` contains only one reward function. - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`. If set to `None`, or if an element of the list corresponding to a [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) is `None`, the tokenizer for the model is automatically loaded using [from_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/model_doc/auto#transformers.AutoTokenizer.from_pretrained). For elements in `reward_funcs` that are custom reward functions (not [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel)), the corresponding entries in `reward_processing_classes` are ignored.", "source_file": "trl/grpo_trainer.md", "section_heading": "trl.GRPOTrainer[[trl.GRPOTrainer]]", "char_start": 47932, "char_end": 49090, "token_estimate": 289, "prev_chunk_id": 183, "next_chunk_id": 185, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 185, "text": "callbacks (list of [TrainerCallback](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/callback#transformers.TrainerCallback), *optional*) : List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed in [here](https://huggingface.co/docs/transformers/main_classes/callback). If you want to remove one of the default callbacks used, use the [remove_callback](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer.remove_callback) method.\n\noptimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`) : A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your model and a scheduler given by [get_linear_schedule_with_warmup](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/optimizer_schedules#transformers.get_linear_schedule_with_warmup) controlled by `args`.", "source_file": "trl/grpo_trainer.md", "section_heading": "trl.GRPOTrainer[[trl.GRPOTrainer]]", "char_start": 49092, "char_end": 50089, "token_estimate": 249, "prev_chunk_id": 184, "next_chunk_id": 186, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 186, "text": "peft_config (`PeftConfig`, *optional*) : PEFT configuration used to wrap the model. If `None`, the model is not wrapped.\n\ntools (list of `Callable`, *optional*) : A list of callable tool functions (sync or async) that the model can invoke during generation. Each tool should be a standard Python function with properly type-hinted arguments and return values, and a Google-style docstring describing its purpose, arguments, and return value. For more details, see: https://huggingface.co/docs/transformers/en/chat_extras#passing-tools. The model uses the function's name, type hints, and docstring to determine how to call it. Ensure that the model's chat template supports tool use and that it has been fine-tuned for tool calling.", "source_file": "trl/grpo_trainer.md", "section_heading": "trl.GRPOTrainer[[trl.GRPOTrainer]]", "char_start": 50091, "char_end": 50823, "token_estimate": 183, "prev_chunk_id": 185, "next_chunk_id": 187, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 187, "text": "rollout_func (`RolloutFunc`, *optional*) : Function to use for generating completions. It receives the list of prompts allocated to the current process and the trainer instance. It must return a dict with `\"prompt_ids\"`, `\"completion_ids\"`, and `\"logprobs\"` fields, and can optionally return `\"logprob_token_ids\"` (same shape as `\"logprobs\"`). Any other fields are forwarded to the reward functions. The function receives the raw per-process prompt slice with no duplication; it is responsible for returning the correct number of completions per prompt (see `num_generations` / `num_generations_eval` on the trainer). This feature is experimental and may change or be removed at any time without prior notice.", "source_file": "trl/grpo_trainer.md", "section_heading": "trl.GRPOTrainer[[trl.GRPOTrainer]]", "char_start": 50825, "char_end": 51534, "token_estimate": 177, "prev_chunk_id": 186, "next_chunk_id": 188, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 188, "text": "environment_factory (`EnvironmentFactory`, *optional*) : A callable that creates and returns an environment instance. The environment class should define methods that can be invoked as tools during generation. Each method should comply with the same requirements as the `tools` described above. If `environment_factory` is provided, an instance of the environment is created for each generation in the batch, allowing for parallel and independent interactions. The environment must also implement a callable `reset` method that can be used to reset state between generations. The `reset` method should return either `None` or a string: when it returns a string, that string is appended to the last user message before generation. This feature is experimental and may change or be removed at any time without prior notice.\n\n**Returns:**\n\n``~trainer_utils.TrainOutput``\n\nObject containing the global step count, training loss, and metrics.", "source_file": "trl/grpo_trainer.md", "section_heading": "trl.GRPOTrainer[[trl.GRPOTrainer]]", "char_start": 51536, "char_end": 52473, "token_estimate": 234, "prev_chunk_id": 187, "next_chunk_id": 189, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 189, "text": "#### save_model[[trl.GRPOTrainer.save_model]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L3746)\n\nWill save the model, so you can reload it using `from_pretrained()`.\n\nWill only save from the main process.", "source_file": "trl/grpo_trainer.md", "section_heading": "save_model[[trl.GRPOTrainer.save_model]]", "char_start": 52474, "char_end": 52716, "token_estimate": 60, "prev_chunk_id": 188, "next_chunk_id": 190, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 190, "text": "#### push_to_hub[[trl.GRPOTrainer.push_to_hub]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L3993)\n\nUpload `self.model` and `self.processing_class` to the \ud83e\udd17 model hub on the repo `self.args.hub_model_id`.\n\n**Parameters:**\n\ncommit_message (`str`, *optional*, defaults to `\"End of training\"`) : Message to commit while pushing.\n\nblocking (`bool`, *optional*, defaults to `True`) : Whether the function should return only when the `git push` has finished.\n\ntoken (`str`, *optional*, defaults to `None`) : Token with write permission to overwrite Trainer's original args.\n\nrevision (`str`, *optional*) : The git revision to commit from. Defaults to the head of the \"main\" branch.\n\nkwargs (`dict[str, Any]`, *optional*) : Additional keyword arguments passed along to `~Trainer.create_model_card`.\n\n**Returns:**\n\nThe URL of the repository where the model was pushed if `blocking=False`, or a `Future` object tracking the\nprogress of the commit if `blocking=True`.", "source_file": "trl/grpo_trainer.md", "section_heading": "push_to_hub[[trl.GRPOTrainer.push_to_hub]]", "char_start": 52717, "char_end": 53711, "token_estimate": 248, "prev_chunk_id": 189, "next_chunk_id": 191, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 191, "text": "## GRPOConfig[[trl.GRPOConfig]]", "source_file": "trl/grpo_trainer.md", "section_heading": "GRPOConfig[[trl.GRPOConfig]]", "char_start": 53713, "char_end": 53744, "token_estimate": 7, "prev_chunk_id": 190, "next_chunk_id": 192, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 192, "text": "#### trl.GRPOConfig[[trl.GRPOConfig]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/trainer/grpo_config.py#L23)\n\nConfiguration class for the [GRPOTrainer](/docs/trl/v1.2.0/en/gspo_token#trl.GRPOTrainer).\n\nThis class includes only the parameters that are specific to GRPO training. For a full list of training arguments,\nplease refer to the [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments) documentation. Note that default values in this class may\ndiffer from those in [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments).\n\nUsing [HfArgumentParser](https://huggingface.co/docs/transformers/v5.5.4/en/internal/trainer_utils#transformers.HfArgumentParser) we can turn this class into\n[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the\ncommand line.", "source_file": "trl/grpo_trainer.md", "section_heading": "trl.GRPOConfig[[trl.GRPOConfig]]", "char_start": 53746, "char_end": 54711, "token_estimate": 241, "prev_chunk_id": 191, "next_chunk_id": 193, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 193, "text": "> [!NOTE]\n> These parameters have default values different from [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments):\n> - `logging_steps`: Defaults to `10` instead of `500`.\n> - `gradient_checkpointing`: Defaults to `True` instead of `False`.\n> - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.\n> - `learning_rate`: Defaults to `1e-6` instead of `5e-5`.", "source_file": "trl/grpo_trainer.md", "section_heading": "trl.GRPOConfig[[trl.GRPOConfig]]", "char_start": 54713, "char_end": 55158, "token_estimate": 111, "prev_chunk_id": 192, "next_chunk_id": null, "url": "https://huggingface.co/docs/trl/grpo_trainer", "doc_title": "GRPO Trainer" }, { "chunk_id": 194, "text": "# PPO Trainer\n\n[![model badge](https://img.shields.io/badge/All_models-PPO-blue)](https://huggingface.co/models?other=ppo,trl)\n\nTRL supports training LLMs with [Proximal Policy Optimization (PPO)](https://huggingface.co/papers/1707.06347).\n\nReferences:\n\n- [Fine-Tuning Language Models from Human Preferences](https://github.com/openai/lm-human-preferences)\n- [Learning to Summarize from Human Feedback](https://github.com/openai/summarize-from-feedback)\n- [The N Implementation Details of RLHF with PPO](https://huggingface.co/blog/the_n_implementation_details_of_rlhf_with_ppo)\n- [The N+ Implementation Details of RLHF with PPO: A Case Study on TL;DR Summarization](https://huggingface.co/papers/2403.17031)", "source_file": "trl/ppo_trainer.md", "section_heading": "PPO Trainer", "char_start": 0, "char_end": 708, "token_estimate": 177, "prev_chunk_id": null, "next_chunk_id": 195, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 195, "text": "## Get started\n\nTo just run a PPO script to make sure the trainer can run, you can run the following command to train a PPO model with a dummy reward model.\n\n```bash\npython examples/scripts/ppo/ppo.py \\\n --dataset_name trl-internal-testing/descriptiveness-sentiment-trl-style \\\n --dataset_train_split descriptiveness \\\n --learning_rate 3e-6 \\\n --num_ppo_epochs 1 \\\n --num_mini_batches 1 \\\n --output_dir models/minimal/ppo \\\n --per_device_train_batch_size 64 \\\n --gradient_accumulation_steps 1 \\\n --total_episodes 10000 \\\n --model_name_or_path EleutherAI/pythia-1b-deduped \\\n --sft_model_path EleutherAI/pythia-1b-deduped \\\n --reward_model_path EleutherAI/pythia-1b-deduped \\\n --missing_eos_penalty 1.0\n```", "source_file": "trl/ppo_trainer.md", "section_heading": "Get started", "char_start": 710, "char_end": 1454, "token_estimate": 186, "prev_chunk_id": 194, "next_chunk_id": 196, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 196, "text": "## Explanation of the logged metrics\n\nThe logged metrics are as follows. Here is an example [tracked run at Weights and Biases](https://wandb.ai/huggingface/trl/runs/dd2o3g35)", "source_file": "trl/ppo_trainer.md", "section_heading": "Explanation of the logged metrics", "char_start": 1456, "char_end": 1631, "token_estimate": 43, "prev_chunk_id": 195, "next_chunk_id": 197, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 197, "text": "- `eps`: Tracks the number of episodes per second.\n- `objective/kl`: The mean Kullback-Leibler (KL) divergence between the current policy and reference policy.\n- `objective/entropy`: The mean entropy of the policy, indicating the randomness of the actions chosen by the policy.\n- `objective/non_score_reward`: The mean reward from non-score-related sources, basically `beta * kl.sum(1)`, where `beta` is the KL penalty coefficient and `kl` is the per-token KL divergence.\n- `objective/rlhf_reward`: The mean RLHF reward, which is `score - non_score_reward`.\n- `objective/scores`: The mean scores returned by the reward model / environment.\n- `policy/approxkl_avg`: The average approximate KL divergence between consecutive PPO policies. Note that this is not the same as `objective/kl`.\n- `policy/clipfrac_avg`: The average fraction of policy updates that are clipped, indicating how often the policy updates are constrained to prevent large changes.\n- `loss/policy_avg`: The average policy loss, indicating how well the policy is performing.\n- `loss/value_avg`: The average value loss, indicating the difference between the predicted value and the actual reward.\n- `val/clipfrac_avg`: The average fraction of value function updates that are clipped, similar to policy/clipfrac_avg but for the value function.\n- `policy/entropy_avg`: The average entropy of the policy during training, indicating how diverse the policy's actions are.\n- `val/ratio`: The mean ratio of the current policy probability to the old policy probability, providing a measure of how much the policy has changed.\n- `val/ratio_var`: The variance of the `val/ratio`, indicating the variability in policy changes.\n- `val/num_eos_tokens`: The number of end-of-sequence (EOS) tokens generated, which can indicate the number of complete responses.\n- `lr`: lr: The current learning rate used by the optimizer.\n- `episode`: episode: The current episode count in the training process.", "source_file": "trl/ppo_trainer.md", "section_heading": "Explanation of the logged metrics", "char_start": 1633, "char_end": 3580, "token_estimate": 486, "prev_chunk_id": 196, "next_chunk_id": 198, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 198, "text": "## Cookbook", "source_file": "trl/ppo_trainer.md", "section_heading": "Cookbook", "char_start": 3582, "char_end": 3593, "token_estimate": 2, "prev_chunk_id": 197, "next_chunk_id": 199, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 199, "text": "- Debugging TIP: `objective/rlhf_reward`: this is the ultimate objective of the RLHF training. If training works as intended, this metric should keep going up.\n- Debugging TIP: `val/ratio`: this number should float around 1.0, and it gets clipped by `--cliprange 0.2` with PPO's surrogate loss. So if this `ratio` is too high like 2.0 or 1000.0 or too small like 0.1, it means the updates between consecutive policies are too drastic. You should try understand why this is happening and try to fix it.\n- Memory TIP: If you are running out of memory, you can try to reduce the `--per_device_train_batch_size` or increase the `--gradient_accumulation_steps` to reduce the memory footprint.\n- Memory TIP: If you have multiple GPUs, you can also run training with DeepSpeed stage 3 to reduce the memory footprint `accelerate launch --config_file examples/accelerate_configs/deepspeed_zero3.yaml`.\n- Usage TIP: We recommend to use the \"EOS trick\" via `--missing_eos_penalty`, which subtracts a static scalar penalty from the score of completions that do not end with an EOS token. This can help the model learn to generate more coherent completions.", "source_file": "trl/ppo_trainer.md", "section_heading": "Cookbook", "char_start": 3595, "char_end": 4739, "token_estimate": 286, "prev_chunk_id": 198, "next_chunk_id": 200, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 200, "text": "## What is my model doing exactly?\n\nTo help you understand what your model is doing, we periodically log some sample completions from the model. Here is an example of a completion. In an example [tracked run at Weights and Biases](https://wandb.ai/huggingface/trl/runs/dd2o3g35), it looks like the following, allowing you to see the model's response at different stages of training. By default we generate `--num_sample_generations 10` during training, but you can customize the number of generations.\n\n![ppov2_completions](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/ppov2_completions.gif)\n\nIn the logs the sampled generations look like", "source_file": "trl/ppo_trainer.md", "section_heading": "What is my model doing exactly?", "char_start": 4741, "char_end": 5408, "token_estimate": 166, "prev_chunk_id": 199, "next_chunk_id": 201, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 201, "text": "```txt\n\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\n\u2503 query \u2503 model response \u2503 score \u2503\n\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\n\u2502 SUBREDDIT: r/AskReddit \u2502 I'm in love with a friend, and \u2502 3.921875 \u2502\n\u2502 \u2502 I don't know how to get rid of \u2502 \u2502\n\u2502 TITLE: How do you get someone \u2502 those feelings. I'm \u2502 \u2502\n\u2502 out of your head? \u2502 desperate.[PAD][P\u2026 \u2502 \u2502\n\u2502 \u2502 \u2502 \u2502\n\u2502 POST: Hi, \u2502 \u2502 \u2502\n\u2502 I'm 22, and I have been with my \u2502 \u2502 \u2502\n\u2502 girlfriend for 5 years now. We \u2502 \u2502 \u2502\n\u2502 recently moved together. We've \u2502 \u2502 \u2502\n\u2502 always loved each other \u2502 \u2502 \u2502\n\u2502 intensely. \u2502 \u2502 \u2502\n\u2502 \u2502 \u2502 \u2502\n\u2502 Problem, I recently started to \u2502 \u2502 \u2502\n\u2502 have feelings for an other \u2502 \u2502 \u2502\n\u2502 person (a friend). This person \u2502 \u2502 \u2502\n\u2502 has had a boyfriend for now 3 \u2502 \u2502 \u2502\n\u2502 years, and has absolutely no \u2502 \u2502 \u2502\n\u2502 ideas. Those feelings were so \u2502 \u2502 \u2502\n\u2502 strong, it was hard to hide \u2502 \u2502 \u2502\n\u2502 them. After 2 months of me \u2502 \u2502 \u2502\n\u2502 being distant and really sad, \u2502 \u2502 \u2502\n\u2502 my girlfriend forced me to say \u2502 \u2502 \u2502\n\u2502 what was bothering me. I'm not \u2502 \u2502 \u2502\n\u2502 a good liar, and now she knows. \u2502 \u2502 \u2502\n\u2502 \u2502 \u2502 \u2502\n\u2502 We decided to give us a week \u2502 \u2502 \u2502\n\u2502 alone, I went to my parents. \u2502 \u2502 \u2502\n\u2502 \u2502 \u2502 \u2502\n\u2502 Now, I'm completely lost. I \u2502 \u2502 \u2502\n\u2502 keep on thinking about this \u2502 \u2502 \u2502\n\u2502 person, and I hate that. I \u2502 \u2502 \u2502\n\u2502 would like for those feelings \u2502 \u2502 \u2502\n\u2502 to go away, to leave me alone. \u2502 \u2502 \u2502\n\u2502 But I can't. \u2502 \u2502 \u2502\n\u2502 \u2502 \u2502 \u2502\n\u2502 What do I do? It's been 3 \u2502 \u2502 \u2502\n\u2502 months now, and I'm just \u2502 \u2502 \u2502\n\u2502 desperate. \u2502 \u2502 \u2502\n\u2502 \u2502 \u2502 \u2502\n\u2502 TL;DR: \u2502 \u2502 \u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\u2502 SUBREDDIT: r/pettyrevenge \u2502 My mom woke me up with a loud \u2502 6.84375 \u2502\n\u2502 \u2502 TV. I blasted Gangnam Style on \u2502 \u2502\n\u2502 TITLE: So, my mom woke me up \u2502 repeat, with the bass cranked \u2502 \u2502\n\u2502 with a loud TV. \u2502 up as high as it could \u2502 \u2502\n\u2502 \u2502 go.[PAD][PAD][PAD\u2026 \u2502 \u2502\n\u2502 POST: She was in her living \u2502 \u2502 \u2502\n\u2502 room, watching TV. This was at \u2502 \u2502 \u2502\n\u2502 about 8:30 in the morning, and \u2502 \u2502 \u2502\n\u2502 she was exercising. She turned \u2502 \u2502 \u2502\n\u2502 the TV up extra loud to hear it \u2502 \u2502 \u2502\n\u2502 over her excercycle, and woke \u2502 \u2502 \u2502\n\u2502 me up. I went in there asking \u2502 \u2502 \u2502\n\u2502 for her to turn it down. She \u2502 \u2502 \u2502\n\u2502 said she didn't have to; I \u2502 \u2502 \u2502\n\u2502 explained that I always used \u2502 \u2502 \u2502\n\u2502 headphones so she didn't have \u2502 \u2502 \u2502\n\u2502 to deal with my noise and that \u2502 \u2502 \u2502\n\u2502 she should give me a little \u2502 \u2502 \u2502\n\u2502 more respect, given that I paid \u2502 \u2502 \u2502\n\u2502 rent at the time. \u2502 \u2502 \u2502\n\u2502 \u2502 \u2502 \u2502\n\u2502 She disagreed. I went back to \u2502 \u2502 \u2502\n\u2502 my room, rather pissed off at \u2502 \u2502 \u2502\n\u2502 the lack of equality. I had no \u2502 \u2502 \u2502\n\u2502 lock on my door; but I had a \u2502 \u2502 \u2502\n\u2502 dresser right next to it, so I \u2502 \u2502 \u2502\n\u2502 pulled one of the drawers out \u2502 \u2502 \u2502\n\u2502 enough so that it caused the \u2502 \u2502 \u2502\n\u2502 door to not be openable. Then, \u2502 \u2502 \u2502\n\u2502 I turned my speakers up really \u2502 \u2502 \u2502\n\u2502 loud and blasted Gangnam Style \u2502 \u2502 \u2502\n\u2502 on repeat, with the bass \u2502 \u2502 \u2502\n\u2502 cranked up as high as it could \u2502 \u2502 \u2502\n\u2502 go. \u2502 \u2502 \u2502\n\u2502 \u2502 \u2502 \u2502\n\u2502 If you hate Gangnam Style for \u2502 \u2502 \u2502\n\u2502 being overplayed, you will see \u2502 \u2502 \u2502\n\u2502 why I chose that particular \u2502 \u2502 \u2502\n\u2502 song. I personally don't mind \u2502 \u2502 \u2502\n\u2502 it. But here's the thing about \u2502 \u2502 \u2502\n\u2502 my bass; it vibrates the walls, \u2502 \u2502 \u2502\n\u2502 making one hell of a lot of \u2502 \u2502 \u2502\n\u2502 noise. Needless to say, my mom \u2502 \u2502 \u2502\n\u2502 was not pleased and shut off \u2502 \u2502 \u2502\n\u2502 the internet. But it was oh so \u2502 \u2502 \u2502\n\u2502 worth it. \u2502 \u2502 \u2502\n\u2502 \u2502 \u2502 \u2502\n\u2502 TL;DR: \u2502 \u2502 \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n```", "source_file": "trl/ppo_trainer.md", "section_heading": "What is my model doing exactly?", "char_start": 5410, "char_end": 12927, "token_estimate": 1879, "prev_chunk_id": 200, "next_chunk_id": 202, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 202, "text": "## Implementation details\n\nThis PPO implementation is based on the [The N+ Implementation Details of RLHF with PPO: A Case Study on TL;DR Summarization](https://huggingface.co/papers/2403.17031).", "source_file": "trl/ppo_trainer.md", "section_heading": "Implementation details", "char_start": 12929, "char_end": 13124, "token_estimate": 48, "prev_chunk_id": 201, "next_chunk_id": 203, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 203, "text": "## Benchmark experiments\n\nTo validate the PPO implementation works, we ran experiment on the 1B model. Here are the command we used to run the experiment. We take the SFT / RM models directly from [The N+ Implementation Details of RLHF with PPO: A Case Study on TL;DR Summarization](https://huggingface.co/papers/2403.17031).", "source_file": "trl/ppo_trainer.md", "section_heading": "Benchmark experiments", "char_start": 13126, "char_end": 13451, "token_estimate": 81, "prev_chunk_id": 202, "next_chunk_id": 204, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 204, "text": "```shell\naccelerate launch --config_file examples/accelerate_configs/deepspeed_zero2.yaml \\\n examples/scripts/ppo/ppo_tldr.py \\\n --dataset_name trl-lib/tldr \\\n --dataset_test_split validation \\\n --output_dir models/minimal/ppo_tldr \\\n --learning_rate 3e-6 \\\n --per_device_train_batch_size 16 \\\n --gradient_accumulation_steps 4 \\\n --total_episodes 1000000 \\\n --model_name_or_path EleutherAI/pythia-1b-deduped \\\n --sft_model_path cleanrl/EleutherAI_pythia-1b-deduped__sft__tldr \\\n --reward_model_path cleanrl/EleutherAI_pythia-1b-deduped__reward__tldr \\\n --local_rollout_forward_batch_size 16 \\\n --missing_eos_penalty 1.0 \\\n --stop_token eos \\\n --eval_strategy steps \\\n --eval_steps 100\n```\n\nCheckpoints and experiment tracking are available at:\n\n- [\ud83e\udd17 Model checkpoint](https://huggingface.co/trl-lib/ppo_tldr)\n- [\ud83d\udc1d Tracked experiment](https://wandb.ai/huggingface/trl/runs/dd2o3g35)", "source_file": "trl/ppo_trainer.md", "section_heading": "Benchmark experiments", "char_start": 13453, "char_end": 14382, "token_estimate": 232, "prev_chunk_id": 203, "next_chunk_id": 205, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 205, "text": "The PPO checkpoint gets a 64.7% preferred rate vs the 33.0% preference rate of the SFT checkpoint (evaluated with GPT-4o mini as a judge). This is a good sign that the PPO training is working as intended.\n\nMetrics:\n\n![PPO v2](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/ppov2.png)\n\n```bash", "source_file": "trl/ppo_trainer.md", "section_heading": "Benchmark experiments", "char_start": 14384, "char_end": 14703, "token_estimate": 79, "prev_chunk_id": 204, "next_chunk_id": 206, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 206, "text": "# pip install openrlbenchmark==0.2.1a5", "source_file": "trl/ppo_trainer.md", "section_heading": "pip install openrlbenchmark==0.2.1a5", "char_start": 14704, "char_end": 14742, "token_estimate": 9, "prev_chunk_id": 205, "next_chunk_id": 207, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 207, "text": "# see https://github.com/openrlbenchmark/openrlbenchmark#get-started for documentation", "source_file": "trl/ppo_trainer.md", "section_heading": "see https://github.com/openrlbenchmark/openrlbenchmark#get-started for documentation", "char_start": 14743, "char_end": 14829, "token_estimate": 21, "prev_chunk_id": 206, "next_chunk_id": 208, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 208, "text": "# to use it, change `?we=huggingface&wpn=trl` to your own project and `?tag=pr-1540` to your own tag\npython -m openrlbenchmark.rlops_multi_metrics \\\n --filters '?we=huggingface&wpn=trl&xaxis=train/episode&ceik=output_dir&cen=sft_model_path&metrics=train/objective/rlhf_reward&metrics=train/objective/scores&metrics=train/objective/kl&metrics=train/objective/non_score_reward&metrics=train/objective/entropy&metrics=train/policy/approxkl_avg&metrics=train/policy/clipfrac_avg&metrics=train/loss/policy_avg&metrics=train/loss/value_avg&metrics=train/val/clipfrac_avg&metrics=train/policy/entropy_avg&metrics=train/val/ratio&metrics=train/val/ratio_var&metrics=train/val/num_eos_tokens&metrics=train/lr&metrics=train/eps' \\\n \"cleanrl/EleutherAI_pythia-1b-deduped__sft__tldr?tag=pr-1540\" \\\n --env-ids models/minimal/ppo_tldr \\\n --pc.ncols 4 \\\n --pc.ncols-legend 1 \\\n --pc.xlabel \"Episode\" \\\n --output-filename benchmark/trl/pr-1540/ppo \\\n --scan-history\n```", "source_file": "trl/ppo_trainer.md", "section_heading": "to use it, change `?we=huggingface&wpn=trl` to your own project and `?tag=pr-1540` to your own tag", "char_start": 14830, "char_end": 15811, "token_estimate": 245, "prev_chunk_id": 207, "next_chunk_id": 209, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 209, "text": "## PPOTrainer[[trl.experimental.ppo.PPOTrainer]]", "source_file": "trl/ppo_trainer.md", "section_heading": "PPOTrainer[[trl.experimental.ppo.PPOTrainer]]", "char_start": 15813, "char_end": 15861, "token_estimate": 12, "prev_chunk_id": 208, "next_chunk_id": 210, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 210, "text": "#### trl.experimental.ppo.PPOTrainer[[trl.experimental.ppo.PPOTrainer]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/ppo_trainer.py#L305)\n\nTrainer for Proximal Policy Optimization (PPO).\n\nFor details on PPO, see the paper: [Proximal Policy Optimization\nAlgorithms](https://huggingface.co/papers/1707.06347).\n\ntraintrl.experimental.ppo.PPOTrainer.trainhttps://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/ppo_trainer.py#L606[]\n\n**Parameters:**\n\nargs ([experimental.ppo.PPOConfig](/docs/trl/v1.2.0/en/ppo_trainer#trl.experimental.ppo.PPOConfig)) : Training arguments.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.PPOTrainer[[trl.experimental.ppo.PPOTrainer]]", "char_start": 15863, "char_end": 16476, "token_estimate": 153, "prev_chunk_id": 209, "next_chunk_id": 211, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 211, "text": "processing_class ([PreTrainedTokenizerBase](https://huggingface.co/docs/transformers/v5.5.4/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase), [BaseImageProcessor](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/image_processor#transformers.BaseImageProcessor), [FeatureExtractionMixin](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/feature_extractor#transformers.FeatureExtractionMixin) or [ProcessorMixin](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/processors#transformers.ProcessorMixin)) : Class to process the data.\n\nmodel (`torch.nn.Module`) : Model to be trained. This is the policy model.\n\nref_model (`torch.nn.Module`, *optional*) : Reference model used to compute the KL divergence. If `None`, a copy of the policy model is created.\n\nreward_model (`torch.nn.Module`) : Reward model used to compute the rewards.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.PPOTrainer[[trl.experimental.ppo.PPOTrainer]]", "char_start": 16478, "char_end": 17372, "token_estimate": 223, "prev_chunk_id": 210, "next_chunk_id": 212, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 212, "text": "train_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset)) : Dataset for training.\n\nvalue_model (`torch.nn.Module`) : Value model used to predict the value of a state.\n\ndata_collator ([DataCollatorWithPadding](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/data_collator#transformers.DataCollatorWithPadding), *optional*) : Data collator to batch and pad samples from the dataset. If `None`, a default data collator is created using the `processing_class`.\n\neval_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) or `dict` of [Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset), *optional*) : Dataset for evaluation.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.PPOTrainer[[trl.experimental.ppo.PPOTrainer]]", "char_start": 17374, "char_end": 18189, "token_estimate": 203, "prev_chunk_id": 211, "next_chunk_id": 213, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 213, "text": "optimizers (`tuple` of `torch.optim.Optimizer` and `torch.optim.lr_scheduler.LambdaLR`, *optional*, defaults to `(None, None)`) : Tuple containing the optimizer and the learning rate scheduler to use for training. If `None`, the optimizer and the learning rate scheduler are created using the [create_optimizer_and_scheduler](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer.create_optimizer_and_scheduler) method.\n\ncallbacks (`list` of [TrainerCallback](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/callback#transformers.TrainerCallback), *optional*) : Callbacks to use during training.\n\npeft_config (`PeftConfig`, *optional*) : PEFT configuration to use PEFT for training. If `None`, PEFT is not used. If provided, the policy `model` will be wrapped with the specified PEFT adapter.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.PPOTrainer[[trl.experimental.ppo.PPOTrainer]]", "char_start": 18191, "char_end": 19038, "token_estimate": 211, "prev_chunk_id": 212, "next_chunk_id": 214, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 214, "text": "#### save_model[[trl.experimental.ppo.PPOTrainer.save_model]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/ppo_trainer.py#L592)", "source_file": "trl/ppo_trainer.md", "section_heading": "save_model[[trl.experimental.ppo.PPOTrainer.save_model]]", "char_start": 19039, "char_end": 19199, "token_estimate": 40, "prev_chunk_id": 213, "next_chunk_id": 215, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 215, "text": "#### push_to_hub[[trl.experimental.ppo.PPOTrainer.push_to_hub]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L3993)\n\nUpload `self.model` and `self.processing_class` to the \ud83e\udd17 model hub on the repo `self.args.hub_model_id`.\n\n**Parameters:**\n\ncommit_message (`str`, *optional*, defaults to `\"End of training\"`) : Message to commit while pushing.\n\nblocking (`bool`, *optional*, defaults to `True`) : Whether the function should return only when the `git push` has finished.\n\ntoken (`str`, *optional*, defaults to `None`) : Token with write permission to overwrite Trainer's original args.\n\nrevision (`str`, *optional*) : The git revision to commit from. Defaults to the head of the \"main\" branch.\n\nkwargs (`dict[str, Any]`, *optional*) : Additional keyword arguments passed along to `~Trainer.create_model_card`.\n\n**Returns:**\n\nThe URL of the repository where the model was pushed if `blocking=False`, or a `Future` object tracking the\nprogress of the commit if `blocking=True`.", "source_file": "trl/ppo_trainer.md", "section_heading": "push_to_hub[[trl.experimental.ppo.PPOTrainer.push_to_hub]]", "char_start": 19200, "char_end": 20210, "token_estimate": 252, "prev_chunk_id": 214, "next_chunk_id": 216, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 216, "text": "## PPOConfig[[trl.experimental.ppo.PPOConfig]]", "source_file": "trl/ppo_trainer.md", "section_heading": "PPOConfig[[trl.experimental.ppo.PPOConfig]]", "char_start": 20212, "char_end": 20258, "token_estimate": 11, "prev_chunk_id": 215, "next_chunk_id": 217, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 217, "text": "#### trl.experimental.ppo.PPOConfig[[trl.experimental.ppo.PPOConfig]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/ppo_config.py#L22)\n\nConfiguration class for the [experimental.ppo.PPOTrainer](/docs/trl/v1.2.0/en/ppo_trainer#trl.experimental.ppo.PPOTrainer).\n\nThis class includes only the parameters that are specific to PPO training. For a full list of training arguments,\nplease refer to the [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments) documentation. Note that default values in this class may\ndiffer from those in [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments).", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.PPOConfig[[trl.experimental.ppo.PPOConfig]]", "char_start": 20260, "char_end": 21014, "token_estimate": 188, "prev_chunk_id": 216, "next_chunk_id": 218, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 218, "text": "Using [HfArgumentParser](https://huggingface.co/docs/transformers/v5.5.4/en/internal/trainer_utils#transformers.HfArgumentParser) we can turn this class into\n[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the\ncommand line.\n\n> [!NOTE]\n> These parameters have default values different from [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments):\n> - `logging_steps`: Defaults to `10` instead of `500`.\n> - `gradient_checkpointing`: Defaults to `True` instead of `False`.\n> - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.\n> - `learning_rate`: Defaults to `3e-6` instead of `5e-5`.\n\n**Parameters:**\n\ndataset_num_proc (`int`, *optional*) : Number of processes to use for processing the dataset.\n\nnum_mini_batches (`int`, *optional*, defaults to `1`) : Number of minibatches to split a batch into.\n\ntotal_episodes (`int`, *optional*) : Total number of episodes in the dataset.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.PPOConfig[[trl.experimental.ppo.PPOConfig]]", "char_start": 21016, "char_end": 22037, "token_estimate": 255, "prev_chunk_id": 217, "next_chunk_id": 219, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 219, "text": "local_rollout_forward_batch_size (`int`, *optional*, defaults to `64`) : Per rank no grad forward pass in the rollout phase.\n\nnum_sample_generations (`int`, *optional*, defaults to `10`) : Number of debugging samples generations (i.e., `generate_completions` calls) throughout training.\n\nresponse_length (`int`, *optional*, defaults to `53`) : Length of the response.\n\nstop_token (`str`, *optional*) : Specifies the stop token to use for text generation. This parameter is mutually exclusive with `stop_token_id`. - `None`: No stop token is applied, unless `stop_token_id` is specified. - `'eos'`: Uses the tokenizer's `eos_token`.\n\nstop_token_id (`int`, *optional*) : Specifies the ID of the stop token to use for text generation. If `None`, no stop token ID is applied, unless `stop_token` is specified. This parameter is mutually exclusive with `stop_token`.\n\ntemperature (`float`, *optional*, defaults to `0.7`) : Sampling temperature.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.PPOConfig[[trl.experimental.ppo.PPOConfig]]", "char_start": 0, "char_end": 940, "token_estimate": 235, "prev_chunk_id": 218, "next_chunk_id": 220, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 220, "text": "missing_eos_penalty (`float`, *optional*) : Penalty applied to the score when the model fails to generate an EOS token. This is useful to encourage to generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be a positive value.\n\nsft_model_path (`str`, *optional*, defaults to `\"EleutherAI/pythia-160m\"`) : Path to the SFT model.\n\nworld_size (`int`, *optional*) : Number of processes (GPUs) to use for the training.\n\nnum_total_batches (`int`, *optional*) : Number of total batches to train.\n\nmicro_batch_size (`int`, *optional*) : Micro batch size across devices (HF's `per_device_train_batch_size` * `world_size`).\n\nlocal_batch_size (`int`, *optional*) : Batch size per GPU (HF's `per_device_train_batch_size` * `gradient_accumulation_steps`).\n\nbatch_size (`int`, *optional*) : Batch size across devices (HF's `per_device_train_batch_size` * `world_size` * `gradient_accumulation_steps`).\n\nlocal_mini_batch_size (`int`, *optional*) : Mini batch size per GPU.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.PPOConfig[[trl.experimental.ppo.PPOConfig]]", "char_start": 22982, "char_end": 23974, "token_estimate": 248, "prev_chunk_id": 219, "next_chunk_id": 221, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 221, "text": "mini_batch_size (`int`, *optional*) : Mini batch size across GPUs.\n\npush_to_hub (`bool`, *optional*, defaults to `False`) : Whether to push the model to the Hub after training.\n\nreward_model_path (`str`, *optional*, defaults to `\"EleutherAI/pythia-160m\"`) : Path to the reward model.\n\nmodel_adapter_name (`str`, *optional*) : Name of the train target PEFT adapter, when using LoRA with multiple adapters.\n\nref_adapter_name (`str`, *optional*) : Name of the reference PEFT adapter, when using LoRA with multiple adapters.\n\nnum_ppo_epochs (`int`, *optional*, defaults to `4`) : Number of epochs to train.\n\nwhiten_rewards (`bool`, *optional*, defaults to `False`) : Whether to whiten the rewards.\n\nkl_coef (`float`, *optional*, defaults to `0.05`) : KL coefficient.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.PPOConfig[[trl.experimental.ppo.PPOConfig]]", "char_start": 23976, "char_end": 24738, "token_estimate": 190, "prev_chunk_id": 220, "next_chunk_id": 222, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 222, "text": "kl_estimator (`Literal[\"k1\", \"k3\"]`, *optional*, defaults to `\"k1\"`) : Which estimator for KL-Divergence to use from [Approximating KL Divergence](http://joschu.net/blog/kl-approx.html). Defaults to \"k1\", a straightforward, unbiased estimator. Can be set to \"k3\", an unbiased estimator with lower variance which \"appears to be a strictly better estimator\". Cannot be set to \"k2\", as it is used for logging purposes.\n\ncliprange (`float`, *optional*, defaults to `0.2`) : Clip range.\n\nvf_coef (`float`, *optional*, defaults to `0.1`) : Value function coefficient.\n\ncliprange_value (`float`, *optional*, defaults to `0.2`) : Clip range for the value function.\n\ngamma (`float`, *optional*, defaults to `1.0`) : Discount factor.\n\nlam (`float`, *optional*, defaults to `0.95`) : Lambda value for GAE.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.PPOConfig[[trl.experimental.ppo.PPOConfig]]", "char_start": 24740, "char_end": 25534, "token_estimate": 198, "prev_chunk_id": 221, "next_chunk_id": 223, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 223, "text": "ds3_gather_for_generation (`bool`, *optional*, defaults to `True`) : This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation, improving generation speed. However, disabling this option allows training models that exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.PPOConfig[[trl.experimental.ppo.PPOConfig]]", "char_start": 25536, "char_end": 25882, "token_estimate": 86, "prev_chunk_id": 222, "next_chunk_id": 224, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 224, "text": "## PreTrainedModelWrapper[[trl.experimental.ppo.PreTrainedModelWrapper]]", "source_file": "trl/ppo_trainer.md", "section_heading": "PreTrainedModelWrapper[[trl.experimental.ppo.PreTrainedModelWrapper]]", "char_start": 25884, "char_end": 25956, "token_estimate": 18, "prev_chunk_id": 223, "next_chunk_id": 225, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 225, "text": "#### trl.experimental.ppo.PreTrainedModelWrapper[[trl.experimental.ppo.PreTrainedModelWrapper]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L52)\n\nWrapper for a [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) implemented as a standard PyTorch `torch.nn.Module`.\n\nThis class provides a compatibility layer that preserves the key attributes and methods of the original\n[PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel), while exposing a uniform interface consistent with PyTorch modules. It enables\nseamless integration of pretrained Transformer models into custom training, evaluation, or inference workflows.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.PreTrainedModelWrapper[[trl.experimental.ppo.PreTrainedModelWrapper]]", "char_start": 25958, "char_end": 26760, "token_estimate": 200, "prev_chunk_id": 224, "next_chunk_id": 226, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 226, "text": "add_and_load_reward_modeling_adaptertrl.experimental.ppo.PreTrainedModelWrapper.add_and_load_reward_modeling_adapterhttps://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L438[{\"name\": \"pretrained_model\", \"val\": \"\"}, {\"name\": \"adapter_model_id\", \"val\": \"\"}, {\"name\": \"adapter_name\", \"val\": \" = 'reward_model_adapter'\"}, {\"name\": \"token\", \"val\": \" = None\"}]\n\nAdd and load a reward modeling adapter. This method can only be used if the model is a `PeftModel` and if you\nhave initialized the model with the `reward_modeling_adapter_id` argument, pointing to the id of the reward\nmodeling adapter. The latest needs also to contain the score head in order to produce the reward.\n\n**Parameters:**\n\npretrained_model ([PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel)) : The model to be wrapped.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.PreTrainedModelWrapper[[trl.experimental.ppo.PreTrainedModelWrapper]]", "char_start": 26762, "char_end": 27653, "token_estimate": 222, "prev_chunk_id": 225, "next_chunk_id": 227, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 227, "text": "parent_class ([PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel)) : The parent class of the model to be wrapped.\n\nsupported_args (`list`) : The list of arguments that are supported by the wrapper class.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.PreTrainedModelWrapper[[trl.experimental.ppo.PreTrainedModelWrapper]]", "char_start": 27655, "char_end": 27924, "token_estimate": 67, "prev_chunk_id": 226, "next_chunk_id": 228, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 228, "text": "#### compute_reward_score[[trl.experimental.ppo.PreTrainedModelWrapper.compute_reward_score]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L563)\n\nComputes the reward score for a given input. The method has first to enable the adapter and then compute the\nreward score. After that the model disables the reward modeling adapter and enables the default ppo adapter\nagain.", "source_file": "trl/ppo_trainer.md", "section_heading": "compute_reward_score[[trl.experimental.ppo.PreTrainedModelWrapper.compute_reward_score]]", "char_start": 27925, "char_end": 28350, "token_estimate": 106, "prev_chunk_id": 227, "next_chunk_id": 229, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 229, "text": "#### from_pretrained[[trl.experimental.ppo.PreTrainedModelWrapper.from_pretrained]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L106)\n\nInstantiates a new model from a pretrained model from `transformers`. The pretrained model is loaded using the\n`from_pretrained` method of the [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) class. The arguments that are specific to the\n[PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) class are passed along this method and filtered out from the `kwargs`\nargument.\n\n**Parameters:**\n\npretrained_model_name_or_path (`str` or [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel)) : The path to the pretrained model or its name.", "source_file": "trl/ppo_trainer.md", "section_heading": "from_pretrained[[trl.experimental.ppo.PreTrainedModelWrapper.from_pretrained]]", "char_start": 28351, "char_end": 29272, "token_estimate": 230, "prev_chunk_id": 228, "next_chunk_id": 230, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 230, "text": "- ***model_args** (`list`, *optional*) : Additional positional arguments passed along to the underlying model's `from_pretrained` method.\n\n- ****kwargs** (`dict`, *optional*) : Additional keyword arguments passed along to the underlying model's `from_pretrained` method. We also pre-process the kwargs to extract the arguments that are specific to the [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) class and the arguments that are specific to trl models. The kwargs also support `prepare_model_for_kbit_training` arguments from `peft` library.", "source_file": "trl/ppo_trainer.md", "section_heading": "from_pretrained[[trl.experimental.ppo.PreTrainedModelWrapper.from_pretrained]]", "char_start": 29274, "char_end": 29889, "token_estimate": 153, "prev_chunk_id": 229, "next_chunk_id": 231, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 231, "text": "#### post_init[[trl.experimental.ppo.PreTrainedModelWrapper.post_init]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L556)\n\nPost initialization method. This method is called after the model is instantiated and loaded from a checkpoint.\nIt can be used to perform additional operations such as loading the state_dict.", "source_file": "trl/ppo_trainer.md", "section_heading": "post_init[[trl.experimental.ppo.PreTrainedModelWrapper.post_init]]", "char_start": 29890, "char_end": 30261, "token_estimate": 92, "prev_chunk_id": 230, "next_chunk_id": 232, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 232, "text": "#### push_to_hub[[trl.experimental.ppo.PreTrainedModelWrapper.push_to_hub]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L509)\n\nPush the pretrained model to the hub. This method is a wrapper around\n[push_to_hub](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.push_to_hub). Please refer to the documentation of\n[push_to_hub](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.push_to_hub) for more information.\n\n**Parameters:**\n\n- ***args** (`list`, *optional*) : Positional arguments passed along to the underlying model's `push_to_hub` method.\n\n- ****kwargs** (`dict`, *optional*) : Keyword arguments passed along to the underlying model's `push_to_hub` method.", "source_file": "trl/ppo_trainer.md", "section_heading": "push_to_hub[[trl.experimental.ppo.PreTrainedModelWrapper.push_to_hub]]", "char_start": 30262, "char_end": 31080, "token_estimate": 204, "prev_chunk_id": 231, "next_chunk_id": 233, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 233, "text": "#### save_pretrained[[trl.experimental.ppo.PreTrainedModelWrapper.save_pretrained]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L523)\n\nSave the pretrained model to a directory. This method is a wrapper around\n[save_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.save_pretrained). Please refer to the documentation of\n[save_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.save_pretrained) for more information.\n\n**Parameters:**\n\n- ***args** (`list`, *optional*) : Positional arguments passed along to the underlying model's `save_pretrained` method.\n\n- ****kwargs** (`dict`, *optional*) : Keyword arguments passed along to the underlying model's `save_pretrained` method.", "source_file": "trl/ppo_trainer.md", "section_heading": "save_pretrained[[trl.experimental.ppo.PreTrainedModelWrapper.save_pretrained]]", "char_start": 31081, "char_end": 31935, "token_estimate": 213, "prev_chunk_id": 232, "next_chunk_id": 234, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 234, "text": "#### state_dict[[trl.experimental.ppo.PreTrainedModelWrapper.state_dict]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L550)\n\nReturn the state_dict of the pretrained model.", "source_file": "trl/ppo_trainer.md", "section_heading": "state_dict[[trl.experimental.ppo.PreTrainedModelWrapper.state_dict]]", "char_start": 31936, "char_end": 32164, "token_estimate": 57, "prev_chunk_id": 233, "next_chunk_id": 235, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 235, "text": "## AutoModelForCausalLMWithValueHead[[trl.experimental.ppo.AutoModelForCausalLMWithValueHead]]", "source_file": "trl/ppo_trainer.md", "section_heading": "AutoModelForCausalLMWithValueHead[[trl.experimental.ppo.AutoModelForCausalLMWithValueHead]]", "char_start": 32166, "char_end": 32260, "token_estimate": 23, "prev_chunk_id": 234, "next_chunk_id": 236, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 236, "text": "#### trl.experimental.ppo.AutoModelForCausalLMWithValueHead[[trl.experimental.ppo.AutoModelForCausalLMWithValueHead]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L634)\n\nAn autoregressive model with a value head in addition to the language model head. This class inherits from\n[experimental.ppo.PreTrainedModelWrapper](/docs/trl/v1.2.0/en/ppo_trainer#trl.experimental.ppo.PreTrainedModelWrapper) and wraps a [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) class. The wrapper class\nsupports classic functions such as `from_pretrained`, `push_to_hub` and `generate`. To call a method of the wrapped\nmodel, simply manipulate the `pretrained_model` attribute of this class.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.AutoModelForCausalLMWithValueHead[[trl.experimental.ppo.AutoModelForCausalLMWithValueHead]]", "char_start": 32262, "char_end": 33057, "token_estimate": 198, "prev_chunk_id": 235, "next_chunk_id": 237, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 237, "text": "Class attributes:\n- **transformers_parent_class** ([PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel)) -- The parent class of the wrapped model.\n This\n should be set to `transformers.AutoModelForCausalLM` for this class.\n- **supported_args** (`tuple`) -- A tuple of strings that are used to identify the arguments that are supported\n by the `ValueHead` class. Currently, the supported args are:\n - **summary_dropout_prob** (`float`, `optional`, defaults to `None`) -- The dropout probability for the\n `ValueHead` class.\n - **v_head_initializer_range** (`float`, `optional`, defaults to `0.2`) -- The initializer range for the\n `ValueHead` if a specific initialization strategy is selected.\n - **v_head_init_strategy** (`str`, `optional`, defaults to `None`) -- The initialization strategy for the\n `ValueHead`. Currently, the supported strategies are:\n - **`None`** -- Initializes the weights of the `ValueHead` with a random distribution. This is the\n default strategy.\n - **\"normal\"** -- Initializes the weights of the `ValueHead` with a normal distribution.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.AutoModelForCausalLMWithValueHead[[trl.experimental.ppo.AutoModelForCausalLMWithValueHead]]", "char_start": 33059, "char_end": 34212, "token_estimate": 288, "prev_chunk_id": 236, "next_chunk_id": 238, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 238, "text": "__init__trl.experimental.ppo.AutoModelForCausalLMWithValueHead.__init__https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L665[{\"name\": \"pretrained_model\", \"val\": \"\"}, {\"name\": \"**kwargs\", \"val\": \"\"}]- **pretrained_model** ([PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel)) --\n The model to wrap. It should be a causal language model such as GPT2. or any model mapped inside the\n `AutoModelForCausalLM` class.\n- **kwargs** (`dict`, `optional`) --\n Additional keyword arguments, that are passed to the `ValueHead` class.0\n\nInitializes the model.\n\n**Parameters:**\n\npretrained_model ([PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel)) : The model to wrap. It should be a causal language model such as GPT2. or any model mapped inside the `AutoModelForCausalLM` class.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.AutoModelForCausalLMWithValueHead[[trl.experimental.ppo.AutoModelForCausalLMWithValueHead]]", "char_start": 34214, "char_end": 35158, "token_estimate": 236, "prev_chunk_id": 237, "next_chunk_id": 239, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 239, "text": "kwargs (`dict`, `optional`) : Additional keyword arguments, that are passed to the `ValueHead` class.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.AutoModelForCausalLMWithValueHead[[trl.experimental.ppo.AutoModelForCausalLMWithValueHead]]", "char_start": 35160, "char_end": 35261, "token_estimate": 25, "prev_chunk_id": 238, "next_chunk_id": 240, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 240, "text": "#### forward[[trl.experimental.ppo.AutoModelForCausalLMWithValueHead.forward]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L703)\n\nApplies a forward pass to the wrapped model and returns the logits of the value head.\n\n**Parameters:**\n\ninput_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*) : Indices of input sequence tokens in the vocabulary.\n\npast_key_values (*tuple(tuple(torch.FloatTensor))*, *optional*) : Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see *past_key_values* input) to speed up sequential decoding.\n\nattention_mask (*torch.FloatTensor* of shape *(batch_size, sequence_length)*, *optional*) : Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**.\n\nreturn_past_key_values (bool) : A flag indicating if the computed hidden-states should be returned.", "source_file": "trl/ppo_trainer.md", "section_heading": "forward[[trl.experimental.ppo.AutoModelForCausalLMWithValueHead.forward]]", "char_start": 35262, "char_end": 36275, "token_estimate": 253, "prev_chunk_id": 239, "next_chunk_id": 241, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 241, "text": "kwargs (*dict*, *optional*) : Additional keyword arguments, that are passed to the wrapped model.", "source_file": "trl/ppo_trainer.md", "section_heading": "forward[[trl.experimental.ppo.AutoModelForCausalLMWithValueHead.forward]]", "char_start": 36277, "char_end": 36374, "token_estimate": 24, "prev_chunk_id": 240, "next_chunk_id": 242, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 242, "text": "#### generate[[trl.experimental.ppo.AutoModelForCausalLMWithValueHead.generate]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L758)\n\nA simple wrapper around the `generate` method of the wrapped model. Please refer to the\n[`generate`](https://huggingface.co/docs/transformers/internal/generation_utils) method of the wrapped model\nfor more information about the supported arguments.\n\n**Parameters:**\n\n- ***args** (`list`, *optional*) : Positional arguments passed to the `generate` method of the wrapped model.\n\n- ****kwargs** (`dict`, *optional*) : Keyword arguments passed to the `generate` method of the wrapped model.", "source_file": "trl/ppo_trainer.md", "section_heading": "generate[[trl.experimental.ppo.AutoModelForCausalLMWithValueHead.generate]]", "char_start": 36375, "char_end": 37051, "token_estimate": 169, "prev_chunk_id": 241, "next_chunk_id": 243, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 243, "text": "#### _init_weights[[trl.experimental.ppo.AutoModelForCausalLMWithValueHead._init_weights]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L681)\n\nInitializes the weights of the value head. The default initialization strategy is random. Users can pass a\ndifferent initialization strategy by passing the `v_head_init_strategy` argument when calling\n`.from_pretrained`. Supported strategies are:\n- `normal`: initializes the weights with a normal distribution.\n\n**Parameters:**\n\n- ****kwargs** (`dict`, `optional`) : Additional keyword arguments, that are passed to the `ValueHead` class. These arguments can contain the `v_head_init_strategy` argument as well as the `v_head_initializer_range` argument.", "source_file": "trl/ppo_trainer.md", "section_heading": "_init_weights[[trl.experimental.ppo.AutoModelForCausalLMWithValueHead._init_weights]]", "char_start": 37052, "char_end": 37805, "token_estimate": 188, "prev_chunk_id": 242, "next_chunk_id": 244, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 244, "text": "## AutoModelForSeq2SeqLMWithValueHead[[trl.experimental.ppo.AutoModelForSeq2SeqLMWithValueHead]]", "source_file": "trl/ppo_trainer.md", "section_heading": "AutoModelForSeq2SeqLMWithValueHead[[trl.experimental.ppo.AutoModelForSeq2SeqLMWithValueHead]]", "char_start": 37807, "char_end": 37903, "token_estimate": 24, "prev_chunk_id": 243, "next_chunk_id": 245, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 245, "text": "#### trl.experimental.ppo.AutoModelForSeq2SeqLMWithValueHead[[trl.experimental.ppo.AutoModelForSeq2SeqLMWithValueHead]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L838)\n\nA seq2seq model with a value head in addition to the language model head. This class inherits from\n[experimental.ppo.PreTrainedModelWrapper](/docs/trl/v1.2.0/en/ppo_trainer#trl.experimental.ppo.PreTrainedModelWrapper) and wraps a [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) class. The wrapper class\nsupports classic functions such as `from_pretrained` and `push_to_hub` and also provides some additional\nfunctionalities such as `generate`.\n\n__init__trl.experimental.ppo.AutoModelForSeq2SeqLMWithValueHead.__init__https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L861[{\"name\": \"pretrained_model\", \"val\": \"\"}, {\"name\": \"**kwargs\", \"val\": \"\"}]\n\n**Parameters:**", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.AutoModelForSeq2SeqLMWithValueHead[[trl.experimental.ppo.AutoModelForSeq2SeqLMWithValueHead]]", "char_start": 37905, "char_end": 38906, "token_estimate": 250, "prev_chunk_id": 244, "next_chunk_id": 246, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 246, "text": "pretrained_model ([PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel)) : The model to wrap. It should be a causal language model such as GPT2. or any model mapped inside the [AutoModelForSeq2SeqLM](https://huggingface.co/docs/transformers/v5.5.4/en/model_doc/auto#transformers.AutoModelForSeq2SeqLM) class.\n\nkwargs : Additional keyword arguments passed along to the `ValueHead` class.", "source_file": "trl/ppo_trainer.md", "section_heading": "trl.experimental.ppo.AutoModelForSeq2SeqLMWithValueHead[[trl.experimental.ppo.AutoModelForSeq2SeqLMWithValueHead]]", "char_start": 38908, "char_end": 39358, "token_estimate": 112, "prev_chunk_id": 245, "next_chunk_id": 247, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 247, "text": "#### forward[[trl.experimental.ppo.AutoModelForSeq2SeqLMWithValueHead.forward]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L969)", "source_file": "trl/ppo_trainer.md", "section_heading": "forward[[trl.experimental.ppo.AutoModelForSeq2SeqLMWithValueHead.forward]]", "char_start": 39359, "char_end": 39545, "token_estimate": 46, "prev_chunk_id": 246, "next_chunk_id": 248, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 248, "text": "#### generate[[trl.experimental.ppo.AutoModelForSeq2SeqLMWithValueHead.generate]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L1003)\n\nWe call `generate` on the wrapped model.", "source_file": "trl/ppo_trainer.md", "section_heading": "generate[[trl.experimental.ppo.AutoModelForSeq2SeqLMWithValueHead.generate]]", "char_start": 39546, "char_end": 39777, "token_estimate": 57, "prev_chunk_id": 247, "next_chunk_id": 249, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 249, "text": "#### _init_weights[[trl.experimental.ppo.AutoModelForSeq2SeqLMWithValueHead._init_weights]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/ppo/modeling_value_head.py#L955)\n\nWe initialize the weights of the value head.", "source_file": "trl/ppo_trainer.md", "section_heading": "_init_weights[[trl.experimental.ppo.AutoModelForSeq2SeqLMWithValueHead._init_weights]]", "char_start": 39778, "char_end": 40022, "token_estimate": 61, "prev_chunk_id": 248, "next_chunk_id": null, "url": "https://huggingface.co/docs/trl/ppo_trainer", "doc_title": "PPO Trainer" }, { "chunk_id": 250, "text": "# Reward Modeling\n\n[![model badge](https://img.shields.io/badge/All_models-Reward_Trainer-blue)](https://huggingface.co/models?other=reward-trainer,trl)", "source_file": "trl/reward_trainer.md", "section_heading": "Reward Modeling", "char_start": 0, "char_end": 152, "token_estimate": 38, "prev_chunk_id": null, "next_chunk_id": 251, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 251, "text": "## Overview\n\nTRL supports the Outcome-supervised Reward Modeling (ORM) Trainer for training reward models.\n\nThis post-training method was contributed by [Younes Belkada](https://huggingface.co/ybelkada).", "source_file": "trl/reward_trainer.md", "section_heading": "Overview", "char_start": 154, "char_end": 357, "token_estimate": 50, "prev_chunk_id": 250, "next_chunk_id": 252, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 252, "text": "## Quick start\n\nThis example demonstrates how to train a reward model using the [RewardTrainer](/docs/trl/v1.2.0/en/reward_trainer#trl.RewardTrainer) from TRL. We train a [Qwen 3 0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) model on the [UltraFeedback dataset](https://huggingface.co/datasets/trl-lib/ultrafeedback_binarized), large-scale, fine-grained, diverse preference dataset.\n\n```python\nfrom trl import RewardTrainer\nfrom datasets import load_dataset\n\ntrainer = RewardTrainer(\n model=\"Qwen/Qwen3-0.6B\",\n train_dataset=load_dataset(\"trl-lib/ultrafeedback_binarized\", split=\"train\"),\n)\ntrainer.train()\n```", "source_file": "trl/reward_trainer.md", "section_heading": "Quick start", "char_start": 359, "char_end": 975, "token_estimate": 154, "prev_chunk_id": 251, "next_chunk_id": 253, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 253, "text": "## Expected dataset type and format\n\n[RewardTrainer](/docs/trl/v1.2.0/en/reward_trainer#trl.RewardTrainer) supports [preference](dataset_formats#preference) datasets type (both implicit and explicit prompt). The [RewardTrainer](/docs/trl/v1.2.0/en/reward_trainer#trl.RewardTrainer) is compatible with both [standard](dataset_formats#standard) and [conversational](dataset_formats#conversational) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset.\n\n```python", "source_file": "trl/reward_trainer.md", "section_heading": "Expected dataset type and format", "char_start": 977, "char_end": 1516, "token_estimate": 134, "prev_chunk_id": 252, "next_chunk_id": 254, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 254, "text": "# Standard preference (implicit prompt)\n{\"chosen\": \"The sky is blue.\",\n \"rejected\": \"The sky is green.\"}", "source_file": "trl/reward_trainer.md", "section_heading": "Standard preference (implicit prompt)", "char_start": 1517, "char_end": 1621, "token_estimate": 26, "prev_chunk_id": 253, "next_chunk_id": 255, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 255, "text": "# Conversational preference (implicit prompt)\n{\"chosen\": [{\"role\": \"user\", \"content\": \"What color is the sky?\"},\n {\"role\": \"assistant\", \"content\": \"It is blue.\"}],\n \"rejected\": [{\"role\": \"user\", \"content\": \"What color is the sky?\"},\n {\"role\": \"assistant\", \"content\": \"It is green.\"}]}", "source_file": "trl/reward_trainer.md", "section_heading": "Conversational preference (implicit prompt)", "char_start": 1623, "char_end": 1931, "token_estimate": 77, "prev_chunk_id": 254, "next_chunk_id": 256, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 256, "text": "# Standard preference (explicit prompt)\n{\"prompt\": \"The sky is\",\n \"chosen\": \" blue.\",\n \"rejected\": \" green.\"}", "source_file": "trl/reward_trainer.md", "section_heading": "Standard preference (explicit prompt)", "char_start": 1933, "char_end": 2042, "token_estimate": 27, "prev_chunk_id": 255, "next_chunk_id": 257, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 257, "text": "# Conversational preference (explicit prompt)\n{\"prompt\": [{\"role\": \"user\", \"content\": \"What color is the sky?\"}],\n \"chosen\": [{\"role\": \"assistant\", \"content\": \"It is blue.\"}],\n \"rejected\": [{\"role\": \"assistant\", \"content\": \"It is green.\"}]}\n```\n\nIf your dataset is not in one of these formats, you can preprocess it to convert it into the expected format. Here is an example with the [lmarena-ai/arena-human-preference-55k](https://huggingface.co/datasets/lmarena-ai/arena-human-preference-55k) dataset:\n\n```python\nfrom datasets import load_dataset\nimport json\n\ndataset = load_dataset(\"lmarena-ai/arena-human-preference-55k\")", "source_file": "trl/reward_trainer.md", "section_heading": "Conversational preference (explicit prompt)", "char_start": 2044, "char_end": 2669, "token_estimate": 156, "prev_chunk_id": 256, "next_chunk_id": 258, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 258, "text": "# Filter out ties\ndataset = dataset.filter(lambda example: example[\"winner_tie\"] == 0)", "source_file": "trl/reward_trainer.md", "section_heading": "Filter out ties", "char_start": 2671, "char_end": 2757, "token_estimate": 21, "prev_chunk_id": 257, "next_chunk_id": 259, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 259, "text": "# Create 'chosen' and 'rejected' fields based on the winner column\ndef response_a_b_to_chosen_rejected(example):\n if example[\"winner_model_a\"] == 1:\n example[\"chosen\"] = example[\"response_a\"]\n example[\"rejected\"] = example[\"response_b\"]\n else:\n example[\"chosen\"] = example[\"response_b\"]\n example[\"rejected\"] = example[\"response_a\"]\n return example\n\ndataset = dataset.map(response_a_b_to_chosen_rejected)", "source_file": "trl/reward_trainer.md", "section_heading": "Create 'chosen' and 'rejected' fields based on the winner column", "char_start": 2759, "char_end": 3199, "token_estimate": 110, "prev_chunk_id": 258, "next_chunk_id": 260, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 260, "text": "# Convert to conversational format\ndef make_conversation(example):\n prompt = json.loads(example[\"prompt\"])[0] # '[\"What color is the sky?\"]' -> \"What color is the sky?\"\n chosen = json.loads(example[\"chosen\"])[0]\n rejected = json.loads(example[\"rejected\"])[0]\n return {\n \"chosen\": [{\"role\": \"user\", \"content\": prompt}, {\"role\": \"assistant\", \"content\": chosen}],\n \"rejected\": [{\"role\": \"user\", \"content\": prompt}, {\"role\": \"assistant\", \"content\": rejected}],\n }\n\ndataset = dataset.map(make_conversation)", "source_file": "trl/reward_trainer.md", "section_heading": "Convert to conversational format", "char_start": 3201, "char_end": 3732, "token_estimate": 132, "prev_chunk_id": 259, "next_chunk_id": 261, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 261, "text": "# Keep only necessary columns\ndataset = dataset.select_columns([\"chosen\", \"rejected\"])\n\nprint(next(iter(dataset[\"train\"])))\n```\n\n```json\n{\n \"chosen\": [\n {\"role\": \"user\", \"content\": \"Is it morally right to try to have a certain percentage of females on managerial positions?\"},\n {\"role\": \"assistant\", \"content\": \"The question of whether it is morally right to aim for a certain percentage of females...\"},\n ],\n \"rejected\": [\n {\"role\": \"user\", \"content\": \"Is it morally right to try to have a certain percentage of females on managerial positions?\"},\n {\"role\": \"assistant\", \"content\": \"As an AI, I don't have personal beliefs or opinions. However, ...\"},\n ],\n}\n```", "source_file": "trl/reward_trainer.md", "section_heading": "Keep only necessary columns", "char_start": 3734, "char_end": 4436, "token_estimate": 175, "prev_chunk_id": 260, "next_chunk_id": 262, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 262, "text": "## Looking deeper into the training method\n\nReward Models (RMs) are typically trained using supervised learning on datasets containing pairs of preferred and non-preferred responses. The goal is to learn a function that assigns higher scores to preferred responses, enabling the model to rank outputs based on preferences.\n\nThis section breaks down how reward modeling works in practice, covering the key steps: **preprocessing** and **loss computation**.", "source_file": "trl/reward_trainer.md", "section_heading": "Looking deeper into the training method", "char_start": 4438, "char_end": 4893, "token_estimate": 113, "prev_chunk_id": 261, "next_chunk_id": 263, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 263, "text": "### Preprocessing and tokenization\n\nDuring training, each example is expected to contain a **chosen** and **rejected** field. For more details on the expected formats, see [Dataset formats - Preference](dataset_formats#preference).\nThe [RewardTrainer](/docs/trl/v1.2.0/en/reward_trainer#trl.RewardTrainer) tokenizes each input using the model's tokenizer. If prompts and completions (chosen and rejected) are provided separately (explicit prompt case), they are concatenated before tokenization.", "source_file": "trl/reward_trainer.md", "section_heading": "Preprocessing and tokenization", "char_start": 4895, "char_end": 5390, "token_estimate": 123, "prev_chunk_id": 262, "next_chunk_id": 264, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 264, "text": "### Computing the loss\n\nLet \\\\( x \\\\) be the input sequence (prompt) and \\\\( y^+ \\\\) and \\\\( y^- \\\\) be the chosen and rejected sequences respectively. Under the Bradley-Terry model ([Bradley & Terry, 1952](https://www.jstor.org/stable/2334029)), the probability that \\\\( y^+ \\\\) is preferred over \\\\( y^- \\\\) given a reward function \\\\( r \\\\) is \\\\( p(y^+ \u227b y^- |x) = \\sigma(r(x, y^+)\u2212r(x, y^-)) \\\\), where \\\\( \u03c3 \\\\) is the sigmoid function.\n\nThe reward model \\\\( r_\\theta(x, y) \\\\) is trained to assign higher scores to preferred responses \\\\( y^+ \\\\) over non-preferred ones \\\\( y^- \\\\). The loss is then defined as the negative log-likelihood of the observed preferences:\n\n$$\n\\mathcal{L}(\\theta) = - \\mathbb{E}_{(x,y^+,y^-) \\sim \\mathcal{D}} \\left[ \\log \\sigma(r_\\theta(x, y^+) - r_\\theta(x, y^-)) \\right].\n$$", "source_file": "trl/reward_trainer.md", "section_heading": "Computing the loss", "char_start": 5392, "char_end": 6216, "token_estimate": 206, "prev_chunk_id": 263, "next_chunk_id": 265, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 265, "text": "> [!TIP]\n> The Bradley-Terry model is underdetermined, meaning that adding a constant to all rewards does not change the preference probabilities. To address this, [Helping or Herding? Reward Model Ensembles Mitigate but do not Eliminate Reward Hacking](https://huggingface.co/papers/2312.09244) proposes adding an auxiliary loss term that encourages the rewards to be centered around zero. This is controlled by the `center_rewards_coefficient` parameter in the [RewardConfig](/docs/trl/v1.2.0/en/reward_trainer#trl.RewardConfig). The recommended value is `1e-2`.", "source_file": "trl/reward_trainer.md", "section_heading": "Computing the loss", "char_start": 6218, "char_end": 6782, "token_estimate": 141, "prev_chunk_id": 264, "next_chunk_id": 266, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 266, "text": "## Logged metrics\n\nWhile training and evaluating we record the following reward metrics:", "source_file": "trl/reward_trainer.md", "section_heading": "Logged metrics", "char_start": 6784, "char_end": 6872, "token_estimate": 22, "prev_chunk_id": 265, "next_chunk_id": 267, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 267, "text": "* `global_step`: The total number of optimizer steps taken so far.\n* `epoch`: The current epoch number, based on dataset iteration.\n* `num_tokens`: The total number of tokens processed so far.\n* `loss`: The average loss over the last logging interval.\n* `accuracy`: The proportion of correct predictions (i.e., the model assigned a higher score to the chosen response than to the rejected one) averaged over the last logging interval.\n* `min_reward`: The minimum reward score assigned by the model. This value is averaged over the logging interval.\n* `mean_reward`: The average reward score assigned by the model over the last logging interval.\n* `max_reward`: The maximum reward score assigned by the model. This value is averaged over the logging interval.\n* `margin`: The average margin (difference between chosen and rejected rewards) over the last logging interval.\n* `learning_rate`: The current learning rate, which may change dynamically if a scheduler is used.\n* `grad_norm`: The L2 norm of the gradients, computed before gradient clipping.", "source_file": "trl/reward_trainer.md", "section_heading": "Logged metrics", "char_start": 6874, "char_end": 7923, "token_estimate": 262, "prev_chunk_id": 266, "next_chunk_id": 268, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 268, "text": "## Customization", "source_file": "trl/reward_trainer.md", "section_heading": "Customization", "char_start": 7925, "char_end": 7941, "token_estimate": 4, "prev_chunk_id": 267, "next_chunk_id": 269, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 269, "text": "### Model initialization\n\nYou can directly pass the kwargs of the `from_pretrained()` method to the [RewardConfig](/docs/trl/v1.2.0/en/reward_trainer#trl.RewardConfig). For example, if you want to load a model in a different precision, analogous to\n\n```python\nmodel = AutoModelForSequenceClassification.from_pretrained(\"Qwen/Qwen3-0.6B\", dtype=torch.bfloat16)\n```\n\nyou can do so by passing the `model_init_kwargs={\"dtype\": torch.bfloat16}` argument to the [RewardConfig](/docs/trl/v1.2.0/en/reward_trainer#trl.RewardConfig).\n\n```python\nfrom trl import RewardConfig\n\ntraining_args = RewardConfig(\n model_init_kwargs={\"dtype\": torch.bfloat16},\n)\n```\n\nNote that all keyword arguments of `from_pretrained()` are supported, except for `num_labels`, which is automatically set to 1.", "source_file": "trl/reward_trainer.md", "section_heading": "Model initialization", "char_start": 7943, "char_end": 8722, "token_estimate": 194, "prev_chunk_id": 268, "next_chunk_id": 270, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 270, "text": "### Train adapters with PEFT\n\nWe support tight integration with \ud83e\udd17 PEFT library, allowing any user to conveniently train adapters and share them on the Hub, rather than training the entire model.\n\n```python\nfrom datasets import load_dataset\nfrom trl import RewardTrainer\nfrom peft import LoraConfig\n\ndataset = load_dataset(\"trl-lib/ultrafeedback_binarized\", split=\"train\")\n\ntrainer = RewardTrainer(\n \"Qwen/Qwen3-4B\",\n train_dataset=dataset,\n peft_config=LoraConfig(modules_to_save=[\"score\"]) # important to include the score head when base model is not a sequence classification model\n)\n\ntrainer.train()\n```\n\nYou can also continue training your `PeftModel`. For that, first load a `PeftModel` outside [RewardTrainer](/docs/trl/v1.2.0/en/reward_trainer#trl.RewardTrainer) and pass it directly to the trainer without the `peft_config` argument being passed.", "source_file": "trl/reward_trainer.md", "section_heading": "Train adapters with PEFT", "char_start": 8724, "char_end": 9588, "token_estimate": 216, "prev_chunk_id": 269, "next_chunk_id": 271, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 271, "text": "```python\nfrom datasets import load_dataset\nfrom trl import RewardTrainer\nfrom peft import AutoPeftModelForCausalLM\n\nmodel = AutoPeftModelForCausalLM.from_pretrained(\"trl-lib/Qwen3-4B-Reward-LoRA\", is_trainable=True)\ndataset = load_dataset(\"trl-lib/Capybara\", split=\"train\")\n\ntrainer = RewardTrainer(\n model=model,\n train_dataset=dataset,\n)\n\ntrainer.train()\n```\n\n> [!TIP]\n> When training adapters, you typically use a higher learning rate (\u22481e\u20113) since only new parameters are being learned.\n>\n> ```python\n> RewardConfig(learning_rate=1e-3, ...)\n> ```", "source_file": "trl/reward_trainer.md", "section_heading": "Train adapters with PEFT", "char_start": 9590, "char_end": 10147, "token_estimate": 139, "prev_chunk_id": 270, "next_chunk_id": 272, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 272, "text": "## Tool Calling with Reward Modeling\n\nThe [RewardTrainer](/docs/trl/v1.2.0/en/reward_trainer#trl.RewardTrainer) fully supports fine-tuning models with _tool calling_ capabilities. In this case, each dataset example should include:\n\n* The conversation messages, including any tool calls (`tool_calls`) and tool responses (`tool` role messages)\n* The list of available tools in the `tools` column, typically provided as JSON schemas\n\nFor details on the expected dataset structure, see the [Dataset Format \u2014 Tool Calling](dataset_formats#tool-calling) section.", "source_file": "trl/reward_trainer.md", "section_heading": "Tool Calling with Reward Modeling", "char_start": 10149, "char_end": 10706, "token_estimate": 139, "prev_chunk_id": 271, "next_chunk_id": 273, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 273, "text": "## RewardTrainer[[trl.RewardTrainer]]", "source_file": "trl/reward_trainer.md", "section_heading": "RewardTrainer[[trl.RewardTrainer]]", "char_start": 10708, "char_end": 10745, "token_estimate": 9, "prev_chunk_id": 272, "next_chunk_id": 274, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 274, "text": "#### trl.RewardTrainer[[trl.RewardTrainer]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/trainer/reward_trainer.py#L229)\n\nTrainer for Outcome-supervised Reward Models (ORM).\n\nThis class is a wrapper around the [Trainer](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer) class and inherits all of its attributes and methods.\n\nExample:\n\n```python\nfrom trl import RewardTrainer\nfrom datasets import load_dataset\n\ndataset = load_dataset(\"trl-lib/ultrafeedback_binarized\", split=\"train\")\n\ntrainer = RewardTrainer(\n model=\"Qwen/Qwen2.5-0.5B-Instruct\",\n train_dataset=dataset,\n)\ntrainer.train()\n```", "source_file": "trl/reward_trainer.md", "section_heading": "trl.RewardTrainer[[trl.RewardTrainer]]", "char_start": 10747, "char_end": 11404, "token_estimate": 164, "prev_chunk_id": 273, "next_chunk_id": 275, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 275, "text": "traintrl.RewardTrainer.trainhttps://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L1323[{\"name\": \"resume_from_checkpoint\", \"val\": \": str | bool | None = None\"}, {\"name\": \"trial\", \"val\": \": optuna.Trial | dict[str, Any] | None = None\"}, {\"name\": \"ignore_keys_for_eval\", \"val\": \": list[str] | None = None\"}]- **resume_from_checkpoint** (`str` or `bool`, *optional*) --\n If a `str`, local path to a saved checkpoint as saved by a previous instance of `Trainer`. If a\n `bool` and equals `True`, load the last checkpoint in *args.output_dir* as saved by a previous instance\n of `Trainer`. If present, training will resume from the model/optimizer/scheduler states loaded here.\n- **trial** (`optuna.Trial` or `dict[str, Any]`, *optional*) --\n The trial run or the hyperparameter dictionary for hyperparameter search.\n- **ignore_keys_for_eval** (`list[str]`, *optional*) --\n A list of keys in the output of your model (if it is a dictionary) that should be ignored when\n gathering predictions for evaluation during the training.0`~trainer_utils.TrainOutput`Object containing the global step count, training loss, and metrics.", "source_file": "trl/reward_trainer.md", "section_heading": "trl.RewardTrainer[[trl.RewardTrainer]]", "char_start": 11406, "char_end": 12547, "token_estimate": 285, "prev_chunk_id": 274, "next_chunk_id": 276, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 276, "text": "Main training entry point.\n\n**Parameters:**\n\nmodel (`str` or [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) or `PeftModel`) : Model to be trained. Can be either: - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a path to a *directory* containing model weights saved using [save_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.save_pretrained), e.g., `'./my_model_directory/'`. The model is loaded using `AutoModelForSequenceClassification.from_pretrained` with the keyword arguments in `args.model_init_kwargs`. - A sequence classification [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) object. - A sequence classification `PeftModel` object.", "source_file": "trl/reward_trainer.md", "section_heading": "trl.RewardTrainer[[trl.RewardTrainer]]", "char_start": 12549, "char_end": 13452, "token_estimate": 225, "prev_chunk_id": 275, "next_chunk_id": 277, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 277, "text": "args ([RewardConfig](/docs/trl/v1.2.0/en/reward_trainer#trl.RewardConfig), *optional*) : Configuration for this trainer. If `None`, a default configuration is used.\n\ndata_collator (`DataCollator`, *optional*) : Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`. Will default to `DataCollatorForPreference`.", "source_file": "trl/reward_trainer.md", "section_heading": "trl.RewardTrainer[[trl.RewardTrainer]]", "char_start": 13454, "char_end": 13817, "token_estimate": 90, "prev_chunk_id": 276, "next_chunk_id": 278, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 278, "text": "train_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) or [IterableDataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset)) : Dataset to use for training. This trainer supports [preference](#preference) type (both implicit and explicit prompt). The format of the samples can be either: - [Standard](dataset_formats#standard): Each sample contains plain text. - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role and content). The trainer also supports processed datasets (tokenized) as long as they contain `chosen_ids` and `rejected_ids` fields.", "source_file": "trl/reward_trainer.md", "section_heading": "trl.RewardTrainer[[trl.RewardTrainer]]", "char_start": 13819, "char_end": 14542, "token_estimate": 180, "prev_chunk_id": 277, "next_chunk_id": 279, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 279, "text": "eval_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset), [IterableDataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) or `dict[str, Dataset | IterableDataset]`) : Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.\n\nprocessing_class ([PreTrainedTokenizerBase](https://huggingface.co/docs/transformers/v5.5.4/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase), *optional*) : Tokenizer used to process the data. If `None`, the tokenizer is loaded from the model's name with [from_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/model_doc/auto#transformers.AutoTokenizer.from_pretrained). A padding token, `processing_class.pad_token`, must be set. If the processing class has not set a padding token, `processing_class.eos_token` will be used as the default.", "source_file": "trl/reward_trainer.md", "section_heading": "trl.RewardTrainer[[trl.RewardTrainer]]", "char_start": 14544, "char_end": 15492, "token_estimate": 237, "prev_chunk_id": 278, "next_chunk_id": 280, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 280, "text": "compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*) : The function that will be used to compute metrics at evaluation. Must take a [EvalPrediction](https://huggingface.co/docs/transformers/v5.5.4/en/internal/trainer_utils#transformers.EvalPrediction) and return a dictionary string to metric values. When passing [RewardConfig](/docs/trl/v1.2.0/en/reward_trainer#trl.RewardConfig) with `batch_eval_metrics` set to `True`, your `compute_metrics` function must take a boolean `compute_result` argument. This will be triggered after the last eval batch to signal that the function needs to calculate and return the global summary statistics rather than accumulating the batch-level statistics.", "source_file": "trl/reward_trainer.md", "section_heading": "trl.RewardTrainer[[trl.RewardTrainer]]", "char_start": 15494, "char_end": 16197, "token_estimate": 175, "prev_chunk_id": 279, "next_chunk_id": 281, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 281, "text": "callbacks (list of [TrainerCallback](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/callback#transformers.TrainerCallback), *optional*) : List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed in [here](https://huggingface.co/docs/transformers/main_classes/callback). If you want to remove one of the default callbacks used, use the [remove_callback](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer.remove_callback) method.\n\noptimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`) : A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your model and a scheduler given by [get_linear_schedule_with_warmup](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/optimizer_schedules#transformers.get_linear_schedule_with_warmup) controlled by `args`.", "source_file": "trl/reward_trainer.md", "section_heading": "trl.RewardTrainer[[trl.RewardTrainer]]", "char_start": 16199, "char_end": 17196, "token_estimate": 249, "prev_chunk_id": 280, "next_chunk_id": 282, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 282, "text": "optimizer_cls_and_kwargs (`tuple[Type[torch.optim.Optimizer], Dict[str, Any]]`, *optional*) : A tuple containing the optimizer class and keyword arguments to use. Overrides `optim` and `optim_args` in `args`. Incompatible with the `optimizers` argument. Unlike `optimizers`, this argument avoids the need to place model parameters on the correct devices before initializing the Trainer.\n\npreprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*) : A function that preprocess the logits right before caching them at each evaluation step. Must take two tensors, the logits and the labels, and return the logits once processed as desired. The modifications made by this function will be reflected in the predictions received by `compute_metrics`. Note that the labels (second parameter) will be `None` if the dataset does not have them.", "source_file": "trl/reward_trainer.md", "section_heading": "trl.RewardTrainer[[trl.RewardTrainer]]", "char_start": 17198, "char_end": 18074, "token_estimate": 219, "prev_chunk_id": 281, "next_chunk_id": 283, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 283, "text": "peft_config (`PeftConfig`, *optional*) : PEFT configuration used to wrap the model. If `None`, the model is not wrapped. Note that if the loaded model is a causal LM, it's highly recommended to set `modules_to_save=[\"score\"]` in the PEFT configuration to ensure that the reward head is properly trained.\n\n**Returns:**\n\n``~trainer_utils.TrainOutput``\n\nObject containing the global step count, training loss, and metrics.", "source_file": "trl/reward_trainer.md", "section_heading": "trl.RewardTrainer[[trl.RewardTrainer]]", "char_start": 18076, "char_end": 18495, "token_estimate": 104, "prev_chunk_id": 282, "next_chunk_id": 284, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 284, "text": "#### save_model[[trl.RewardTrainer.save_model]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L3746)\n\nWill save the model, so you can reload it using `from_pretrained()`.\n\nWill only save from the main process.", "source_file": "trl/reward_trainer.md", "section_heading": "save_model[[trl.RewardTrainer.save_model]]", "char_start": 18496, "char_end": 18740, "token_estimate": 61, "prev_chunk_id": 283, "next_chunk_id": 285, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 285, "text": "#### push_to_hub[[trl.RewardTrainer.push_to_hub]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L3993)\n\nUpload `self.model` and `self.processing_class` to the \ud83e\udd17 model hub on the repo `self.args.hub_model_id`.\n\n**Parameters:**\n\ncommit_message (`str`, *optional*, defaults to `\"End of training\"`) : Message to commit while pushing.\n\nblocking (`bool`, *optional*, defaults to `True`) : Whether the function should return only when the `git push` has finished.\n\ntoken (`str`, *optional*, defaults to `None`) : Token with write permission to overwrite Trainer's original args.\n\nrevision (`str`, *optional*) : The git revision to commit from. Defaults to the head of the \"main\" branch.\n\nkwargs (`dict[str, Any]`, *optional*) : Additional keyword arguments passed along to `~Trainer.create_model_card`.\n\n**Returns:**\n\nThe URL of the repository where the model was pushed if `blocking=False`, or a `Future` object tracking the\nprogress of the commit if `blocking=True`.", "source_file": "trl/reward_trainer.md", "section_heading": "push_to_hub[[trl.RewardTrainer.push_to_hub]]", "char_start": 18741, "char_end": 19737, "token_estimate": 249, "prev_chunk_id": 284, "next_chunk_id": 286, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 286, "text": "## RewardConfig[[trl.RewardConfig]]", "source_file": "trl/reward_trainer.md", "section_heading": "RewardConfig[[trl.RewardConfig]]", "char_start": 19739, "char_end": 19774, "token_estimate": 8, "prev_chunk_id": 285, "next_chunk_id": 287, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 287, "text": "#### trl.RewardConfig[[trl.RewardConfig]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/trainer/reward_config.py#L23)\n\nConfiguration class for the [RewardTrainer](/docs/trl/v1.2.0/en/reward_trainer#trl.RewardTrainer).\n\nThis class includes only the parameters that are specific to Reward training. For a full list of training\narguments, please refer to the [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments) documentation. Note that default values in this\nclass may differ from those in [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments).\n\nUsing [HfArgumentParser](https://huggingface.co/docs/transformers/v5.5.4/en/internal/trainer_utils#transformers.HfArgumentParser) we can turn this class into\n[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the\ncommand line.", "source_file": "trl/reward_trainer.md", "section_heading": "trl.RewardConfig[[trl.RewardConfig]]", "char_start": 19776, "char_end": 20757, "token_estimate": 245, "prev_chunk_id": 286, "next_chunk_id": 288, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 288, "text": "> [!NOTE]\n> These parameters have default values different from [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments):\n> - `logging_steps`: Defaults to `10` instead of `500`.\n> - `gradient_checkpointing`: Defaults to `True` instead of `False`.\n> - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.\n> - `learning_rate`: Defaults to `1e-4` instead of `5e-5`.", "source_file": "trl/reward_trainer.md", "section_heading": "trl.RewardConfig[[trl.RewardConfig]]", "char_start": 20759, "char_end": 21204, "token_estimate": 111, "prev_chunk_id": 287, "next_chunk_id": null, "url": "https://huggingface.co/docs/trl/reward_trainer", "doc_title": "Reward Modeling" }, { "chunk_id": 289, "text": "# KTO Trainer\n\n[![model badge](https://img.shields.io/badge/All_models-KTO-blue)](https://huggingface.co/models?other=kto,trl)\n\n> [!WARNING]\n> As of TRL v1.0, `KTOTrainer` and `KTOConfig` have been moved to the `trl.experimental.kto` module. \n> KTO API is experimental and may change at any time.\n> Promoting KTO back into the stable API is a high-priority task: KTO is slated for refactoring to align with the standard core trainer architecture.", "source_file": "trl/kto_trainer.md", "section_heading": "KTO Trainer", "char_start": 0, "char_end": 447, "token_estimate": 111, "prev_chunk_id": null, "next_chunk_id": 290, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 290, "text": "## Overview\n\nKahneman-Tversky Optimization (KTO) was introduced in [KTO: Model Alignment as Prospect Theoretic Optimization](https://huggingface.co/papers/2402.01306) by [Kawin Ethayarajh](https://huggingface.co/kawine), [Winnie Xu](https://huggingface.co/xwinxu), [Niklas Muennighoff](https://huggingface.co/Muennighoff), Dan Jurafsky, [Douwe Kiela](https://huggingface.co/douwekiela).\n\nThe abstract from the paper is the following:", "source_file": "trl/kto_trainer.md", "section_heading": "Overview", "char_start": 449, "char_end": 882, "token_estimate": 108, "prev_chunk_id": 289, "next_chunk_id": 291, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 291, "text": "> Kahneman & Tversky's prospect theory tells us that humans perceive random variables in a biased but well-defined manner; for example, humans are famously loss-averse. We show that objectives for aligning LLMs with human feedback implicitly incorporate many of these biases -- the success of these objectives (e.g., DPO) over cross-entropy minimization can partly be ascribed to them being human-aware loss functions (HALOs). However, the utility functions these methods attribute to humans still differ from those in the prospect theory literature. Using a Kahneman-Tversky model of human utility, we propose a HALO that directly maximizes the utility of generations instead of maximizing the log-likelihood of preferences, as current methods do. We call this approach Kahneman-Tversky Optimization (KTO), and it matches or exceeds the performance of preference-based methods at scales from 1B to 30B. Crucially, KTO does not need preferences -- only a binary signal of whether an output is desirable or undesirable for a given input. This makes it far easier to use in the real world, where preference data is scarce and expensive.", "source_file": "trl/kto_trainer.md", "section_heading": "Overview", "char_start": 884, "char_end": 2018, "token_estimate": 283, "prev_chunk_id": 290, "next_chunk_id": 292, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 292, "text": "The official code can be found in [ContextualAI/HALOs](https://github.com/ContextualAI/HALOs).\n\nThis post-training method was contributed by [Kashif Rasul](https://huggingface.co/kashif), [Younes Belkada](https://huggingface.co/ybelkada), [Lewis Tunstall](https://huggingface.co/lewtun) and Pablo Vicente.", "source_file": "trl/kto_trainer.md", "section_heading": "Overview", "char_start": 2020, "char_end": 2325, "token_estimate": 76, "prev_chunk_id": 291, "next_chunk_id": 293, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 293, "text": "## Quick start\n\nThis example demonstrates how to train a model using the KTO method. We use the [Qwen 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) as the base model. We use the preference data from the [KTO Mix 14k](https://huggingface.co/datasets/trl-lib/kto-mix-14k). You can view the data in the dataset here:\n\nBelow is the script to train the model:\n\n```python", "source_file": "trl/kto_trainer.md", "section_heading": "Quick start", "char_start": 2327, "char_end": 2707, "token_estimate": 95, "prev_chunk_id": 292, "next_chunk_id": 294, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 294, "text": "# train_kto.py\nfrom datasets import load_dataset\nfrom trl.experimental.kto import KTOConfig, KTOTrainer\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\nmodel = AutoModelForCausalLM.from_pretrained(\"Qwen/Qwen2-0.5B-Instruct\")\ntokenizer = AutoTokenizer.from_pretrained(\"Qwen/Qwen2-0.5B-Instruct\")\ntrain_dataset = load_dataset(\"trl-lib/kto-mix-14k\", split=\"train\")\n\ntraining_args = KTOConfig(output_dir=\"Qwen2-0.5B-KTO\")\ntrainer = KTOTrainer(model=model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset)\ntrainer.train()\n```\n\nExecute the script using the following command:\n\n```bash\naccelerate launch train_kto.py\n```\n\nDistributed across 8 x H100 GPUs, the training takes approximately 30 minutes. You can verify the training progress by checking the reward graph. An increasing trend in the reward margin indicates that the model is improving and generating better responses over time.", "source_file": "trl/kto_trainer.md", "section_heading": "train_kto.py", "char_start": 2708, "char_end": 3632, "token_estimate": 231, "prev_chunk_id": 293, "next_chunk_id": 295, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 295, "text": "![kto qwen2 reward margin](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/kto-qwen2-reward-margin.png)\n\nTo see how the [trained model](https://huggingface.co/trl-lib/Qwen2-0.5B-KTO) performs, you can use the [Transformers Chat CLI](https://huggingface.co/docs/transformers/quicktour#chat-with-text-generation-models).\n\n$ transformers chat trl-lib/Qwen2-0.5B-KTO\n<quentin_gallouedec>:\nWhat is the best programming language?\n\n<trl-lib/Qwen2-0.5B-KTO>:\nThe best programming language can vary depending on individual preferences, industry-specific requirements, technical skills, and familiarity with the specific use case or task. Here are some widely-used programming languages that have been noted as popular and widely used:\n\nHere are some other factors to consider when choosing a programming language for a project:", "source_file": "trl/kto_trainer.md", "section_heading": "train_kto.py", "char_start": 3634, "char_end": 4490, "token_estimate": 214, "prev_chunk_id": 294, "next_chunk_id": 296, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 296, "text": "1 JavaScript: JavaScript is at the heart of the web and can be used for building web applications, APIs, and interactive front-end applications like frameworks like React and Angular. It's similar to C, C++, and F# in syntax structure and is accessible and easy to learn, making it a popular choice for beginners and professionals alike.\n 2 Java: Known for its object-oriented programming (OOP) and support for Java 8 and .NET, Java is used for developing enterprise-level software applications, high-performance games, as well as mobile apps, game development, and desktop applications.\n 3 C++: Known for its flexibility and scalability, C++ offers comprehensive object-oriented programming and is a popular choice for high-performance computing and other technical fields. It's a powerful platform for building real-world applications and games at scale.\n 4 Python: Developed by Guido van Rossum in 1991, Python is a high-level, interpreted, and dynamically typed language known for its simplicity, readability, and versatility.", "source_file": "trl/kto_trainer.md", "section_heading": "train_kto.py", "char_start": 4493, "char_end": 5523, "token_estimate": 257, "prev_chunk_id": 295, "next_chunk_id": 297, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 297, "text": "## Expected dataset format\n\nKTO requires an [unpaired preference dataset](dataset_formats#unpaired-preference). Alternatively, you can provide a *paired* preference dataset (also known simply as a *preference dataset*). In this case, the trainer will automatically convert it to an unpaired format by separating the chosen and rejected responses, assigning `label = True` to the chosen completions and `label = False` to the rejected ones.\n\nThe [experimental.kto.KTOTrainer](/docs/trl/v1.2.0/en/kto_trainer#trl.KTOTrainer) supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset.\n\nIn theory, the dataset should contain at least one chosen and one rejected completion. However, some users have successfully run KTO using *only* chosen or only rejected data. If using only rejected data, it is advisable to adopt a conservative learning rate.", "source_file": "trl/kto_trainer.md", "section_heading": "Expected dataset format", "char_start": 5525, "char_end": 6545, "token_estimate": 255, "prev_chunk_id": 296, "next_chunk_id": 298, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 298, "text": "## Example script\n\nWe provide an example script to train a model using the KTO method. The script is available in [`trl/scripts/kto.py`](https://github.com/huggingface/trl/blob/main/trl/scripts/kto.py)\n\nTo test the KTO script with the [Qwen2 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) on the [UltraFeedback dataset](https://huggingface.co/datasets/trl-lib/kto-mix-14k), run the following command:\n\n```bash\naccelerate launch trl/scripts/kto.py \\\n --model_name_or_path Qwen/Qwen2-0.5B-Instruct \\\n --dataset_name trl-lib/kto-mix-14k \\\n --num_train_epochs 1 \\\n --output_dir Qwen2-0.5B-KTO\n```", "source_file": "trl/kto_trainer.md", "section_heading": "Example script", "char_start": 6547, "char_end": 7165, "token_estimate": 154, "prev_chunk_id": 297, "next_chunk_id": 299, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 299, "text": "## Usage tips", "source_file": "trl/kto_trainer.md", "section_heading": "Usage tips", "char_start": 7167, "char_end": 7180, "token_estimate": 3, "prev_chunk_id": 298, "next_chunk_id": 300, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 300, "text": "### For Mixture of Experts Models: Enabling the auxiliary loss\n\nMOEs are the most efficient if the load is about equally distributed between experts. \nTo ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss.\n\nThis option is enabled by setting `output_router_logits=True` in the model config (e.g. [MixtralConfig](https://huggingface.co/docs/transformers/v5.5.4/en/model_doc/mixtral#transformers.MixtralConfig)). \nTo scale how much the auxiliary loss contributes to the total loss, use the hyperparameter `router_aux_loss_coef=...` (default: `0.001`) in the model config.", "source_file": "trl/kto_trainer.md", "section_heading": "For Mixture of Experts Models: Enabling the auxiliary loss", "char_start": 7182, "char_end": 7847, "token_estimate": 166, "prev_chunk_id": 299, "next_chunk_id": 301, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 301, "text": "### Batch size recommendations\n\nUse a per-step batch size that is at least 4, and an effective batch size between 16 and 128. Even if your effective batch size is large, if your per-step batch size is poor, then the KL estimate in KTO will be poor.", "source_file": "trl/kto_trainer.md", "section_heading": "Batch size recommendations", "char_start": 7849, "char_end": 8097, "token_estimate": 62, "prev_chunk_id": 300, "next_chunk_id": 302, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 302, "text": "### Learning rate recommendations\n\nEach choice of `beta` has a maximum learning rate it can tolerate before learning performance degrades. For the default setting of `beta = 0.1`, the learning rate should typically not exceed `1e-6` for most models. As `beta` decreases, the learning rate should also be reduced accordingly. In general, we strongly recommend keeping the learning rate between `5e-7` and `5e-6`. Even with small datasets, we advise against using a learning rate outside this range. Instead, opt for more epochs to achieve better results.", "source_file": "trl/kto_trainer.md", "section_heading": "Learning rate recommendations", "char_start": 8099, "char_end": 8652, "token_estimate": 138, "prev_chunk_id": 301, "next_chunk_id": 303, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 303, "text": "### Imbalanced data\n\nThe `desirable_weight` and `undesirable_weight` of the [experimental.kto.KTOConfig](/docs/trl/v1.2.0/en/kto_trainer#trl.KTOConfig) refer to the weights placed on the losses for desirable/positive and undesirable/negative examples.\nBy default, they are both 1. However, if you have more of one or the other, then you should upweight the less common type such that the ratio of (`desirable_weight` \\\\(\\times\\\\) number of positives) to (`undesirable_weight` \\\\(\\times\\\\) number of negatives) is in the range 1:1 to 4:3.", "source_file": "trl/kto_trainer.md", "section_heading": "Imbalanced data", "char_start": 8654, "char_end": 9193, "token_estimate": 134, "prev_chunk_id": 302, "next_chunk_id": 304, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 304, "text": "## Logged metrics\n\nWhile training and evaluating, we record the following reward metrics:\n\n- `rewards/chosen_sum`: the sum of log probabilities of the policy model for the chosen responses scaled by beta\n- `rewards/rejected_sum`: the sum of log probabilities of the policy model for the rejected responses scaled by beta\n- `logps/chosen_sum`: the sum of log probabilities of the chosen completions\n- `logps/rejected_sum`: the sum of log probabilities of the rejected completions\n- `logits/chosen_sum`: the sum of logits of the chosen completions\n- `logits/rejected_sum`: the sum of logits of the rejected completions\n- `count/chosen`: the count of chosen samples in a batch\n- `count/rejected`: the count of rejected samples in a batch", "source_file": "trl/kto_trainer.md", "section_heading": "Logged metrics", "char_start": 9195, "char_end": 9929, "token_estimate": 183, "prev_chunk_id": 303, "next_chunk_id": 305, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 305, "text": "## KTOTrainer[[trl.KTOTrainer]]", "source_file": "trl/kto_trainer.md", "section_heading": "KTOTrainer[[trl.KTOTrainer]]", "char_start": 9931, "char_end": 9962, "token_estimate": 7, "prev_chunk_id": 304, "next_chunk_id": 306, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 306, "text": "#### trl.KTOTrainer[[trl.KTOTrainer]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/kto/kto_trainer.py#L240)\n\nInitialize KTOTrainer.", "source_file": "trl/kto_trainer.md", "section_heading": "trl.KTOTrainer[[trl.KTOTrainer]]", "char_start": 9964, "char_end": 10124, "token_estimate": 40, "prev_chunk_id": 305, "next_chunk_id": 307, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 307, "text": "traintrl.KTOTrainer.trainhttps://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L1323[{\"name\": \"resume_from_checkpoint\", \"val\": \": str | bool | None = None\"}, {\"name\": \"trial\", \"val\": \": optuna.Trial | dict[str, Any] | None = None\"}, {\"name\": \"ignore_keys_for_eval\", \"val\": \": list[str] | None = None\"}]- **resume_from_checkpoint** (`str` or `bool`, *optional*) --\n If a `str`, local path to a saved checkpoint as saved by a previous instance of `Trainer`. If a\n `bool` and equals `True`, load the last checkpoint in *args.output_dir* as saved by a previous instance\n of `Trainer`. If present, training will resume from the model/optimizer/scheduler states loaded here.\n- **trial** (`optuna.Trial` or `dict[str, Any]`, *optional*) --\n The trial run or the hyperparameter dictionary for hyperparameter search.\n- **ignore_keys_for_eval** (`list[str]`, *optional*) --\n A list of keys in the output of your model (if it is a dictionary) that should be ignored when\n gathering predictions for evaluation during the training.0`~trainer_utils.TrainOutput`Object containing the global step count, training loss, and metrics.", "source_file": "trl/kto_trainer.md", "section_heading": "trl.KTOTrainer[[trl.KTOTrainer]]", "char_start": 10126, "char_end": 11264, "token_estimate": 284, "prev_chunk_id": 306, "next_chunk_id": 308, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 308, "text": "Main training entry point.\n\n**Parameters:**\n\nmodel (`str` or [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) or `PeftModel`) : Model to be trained. Can be either: - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a path to a *directory* containing model weights saved using [save_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.save_pretrained), e.g., `'./my_model_directory/'`. The model is loaded using `.from_pretrained` (where `` is derived from the model config) with the keyword arguments in `args.model_init_kwargs`. - A [PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel) object. Only causal language models are supported. - A `PeftModel` object. Only causal language models are supported.", "source_file": "trl/kto_trainer.md", "section_heading": "trl.KTOTrainer[[trl.KTOTrainer]]", "char_start": 11266, "char_end": 12217, "token_estimate": 237, "prev_chunk_id": 307, "next_chunk_id": 309, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 309, "text": "ref_model ([PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel), *optional*) : Reference model used to compute the reference log probabilities. - If provided, this model is used directly as the reference policy. - If `None`, the trainer will automatically use the initial policy corresponding to `model`, i.e. the model state before KTO training starts.\n\nargs ([experimental.kto.KTOConfig](/docs/trl/v1.2.0/en/kto_trainer#trl.KTOConfig), *optional*) : Configuration for this trainer. If `None`, a default configuration is used.\n\ntrain_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset)) : The dataset to use for training.\n\neval_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset)) : The dataset to use for evaluation.", "source_file": "trl/kto_trainer.md", "section_heading": "trl.KTOTrainer[[trl.KTOTrainer]]", "char_start": 12219, "char_end": 13129, "token_estimate": 227, "prev_chunk_id": 308, "next_chunk_id": 310, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 310, "text": "processing_class ([PreTrainedTokenizerBase](https://huggingface.co/docs/transformers/v5.5.4/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase), [BaseImageProcessor](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/image_processor#transformers.BaseImageProcessor), [FeatureExtractionMixin](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/feature_extractor#transformers.FeatureExtractionMixin) or [ProcessorMixin](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/processors#transformers.ProcessorMixin), *optional*) : Processing class used to process the data. If provided, will be used to automatically process the inputs for the model, and it will be saved along the model to make it easier to rerun an interrupted training or reuse the fine-tuned model.", "source_file": "trl/kto_trainer.md", "section_heading": "trl.KTOTrainer[[trl.KTOTrainer]]", "char_start": 13131, "char_end": 13949, "token_estimate": 204, "prev_chunk_id": 309, "next_chunk_id": 311, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 311, "text": "data_collator (`DataCollator`, *optional*) : The data collator to use for training. If None is specified, the default data collator (`experimental.utils.DPODataCollatorWithPadding`) will be used which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences.\n\nmodel_init (`Callable[[], transformers.PreTrainedModel]`) : The model initializer to use for training. If None is specified, the default model initializer will be used.\n\ncallbacks (`list[transformers.TrainerCallback]`) : The callbacks to use for training.\n\noptimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`) : The optimizer and scheduler to use for training.\n\npreprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`) : The function to use to preprocess the logits before computing the metrics.", "source_file": "trl/kto_trainer.md", "section_heading": "trl.KTOTrainer[[trl.KTOTrainer]]", "char_start": 13951, "char_end": 14817, "token_estimate": 216, "prev_chunk_id": 310, "next_chunk_id": 312, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 312, "text": "peft_config (`dict`, defaults to `None`) : The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model.\n\ncompute_metrics (`Callable[[EvalPrediction], dict]`, *optional*) : The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to metric values.\n\n**Returns:**\n\n``~trainer_utils.TrainOutput``\n\nObject containing the global step count, training loss, and metrics.", "source_file": "trl/kto_trainer.md", "section_heading": "trl.KTOTrainer[[trl.KTOTrainer]]", "char_start": 14819, "char_end": 15288, "token_estimate": 117, "prev_chunk_id": 311, "next_chunk_id": 313, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 313, "text": "#### save_model[[trl.KTOTrainer.save_model]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L3746)\n\nWill save the model, so you can reload it using `from_pretrained()`.\n\nWill only save from the main process.", "source_file": "trl/kto_trainer.md", "section_heading": "save_model[[trl.KTOTrainer.save_model]]", "char_start": 15289, "char_end": 15530, "token_estimate": 60, "prev_chunk_id": 312, "next_chunk_id": 314, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 314, "text": "#### push_to_hub[[trl.KTOTrainer.push_to_hub]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L3993)\n\nUpload `self.model` and `self.processing_class` to the \ud83e\udd17 model hub on the repo `self.args.hub_model_id`.\n\n**Parameters:**\n\ncommit_message (`str`, *optional*, defaults to `\"End of training\"`) : Message to commit while pushing.\n\nblocking (`bool`, *optional*, defaults to `True`) : Whether the function should return only when the `git push` has finished.\n\ntoken (`str`, *optional*, defaults to `None`) : Token with write permission to overwrite Trainer's original args.\n\nrevision (`str`, *optional*) : The git revision to commit from. Defaults to the head of the \"main\" branch.\n\nkwargs (`dict[str, Any]`, *optional*) : Additional keyword arguments passed along to `~Trainer.create_model_card`.\n\n**Returns:**\n\nThe URL of the repository where the model was pushed if `blocking=False`, or a `Future` object tracking the\nprogress of the commit if `blocking=True`.", "source_file": "trl/kto_trainer.md", "section_heading": "push_to_hub[[trl.KTOTrainer.push_to_hub]]", "char_start": 15531, "char_end": 16524, "token_estimate": 248, "prev_chunk_id": 313, "next_chunk_id": 315, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 315, "text": "## KTOConfig[[trl.KTOConfig]]", "source_file": "trl/kto_trainer.md", "section_heading": "KTOConfig[[trl.KTOConfig]]", "char_start": 16526, "char_end": 16555, "token_estimate": 7, "prev_chunk_id": 314, "next_chunk_id": 316, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 316, "text": "#### trl.KTOConfig[[trl.KTOConfig]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/kto/kto_config.py#L22)\n\nConfiguration class for the [experimental.kto.KTOTrainer](/docs/trl/v1.2.0/en/kto_trainer#trl.KTOTrainer).\n\nThis class includes only the parameters that are specific to KTO training. For a full list of training arguments,\nplease refer to the [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments) documentation. Note that default values in this class may\ndiffer from those in [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments).\n\nUsing [HfArgumentParser](https://huggingface.co/docs/transformers/v5.5.4/en/internal/trainer_utils#transformers.HfArgumentParser) we can turn this class into\n[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the\ncommand line.", "source_file": "trl/kto_trainer.md", "section_heading": "trl.KTOConfig[[trl.KTOConfig]]", "char_start": 16557, "char_end": 17543, "token_estimate": 246, "prev_chunk_id": 315, "next_chunk_id": 317, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 317, "text": "> [!NOTE]\n> These parameters have default values different from [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments):\n> - `logging_steps`: Defaults to `10` instead of `500`.\n> - `gradient_checkpointing`: Defaults to `True` instead of `False`.\n> - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.\n> - `learning_rate`: Defaults to `1e-6` instead of `5e-5`.", "source_file": "trl/kto_trainer.md", "section_heading": "trl.KTOConfig[[trl.KTOConfig]]", "char_start": 17545, "char_end": 17990, "token_estimate": 111, "prev_chunk_id": 316, "next_chunk_id": null, "url": "https://huggingface.co/docs/trl/kto_trainer", "doc_title": "KTO Trainer" }, { "chunk_id": 318, "text": "# ORPO Trainer\n\n[![model badge](https://img.shields.io/badge/All_models-ORPO-blue)](https://huggingface.co/models?other=orpo,trl) [![model badge](https://img.shields.io/badge/smol_course-Chapter_2-yellow)](https://github.com/huggingface/smol-course/tree/main/2_preference_alignment)", "source_file": "trl/orpo_trainer.md", "section_heading": "ORPO Trainer", "char_start": 0, "char_end": 282, "token_estimate": 70, "prev_chunk_id": null, "next_chunk_id": 319, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 319, "text": "## Overview\n\nOdds Ratio Preference Optimization (ORPO) was introduced in [ORPO: Monolithic Preference Optimization without Reference Model](https://huggingface.co/papers/2403.07691) by [Jiwoo Hong](https://huggingface.co/JW17), [Noah Lee](https://huggingface.co/nlee-208), and [James Thorne](https://huggingface.co/j6mes).\n\nThe abstract from the paper is the following:", "source_file": "trl/orpo_trainer.md", "section_heading": "Overview", "char_start": 284, "char_end": 653, "token_estimate": 92, "prev_chunk_id": 318, "next_chunk_id": 320, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 320, "text": "> While recent preference alignment algorithms for language models have demonstrated promising results, supervised fine-tuning (SFT) remains imperative for achieving successful convergence. In this paper, we study the crucial role of SFT within the context of preference alignment, emphasizing that a minor penalty for the disfavored generation style is sufficient for preference-aligned SFT. Building on this foundation, we introduce a straightforward and innovative reference model-free monolithic odds ratio preference optimization algorithm, ORPO, eliminating the necessity for an additional preference alignment phase. We demonstrate, both empirically and theoretically, that the odds ratio is a sensible choice for contrasting favored and disfavored styles during SFT across the diverse sizes from 125M to 7B. Specifically, fine-tuning Phi-2 (2.7B), Llama-2 (7B), and Mistral (7B) with ORPO on the UltraFeedback alone surpasses the performance of state-of-the-art language models with more than 7B and 13B parameters: achieving up to 12.20% on AlpacaEval_{2.0} (Figure 1), 66.19% on IFEval (instruction-level loose, Table 6), and 7.32 in MT-Bench (Figure 12). We release code and model checkpoints for Mistral-ORPO-alpha (7B) and Mistral-ORPO-beta (7B).", "source_file": "trl/orpo_trainer.md", "section_heading": "Overview", "char_start": 655, "char_end": 1914, "token_estimate": 314, "prev_chunk_id": 319, "next_chunk_id": 321, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 321, "text": "It studies the crucial role of SFT within the context of preference alignment. Using preference data the method posits that a minor penalty for the disfavored generation together with a strong adaption signal to the chosen response via a simple log odds ratio term appended to the NLL loss is sufficient for preference-aligned SFT.\n\nThus ORPO is a reference model-free preference optimization algorithm eliminating the necessity for an additional preference alignment phase thus saving compute and memory.\n\nThe official code can be found in [xfactlab/orpo](https://github.com/xfactlab/orpo).\n\nThis post-training method was contributed by [Kashif Rasul](https://huggingface.co/kashif), [Lewis Tunstall](https://huggingface.co/lewtun) and [Alvaro Bartolome](https://huggingface.co/alvarobartt).", "source_file": "trl/orpo_trainer.md", "section_heading": "Overview", "char_start": 1916, "char_end": 2708, "token_estimate": 198, "prev_chunk_id": 320, "next_chunk_id": 322, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 322, "text": "## Quick start\n\nThis example demonstrates how to train a model using the ORPO method. We use the [Qwen 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) as the base model. We use the preference data from the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback). You can view the data in the dataset here:\n\nBelow is the script to train the model:\n\n```python", "source_file": "trl/orpo_trainer.md", "section_heading": "Quick start", "char_start": 2710, "char_end": 3103, "token_estimate": 98, "prev_chunk_id": 321, "next_chunk_id": 323, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 323, "text": "# train_orpo.py\nfrom datasets import load_dataset\nfrom trl.experimental.orpo import ORPOConfig, ORPOTrainer\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\nmodel = AutoModelForCausalLM.from_pretrained(\"Qwen/Qwen2-0.5B-Instruct\")\ntokenizer = AutoTokenizer.from_pretrained(\"Qwen/Qwen2-0.5B-Instruct\")\ntrain_dataset = load_dataset(\"trl-lib/ultrafeedback_binarized\", split=\"train\")\n\ntraining_args = ORPOConfig(output_dir=\"Qwen2-0.5B-ORPO\")\ntrainer = ORPOTrainer(model=model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset)\ntrainer.train()\n```\n\nExecute the script using the following command:\n\n```bash\naccelerate launch train_orpo.py\n```\n\nDistributed across 8 GPUs, the training takes approximately 30 minutes. You can verify the training progress by checking the reward graph. An increasing trend in the reward margin indicates that the model is improving and generating better responses over time.", "source_file": "trl/orpo_trainer.md", "section_heading": "train_orpo.py", "char_start": 3104, "char_end": 4041, "token_estimate": 234, "prev_chunk_id": 322, "next_chunk_id": 324, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 324, "text": "![orpo qwen2 reward margin](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/orpo-qwen2-reward-margin.png)\n\nTo see how the [trained model](https://huggingface.co/trl-lib/Qwen2-0.5B-ORPO) performs, you can use the [Transformers Chat CLI](https://huggingface.co/docs/transformers/quicktour#chat-with-text-generation-models).\n\n$ transformers chat trl-lib/Qwen2-0.5B-ORPO\n<quentin_gallouedec>:\nWhat is the best programming language?\n\n<trl-lib/Qwen2-0.5B-ORPO>:\nIt's challenging to determine the best programming language as no one language is perfect, as the complexity of a task and the type of project are significant factors. Some popular languages include Java, Python, JavaScript, and\nC++. If you have specific needs or requirements for a specific project, it's important to choose the language that best suits those needs.\n\nHere are some other factors to consider when choosing a programming language for a project:", "source_file": "trl/orpo_trainer.md", "section_heading": "train_orpo.py", "char_start": 4043, "char_end": 4997, "token_estimate": 238, "prev_chunk_id": 323, "next_chunk_id": 325, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 325, "text": "\u2022 Language proficiency: A good programming language is more likely to be easy to understand and use, and will allow developers to collaborate on projects more efficiently.\n \u2022 Ease of use: There are tools and libraries available to make programming more accessible, so developers should choose a language that can help them get started easier.\n \u2022 Code readability: A clear and concise codebase should be easy to read and understand, especially when working with large projects.\n \u2022 Tool and framework support: There are numerous libraries available for Python, Java, and JavaScript, along with tools like IDEs and static code analysis tools.\n \u2022 Accessibility: Some languages and tools have features that make them more accessible to developers with disabilities, such as support for screen readers.\n \u2022 Version control: As your projects grow and complexity increases, version control tools can be beneficial for tracking changes.", "source_file": "trl/orpo_trainer.md", "section_heading": "train_orpo.py", "char_start": 5000, "char_end": 5926, "token_estimate": 231, "prev_chunk_id": 324, "next_chunk_id": 326, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 326, "text": "## Expected dataset type\n\nORPO requires a [preference dataset](dataset_formats#preference). The [experimental.orpo.ORPOTrainer](/docs/trl/v1.2.0/en/orpo_trainer#trl.experimental.orpo.ORPOTrainer) supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset format. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset.\n\nAlthough the [experimental.orpo.ORPOTrainer](/docs/trl/v1.2.0/en/orpo_trainer#trl.experimental.orpo.ORPOTrainer) supports both explicit and implicit prompts, we recommend using explicit prompts. If provided with an implicit prompt dataset, the trainer will automatically extract the prompt from the `\"chosen\"` and `\"rejected\"` columns. For more information, refer to the [preference style](dataset_formats#preference) section.", "source_file": "trl/orpo_trainer.md", "section_heading": "Expected dataset type", "char_start": 5928, "char_end": 6787, "token_estimate": 214, "prev_chunk_id": 325, "next_chunk_id": 327, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 327, "text": "## Example script\n\nWe provide an example script to train a model using the ORPO method. The script is available in [`examples/scripts/orpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/orpo.py)\n\nTo test the ORPO script with the [Qwen2 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) on the [UltraFeedback dataset](https://huggingface.co/datasets/trl-lib/ultrafeedback_binarized), run the following command:\n\n```bash\naccelerate launch examples/scripts/orpo.py \\\n --model_name_or_path Qwen/Qwen2-0.5B-Instruct \\\n --dataset_name trl-lib/ultrafeedback_binarized \\\n --num_train_epochs 1 \\\n --output_dir Qwen2-0.5B-ORPO\n```", "source_file": "trl/orpo_trainer.md", "section_heading": "Example script", "char_start": 6789, "char_end": 7452, "token_estimate": 165, "prev_chunk_id": 326, "next_chunk_id": 328, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 328, "text": "## Usage tips", "source_file": "trl/orpo_trainer.md", "section_heading": "Usage tips", "char_start": 7454, "char_end": 7467, "token_estimate": 3, "prev_chunk_id": 327, "next_chunk_id": 329, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 329, "text": "### For Mixture of Experts Models: Enabling the auxiliary loss\n\nMOEs are the most efficient if the load is about equally distributed between experts. \nTo ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss.\n\nThis option is enabled by setting `output_router_logits=True` in the model config (e.g. [MixtralConfig](https://huggingface.co/docs/transformers/v5.5.4/en/model_doc/mixtral#transformers.MixtralConfig)). \nTo scale how much the auxiliary loss contributes to the total loss, use the hyperparameter `router_aux_loss_coef=...` (default: `0.001`) in the model config.", "source_file": "trl/orpo_trainer.md", "section_heading": "For Mixture of Experts Models: Enabling the auxiliary loss", "char_start": 7469, "char_end": 8134, "token_estimate": 166, "prev_chunk_id": 328, "next_chunk_id": 330, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 330, "text": "## Logged metrics\n\nWhile training and evaluating, we record the following reward metrics:\n\n- `rewards/chosen`: the mean log probabilities of the policy model for the chosen responses scaled by beta\n- `rewards/rejected`: the mean log probabilities of the policy model for the rejected responses scaled by beta\n- `rewards/accuracies`: mean of how often the chosen rewards are > than the corresponding rejected rewards\n- `rewards/margins`: the mean difference between the chosen and corresponding rejected rewards\n- `log_odds_chosen`: the mean log odds ratio of the chosen responses over the rejected responses\n- `log_odds_ratio`: the mean of the `log(sigmoid(log_odds_chosen))`\n- `nll_loss`: the mean negative log likelihood loss from the SFT part of the loss over chosen responses", "source_file": "trl/orpo_trainer.md", "section_heading": "Logged metrics", "char_start": 8136, "char_end": 8915, "token_estimate": 194, "prev_chunk_id": 329, "next_chunk_id": 331, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 331, "text": "## ORPOTrainer[[trl.experimental.orpo.ORPOTrainer]]", "source_file": "trl/orpo_trainer.md", "section_heading": "ORPOTrainer[[trl.experimental.orpo.ORPOTrainer]]", "char_start": 8917, "char_end": 8968, "token_estimate": 12, "prev_chunk_id": 330, "next_chunk_id": 332, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 332, "text": "#### trl.experimental.orpo.ORPOTrainer[[trl.experimental.orpo.ORPOTrainer]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/orpo/orpo_trainer.py#L85)\n\nInitialize ORPOTrainer.", "source_file": "trl/orpo_trainer.md", "section_heading": "trl.experimental.orpo.ORPOTrainer[[trl.experimental.orpo.ORPOTrainer]]", "char_start": 8970, "char_end": 9170, "token_estimate": 50, "prev_chunk_id": 331, "next_chunk_id": 333, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 333, "text": "traintrl.experimental.orpo.ORPOTrainer.trainhttps://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L1323[{\"name\": \"resume_from_checkpoint\", \"val\": \": str | bool | None = None\"}, {\"name\": \"trial\", \"val\": \": optuna.Trial | dict[str, Any] | None = None\"}, {\"name\": \"ignore_keys_for_eval\", \"val\": \": list[str] | None = None\"}]- **resume_from_checkpoint** (`str` or `bool`, *optional*) --\n If a `str`, local path to a saved checkpoint as saved by a previous instance of `Trainer`. If a\n `bool` and equals `True`, load the last checkpoint in *args.output_dir* as saved by a previous instance\n of `Trainer`. If present, training will resume from the model/optimizer/scheduler states loaded here.\n- **trial** (`optuna.Trial` or `dict[str, Any]`, *optional*) --\n The trial run or the hyperparameter dictionary for hyperparameter search.\n- **ignore_keys_for_eval** (`list[str]`, *optional*) --\n A list of keys in the output of your model (if it is a dictionary) that should be ignored when\n gathering predictions for evaluation during the training.0`~trainer_utils.TrainOutput`Object containing the global step count, training loss, and metrics.", "source_file": "trl/orpo_trainer.md", "section_heading": "trl.experimental.orpo.ORPOTrainer[[trl.experimental.orpo.ORPOTrainer]]", "char_start": 9172, "char_end": 10329, "token_estimate": 289, "prev_chunk_id": 332, "next_chunk_id": 334, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 334, "text": "Main training entry point.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel)) : The model to train, preferably an [AutoModelForSequenceClassification](https://huggingface.co/docs/transformers/v5.5.4/en/model_doc/auto#transformers.AutoModelForSequenceClassification).\n\nargs ([experimental.orpo.ORPOConfig](/docs/trl/v1.2.0/en/orpo_trainer#trl.experimental.orpo.ORPOConfig)) : The ORPO config arguments to use for training.\n\ndata_collator (`DataCollator`) : The data collator to use for training. If None is specified, the default data collator (`experimental.utils.DPODataCollatorWithPadding`) will be used which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences.\n\ntrain_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset)) : The dataset to use for training.", "source_file": "trl/orpo_trainer.md", "section_heading": "trl.experimental.orpo.ORPOTrainer[[trl.experimental.orpo.ORPOTrainer]]", "char_start": 10331, "char_end": 11306, "token_estimate": 243, "prev_chunk_id": 333, "next_chunk_id": 335, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 335, "text": "eval_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset)) : The dataset to use for evaluation.\n\nprocessing_class ([PreTrainedTokenizerBase](https://huggingface.co/docs/transformers/v5.5.4/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase), [BaseImageProcessor](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/image_processor#transformers.BaseImageProcessor), [FeatureExtractionMixin](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/feature_extractor#transformers.FeatureExtractionMixin) or [ProcessorMixin](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/processors#transformers.ProcessorMixin), *optional*) : Processing class used to process the data. If provided, will be used to automatically process the inputs for the model, and it will be saved along the model to make it easier to rerun an interrupted training or reuse the fine-tuned model.", "source_file": "trl/orpo_trainer.md", "section_heading": "trl.experimental.orpo.ORPOTrainer[[trl.experimental.orpo.ORPOTrainer]]", "char_start": 11308, "char_end": 12285, "token_estimate": 244, "prev_chunk_id": 334, "next_chunk_id": 336, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 336, "text": "model_init (`Callable[[], transformers.PreTrainedModel]`) : The model initializer to use for training. If None is specified, the default model initializer will be used.\n\ncallbacks (`list[transformers.TrainerCallback]`) : The callbacks to use for training.\n\noptimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`) : The optimizer and scheduler to use for training.\n\npreprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`) : The function to use to preprocess the logits before computing the metrics.\n\npeft_config (`dict`, defaults to `None`) : The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model.\n\ncompute_metrics (`Callable[[EvalPrediction], dict]`, *optional*) : The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to metric values.\n\n**Returns:**\n\n``~trainer_utils.TrainOutput``\n\nObject containing the global step count, training loss, and metrics.", "source_file": "trl/orpo_trainer.md", "section_heading": "trl.experimental.orpo.ORPOTrainer[[trl.experimental.orpo.ORPOTrainer]]", "char_start": 12287, "char_end": 13309, "token_estimate": 255, "prev_chunk_id": 335, "next_chunk_id": 337, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 337, "text": "#### save_model[[trl.experimental.orpo.ORPOTrainer.save_model]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L3746)\n\nWill save the model, so you can reload it using `from_pretrained()`.\n\nWill only save from the main process.", "source_file": "trl/orpo_trainer.md", "section_heading": "save_model[[trl.experimental.orpo.ORPOTrainer.save_model]]", "char_start": 13310, "char_end": 13570, "token_estimate": 65, "prev_chunk_id": 336, "next_chunk_id": 338, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 338, "text": "#### push_to_hub[[trl.experimental.orpo.ORPOTrainer.push_to_hub]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L3993)\n\nUpload `self.model` and `self.processing_class` to the \ud83e\udd17 model hub on the repo `self.args.hub_model_id`.\n\n**Parameters:**\n\ncommit_message (`str`, *optional*, defaults to `\"End of training\"`) : Message to commit while pushing.\n\nblocking (`bool`, *optional*, defaults to `True`) : Whether the function should return only when the `git push` has finished.\n\ntoken (`str`, *optional*, defaults to `None`) : Token with write permission to overwrite Trainer's original args.\n\nrevision (`str`, *optional*) : The git revision to commit from. Defaults to the head of the \"main\" branch.\n\nkwargs (`dict[str, Any]`, *optional*) : Additional keyword arguments passed along to `~Trainer.create_model_card`.\n\n**Returns:**\n\nThe URL of the repository where the model was pushed if `blocking=False`, or a `Future` object tracking the\nprogress of the commit if `blocking=True`.", "source_file": "trl/orpo_trainer.md", "section_heading": "push_to_hub[[trl.experimental.orpo.ORPOTrainer.push_to_hub]]", "char_start": 13571, "char_end": 14583, "token_estimate": 253, "prev_chunk_id": 337, "next_chunk_id": 339, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 339, "text": "## ORPOConfig[[trl.experimental.orpo.ORPOConfig]]", "source_file": "trl/orpo_trainer.md", "section_heading": "ORPOConfig[[trl.experimental.orpo.ORPOConfig]]", "char_start": 14585, "char_end": 14634, "token_estimate": 12, "prev_chunk_id": 338, "next_chunk_id": 340, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 340, "text": "#### trl.experimental.orpo.ORPOConfig[[trl.experimental.orpo.ORPOConfig]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/orpo/orpo_config.py#L22)\n\nConfiguration class for the [experimental.orpo.ORPOTrainer](/docs/trl/v1.2.0/en/orpo_trainer#trl.experimental.orpo.ORPOTrainer).\n\nThis class includes only the parameters that are specific to ORPO training. For a full list of training arguments,\nplease refer to the [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments) documentation. Note that default values in this class may\ndiffer from those in [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments).", "source_file": "trl/orpo_trainer.md", "section_heading": "trl.experimental.orpo.ORPOConfig[[trl.experimental.orpo.ORPOConfig]]", "char_start": 14636, "char_end": 15402, "token_estimate": 191, "prev_chunk_id": 339, "next_chunk_id": 341, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 341, "text": "Using [HfArgumentParser](https://huggingface.co/docs/transformers/v5.5.4/en/internal/trainer_utils#transformers.HfArgumentParser) we can turn this class into\n[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the\ncommand line.\n\n> [!NOTE]\n> These parameters have default values different from [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments):\n> - `logging_steps`: Defaults to `10` instead of `500`.\n> - `gradient_checkpointing`: Defaults to `True` instead of `False`.\n> - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.\n> - `learning_rate`: Defaults to `1e-6` instead of `5e-5`.\n\n**Parameters:**\n\nmax_length (`int` or `None`, *optional*, defaults to `1024`) : Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want to use the default data collator.", "source_file": "trl/orpo_trainer.md", "section_heading": "trl.experimental.orpo.ORPOConfig[[trl.experimental.orpo.ORPOConfig]]", "char_start": 15404, "char_end": 16353, "token_estimate": 237, "prev_chunk_id": 340, "next_chunk_id": 342, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 342, "text": "max_completion_length (`int`, *optional*) : Maximum length of the completion. This argument is required if you want to use the default data collator and your model is an encoder-decoder.\n\nbeta (`float`, *optional*, defaults to `0.1`) : Parameter controlling the relative ratio loss weight in the ORPO loss. In the [paper](https://huggingface.co/papers/2403.07691), it is denoted by \u03bb. In the [code](https://github.com/xfactlab/orpo), it is denoted by `alpha`.\n\ndisable_dropout (`bool`, *optional*, defaults to `True`) : Whether to disable dropout in the model.\n\npadding_value (`int`, *optional*) : Padding value to use. If `None`, the padding value of the tokenizer is used.\n\ngenerate_during_eval (`bool`, *optional*, defaults to `False`) : If `True`, generates and logs completions from the model to W&B or Comet during evaluation.", "source_file": "trl/orpo_trainer.md", "section_heading": "trl.experimental.orpo.ORPOConfig[[trl.experimental.orpo.ORPOConfig]]", "char_start": 16355, "char_end": 17187, "token_estimate": 208, "prev_chunk_id": 341, "next_chunk_id": 343, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 343, "text": "is_encoder_decoder (`bool`, *optional*) : When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument, you need to specify if the model returned by the callable is an encoder-decoder model.\n\nmodel_init_kwargs (`dict[str, Any]`, *optional*) : Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a string.\n\ndataset_num_proc (`int`, *optional*) : Number of processes to use for processing the dataset.", "source_file": "trl/orpo_trainer.md", "section_heading": "trl.experimental.orpo.ORPOConfig[[trl.experimental.orpo.ORPOConfig]]", "char_start": 17189, "char_end": 17682, "token_estimate": 123, "prev_chunk_id": 342, "next_chunk_id": null, "url": "https://huggingface.co/docs/trl/orpo_trainer", "doc_title": "ORPO Trainer" }, { "chunk_id": 344, "text": "# CPO Trainer\n\n[![model badge](https://img.shields.io/badge/All_models-CPO-blue)](https://huggingface.co/models?other=cpo,trl)", "source_file": "trl/cpo_trainer.md", "section_heading": "CPO Trainer", "char_start": 0, "char_end": 126, "token_estimate": 31, "prev_chunk_id": null, "next_chunk_id": 345, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 345, "text": "## Overview\n\nContrastive Preference Optimization (CPO) as introduced in the paper [Contrastive Preference Optimization: Pushing the Boundaries of LLM Performance in Machine Translation](https://huggingface.co/papers/2401.08417) by [Haoran Xu](https://huggingface.co/haoranxu), [Amr Sharaf](https://huggingface.co/amrsharaf), [Yunmo Chen](https://huggingface.co/yunmochen), Weiting Tan, Lingfeng Shen, Benjamin Van Durme, [Kenton Murray](https://huggingface.co/Kenton), and [Young Jin Kim](https://huggingface.co/ykim362). At a high level, CPO trains models to avoid generating adequate, but not perfect, translations in Machine Translation (MT) tasks. However, CPO is a general approximation of the DPO loss and can be applied to other domains, such as chat.", "source_file": "trl/cpo_trainer.md", "section_heading": "Overview", "char_start": 128, "char_end": 886, "token_estimate": 189, "prev_chunk_id": 344, "next_chunk_id": 346, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 346, "text": "CPO aims to mitigate two fundamental shortcomings of SFT. First, SFT\u2019s methodology of minimizing the discrepancy between predicted outputs and gold-standard references inherently caps model performance at the quality level of the training data. Secondly, SFT lacks a mechanism to prevent the model from rejecting mistakes in translations. The CPO objective is derived from the DPO objective.", "source_file": "trl/cpo_trainer.md", "section_heading": "Overview", "char_start": 888, "char_end": 1279, "token_estimate": 97, "prev_chunk_id": 345, "next_chunk_id": 347, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 347, "text": "## Quick start\n\nThis example demonstrates how to train a model using the CPO method. We use the [Qwen 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) as the base model. We use the preference data from the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback). You can view the data in the dataset here:\n\nBelow is the script to train the model:\n\n```python", "source_file": "trl/cpo_trainer.md", "section_heading": "Quick start", "char_start": 1281, "char_end": 1673, "token_estimate": 98, "prev_chunk_id": 346, "next_chunk_id": 348, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 348, "text": "# train_cpo.py\nfrom datasets import load_dataset\nfrom trl.experimental.cpo import CPOConfig, CPOTrainer\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\nmodel = AutoModelForCausalLM.from_pretrained(\"Qwen/Qwen2-0.5B-Instruct\")\ntokenizer = AutoTokenizer.from_pretrained(\"Qwen/Qwen2-0.5B-Instruct\")\ntrain_dataset = load_dataset(\"trl-lib/ultrafeedback_binarized\", split=\"train\")\n\ntraining_args = CPOConfig(output_dir=\"Qwen2-0.5B-CPO\")\ntrainer = CPOTrainer(model=model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset)\ntrainer.train()\n```\n\nExecute the script using the following command:\n\n```bash\naccelerate launch train_cpo.py\n```", "source_file": "trl/cpo_trainer.md", "section_heading": "train_cpo.py", "char_start": 1674, "char_end": 2341, "token_estimate": 166, "prev_chunk_id": 347, "next_chunk_id": 349, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 349, "text": "## Expected dataset type\n\nCPO requires a [preference dataset](dataset_formats#preference). The [experimental.cpo.CPOTrainer](/docs/trl/v1.2.0/en/cpo_trainer#trl.experimental.cpo.CPOTrainer) supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset.", "source_file": "trl/cpo_trainer.md", "section_heading": "Expected dataset type", "char_start": 2343, "char_end": 2769, "token_estimate": 106, "prev_chunk_id": 348, "next_chunk_id": 350, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 350, "text": "## Example script\n\nWe provide an example script to train a model using the CPO method. The script is available in [`examples/scripts/cpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/cpo.py)\n\nTo test the CPO script with the [Qwen2 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) on the [UltraFeedback dataset](https://huggingface.co/datasets/trl-lib/ultrafeedback_binarized), run the following command:\n\n```bash\naccelerate launch examples/scripts/cpo.py \\\n --model_name_or_path Qwen/Qwen2-0.5B-Instruct \\\n --dataset_name trl-lib/ultrafeedback_binarized \\\n --num_train_epochs 1 \\\n --output_dir Qwen2-0.5B-CPO\n```", "source_file": "trl/cpo_trainer.md", "section_heading": "Example script", "char_start": 2771, "char_end": 3428, "token_estimate": 164, "prev_chunk_id": 349, "next_chunk_id": 351, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 351, "text": "## Logged metrics\n\nWhile training and evaluating, we record the following reward metrics:\n\n* `rewards/chosen`: the mean log probabilities of the policy model for the chosen responses scaled by beta\n* `rewards/rejected`: the mean log probabilities of the policy model for the rejected responses scaled by beta\n* `rewards/accuracies`: mean of how often the chosen rewards are > than the corresponding rejected rewards\n* `rewards/margins`: the mean difference between the chosen and corresponding rejected rewards\n* `nll_loss`: the mean negative log likelihood loss of the policy model for the chosen responses", "source_file": "trl/cpo_trainer.md", "section_heading": "Logged metrics", "char_start": 3430, "char_end": 4037, "token_estimate": 151, "prev_chunk_id": 350, "next_chunk_id": 352, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 352, "text": "## CPO variants", "source_file": "trl/cpo_trainer.md", "section_heading": "CPO variants", "char_start": 4039, "char_end": 4054, "token_estimate": 3, "prev_chunk_id": 351, "next_chunk_id": 353, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 353, "text": "### Simple Preference Optimization (SimPO)\n\n[Simple Preference Optimization](https://huggingface.co/papers/2405.14734) (SimPO) by [Yu Meng](https://huggingface.co/yumeng5), [Mengzhou Xia](https://huggingface.co/mengzhouxia), and [Danqi Chen](https://huggingface.co/cdq10131) proposes a simpler and more effective preference optimization algorithm than DPO without using a reference model. The key designs in SimPO are (1) using length-normalized log likelihood as the implicit reward, and (2) incorporating a target reward margin in the Bradley-Terry ranking objective. The official code can be found at [princeton-nlp/SimPO](https://github.com/princeton-nlp/SimPO).\n\nThe abstract from the paper is the following:", "source_file": "trl/cpo_trainer.md", "section_heading": "Simple Preference Optimization (SimPO)", "char_start": 4056, "char_end": 4769, "token_estimate": 178, "prev_chunk_id": 352, "next_chunk_id": 354, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 354, "text": "> Direct Preference Optimization (DPO) is a widely used offline preference optimization algorithm that reparameterizes reward functions in reinforcement learning from human feedback (RLHF) to enhance simplicity and training stability. In this work, we propose SimPO, a simpler yet more effective approach. The effectiveness of SimPO is attributed to a key design: using the average log probability of a sequence as the implicit reward. This reward formulation better aligns with model generation and eliminates the need for a reference model, making it more compute and memory efficient. Additionally, we introduce a target reward margin to the Bradley-Terry objective to encourage a larger margin between the winning and losing responses, further enhancing the algorithm's performance. We compare SimPO to DPO and its latest variants across various state-of-the-art training setups, including both base and instruction-tuned models like Mistral and Llama3. We evaluated on extensive instruction-following benchmarks, including AlpacaEval 2, MT-Bench, and the recent challenging Arena-Hard benchmark. Our results demonstrate that SimPO consistently and significantly outperforms existing approaches without substantially increasing response length. Specifically, SimPO outperforms DPO by up to 6.4 points on AlpacaEval 2 and by up to 7.5 points on Arena-Hard. Our top-performing model, built on Llama3-8B-Instruct, achieves a remarkable 44.7 length-controlled win rate on AlpacaEval 2 -- surpassing Claude 3 Opus on the leaderboard, and a 33.8 win rate on Arena-Hard -- making it the strongest 8B open-source model.", "source_file": "trl/cpo_trainer.md", "section_heading": "Simple Preference Optimization (SimPO)", "char_start": 4771, "char_end": 6386, "token_estimate": 403, "prev_chunk_id": 353, "next_chunk_id": 355, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 355, "text": "The SimPO loss is integrated in the [experimental.cpo.CPOTrainer](/docs/trl/v1.2.0/en/cpo_trainer#trl.experimental.cpo.CPOTrainer), as it's an alternative loss that adds a reward margin, allows for length normalization, and does not use BC regularization. To use this loss, just turn on `loss_type=\"simpo\"` and `cpo_alpha=0.0` in the [experimental.cpo.CPOConfig](/docs/trl/v1.2.0/en/cpo_trainer#trl.experimental.cpo.CPOConfig) and set the `simpo_gamma` to a recommended value.", "source_file": "trl/cpo_trainer.md", "section_heading": "Simple Preference Optimization (SimPO)", "char_start": 6388, "char_end": 6864, "token_estimate": 119, "prev_chunk_id": 354, "next_chunk_id": 356, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 356, "text": "### CPO-SimPO\n\nWe also offer the combined use of CPO and SimPO, which enables more stable training and improved performance. Learn more details at [CPO-SimPO GitHub](https://github.com/fe1ixxu/CPO_SIMPO). To use this method, simply enable SimPO by setting `loss_type=\"simpo\"` and a non-zero `cpo_alpha` in the [experimental.cpo.CPOConfig](/docs/trl/v1.2.0/en/cpo_trainer#trl.experimental.cpo.CPOConfig).", "source_file": "trl/cpo_trainer.md", "section_heading": "CPO-SimPO", "char_start": 6866, "char_end": 7269, "token_estimate": 100, "prev_chunk_id": 355, "next_chunk_id": 357, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 357, "text": "### AlphaPO\n\nThe [AlphaPO -- Reward shape matters for LLM alignment](https://huggingface.co/papers/2501.03884) (AlphaPO) method by Aman Gupta, Shao Tang, Qingquan Song, Sirou Zhu, [Jiwoo Hong](https://huggingface.co/JW17), Ankan Saha, Viral Gupta, Noah Lee, Eunki Kim, Jason Zhu, Natesh Pillai, and S. Sathiya Keerthi is also implemented in the [experimental.cpo.CPOTrainer](/docs/trl/v1.2.0/en/cpo_trainer#trl.experimental.cpo.CPOTrainer). AlphaPO is an alternative method that applies a transformation to the reward function shape in the context of SimPO loss. The abstract from the paper is the following:", "source_file": "trl/cpo_trainer.md", "section_heading": "AlphaPO", "char_start": 7271, "char_end": 7879, "token_estimate": 152, "prev_chunk_id": 356, "next_chunk_id": 358, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 358, "text": "> Reinforcement Learning with Human Feedback (RLHF) and its variants have made huge strides toward the effective alignment of large language models (LLMs) to follow instructions and reflect human values. More recently, Direct Alignment Algorithms (DAAs) have emerged in which the reward modeling stage of RLHF is skipped by characterizing the reward directly as a function of the policy being learned. Some popular examples of DAAs include Direct Preference Optimization (DPO) and Simple Preference Optimization (SimPO). These methods often suffer from likelihood displacement, a phenomenon by which the probabilities of preferred responses are often reduced undesirably. In this paper, we argue that, for DAAs the reward (function) shape matters. We introduce AlphaPO, a new DAA method that leverages an \u03b1-parameter to help change the shape of the reward function beyond the standard log reward. AlphaPO helps maintain fine-grained control over likelihood displacement and overoptimization. Compared to SimPO, one of the best performing DAAs, AlphaPO leads to about 7% to 10% relative improvement in alignment performance for the instruct versions of Mistral-7B and Llama3-8B while achieving 15% to 50% relative improvement over DPO on the same models. The analysis and results presented highlight the importance of the reward shape and how one can systematically change it to affect training dynamics, as well as improve alignment performance.", "source_file": "trl/cpo_trainer.md", "section_heading": "AlphaPO", "char_start": 7881, "char_end": 9326, "token_estimate": 361, "prev_chunk_id": 357, "next_chunk_id": 359, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 359, "text": "To use this loss as described in the paper, we can set the `loss_type=\"alphapo\"` which automatically sets `loss_type=\"simpo\"` and `cpo_alpha=0.0`, together with `alpha` and `simpo_gamma` to recommended values in the [experimental.cpo.CPOConfig](/docs/trl/v1.2.0/en/cpo_trainer#trl.experimental.cpo.CPOConfig). Alternatively, you can manually set `loss_type=\"simpo\"`, `cpo_alpha=0.0`, together with `alpha` and `simpo_gamma` to recommended values. Other variants of this method are also possible, such as setting `loss_type=\"ipo\"` and `alpha` to any non-zero value.", "source_file": "trl/cpo_trainer.md", "section_heading": "AlphaPO", "char_start": 9328, "char_end": 9892, "token_estimate": 141, "prev_chunk_id": 358, "next_chunk_id": 360, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 360, "text": "## Loss functions\n\nThe CPO algorithm supports several loss functions. The loss function can be set using the `loss_type` parameter in the [experimental.cpo.CPOConfig](/docs/trl/v1.2.0/en/cpo_trainer#trl.experimental.cpo.CPOConfig). The following loss functions are supported:", "source_file": "trl/cpo_trainer.md", "section_heading": "Loss functions", "char_start": 9894, "char_end": 10169, "token_estimate": 68, "prev_chunk_id": 359, "next_chunk_id": 361, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 361, "text": "| `loss_type=` | Description |\n| --- | --- |\n| `\"sigmoid\"` (default) | Given the preference data, we can fit a binary classifier according to the Bradley-Terry model, and in fact, the [DPO](https://huggingface.co/papers/2305.18290) authors propose the sigmoid loss on the normalized likelihood via the `logsigmoid` to fit a logistic regression. |\n| `\"hinge\"` | The [RSO](https://huggingface.co/papers/2309.06657) authors propose to use a hinge loss on the normalized likelihood from the [SLiC](https://huggingface.co/papers/2305.10425) paper. In this case, the `beta` is the reciprocal of the margin. |\n| `\"ipo\"` | The [IPO](https://huggingface.co/papers/2310.12036) authors provide a deeper theoretical understanding of the DPO algorithms and identify an issue with overfitting and propose an alternative loss. In this case, the `beta` is the reciprocal of the gap between the log-likelihood ratios of the chosen vs the rejected completion pair, and thus the smaller the `beta`, the larger this gap is. As per the paper, the loss is averaged over log-likelihoods of the completion (unlike DPO, which is summed only). |\n| `\"simpo\"` | The [SimPO](https://huggingface.co/papers/2405.14734) method is also implemented in the [experimental.cpo.CPOTrainer](/docs/trl/v1.2.0/en/cpo_trainer#trl.experimental.cpo.CPOTrainer). SimPO is an alternative loss that adds a reward margin, allows for length normalization, and does not use BC regularization. To use this loss, simply set `loss_type=\"simpo\"` and `cpo_alpha=0.0` in the [experimental.cpo.CPOConfig](/docs/trl/v1.2.0/en/cpo_trainer#trl.experimental.cpo.CPOConfig) and `simpo_gamma` to a recommended value. |\n| `\"alphapo\"` | The [AlphaPO](https://huggingface.co/papers/2501.03884) method is also implemented in the [experimental.cpo.CPOTrainer](/docs/trl/v1.2.0/en/cpo_trainer#trl.experimental.cpo.CPOTrainer). This is syntactic sugar that automatically sets `loss_type=\"simpo\"` and `cpo_alpha=0.0`. AlphaPO applies a transformation to the reward function shape in the context of SimPO loss when the `alpha` parameter is non-zero. |", "source_file": "trl/cpo_trainer.md", "section_heading": "Loss functions", "char_start": 10171, "char_end": 12250, "token_estimate": 519, "prev_chunk_id": 360, "next_chunk_id": 362, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 362, "text": "### For Mixture of Experts Models: Enabling the auxiliary loss\n\nMOEs are the most efficient if the load is about equally distributed between experts. \nTo ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss.\n\nThis option is enabled by setting `output_router_logits=True` in the model config (e.g., [MixtralConfig](https://huggingface.co/docs/transformers/v5.5.4/en/model_doc/mixtral#transformers.MixtralConfig)). \nTo scale how much the auxiliary loss contributes to the total loss, use the hyperparameter `router_aux_loss_coef=...` (default: `0.001`) in the model config.", "source_file": "trl/cpo_trainer.md", "section_heading": "For Mixture of Experts Models: Enabling the auxiliary loss", "char_start": 12252, "char_end": 12918, "token_estimate": 166, "prev_chunk_id": 361, "next_chunk_id": 363, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 363, "text": "## CPOTrainer[[trl.experimental.cpo.CPOTrainer]]", "source_file": "trl/cpo_trainer.md", "section_heading": "CPOTrainer[[trl.experimental.cpo.CPOTrainer]]", "char_start": 12920, "char_end": 12968, "token_estimate": 12, "prev_chunk_id": 362, "next_chunk_id": 364, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 364, "text": "#### trl.experimental.cpo.CPOTrainer[[trl.experimental.cpo.CPOTrainer]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/cpo/cpo_trainer.py#L74)\n\nInitialize CPOTrainer.", "source_file": "trl/cpo_trainer.md", "section_heading": "trl.experimental.cpo.CPOTrainer[[trl.experimental.cpo.CPOTrainer]]", "char_start": 12970, "char_end": 13163, "token_estimate": 48, "prev_chunk_id": 363, "next_chunk_id": 365, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 365, "text": "traintrl.experimental.cpo.CPOTrainer.trainhttps://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L1323[{\"name\": \"resume_from_checkpoint\", \"val\": \": str | bool | None = None\"}, {\"name\": \"trial\", \"val\": \": optuna.Trial | dict[str, Any] | None = None\"}, {\"name\": \"ignore_keys_for_eval\", \"val\": \": list[str] | None = None\"}]- **resume_from_checkpoint** (`str` or `bool`, *optional*) --\n If a `str`, local path to a saved checkpoint as saved by a previous instance of `Trainer`. If a\n `bool` and equals `True`, load the last checkpoint in *args.output_dir* as saved by a previous instance\n of `Trainer`. If present, training will resume from the model/optimizer/scheduler states loaded here.\n- **trial** (`optuna.Trial` or `dict[str, Any]`, *optional*) --\n The trial run or the hyperparameter dictionary for hyperparameter search.\n- **ignore_keys_for_eval** (`list[str]`, *optional*) --\n A list of keys in the output of your model (if it is a dictionary) that should be ignored when\n gathering predictions for evaluation during the training.0`~trainer_utils.TrainOutput`Object containing the global step count, training loss, and metrics.", "source_file": "trl/cpo_trainer.md", "section_heading": "trl.experimental.cpo.CPOTrainer[[trl.experimental.cpo.CPOTrainer]]", "char_start": 13165, "char_end": 14320, "token_estimate": 288, "prev_chunk_id": 364, "next_chunk_id": 366, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 366, "text": "Main training entry point.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel)) : The model to train, preferably an [AutoModelForSequenceClassification](https://huggingface.co/docs/transformers/v5.5.4/en/model_doc/auto#transformers.AutoModelForSequenceClassification).\n\nargs ([experimental.cpo.CPOConfig](/docs/trl/v1.2.0/en/cpo_trainer#trl.experimental.cpo.CPOConfig)) : The CPO config arguments to use for training.\n\ndata_collator (`DataCollator`) : The data collator to use for training. If None is specified, the default data collator (`experimental.utils.DPODataCollatorWithPadding`) will be used which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences.\n\ntrain_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset)) : The dataset to use for training.", "source_file": "trl/cpo_trainer.md", "section_heading": "trl.experimental.cpo.CPOTrainer[[trl.experimental.cpo.CPOTrainer]]", "char_start": 14322, "char_end": 15291, "token_estimate": 242, "prev_chunk_id": 365, "next_chunk_id": 367, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 367, "text": "eval_dataset ([Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset)) : The dataset to use for evaluation.\n\nprocessing_class ([PreTrainedTokenizerBase](https://huggingface.co/docs/transformers/v5.5.4/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase), [BaseImageProcessor](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/image_processor#transformers.BaseImageProcessor), [FeatureExtractionMixin](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/feature_extractor#transformers.FeatureExtractionMixin) or [ProcessorMixin](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/processors#transformers.ProcessorMixin), *optional*) : Processing class used to process the data. If provided, will be used to automatically process the inputs for the model, and it will be saved along the model to make it easier to rerun an interrupted training or reuse the fine-tuned model.", "source_file": "trl/cpo_trainer.md", "section_heading": "trl.experimental.cpo.CPOTrainer[[trl.experimental.cpo.CPOTrainer]]", "char_start": 15293, "char_end": 16270, "token_estimate": 244, "prev_chunk_id": 366, "next_chunk_id": 368, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 368, "text": "model_init (`Callable[[], transformers.PreTrainedModel]`) : The model initializer to use for training. If None is specified, the default model initializer will be used.\n\ncallbacks (`list[transformers.TrainerCallback]`) : The callbacks to use for training.\n\noptimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`) : The optimizer and scheduler to use for training.\n\npreprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`) : The function to use to preprocess the logits before computing the metrics.\n\npeft_config (`dict`, defaults to `None`) : The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model.\n\ncompute_metrics (`Callable[[EvalPrediction], dict]`, *optional*) : The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to metric values.\n\n**Returns:**\n\n``~trainer_utils.TrainOutput``\n\nObject containing the global step count, training loss, and metrics.", "source_file": "trl/cpo_trainer.md", "section_heading": "trl.experimental.cpo.CPOTrainer[[trl.experimental.cpo.CPOTrainer]]", "char_start": 16272, "char_end": 17294, "token_estimate": 255, "prev_chunk_id": 367, "next_chunk_id": 369, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 369, "text": "#### save_model[[trl.experimental.cpo.CPOTrainer.save_model]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L3746)\n\nWill save the model, so you can reload it using `from_pretrained()`.\n\nWill only save from the main process.", "source_file": "trl/cpo_trainer.md", "section_heading": "save_model[[trl.experimental.cpo.CPOTrainer.save_model]]", "char_start": 17295, "char_end": 17553, "token_estimate": 64, "prev_chunk_id": 368, "next_chunk_id": 370, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 370, "text": "#### push_to_hub[[trl.experimental.cpo.CPOTrainer.push_to_hub]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/transformers/trainer.py#L3993)\n\nUpload `self.model` and `self.processing_class` to the \ud83e\udd17 model hub on the repo `self.args.hub_model_id`.\n\n**Parameters:**\n\ncommit_message (`str`, *optional*, defaults to `\"End of training\"`) : Message to commit while pushing.\n\nblocking (`bool`, *optional*, defaults to `True`) : Whether the function should return only when the `git push` has finished.\n\ntoken (`str`, *optional*, defaults to `None`) : Token with write permission to overwrite Trainer's original args.\n\nrevision (`str`, *optional*) : The git revision to commit from. Defaults to the head of the \"main\" branch.\n\nkwargs (`dict[str, Any]`, *optional*) : Additional keyword arguments passed along to `~Trainer.create_model_card`.\n\n**Returns:**\n\nThe URL of the repository where the model was pushed if `blocking=False`, or a `Future` object tracking the\nprogress of the commit if `blocking=True`.", "source_file": "trl/cpo_trainer.md", "section_heading": "push_to_hub[[trl.experimental.cpo.CPOTrainer.push_to_hub]]", "char_start": 17554, "char_end": 18564, "token_estimate": 252, "prev_chunk_id": 369, "next_chunk_id": 371, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 371, "text": "## CPOConfig[[trl.experimental.cpo.CPOConfig]]", "source_file": "trl/cpo_trainer.md", "section_heading": "CPOConfig[[trl.experimental.cpo.CPOConfig]]", "char_start": 18566, "char_end": 18612, "token_estimate": 11, "prev_chunk_id": 370, "next_chunk_id": 372, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 372, "text": "#### trl.experimental.cpo.CPOConfig[[trl.experimental.cpo.CPOConfig]]\n\n[Source](https://github.com/huggingface/trl/blob/v1.2.0/trl/experimental/cpo/cpo_config.py#L22)\n\nConfiguration class for the [experimental.cpo.CPOTrainer](/docs/trl/v1.2.0/en/cpo_trainer#trl.experimental.cpo.CPOTrainer).\n\nThis class includes only the parameters that are specific to CPO training. For a full list of training arguments,\nplease refer to the [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments) documentation. Note that default values in this class may\ndiffer from those in [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments).", "source_file": "trl/cpo_trainer.md", "section_heading": "trl.experimental.cpo.CPOConfig[[trl.experimental.cpo.CPOConfig]]", "char_start": 18614, "char_end": 19368, "token_estimate": 188, "prev_chunk_id": 371, "next_chunk_id": 373, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 373, "text": "Using [HfArgumentParser](https://huggingface.co/docs/transformers/v5.5.4/en/internal/trainer_utils#transformers.HfArgumentParser) we can turn this class into\n[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the\ncommand line.\n\n> [!NOTE]\n> These parameters have default values different from [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments):\n> - `logging_steps`: Defaults to `10` instead of `500`.\n> - `gradient_checkpointing`: Defaults to `True` instead of `False`.\n> - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.\n> - `learning_rate`: Defaults to `1e-6` instead of `5e-5`.\n\n**Parameters:**\n\nmax_length (`int` or `None`, *optional*, defaults to `1024`) : Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want to use the default data collator.", "source_file": "trl/cpo_trainer.md", "section_heading": "trl.experimental.cpo.CPOConfig[[trl.experimental.cpo.CPOConfig]]", "char_start": 19370, "char_end": 20319, "token_estimate": 237, "prev_chunk_id": 372, "next_chunk_id": 374, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 374, "text": "max_completion_length (`int`, *optional*) : Maximum length of the completion. This argument is required if you want to use the default data collator and your model is an encoder-decoder.\n\nbeta (`float`, *optional*, defaults to `0.1`) : Parameter controlling the deviation from the reference model. Higher \u03b2 means less deviation from the reference model. For the IPO loss (`loss_type=\"ipo\"`), \u03b2 is the regularization parameter denoted by \u03c4 in the [paper](https://huggingface.co/papers/2310.12036).\n\nlabel_smoothing (`float`, *optional*, defaults to `0.0`) : Label smoothing factor. This argument is required if you want to use the default data collator.", "source_file": "trl/cpo_trainer.md", "section_heading": "trl.experimental.cpo.CPOConfig[[trl.experimental.cpo.CPOConfig]]", "char_start": 20321, "char_end": 20973, "token_estimate": 163, "prev_chunk_id": 373, "next_chunk_id": 375, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 375, "text": "loss_type (`str`, *optional*, defaults to `\"sigmoid\"`) : Type of loss to use. Possible values are: - `\"sigmoid\"`: sigmoid loss from the original [DPO](https://huggingface.co/papers/2305.18290) paper. - `\"hinge\"`: hinge loss on the normalized likelihood from the [SLiC](https://huggingface.co/papers/2305.10425) paper. - `\"ipo\"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper. - `\"simpo\"`: SimPO loss from the [SimPO](https://huggingface.co/papers/2405.14734) paper. - `\"alphapo\"`: AlphaPO loss from the [AlphaPO](https://huggingface.co/papers/2501.03884) paper. This automatically sets `loss_type=\"simpo\"` and `cpo_alpha=0.0`. \n\ndisable_dropout (`bool`, *optional*, defaults to `True`) : Whether to disable dropout in the model.\n\ncpo_alpha (`float`, *optional*, defaults to `1.0`) : Weight of the BC regularizer in CPO training.\n\nsimpo_gamma (`float`, *optional*, defaults to `0.5`) : Target reward margin for the SimPO loss, used only when the `loss_type=\"simpo\"`.", "source_file": "trl/cpo_trainer.md", "section_heading": "trl.experimental.cpo.CPOConfig[[trl.experimental.cpo.CPOConfig]]", "char_start": 20975, "char_end": 21967, "token_estimate": 248, "prev_chunk_id": 374, "next_chunk_id": 376, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 376, "text": "alpha (`float`, *optional*, defaults to `0.0`) : Alpha parameter that controls reward function shape across all loss types. When alpha=0 (default), uses standard log probability rewards. When `alpha != 0`, applies AlphaPO transformation: `r = (1 - p^(-alpha)) / alpha` from the [AlphaPO paper](https://huggingface.co/papers/2501.03884). This parameter works with all loss types.\n\ngenerate_during_eval (`bool`, *optional*, defaults to `False`) : If `True`, generates and logs completions from the model to W&B or Comet during evaluation.\n\nis_encoder_decoder (`bool`, *optional*) : When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument, you need to specify if the model returned by the callable is an encoder-decoder model.\n\nmodel_init_kwargs (`dict[str, Any]`, *optional*) : Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a string.", "source_file": "trl/cpo_trainer.md", "section_heading": "trl.experimental.cpo.CPOConfig[[trl.experimental.cpo.CPOConfig]]", "char_start": 21969, "char_end": 22905, "token_estimate": 234, "prev_chunk_id": 375, "next_chunk_id": 377, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 377, "text": "dataset_num_proc (`int`, *optional*) : Number of processes to use for processing the dataset.", "source_file": "trl/cpo_trainer.md", "section_heading": "trl.experimental.cpo.CPOConfig[[trl.experimental.cpo.CPOConfig]]", "char_start": 22907, "char_end": 23000, "token_estimate": 23, "prev_chunk_id": 376, "next_chunk_id": null, "url": "https://huggingface.co/docs/trl/cpo_trainer", "doc_title": "CPO Trainer" }, { "chunk_id": 378, "text": "# PEFT\n\n\ud83e\udd17 PEFT (Parameter-Efficient Fine-Tuning) is a library for efficiently adapting large pretrained models to various downstream applications without fine-tuning all of a model's parameters because it is prohibitively costly. PEFT methods only fine-tune a small number of (extra) model parameters - significantly decreasing computational and storage costs - while yielding performance comparable to a fully fine-tuned model. This makes it more accessible to train and store large language models (LLMs) on consumer hardware.\n\nPEFT is integrated with the Transformers, Diffusers, and Accelerate libraries to provide a faster and easier way to load, train, and use large models for inference.", "source_file": "peft/index.md", "section_heading": "PEFT", "char_start": 0, "char_end": 694, "token_estimate": 173, "prev_chunk_id": null, "next_chunk_id": 379, "url": "https://huggingface.co/docs/peft/index", "doc_title": "PEFT" }, { "chunk_id": 379, "text": "Quicktour\n Start here if you're new to \ud83e\udd17 PEFT to get an overview of the library's main features, and how to train a model with a PEFT method.\n \n How-to guides\n Practical guides demonstrating how to apply various PEFT methods across different types of tasks like image classification, causal language modeling, automatic speech recognition, and more. Learn how to use \ud83e\udd17 PEFT with the DeepSpeed and Fully Sharded Data Parallel scripts.\n \n Conceptual guides\n Get a better theoretical understanding of how LoRA and various soft prompting methods help reduce the number of trainable parameters to make training more efficient.\n \n Reference\n Technical descriptions of how \ud83e\udd17 PEFT classes and methods work.", "source_file": "peft/index.md", "section_heading": "PEFT", "char_start": 703, "char_end": 1438, "token_estimate": 185, "prev_chunk_id": 378, "next_chunk_id": null, "url": "https://huggingface.co/docs/peft/index", "doc_title": "PEFT" }, { "chunk_id": 380, "text": "# Quicktour\n\nPEFT offers parameter-efficient methods for finetuning large pretrained models. The traditional paradigm is to finetune all of a model's parameters for each downstream task, but this is becoming exceedingly costly and impractical because of the enormous number of parameters in models today. Instead, it is more efficient to train a smaller number of prompt parameters or use a reparametrization method like low-rank adaptation (LoRA) to reduce the number of trainable parameters.\n\nThis quicktour will show you PEFT's main features and how you can train or run inference on large models that would typically be inaccessible on consumer devices.", "source_file": "peft/quicktour.md", "section_heading": "Quicktour", "char_start": 0, "char_end": 657, "token_estimate": 164, "prev_chunk_id": null, "next_chunk_id": 381, "url": "https://huggingface.co/docs/peft/quicktour", "doc_title": "Quicktour" }, { "chunk_id": 381, "text": "## Train\n\nEach PEFT method is defined by a [PeftConfig](/docs/peft/v0.19.0/en/package_reference/config#peft.PeftConfig) class that stores all the important parameters for building a [PeftModel](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel). For example, to train with LoRA, load and create a [LoraConfig](/docs/peft/v0.19.0/en/package_reference/lora#peft.LoraConfig) class and specify the following parameters:\n\n- `task_type`: the task to train for (sequence-to-sequence language modeling in this case)\n- `inference_mode`: whether you're using the model for inference or not\n- `r`: the dimension of the low-rank matrices\n- `lora_alpha`: the scaling factor for the low-rank matrices\n- `lora_dropout`: the dropout probability of the LoRA layers\n\n```python\nfrom peft import LoraConfig, TaskType\n\npeft_config = LoraConfig(task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1)\n```", "source_file": "peft/quicktour.md", "section_heading": "Train", "char_start": 659, "char_end": 1594, "token_estimate": 233, "prev_chunk_id": 380, "next_chunk_id": 382, "url": "https://huggingface.co/docs/peft/quicktour", "doc_title": "Quicktour" }, { "chunk_id": 382, "text": "> [!TIP]\n> See the [LoraConfig](/docs/peft/v0.19.0/en/package_reference/lora#peft.LoraConfig) reference for more details about other parameters you can adjust, such as the modules to target or the bias type.\n\nOnce the [LoraConfig](/docs/peft/v0.19.0/en/package_reference/lora#peft.LoraConfig) is setup, create a [PeftModel](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel) with the [get_peft_model()](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.get_peft_model) function. It takes a base model - which you can load from the Transformers library - and the [LoraConfig](/docs/peft/v0.19.0/en/package_reference/lora#peft.LoraConfig) containing the parameters for how to configure a model for training with LoRA.\n\nLoad the base model you want to finetune.\n\n```python\nfrom transformers import AutoModelForSeq2SeqLM\n\nmodel = AutoModelForSeq2SeqLM.from_pretrained(\"bigscience/mt0-large\")\n```", "source_file": "peft/quicktour.md", "section_heading": "Train", "char_start": 1596, "char_end": 2509, "token_estimate": 228, "prev_chunk_id": 381, "next_chunk_id": 383, "url": "https://huggingface.co/docs/peft/quicktour", "doc_title": "Quicktour" }, { "chunk_id": 383, "text": "Wrap the base model and `peft_config` with the [get_peft_model()](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.get_peft_model) function to create a [PeftModel](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel). To get a sense of the number of trainable parameters in your model, use the `print_trainable_parameters` method.\n\n```python\nfrom peft import get_peft_model\n\nmodel = get_peft_model(model, peft_config)\nmodel.print_trainable_parameters()\n\"output: trainable params: 2359296 || all params: 1231940608 || trainable%: 0.19151053100118282\"\n```\n\nOut of [bigscience/mt0-large's](https://huggingface.co/bigscience/mt0-large) 1.2B parameters, you're only training 0.19% of them!\n\nThat is it \ud83c\udf89! Now you can train the model with the Transformers [Trainer](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer), Accelerate, or any custom PyTorch training loop.", "source_file": "peft/quicktour.md", "section_heading": "Train", "char_start": 2511, "char_end": 3435, "token_estimate": 231, "prev_chunk_id": 382, "next_chunk_id": 384, "url": "https://huggingface.co/docs/peft/quicktour", "doc_title": "Quicktour" }, { "chunk_id": 384, "text": "For example, to train with the [Trainer](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer) class, setup a [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments) class with some training hyperparameters.\n\n```py\ntraining_args = TrainingArguments(\n output_dir=\"your-name/bigscience/mt0-large-lora\",\n learning_rate=1e-3,\n per_device_train_batch_size=32,\n per_device_eval_batch_size=32,\n num_train_epochs=2,\n weight_decay=0.01,\n eval_strategy=\"epoch\",\n save_strategy=\"epoch\",\n load_best_model_at_end=True,\n)\n```\n\nPass the model, training arguments, dataset, tokenizer, and any other necessary component to the [Trainer](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer), and call [train](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer.train) to start training.", "source_file": "peft/quicktour.md", "section_heading": "Train", "char_start": 3437, "char_end": 4422, "token_estimate": 246, "prev_chunk_id": 383, "next_chunk_id": 385, "url": "https://huggingface.co/docs/peft/quicktour", "doc_title": "Quicktour" }, { "chunk_id": 385, "text": "```py\ntrainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=tokenized_datasets[\"train\"],\n eval_dataset=tokenized_datasets[\"test\"],\n processing_class=tokenizer,\n data_collator=data_collator,\n compute_metrics=compute_metrics,\n)\n\ntrainer.train()\n```", "source_file": "peft/quicktour.md", "section_heading": "Train", "char_start": 4424, "char_end": 4706, "token_estimate": 70, "prev_chunk_id": 384, "next_chunk_id": 386, "url": "https://huggingface.co/docs/peft/quicktour", "doc_title": "Quicktour" }, { "chunk_id": 386, "text": "### Save model\n\nAfter your model is finished training, you can save your model to a directory using the [save_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.save_pretrained) function.\n\n```py\nmodel.save_pretrained(\"output_dir\")\n```\n\nYou can also save your model to the Hub (make sure you're logged in to your Hugging Face account first) with the [push_to_hub](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.push_to_hub) function.\n\n```python\nfrom huggingface_hub import notebook_login\n\nnotebook_login()\nmodel.push_to_hub(\"your-name/bigscience/mt0-large-lora\")\n```", "source_file": "peft/quicktour.md", "section_heading": "Save model", "char_start": 4708, "char_end": 5385, "token_estimate": 169, "prev_chunk_id": 385, "next_chunk_id": 387, "url": "https://huggingface.co/docs/peft/quicktour", "doc_title": "Quicktour" }, { "chunk_id": 387, "text": "Both methods only save the extra PEFT weights that were trained, meaning it is super efficient to store, transfer, and load. For example, this [facebook/opt-350m](https://huggingface.co/ybelkada/opt-350m-lora) model trained with LoRA only contains two files: `adapter_config.json` and `adapter_model.safetensors`. The `adapter_model.safetensors` file is just 6.3MB!\n\n \n The adapter weights for a opt-350m model stored on the Hub are only ~6MB compared to the full size of the model weights, which can be ~700MB.", "source_file": "peft/quicktour.md", "section_heading": "Save model", "char_start": 5387, "char_end": 5900, "token_estimate": 128, "prev_chunk_id": 386, "next_chunk_id": 388, "url": "https://huggingface.co/docs/peft/quicktour", "doc_title": "Quicktour" }, { "chunk_id": 388, "text": "## Inference\n\n> [!TIP]\n> Take a look at the [AutoPeftModel](package_reference/auto_class) API reference for a complete list of available `AutoPeftModel` classes.\n\nEasily load any PEFT-trained model for inference with the [AutoPeftModel](/docs/peft/v0.19.0/en/package_reference/auto_class#peft.AutoPeftModel) class and the [from_pretrained](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method:", "source_file": "peft/quicktour.md", "section_heading": "Inference", "char_start": 5902, "char_end": 6365, "token_estimate": 115, "prev_chunk_id": 387, "next_chunk_id": 389, "url": "https://huggingface.co/docs/peft/quicktour", "doc_title": "Quicktour" }, { "chunk_id": 389, "text": "```py\nfrom peft import AutoPeftModelForCausalLM\nfrom transformers import AutoTokenizer\nimport torch\n\nmodel = AutoPeftModelForCausalLM.from_pretrained(\"ybelkada/opt-350m-lora\")\ntokenizer = AutoTokenizer.from_pretrained(\"facebook/opt-350m\")\n\nmodel = model.to(\"cuda\")\nmodel.eval()\ninputs = tokenizer(\"Preheat the oven to 350 degrees and place the cookie dough\", return_tensors=\"pt\")\n\noutputs = model.generate(input_ids=inputs[\"input_ids\"].to(\"cuda\"), max_new_tokens=50)\nprint(tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True)[0])\n\n\"Preheat the oven to 350 degrees and place the cookie dough in the center of the oven. In a large bowl, combine the flour, baking powder, baking soda, salt, and cinnamon. In a separate bowl, combine the egg yolks, sugar, and vanilla.\"\n```", "source_file": "peft/quicktour.md", "section_heading": "Inference", "char_start": 6367, "char_end": 7164, "token_estimate": 199, "prev_chunk_id": 388, "next_chunk_id": 390, "url": "https://huggingface.co/docs/peft/quicktour", "doc_title": "Quicktour" }, { "chunk_id": 390, "text": "For other tasks that aren't explicitly supported with an `AutoPeftModelFor` class - such as automatic speech recognition - you can still use the base [AutoPeftModel](/docs/peft/v0.19.0/en/package_reference/auto_class#peft.AutoPeftModel) class to load a model for the task.\n\n```py\nfrom peft import AutoPeftModel\n\nmodel = AutoPeftModel.from_pretrained(\"smangrul/openai-whisper-large-v2-LORA-colab\")\n```", "source_file": "peft/quicktour.md", "section_heading": "Inference", "char_start": 7166, "char_end": 7566, "token_estimate": 100, "prev_chunk_id": 389, "next_chunk_id": 391, "url": "https://huggingface.co/docs/peft/quicktour", "doc_title": "Quicktour" }, { "chunk_id": 391, "text": "## Next steps\n\nNow that you've seen how to train a model with one of the PEFT methods, we encourage you to try out some of the other methods like prompt tuning. The steps are very similar to the ones shown in the quicktour:\n\n1. prepare a [PeftConfig](/docs/peft/v0.19.0/en/package_reference/config#peft.PeftConfig) for a PEFT method\n2. use the [get_peft_model()](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.get_peft_model) method to create a [PeftModel](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel) from the configuration and base model\n\nThen you can train it however you like! To load a PEFT model for inference, you can use the [AutoPeftModel](/docs/peft/v0.19.0/en/package_reference/auto_class#peft.AutoPeftModel) class.\n\nFeel free to also take a look at the task guides if you're interested in training a model with another PEFT method for a specific task such as semantic segmentation, multilingual automatic speech recognition, DreamBooth, token classification, and more.", "source_file": "peft/quicktour.md", "section_heading": "Next steps", "char_start": 7568, "char_end": 8579, "token_estimate": 252, "prev_chunk_id": 390, "next_chunk_id": null, "url": "https://huggingface.co/docs/peft/quicktour", "doc_title": "Quicktour" }, { "chunk_id": 392, "text": "# Installation\n\nBefore you start, you will need to setup your environment, install the appropriate packages, and configure \ud83e\udd17 PEFT. \ud83e\udd17 PEFT is tested on **Python 3.9+**.\n\n\ud83e\udd17 PEFT is available on PyPI, as well as GitHub:", "source_file": "peft/install.md", "section_heading": "Installation", "char_start": 0, "char_end": 216, "token_estimate": 54, "prev_chunk_id": null, "next_chunk_id": 393, "url": "https://huggingface.co/docs/peft/install", "doc_title": "Installation" }, { "chunk_id": 393, "text": "## PyPI\n\nTo install \ud83e\udd17 PEFT from PyPI:\n\n```bash\npip install peft\n```", "source_file": "peft/install.md", "section_heading": "PyPI", "char_start": 218, "char_end": 285, "token_estimate": 16, "prev_chunk_id": 392, "next_chunk_id": 394, "url": "https://huggingface.co/docs/peft/install", "doc_title": "Installation" }, { "chunk_id": 394, "text": "## Source\n\nNew features that haven't been released yet are added every day, which also means there may be some bugs. To try them out, install from the GitHub repository:\n\n```bash\npip install git+https://github.com/huggingface/peft\n```\n\nIf you're working on contributing to the library or wish to play with the source code and see live \nresults as you run the code, an editable version can be installed from a locally-cloned version of the \nrepository:\n\n```bash\ngit clone https://github.com/huggingface/peft\ncd peft\npip install -e .[test]\n```", "source_file": "peft/install.md", "section_heading": "Source", "char_start": 287, "char_end": 828, "token_estimate": 135, "prev_chunk_id": 393, "next_chunk_id": null, "url": "https://huggingface.co/docs/peft/install", "doc_title": "Installation" }, { "chunk_id": 395, "text": "# PEFT configurations and models\n\nThe sheer size of today's large pretrained models - which commonly have billions of parameters - presents a significant training challenge because they require more storage space and more computational power to crunch all those calculations. You'll need access to powerful GPUs or TPUs to train these large pretrained models which is expensive, not widely accessible to everyone, not environmentally friendly, and not very practical. PEFT methods address many of these challenges. There are several types of PEFT methods (soft prompting, matrix decomposition, adapters), but they all focus on the same thing, reduce the number of trainable parameters. This makes it more accessible to train and store large models on consumer hardware.", "source_file": "peft/tutorial/peft_model_config.md", "section_heading": "PEFT configurations and models", "char_start": 0, "char_end": 769, "token_estimate": 192, "prev_chunk_id": null, "next_chunk_id": 396, "url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "doc_title": "PEFT configurations and models" }, { "chunk_id": 396, "text": "The PEFT library is designed to help you quickly train large models on free or low-cost GPUs, and in this tutorial, you'll learn how to setup a configuration to apply a PEFT method to a pretrained base model for training. Once the PEFT configuration is setup, you can use any training framework you like (Transformer's [Trainer](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer) class, [Accelerate](https://hf.co/docs/accelerate), a custom PyTorch training loop).", "source_file": "peft/tutorial/peft_model_config.md", "section_heading": "PEFT configurations and models", "char_start": 771, "char_end": 1278, "token_estimate": 126, "prev_chunk_id": 395, "next_chunk_id": 397, "url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "doc_title": "PEFT configurations and models" }, { "chunk_id": 397, "text": "## PEFT configurations\n\n> [!TIP]\n> Learn more about the parameters you can configure for each PEFT method in their respective API reference page.\n\nA configuration stores important parameters that specify how a particular PEFT method should be applied.\n\nFor example, take a look at the following [`LoraConfig`](https://huggingface.co/ybelkada/opt-350m-lora/blob/main/adapter_config.json) for applying LoRA and [`PromptEncoderConfig`](https://huggingface.co/smangrul/roberta-large-peft-p-tuning/blob/main/adapter_config.json) for applying p-tuning (these configuration files are already JSON-serialized). Whenever you load a PEFT adapter, it is a good idea to check whether it has an associated adapter_config.json file which is required.", "source_file": "peft/tutorial/peft_model_config.md", "section_heading": "PEFT configurations", "char_start": 1280, "char_end": 2016, "token_estimate": 184, "prev_chunk_id": 396, "next_chunk_id": 398, "url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "doc_title": "PEFT configurations and models" }, { "chunk_id": 398, "text": "```json\n{\n \"base_model_name_or_path\": \"facebook/opt-350m\", #base model to apply LoRA to\n \"bias\": \"none\",\n \"fan_in_fan_out\": false,\n \"inference_mode\": true,\n \"init_lora_weights\": true,\n \"layers_pattern\": null,\n \"layers_to_transform\": null,\n \"lora_alpha\": 32,\n \"lora_dropout\": 0.05,\n \"modules_to_save\": null,\n \"peft_type\": \"LORA\", #PEFT method type\n \"r\": 16,\n \"revision\": null,\n \"target_modules\": [\n \"q_proj\", #model modules to apply LoRA to (query and value projection layers)\n \"v_proj\"\n ],\n \"task_type\": \"CAUSAL_LM\" #type of task to train model on\n}\n```\n\nYou can create your own configuration for training by initializing a [LoraConfig](/docs/peft/v0.19.0/en/package_reference/lora#peft.LoraConfig).\n\n```py\nfrom peft import LoraConfig, TaskType\n\nlora_config = LoraConfig(\n r=16,\n target_modules=[\"q_proj\", \"v_proj\"],\n task_type=TaskType.CAUSAL_LM,\n lora_alpha=32,\n lora_dropout=0.05\n)\n```", "source_file": "peft/tutorial/peft_model_config.md", "section_heading": "PEFT configurations", "char_start": 2018, "char_end": 2943, "token_estimate": 231, "prev_chunk_id": 397, "next_chunk_id": 399, "url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "doc_title": "PEFT configurations and models" }, { "chunk_id": 399, "text": "```json\n{\n \"base_model_name_or_path\": \"roberta-large\", #base model to apply p-tuning to\n \"encoder_dropout\": 0.0,\n \"encoder_hidden_size\": 128,\n \"encoder_num_layers\": 2,\n \"encoder_reparameterization_type\": \"MLP\",\n \"inference_mode\": true,\n \"num_attention_heads\": 16,\n \"num_layers\": 24,\n \"num_transformer_submodules\": 1,\n \"num_virtual_tokens\": 20,\n \"peft_type\": \"P_TUNING\", #PEFT method type\n \"task_type\": \"SEQ_CLS\", #type of task to train model on\n \"token_dim\": 1024\n}\n```\n\nYou can create your own configuration for training by initializing a [PromptEncoderConfig](/docs/peft/v0.19.0/en/package_reference/p_tuning#peft.PromptEncoderConfig).\n\n```py\nfrom peft import PromptEncoderConfig, TaskType\n\np_tuning_config = PromptEncoderConfig(\n encoder_reparameterization_type=\"MLP\",\n encoder_hidden_size=128,\n num_attention_heads=16,\n num_layers=24,\n num_transformer_submodules=1,\n num_virtual_tokens=20,\n token_dim=1024,\n task_type=TaskType.SEQ_CLS\n)\n```", "source_file": "peft/tutorial/peft_model_config.md", "section_heading": "PEFT configurations", "char_start": 2945, "char_end": 3926, "token_estimate": 245, "prev_chunk_id": 398, "next_chunk_id": 400, "url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "doc_title": "PEFT configurations and models" }, { "chunk_id": 400, "text": "## PEFT models\n\nWith a PEFT configuration in hand, you can now apply it to any pretrained model to create a [PeftModel](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel). Choose from any of the state-of-the-art models from the [Transformers](https://hf.co/docs/transformers) library, a custom model, and even new and unsupported transformer architectures.\n\nFor this tutorial, load a base [facebook/opt-350m](https://huggingface.co/facebook/opt-350m) model to finetune.\n\n```py\nfrom transformers import AutoModelForCausalLM\n\nmodel = AutoModelForCausalLM.from_pretrained(\"facebook/opt-350m\")\n```\n\nUse the [get_peft_model()](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.get_peft_model) function to create a [PeftModel](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel) from the base facebook/opt-350m model and the `lora_config` you created earlier.", "source_file": "peft/tutorial/peft_model_config.md", "section_heading": "PEFT models", "char_start": 3928, "char_end": 4818, "token_estimate": 222, "prev_chunk_id": 399, "next_chunk_id": 401, "url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "doc_title": "PEFT configurations and models" }, { "chunk_id": 401, "text": "```py\nfrom peft import get_peft_model\n\nlora_model = get_peft_model(model, lora_config)\nlora_model.print_trainable_parameters()\n\"trainable params: 1,572,864 || all params: 332,769,280 || trainable%: 0.472659014678278\"\n```", "source_file": "peft/tutorial/peft_model_config.md", "section_heading": "PEFT models", "char_start": 4820, "char_end": 5040, "token_estimate": 55, "prev_chunk_id": 400, "next_chunk_id": 402, "url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "doc_title": "PEFT configurations and models" }, { "chunk_id": 402, "text": "> [!WARNING]\n> When calling [get_peft_model()](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.get_peft_model), the base model will be modified *in-place*. That means, when calling [get_peft_model()](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.get_peft_model) on a model that was already modified in the same way before, this model will be further mutated. Therefore, if you would like to modify your PEFT configuration after having called `get_peft_model()` before, you would first have to unload the model with [unload()](/docs/peft/v0.19.0/en/package_reference/tuners#peft.tuners.tuners_utils.BaseTuner.unload) and then call `get_peft_model()` with your new configuration. Alternatively, you can re-initialize the model to ensure a fresh, unmodified state before applying a new PEFT configuration.", "source_file": "peft/tutorial/peft_model_config.md", "section_heading": "PEFT models", "char_start": 5042, "char_end": 5862, "token_estimate": 205, "prev_chunk_id": 401, "next_chunk_id": 403, "url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "doc_title": "PEFT configurations and models" }, { "chunk_id": 403, "text": "Now you can train the [PeftModel](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel) with your preferred training framework! After training, you can save your model locally with [save_pretrained()](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel.save_pretrained) or upload it to the Hub with the [push_to_hub](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.push_to_hub) method.\n\n```py", "source_file": "peft/tutorial/peft_model_config.md", "section_heading": "PEFT models", "char_start": 5864, "char_end": 6334, "token_estimate": 117, "prev_chunk_id": 402, "next_chunk_id": 404, "url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "doc_title": "PEFT configurations and models" }, { "chunk_id": 404, "text": "# save locally\nlora_model.save_pretrained(\"your-name/opt-350m-lora\")", "source_file": "peft/tutorial/peft_model_config.md", "section_heading": "save locally", "char_start": 6335, "char_end": 6403, "token_estimate": 17, "prev_chunk_id": 403, "next_chunk_id": 405, "url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "doc_title": "PEFT configurations and models" }, { "chunk_id": 405, "text": "# push to Hub\nlora_model.push_to_hub(\"your-name/opt-350m-lora\")\n```\n\nTo load a [PeftModel](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel) for inference, you'll need to provide the [PeftConfig](/docs/peft/v0.19.0/en/package_reference/config#peft.PeftConfig) used to create it and the base model it was trained from.\n\n```py\nfrom peft import PeftModel, PeftConfig", "source_file": "peft/tutorial/peft_model_config.md", "section_heading": "push to Hub", "char_start": 6405, "char_end": 6785, "token_estimate": 95, "prev_chunk_id": 404, "next_chunk_id": 406, "url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "doc_title": "PEFT configurations and models" }, { "chunk_id": 406, "text": "config = PeftConfig.from_pretrained(\"ybelkada/opt-350m-lora\")\nmodel = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path)\nlora_model = PeftModel.from_pretrained(model, \"ybelkada/opt-350m-lora\")\n```\n\n> [!TIP]\n> By default, the [PeftModel](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel) is set for inference, but if you'd like to train the adapter some more you can set `is_trainable=True`.\n>\n> ```py\n> lora_model = PeftModel.from_pretrained(model, \"ybelkada/opt-350m-lora\", is_trainable=True)\n> ```\n\nThe [PeftModel.from_pretrained()](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel.from_pretrained) method is the most flexible way to load a [PeftModel](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel) because it doesn't matter what model framework was used (Transformers, timm, a generic PyTorch model). Other classes, like [AutoPeftModel](/docs/peft/v0.19.0/en/package_reference/auto_class#peft.AutoPeftModel), are just a convenient wrapper around the base [PeftModel](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel), and makes it easier to load PEFT models directly from the Hub or locally where the PEFT weights are stored.\n\n```py\nfrom peft import AutoPeftModelForCausalLM", "source_file": "peft/tutorial/peft_model_config.md", "section_heading": "push to Hub", "char_start": 6787, "char_end": 8054, "token_estimate": 316, "prev_chunk_id": 405, "next_chunk_id": 407, "url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "doc_title": "PEFT configurations and models" }, { "chunk_id": 407, "text": "lora_model = AutoPeftModelForCausalLM.from_pretrained(\"ybelkada/opt-350m-lora\")\n```\n\nTake a look at the [AutoPeftModel](package_reference/auto_class) API reference to learn more about the [AutoPeftModel](/docs/peft/v0.19.0/en/package_reference/auto_class#peft.AutoPeftModel) classes.", "source_file": "peft/tutorial/peft_model_config.md", "section_heading": "push to Hub", "char_start": 8056, "char_end": 8339, "token_estimate": 70, "prev_chunk_id": 406, "next_chunk_id": 408, "url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "doc_title": "PEFT configurations and models" }, { "chunk_id": 408, "text": "## Next steps\n\nWith the appropriate [PeftConfig](/docs/peft/v0.19.0/en/package_reference/config#peft.PeftConfig), you can apply it to any pretrained model to create a [PeftModel](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel) and train large powerful models faster on freely available GPUs! To learn more about PEFT configurations and models, the following guide may be helpful:\n\n* Learn how to configure a PEFT method for models that aren't from Transformers in the [Working with custom models](../developer_guides/custom_models) guide.", "source_file": "peft/tutorial/peft_model_config.md", "section_heading": "Next steps", "char_start": 8341, "char_end": 8898, "token_estimate": 139, "prev_chunk_id": 407, "next_chunk_id": null, "url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "doc_title": "PEFT configurations and models" }, { "chunk_id": 409, "text": "# LoRA methods\n\nA popular way to efficiently train large models is to insert (typically in the attention blocks) smaller trainable matrices that are a low-rank decomposition of the delta weight matrix to be learnt during finetuning. The pretrained model's original weight matrix is frozen and only the smaller matrices are updated during training. This reduces the number of trainable parameters, reducing memory usage and training time which can be very expensive for large models.", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "LoRA methods", "char_start": 0, "char_end": 482, "token_estimate": 120, "prev_chunk_id": null, "next_chunk_id": 410, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 410, "text": "There are several different ways to express the weight matrix as a low-rank decomposition, but [Low-Rank Adaptation (LoRA)](../conceptual_guides/adapter#low-rank-adaptation-lora) is the most common method. The PEFT library supports several other LoRA variants, such as [Low-Rank Hadamard Product (LoHa)](../conceptual_guides/adapter#low-rank-hadamard-product-loha), [Low-Rank Kronecker Product (LoKr)](../conceptual_guides/adapter#low-rank-kronecker-product-lokr), and [Adaptive Low-Rank Adaptation (AdaLoRA)](../conceptual_guides/adapter#adaptive-low-rank-adaptation-adalora). You can learn more about how these methods work conceptually in the [Adapters](../conceptual_guides/adapter) guide. If you're interested in applying these methods to other tasks and use cases like semantic segmentation, token classification, take a look at our [notebook collection](https://huggingface.co/collections/PEFT/notebooks-6573b28b33e5a4bf5b157fc1)!", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "LoRA methods", "char_start": 484, "char_end": 1421, "token_estimate": 234, "prev_chunk_id": 409, "next_chunk_id": 411, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 411, "text": "Additionally, PEFT supports the [X-LoRA](../conceptual_guides/adapter#mixture-of-lora-experts-x-lora) Mixture of LoRA Experts method.\n\nThis guide will show you how to quickly train an image classification model - with a low-rank decomposition method - to identify the class of food shown in an image.\n\n> [!TIP]\n> Some familiarity with the general process of training an image classification model would be really helpful and allow you to focus on the low-rank decomposition methods. If you're new, we recommend taking a look at the [Image classification](https://huggingface.co/docs/transformers/tasks/image_classification) guide first from the Transformers documentation. When you're ready, come back and see how easy it is to drop PEFT in to your training!\n\nBefore you begin, make sure you have all the necessary libraries installed.\n\n```bash\npip install -q peft transformers datasets\n```", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "LoRA methods", "char_start": 1423, "char_end": 2313, "token_estimate": 222, "prev_chunk_id": 410, "next_chunk_id": 412, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 412, "text": "## Dataset\n\nIn this guide, you'll use the [Food-101](https://huggingface.co/datasets/food101) dataset which contains images of 101 food classes (take a look at the [dataset viewer](https://huggingface.co/datasets/food101/viewer/default/train) to get a better idea of what the dataset looks like).\n\nLoad the dataset with the [load_dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset) function.\n\n```py\nfrom datasets import load_dataset\n\nds = load_dataset(\"food101\")\n```\n\nEach food class is labeled with an integer, so to make it easier to understand what these integers represent, you'll create a `label2id` and `id2label` dictionary to map the integer to its class label.\n\n```py\nlabels = ds[\"train\"].features[\"label\"].names\nlabel2id, id2label = dict(), dict()\nfor i, label in enumerate(labels):\n label2id[label] = i\n id2label[i] = label\n\nid2label[2]\n\"baklava\"\n```", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "Dataset", "char_start": 2315, "char_end": 3243, "token_estimate": 232, "prev_chunk_id": 411, "next_chunk_id": 413, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 413, "text": "Load an image processor to properly resize and normalize the pixel values of the training and evaluation images.\n\n```py\nfrom transformers import AutoImageProcessor\n\nimage_processor = AutoImageProcessor.from_pretrained(\"google/vit-base-patch16-224-in21k\")\n```\n\nYou can also use the image processor to prepare some transformation functions for data augmentation and pixel scaling.", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "Dataset", "char_start": 3245, "char_end": 3623, "token_estimate": 94, "prev_chunk_id": 412, "next_chunk_id": 414, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 414, "text": "```py\nfrom torchvision.transforms import (\n CenterCrop,\n Compose,\n Normalize,\n RandomHorizontalFlip,\n RandomResizedCrop,\n Resize,\n ToTensor,\n)\n\nnormalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std)\ntrain_transforms = Compose(\n [\n RandomResizedCrop(image_processor.size[\"height\"]),\n RandomHorizontalFlip(),\n ToTensor(),\n normalize,\n ]\n)\n\nval_transforms = Compose(\n [\n Resize(image_processor.size[\"height\"]),\n CenterCrop(image_processor.size[\"height\"]),\n ToTensor(),\n normalize,\n ]\n)\n\ndef preprocess_train(example_batch):\n example_batch[\"pixel_values\"] = [train_transforms(image.convert(\"RGB\")) for image in example_batch[\"image\"]]\n return example_batch\n\ndef preprocess_val(example_batch):\n example_batch[\"pixel_values\"] = [val_transforms(image.convert(\"RGB\")) for image in example_batch[\"image\"]]\n return example_batch\n```", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "Dataset", "char_start": 3625, "char_end": 4579, "token_estimate": 238, "prev_chunk_id": 413, "next_chunk_id": 415, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 415, "text": "Define the training and validation datasets, and use the [set_transform](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.set_transform) function to apply the transformations on-the-fly.\n\n```py\ntrain_ds = ds[\"train\"]\nval_ds = ds[\"validation\"]\n\ntrain_ds.set_transform(preprocess_train)\nval_ds.set_transform(preprocess_val)\n```\n\nFinally, you'll need a data collator to create a batch of training and evaluation data and convert the labels to `torch.tensor` objects.\n\n```py\nimport torch\n\ndef collate_fn(examples):\n pixel_values = torch.stack([example[\"pixel_values\"] for example in examples])\n labels = torch.tensor([example[\"label\"] for example in examples])\n return {\"pixel_values\": pixel_values, \"labels\": labels}\n```", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "Dataset", "char_start": 4581, "char_end": 5353, "token_estimate": 193, "prev_chunk_id": 414, "next_chunk_id": 416, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 416, "text": "## Model\n\nNow let's load a pretrained model to use as the base model. This guide uses the [google/vit-base-patch16-224-in21k](https://huggingface.co/google/vit-base-patch16-224-in21k) model, but you can use any image classification model you want. Pass the `label2id` and `id2label` dictionaries to the model so it knows how to map the integer labels to their class labels, and you can optionally pass the `ignore_mismatched_sizes=True` parameter if you're finetuning a checkpoint that has already been finetuned.\n\n```py\nfrom transformers import AutoModelForImageClassification, TrainingArguments, Trainer\n\nmodel = AutoModelForImageClassification.from_pretrained(\n \"google/vit-base-patch16-224-in21k\",\n label2id=label2id,\n id2label=id2label,\n ignore_mismatched_sizes=True,\n)\n```", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "Model", "char_start": 5355, "char_end": 6145, "token_estimate": 197, "prev_chunk_id": 415, "next_chunk_id": 417, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 417, "text": "### PEFT configuration and model\n\nEvery PEFT method requires a configuration that holds all the parameters specifying how the PEFT method should be applied. Once the configuration is setup, pass it to the [get_peft_model()](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.get_peft_model) function along with the base model to create a trainable [PeftModel](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel).\n\n> [!TIP]\n> Call the [print_trainable_parameters()](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel.print_trainable_parameters) method to compare the number of parameters of [PeftModel](/docs/peft/v0.19.0/en/package_reference/peft_model#peft.PeftModel) versus the number of parameters in the base model!", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "PEFT configuration and model", "char_start": 6147, "char_end": 6901, "token_estimate": 188, "prev_chunk_id": 416, "next_chunk_id": 418, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 418, "text": "[LoRA](../conceptual_guides/adapter#low-rank-adaptation-lora) decomposes the weight update matrix into *two* smaller matrices. The size of these low-rank matrices is determined by its *rank* or `r`. A higher rank means the model has more parameters to train, but it also means the model has more learning capacity. You'll also want to specify the `target_modules` which determine where the smaller matrices are inserted. For this guide, you'll target the *query* and *value* matrices of the attention blocks. Other important parameters to set are `lora_alpha` (scaling factor), `bias` (whether `none`, `all` or only the LoRA bias parameters should be trained), and `modules_to_save` (the modules apart from the LoRA layers to be trained and saved). All of these parameters - and more - are found in the [LoraConfig](/docs/peft/v0.19.0/en/package_reference/lora#peft.LoraConfig).", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "PEFT configuration and model", "char_start": 6903, "char_end": 7781, "token_estimate": 219, "prev_chunk_id": 417, "next_chunk_id": 419, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 419, "text": "```py\nfrom peft import LoraConfig, get_peft_model\n\nconfig = LoraConfig(\n r=16,\n lora_alpha=16,\n target_modules=[\"query\", \"value\"],\n lora_dropout=0.1,\n bias=\"none\",\n modules_to_save=[\"classifier\"],\n)\nmodel = get_peft_model(model, config)\nmodel.print_trainable_parameters()\n\"trainable params: 667,493 || all params: 86,543,818 || trainable%: 0.7712775047664294\"\n```", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "PEFT configuration and model", "char_start": 7783, "char_end": 8164, "token_estimate": 95, "prev_chunk_id": 418, "next_chunk_id": 420, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 420, "text": "[LoHa](../conceptual_guides/adapter#low-rank-hadamard-product-loha) decomposes the weight update matrix into *four* smaller matrices and each pair of smaller matrices is combined with the Hadamard product. This allows the weight update matrix to keep the same number of trainable parameters when compared to LoRA, but with a higher rank (`r^2` for LoHA when compared to `2*r` for LoRA). The size of the smaller matrices is determined by its *rank* or `r`. You'll also want to specify the `target_modules` which determines where the smaller matrices are inserted. For this guide, you'll target the *query* and *value* matrices of the attention blocks. Other important parameters to set are `alpha` (scaling factor), and `modules_to_save` (the modules apart from the LoHa layers to be trained and saved). All of these parameters - and more - are found in the [LoHaConfig](/docs/peft/v0.19.0/en/package_reference/loha#peft.LoHaConfig).", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "PEFT configuration and model", "char_start": 8166, "char_end": 9098, "token_estimate": 233, "prev_chunk_id": 419, "next_chunk_id": 421, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 421, "text": "```py\nfrom peft import LoHaConfig, get_peft_model\n\nconfig = LoHaConfig(\n r=16,\n alpha=16,\n target_modules=[\"query\", \"value\"],\n module_dropout=0.1,\n modules_to_save=[\"classifier\"],\n)\nmodel = get_peft_model(model, config)\nmodel.print_trainable_parameters()\n\"trainable params: 1,257,317 || all params: 87,133,642 || trainable%: 1.4429753779831676\"\n```", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "PEFT configuration and model", "char_start": 9100, "char_end": 9463, "token_estimate": 90, "prev_chunk_id": 420, "next_chunk_id": 422, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 422, "text": "[LoKr](../conceptual_guides/adapter#low-rank-kronecker-product-lokr) expresses the weight update matrix as a decomposition of a Kronecker product, creating a block matrix that is able to preserve the rank of the original weight matrix. The size of the smaller matrices are determined by its *rank* or `r`. You'll also want to specify the `target_modules` which determines where the smaller matrices are inserted. For this guide, you'll target the *query* and *value* matrices of the attention blocks. Other important parameters to set are `alpha` (scaling factor), and `modules_to_save` (the modules apart from the LoKr layers to be trained and saved). All of these parameters - and more - are found in the [LoKrConfig](/docs/peft/v0.19.0/en/package_reference/lokr#peft.LoKrConfig).", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "PEFT configuration and model", "char_start": 9465, "char_end": 10247, "token_estimate": 195, "prev_chunk_id": 421, "next_chunk_id": 423, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 423, "text": "```py\nfrom peft import LoKrConfig, get_peft_model\n\nconfig = LoKrConfig(\n r=16,\n alpha=16,\n target_modules=[\"query\", \"value\"],\n module_dropout=0.1,\n modules_to_save=[\"classifier\"],\n)\nmodel = get_peft_model(model, config)\nmodel.print_trainable_parameters()\n\"trainable params: 116,069 || all params: 87,172,042 || trainable%: 0.13314934162033282\"\n```", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "PEFT configuration and model", "char_start": 10249, "char_end": 10611, "token_estimate": 90, "prev_chunk_id": 422, "next_chunk_id": 424, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 424, "text": "[AdaLoRA](../conceptual_guides/adapter#adaptive-low-rank-adaptation-adalora) efficiently manages the LoRA parameter budget by assigning important weight matrices more parameters and pruning less important ones. In contrast, LoRA evenly distributes parameters across all modules. You can control the average desired *rank* or `r` of the matrices, and which modules to apply AdaLoRA to with `target_modules`. Other important parameters to set are `lora_alpha` (scaling factor), and `modules_to_save` (the modules apart from the AdaLoRA layers to be trained and saved). All of these parameters - and more - are found in the [AdaLoraConfig](/docs/peft/v0.19.0/en/package_reference/adalora#peft.AdaLoraConfig).", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "PEFT configuration and model", "char_start": 10613, "char_end": 11318, "token_estimate": 176, "prev_chunk_id": 423, "next_chunk_id": 425, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 425, "text": "```py\nfrom peft import AdaLoraConfig, get_peft_model\n\nconfig = AdaLoraConfig(\n r=8,\n init_r=12,\n tinit=200,\n tfinal=1000,\n deltaT=10,\n target_modules=[\"query\", \"value\"],\n modules_to_save=[\"classifier\"],\n)\nmodel = get_peft_model(model, config)\nmodel.print_trainable_parameters()\n\"trainable params: 520,325 || all params: 87,614,722 || trainable%: 0.5938785036606062\"\n```", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "PEFT configuration and model", "char_start": 11320, "char_end": 11710, "token_estimate": 97, "prev_chunk_id": 424, "next_chunk_id": 426, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 426, "text": "### Training\n\nFor training, let's use the [Trainer](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer) class from Transformers. The `Trainer` contains a PyTorch training loop, and when you're ready, call [train](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer.train) to start training. To customize the training run, configure the training hyperparameters in the [TrainingArguments](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.TrainingArguments) class. With LoRA-like methods, you can afford to use a higher batch size and learning rate.", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "Training", "char_start": 11712, "char_end": 12378, "token_estimate": 166, "prev_chunk_id": 425, "next_chunk_id": 427, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 427, "text": "> [!WARNING]\n> AdaLoRA has an [update_and_allocate()](/docs/peft/v0.19.0/en/package_reference/adalora#peft.AdaLoraModel.update_and_allocate) method that should be called at each training step to update the parameter budget and mask, otherwise the adaptation step is not performed. This requires writing a custom training loop or subclassing the [Trainer](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer) to incorporate this method. As an example, take a look at this [custom training loop](https://github.com/huggingface/peft/blob/912ad41e96e03652cabf47522cd876076f7a0c4f/examples/conditional_generation/peft_adalora_seq2seq.py#L120).", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "Training", "char_start": 12380, "char_end": 13059, "token_estimate": 169, "prev_chunk_id": 426, "next_chunk_id": 428, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 428, "text": "```py\nfrom transformers import TrainingArguments, Trainer\n\naccount = \"stevhliu\"\npeft_model_id = f\"{account}/google/vit-base-patch16-224-in21k-lora\"\nbatch_size = 128\n\nargs = TrainingArguments(\n peft_model_id,\n remove_unused_columns=False,\n eval_strategy=\"epoch\",\n save_strategy=\"epoch\",\n learning_rate=5e-3,\n per_device_train_batch_size=batch_size,\n gradient_accumulation_steps=4,\n per_device_eval_batch_size=batch_size,\n fp16=True,\n num_train_epochs=5,\n logging_steps=10,\n load_best_model_at_end=True,\n label_names=[\"labels\"],\n)\n```\n\nBegin training with [train](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/trainer#transformers.Trainer.train).\n\n```py\ntrainer = Trainer(\n model,\n args,\n train_dataset=train_ds,\n eval_dataset=val_ds,\n processing_class=image_processor,\n data_collator=collate_fn,\n)\ntrainer.train()\n```", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "Training", "char_start": 13061, "char_end": 13952, "token_estimate": 222, "prev_chunk_id": 427, "next_chunk_id": 429, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 429, "text": "## Share your model\n\nOnce training is complete, you can upload your model to the Hub with the [push_to_hub](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.push_to_hub) method. You\u2019ll need to login to your Hugging Face account first and enter your token when prompted.\n\n```py\nfrom huggingface_hub import notebook_login\n\nnotebook_login()\n```\n\nCall [push_to_hub](https://huggingface.co/docs/transformers/v5.5.4/en/main_classes/model#transformers.PreTrainedModel.push_to_hub) to save your model to your repositoy.\n\n```py\nmodel.push_to_hub(peft_model_id)\n```", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "Share your model", "char_start": 13954, "char_end": 14559, "token_estimate": 151, "prev_chunk_id": 428, "next_chunk_id": 430, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 430, "text": "## Inference\n\nLet's load the model from the Hub and test it out on a food image.\n\n```py\nfrom peft import PeftConfig, PeftModel\nfrom transformers import AutoImageProcessor\nfrom PIL import Image\nimport requests\n\nconfig = PeftConfig.from_pretrained(\"stevhliu/vit-base-patch16-224-in21k-lora\")\nmodel = AutoModelForImageClassification.from_pretrained(\n config.base_model_name_or_path,\n label2id=label2id,\n id2label=id2label,\n ignore_mismatched_sizes=True,\n)\nmodel = PeftModel.from_pretrained(model, \"stevhliu/vit-base-patch16-224-in21k-lora\")\n\nurl = \"https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/beignets.jpeg\"\nimage = Image.open(requests.get(url, stream=True).raw)\nimage\n```\n\nConvert the image to RGB and return the underlying PyTorch tensors.\n\n```py\nencoding = image_processor(image.convert(\"RGB\"), return_tensors=\"pt\")\n```\n\nNow run the model and return the predicted class!", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "Inference", "char_start": 0, "char_end": 909, "token_estimate": 227, "prev_chunk_id": 429, "next_chunk_id": 431, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 431, "text": "```py\nwith torch.no_grad():\n outputs = model(**encoding)\n logits = outputs.logits\n\npredicted_class_idx = logits.argmax(-1).item()\nprint(\"Predicted class:\", model.config.id2label[predicted_class_idx])\n\"Predicted class: beignets\"\n```", "source_file": "peft/task_guides/lora_based_methods.md", "section_heading": "Inference", "char_start": 15478, "char_end": 15715, "token_estimate": 59, "prev_chunk_id": 430, "next_chunk_id": null, "url": "https://huggingface.co/docs/peft/task_guides/lora_based_methods", "doc_title": "LoRA methods" }, { "chunk_id": 432, "text": "# Datasets\n\n\ud83e\udd17 Datasets is a library for easily accessing and sharing AI datasets for Audio, Computer Vision, and Natural Language Processing (NLP) tasks.\n\nLoad a dataset in a single line of code, and use our powerful data processing and streaming methods to quickly get your dataset ready for training in a deep learning model. Backed by the Apache Arrow format, process large datasets with zero-copy reads without any memory constraints for optimal speed and efficiency. We also feature a deep integration with the [Hugging Face Hub](https://huggingface.co/datasets), allowing you to easily load and share a dataset with the wider machine learning community.\n\nFind your dataset today on the [Hugging Face Hub](https://huggingface.co/datasets), and take an in-depth look inside of it with the live viewer.", "source_file": "datasets/index.md", "section_heading": "Datasets", "char_start": 0, "char_end": 805, "token_estimate": 201, "prev_chunk_id": null, "next_chunk_id": 433, "url": "https://huggingface.co/docs/datasets/index", "doc_title": "Datasets" }, { "chunk_id": 433, "text": "Tutorials\n Learn the basics and become familiar with loading, accessing, and processing a dataset. Start here if you are using \ud83e\udd17 Datasets for the first time!\n \n How-to guides\n Practical guides to help you achieve a specific goal. Take a look at these guides to learn how to use \ud83e\udd17 Datasets to solve real-world problems.\n \n Conceptual guides\n High-level explanations for building a better understanding about important topics such as the underlying data format, the cache, and how datasets are generated.\n \n Reference\n Technical descriptions of how \ud83e\udd17 Datasets classes and methods work.", "source_file": "datasets/index.md", "section_heading": "Datasets", "char_start": 814, "char_end": 1434, "token_estimate": 156, "prev_chunk_id": 432, "next_chunk_id": null, "url": "https://huggingface.co/docs/datasets/index", "doc_title": "Datasets" }, { "chunk_id": 434, "text": "# Quickstart\n\nThis quickstart is intended for developers who are ready to dive into the code and see an example of how to integrate \ud83e\udd17 Datasets into their model training workflow. If you're a beginner, we recommend starting with our [tutorials](./tutorial), where you'll get a more thorough introduction.\n\nEach dataset is unique, and depending on the task, some datasets may require additional steps to prepare it for training. But you can always use \ud83e\udd17 Datasets tools to load and process a dataset. The fastest and easiest way to get started is by loading an existing dataset from the [Hugging Face Hub](https://huggingface.co/datasets). There are thousands of datasets to choose from, spanning many tasks. Choose the type of dataset you want to work with, and let's get started!", "source_file": "datasets/quickstart.md", "section_heading": "Quickstart", "char_start": 0, "char_end": 778, "token_estimate": 194, "prev_chunk_id": null, "next_chunk_id": 435, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 435, "text": "Audio\n \n \n Resample an audio dataset and get it ready for a model to classify what\n type of banking issue a speaker is calling about.\n \n \n \n \n Vision\n \n \n Apply data augmentation to an image dataset and get it ready for a model\n to diagnose disease in bean plants.\n \n \n \n \n NLP\n \n \n Tokenize a dataset and get it ready for a model to determine whether a\n pair of sentences have the same meaning.\n \n \n \n\n> [!TIP]\n> Check out [Chapter 5](https://huggingface.co/course/chapter5/1?fw=pt) of the Hugging Face course to learn more about other important topics such as loading remote or local datasets, tools for cleaning up a dataset, and creating your own dataset.\n\nStart by installing \ud83e\udd17 Datasets:\n\n```bash\npip install datasets\n```\n\n\ud83e\udd17 Datasets also support audio and image data formats:", "source_file": "datasets/quickstart.md", "section_heading": "Quickstart", "char_start": 803, "char_end": 1711, "token_estimate": 227, "prev_chunk_id": 434, "next_chunk_id": 436, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 436, "text": "- To work with audio datasets, install the [Audio](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Audio) feature:\n\n ```bash\n pip install datasets[audio]\n ```\n\n- To work with image datasets, install the [Image](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Image) feature:\n\n ```bash\n pip install datasets[vision]\n ```\n\nBesides \ud83e\udd17 Datasets, make sure your preferred machine learning framework is installed:\n\n ```bash pip install torch ```\n ```bash pip install tensorflow ```", "source_file": "datasets/quickstart.md", "section_heading": "Quickstart", "char_start": 1713, "char_end": 2229, "token_estimate": 129, "prev_chunk_id": 435, "next_chunk_id": 437, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 437, "text": "## Audio\n\nAudio datasets are loaded just like text datasets. However, an audio dataset is preprocessed a bit differently. Instead of a tokenizer, you'll need a [feature extractor](https://huggingface.co/docs/transformers/main_classes/feature_extractor#feature-extractor). An audio input may also require resampling its sampling rate to match the sampling rate of the pretrained model you're using. In this quickstart, you'll prepare the [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset for a model train on and classify the banking issue a customer is having.\n\n**1**. Load the MInDS-14 dataset by providing the [load_dataset()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset) function with the dataset name, dataset configuration (not all datasets will have a configuration), and a dataset split:\n\n```py\n>>> from datasets import load_dataset, Audio\n\n>>> dataset = load_dataset(\"PolyAI/minds14\", \"en-US\", split=\"train\")\n```", "source_file": "datasets/quickstart.md", "section_heading": "Audio", "char_start": 2231, "char_end": 3205, "token_estimate": 243, "prev_chunk_id": 436, "next_chunk_id": 438, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 438, "text": "**2**. Next, load a pretrained [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base) model and its corresponding feature extractor from the [\ud83e\udd17 Transformers](https://huggingface.co/transformers/) library. It is totally normal to see a warning after you load the model about some weights not being initialized. This is expected because you are loading this model checkpoint for training with another task.\n\n```py\n>>> from transformers import AutoModelForAudioClassification, AutoFeatureExtractor\n\n>>> model = AutoModelForAudioClassification.from_pretrained(\"facebook/wav2vec2-base\")\n>>> feature_extractor = AutoFeatureExtractor.from_pretrained(\"facebook/wav2vec2-base\")\n```", "source_file": "datasets/quickstart.md", "section_heading": "Audio", "char_start": 3207, "char_end": 3882, "token_estimate": 168, "prev_chunk_id": 437, "next_chunk_id": 439, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 439, "text": "**3**. The [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset card indicates the sampling rate is 8kHz, but the Wav2Vec2 model was pretrained on a sampling rate of 16kHZ. You'll need to upsample the `audio` column with the [cast_column()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.cast_column) function and [Audio](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Audio) feature to match the model's sampling rate.\n\n```py\n>>> dataset = dataset.cast_column(\"audio\", Audio(sampling_rate=16000))\n>>> dataset[0][\"audio\"]\n\n```\n\n**4**. Create a function to preprocess the audio `array` with the feature extractor, and truncate and pad the sequences into tidy rectangular tensors. The most important thing to remember is to call the audio `array` in the feature extractor since the `array` - the actual speech signal - is the model input.", "source_file": "datasets/quickstart.md", "section_heading": "Audio", "char_start": 3884, "char_end": 4778, "token_estimate": 223, "prev_chunk_id": 438, "next_chunk_id": 440, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 440, "text": "Once you have a preprocessing function, use the [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) function to speed up processing by applying the function to batches of examples in the dataset.\n\n```py\n>>> def preprocess_function(examples):\n... audio_arrays = [x.get_all_samples().data for x in examples[\"audio\"]]\n... inputs = feature_extractor(\n... audio_arrays,\n... sampling_rate=16000,\n... padding=True,\n... max_length=100000,\n... truncation=True,\n... )\n... return inputs\n\n>>> dataset = dataset.map(preprocess_function, batched=True)\n```\n\n**5**. Use the [rename_column()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.rename_column) function to rename the `intent_class` column to `labels`, which is the expected input name in [Wav2Vec2ForSequenceClassification](https://huggingface.co/docs/transformers/main/en/model_doc/wav2vec2#transformers.Wav2Vec2ForSequenceClassification):", "source_file": "datasets/quickstart.md", "section_heading": "Audio", "char_start": 4780, "char_end": 5780, "token_estimate": 250, "prev_chunk_id": 439, "next_chunk_id": 441, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 441, "text": "```py\n>>> dataset = dataset.rename_column(\"intent_class\", \"labels\")\n```\n\n**6**. Set the dataset format according to the machine learning framework you're using.\n\nUse the [set_format()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.set_format) function to set the dataset format to `torch` and specify the columns you want to format. This function applies formatting on-the-fly. After converting to PyTorch tensors, wrap the dataset in [`torch.utils.data.DataLoader`](https://alband.github.io/doc_view/data.html?highlight=torch%20utils%20data%20dataloader#torch.utils.data.DataLoader):\n\n```py\n>>> from torch.utils.data import DataLoader\n\n>>> dataset.set_format(type=\"torch\", columns=[\"input_values\", \"labels\"])\n>>> dataloader = DataLoader(dataset, batch_size=4)\n```", "source_file": "datasets/quickstart.md", "section_heading": "Audio", "char_start": 5782, "char_end": 6573, "token_estimate": 197, "prev_chunk_id": 440, "next_chunk_id": 442, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 442, "text": "Use the `prepare_tf_dataset` method from \ud83e\udd17 Transformers to prepare the dataset to be compatible with\nTensorFlow, and ready to train/fine-tune a model, as it wraps a HuggingFace [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) as a `tf.data.Dataset`\nwith collation and batching, so one can pass it directly to Keras methods like `fit()` without further modification.\n\n```py\n>>> import tensorflow as tf\n\n>>> tf_dataset = model.prepare_tf_dataset(\n... dataset,\n... batch_size=4,\n... shuffle=True,\n... )\n```\n\n**7**. Start training with your machine learning framework! Check out the \ud83e\udd17 Transformers [audio classification guide](https://huggingface.co/docs/transformers/tasks/audio_classification) for an end-to-end example of how to train a model on an audio dataset.", "source_file": "datasets/quickstart.md", "section_heading": "Audio", "char_start": 6575, "char_end": 7384, "token_estimate": 202, "prev_chunk_id": 441, "next_chunk_id": 443, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 443, "text": "## Vision\n\nImage datasets are loaded just like text datasets. However, instead of a tokenizer, you'll need a [feature extractor](https://huggingface.co/docs/transformers/main_classes/feature_extractor#feature-extractor) to preprocess the dataset. Applying data augmentation to an image is common in computer vision to make the model more robust against overfitting. You're free to use any data augmentation library you want, and then you can apply the augmentations with \ud83e\udd17 Datasets. In this quickstart, you'll load the [Beans](https://huggingface.co/datasets/beans) dataset and get it ready for the model to train on and identify disease from the leaf images.\n\n**1**. Load the Beans dataset by providing the [load_dataset()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset) function with the dataset name and a dataset split:\n\n```py\n>>> from datasets import load_dataset, Image\n\n>>> dataset = load_dataset(\"AI-Lab-Makerere/beans\", split=\"train\")\n```", "source_file": "datasets/quickstart.md", "section_heading": "Vision", "char_start": 7386, "char_end": 8368, "token_estimate": 245, "prev_chunk_id": 442, "next_chunk_id": 444, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 444, "text": "Most image models work with RBG images. If your dataset contains images in a different mode, you can use the [cast_column()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.cast_column) function to set the mode to RGB:\n\n```py\n>>> dataset = dataset.cast_column(\"image\", Image(mode=\"RGB\"))\n```\n\nThe Beans dataset contains only RGB images, so this step is unnecessary here.\n\n**2**. Now you can add some data augmentations with any library ([Albumentations](https://albumentations.ai/), [imgaug](https://imgaug.readthedocs.io/en/latest/), [Kornia](https://kornia.readthedocs.io/en/latest/)) you like. Here, you'll use [torchvision](https://pytorch.org/vision/stable/transforms.html) to randomly change the color properties of an image:\n\n```py\n>>> from torchvision.transforms import Compose, ColorJitter, ToTensor\n\n>>> jitter = Compose(\n... [ColorJitter(brightness=0.5, hue=0.5), ToTensor()]\n... )\n```", "source_file": "datasets/quickstart.md", "section_heading": "Vision", "char_start": 8370, "char_end": 9295, "token_estimate": 231, "prev_chunk_id": 443, "next_chunk_id": 445, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 445, "text": "**3**. Create a function to apply your transform to the dataset and generate the model input: `pixel_values`.\n\n```python\n>>> def transforms(examples):\n... examples[\"pixel_values\"] = [jitter(image.convert(\"RGB\")) for image in examples[\"image\"]]\n... return examples\n```\n\n**4**. Use the [with_transform()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.with_transform) function to apply the data augmentations on-the-fly:\n\n```py\n>>> dataset = dataset.with_transform(transforms)\n```\n\n**5**. Set the dataset format according to the machine learning framework you're using.\n\nWrap the dataset in [`torch.utils.data.DataLoader`](https://alband.github.io/doc_view/data.html?highlight=torch%20utils%20data%20dataloader#torch.utils.data.DataLoader). You'll also need to create a collate function to collate the samples into batches:", "source_file": "datasets/quickstart.md", "section_heading": "Vision", "char_start": 9297, "char_end": 10152, "token_estimate": 213, "prev_chunk_id": 444, "next_chunk_id": 446, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 446, "text": "```py\n>>> from torch.utils.data import DataLoader\n\n>>> def collate_fn(examples):\n... images = []\n... labels = []\n... for example in examples:\n... images.append((example[\"pixel_values\"]))\n... labels.append(example[\"labels\"])\n...\n... pixel_values = torch.stack(images)\n... labels = torch.tensor(labels)\n... return {\"pixel_values\": pixel_values, \"labels\": labels}\n>>> dataloader = DataLoader(dataset, collate_fn=collate_fn, batch_size=4)\n```\n\nUse the `prepare_tf_dataset` method from \ud83e\udd17 Transformers to prepare the dataset to be compatible with\nTensorFlow, and ready to train/fine-tune a model, as it wraps a HuggingFace [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) as a `tf.data.Dataset`\nwith collation and batching, so one can pass it directly to Keras methods like `fit()` without further modification.\n\nBefore you start, make sure you have up-to-date versions of `albumentations` and `cv2` installed:", "source_file": "datasets/quickstart.md", "section_heading": "Vision", "char_start": 10154, "char_end": 11133, "token_estimate": 244, "prev_chunk_id": 445, "next_chunk_id": 447, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 447, "text": "```bash\npip install -U albumentations opencv-python\n```\n\n```py\n>>> import albumentations\n>>> import numpy as np\n\n>>> transform = albumentations.Compose([\n... albumentations.RandomCrop(width=256, height=256),\n... albumentations.HorizontalFlip(p=0.5),\n... albumentations.RandomBrightnessContrast(p=0.2),\n... ])\n\n>>> def transforms(examples):\n... examples[\"pixel_values\"] = [\n... transform(image=np.array(image))[\"image\"] for image in examples[\"image\"]\n... ]\n... return examples\n\n>>> dataset.set_transform(transforms)\n>>> tf_dataset = model.prepare_tf_dataset(\n... dataset,\n... batch_size=4,\n... shuffle=True,\n... )\n```\n\n**6**. Start training with your machine learning framework! Check out the \ud83e\udd17 Transformers [image classification guide](https://huggingface.co/docs/transformers/tasks/image_classification) for an end-to-end example of how to train a model on an image dataset.", "source_file": "datasets/quickstart.md", "section_heading": "Vision", "char_start": 11135, "char_end": 12054, "token_estimate": 229, "prev_chunk_id": 446, "next_chunk_id": 448, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 448, "text": "## NLP\n\nText needs to be tokenized into individual tokens by a [tokenizer](https://huggingface.co/docs/transformers/main_classes/tokenizer). For the quickstart, you'll load the [Microsoft Research Paraphrase Corpus (MRPC)](https://huggingface.co/datasets/nyu-mll/glue/viewer/mrpc) training dataset to train a model to determine whether a pair of sentences mean the same thing.\n\n**1**. Load the MRPC dataset by providing the [load_dataset()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset) function with the dataset name, dataset configuration (not all datasets will have a configuration), and dataset split:\n\n```py\n>>> from datasets import load_dataset\n\n>>> dataset = load_dataset(\"nyu-mll/glue\", \"mrpc\", split=\"train\")\n```", "source_file": "datasets/quickstart.md", "section_heading": "NLP", "char_start": 12056, "char_end": 12813, "token_estimate": 189, "prev_chunk_id": 447, "next_chunk_id": 449, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 449, "text": "**2**. Next, load a pretrained [BERT](https://huggingface.co/bert-base-uncased) model and its corresponding tokenizer from the [\ud83e\udd17 Transformers](https://huggingface.co/transformers/) library. It is totally normal to see a warning after you load the model about some weights not being initialized. This is expected because you are loading this model checkpoint for training with another task.\n\n```py\n>>> from transformers import AutoModelForSequenceClassification, AutoTokenizer\n\n>>> model = AutoModelForSequenceClassification.from_pretrained(\"bert-base-uncased\")\n>>> tokenizer = AutoTokenizer.from_pretrained(\"bert-base-uncased\")\n===PT-TF-SPLIT===\n>>> from transformers import TFAutoModelForSequenceClassification, AutoTokenizer\n\n>>> model = TFAutoModelForSequenceClassification.from_pretrained(\"bert-base-uncased\")\n>>> tokenizer = AutoTokenizer.from_pretrained(\"bert-base-uncased\")\n```", "source_file": "datasets/quickstart.md", "section_heading": "NLP", "char_start": 12815, "char_end": 13700, "token_estimate": 221, "prev_chunk_id": 448, "next_chunk_id": 450, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 450, "text": "**3**. Create a function to tokenize the dataset, and you should also truncate and pad the text into tidy rectangular tensors. The tokenizer generates three new columns in the dataset: `input_ids`, `token_type_ids`, and an `attention_mask`. These are the model inputs.\n\nUse the [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) function to speed up processing by applying your tokenization function to batches of examples in the dataset:", "source_file": "datasets/quickstart.md", "section_heading": "NLP", "char_start": 13702, "char_end": 14175, "token_estimate": 118, "prev_chunk_id": 449, "next_chunk_id": 451, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 451, "text": "```py\n>>> def encode(examples):\n... return tokenizer(examples[\"sentence1\"], examples[\"sentence2\"], truncation=True, padding=\"max_length\")\n\n>>> dataset = dataset.map(encode, batched=True)\n>>> dataset[0]\n{'sentence1': 'Amrozi accused his brother , whom he called \" the witness \" , of deliberately distorting his evidence .',\n'sentence2': 'Referring to him as only \" the witness \" , Amrozi accused his brother of deliberately distorting his evidence .',\n'label': 1,\n'idx': 0,\n'input_ids': [ 101, 7277, 2180, 5303, 4806, 1117, 1711, 117, 2292, 1119, 1270, 107, 1103, 7737, 107, 117, 1104, 9938, 4267, 12223, 21811, 1117, 2554, 119, 102, 11336, 6732, 3384, 1106, 1140, 1112, 1178, 107, 1103, 7737, 107, 117, 7277, 2180, 5303, 4806, 1117, 1711, 1104, 9938, 4267, 12223, 21811, 1117, 2554, 119, 102, 0, 0, ...],\n'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, ...],\n'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, ...]}\n```", "source_file": "datasets/quickstart.md", "section_heading": "NLP", "char_start": 14177, "char_end": 15415, "token_estimate": 309, "prev_chunk_id": 450, "next_chunk_id": 452, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 452, "text": "**4**. Rename the `label` column to `labels`, which is the expected input name in [BertForSequenceClassification](https://huggingface.co/docs/transformers/main/en/model_doc/bert#transformers.BertForSequenceClassification):\n\n```py\n>>> dataset = dataset.map(lambda examples: {\"labels\": examples[\"label\"]}, batched=True)\n```\n\n**5**. Set the dataset format according to the machine learning framework you're using.\n\nUse the [with_format()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.with_format) function to set the dataset format to `torch` and specify the columns you want to format. This function applies formatting on-the-fly. After converting to PyTorch tensors, wrap the dataset in [`torch.utils.data.DataLoader`](https://alband.github.io/doc_view/data.html?highlight=torch%20utils%20data%20dataloader#torch.utils.data.DataLoader):", "source_file": "datasets/quickstart.md", "section_heading": "NLP", "char_start": 15417, "char_end": 16280, "token_estimate": 215, "prev_chunk_id": 451, "next_chunk_id": 453, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 453, "text": "```py\n>>> import torch\n\n>>> dataset = dataset.select_columns([\"input_ids\", \"token_type_ids\", \"attention_mask\", \"labels\"])\n>>> dataset = dataset.with_format(type=\"torch\")\n>>> dataloader = torch.utils.data.DataLoader(dataset, batch_size=32)\n```\n\nUse the `prepare_tf_dataset` method from \ud83e\udd17 Transformers to prepare the dataset to be compatible with\nTensorFlow, and ready to train/fine-tune a model, as it wraps a HuggingFace [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) as a `tf.data.Dataset`\nwith collation and batching, so one can pass it directly to Keras methods like `fit()` without further modification.\n\n```py\n>>> import tensorflow as tf\n\n>>> tf_dataset = model.prepare_tf_dataset(\n... dataset,\n... batch_size=4,\n... shuffle=True,\n... )\n```", "source_file": "datasets/quickstart.md", "section_heading": "NLP", "char_start": 16282, "char_end": 17076, "token_estimate": 198, "prev_chunk_id": 452, "next_chunk_id": 454, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 454, "text": "**6**. Start training with your machine learning framework! Check out the \ud83e\udd17 Transformers [text classification guide](https://huggingface.co/docs/transformers/tasks/sequence_classification) for an end-to-end example of how to train a model on a text dataset.", "source_file": "datasets/quickstart.md", "section_heading": "NLP", "char_start": 17078, "char_end": 17335, "token_estimate": 64, "prev_chunk_id": 453, "next_chunk_id": 455, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 455, "text": "## What's next?\n\nThis completes the \ud83e\udd17 Datasets quickstart! You can load any text, audio, or image dataset with a single function and get it ready for your model to train on.\n\nFor your next steps, take a look at our [How-to guides](./how_to) and learn how to do more specific things like loading different dataset formats, aligning labels, and streaming large datasets. If you're interested in learning more about \ud83e\udd17 Datasets core concepts, grab a cup of coffee and read our [Conceptual Guides](./about_arrow)!", "source_file": "datasets/quickstart.md", "section_heading": "What's next?", "char_start": 17337, "char_end": 17845, "token_estimate": 127, "prev_chunk_id": 454, "next_chunk_id": null, "url": "https://huggingface.co/docs/datasets/quickstart", "doc_title": "Quickstart" }, { "chunk_id": 456, "text": "# Installation\n\nBefore you start, you'll need to setup your environment and install the appropriate packages. \ud83e\udd17 Datasets is tested on **Python 3.10+**.\n\n> [!TIP]\n> If you want to use \ud83e\udd17 Datasets with TensorFlow or PyTorch, you'll need to install them separately. Refer to the [TensorFlow installation page](https://www.tensorflow.org/install/pip#tensorflow-2-packages-are-available) or the [PyTorch installation page](https://pytorch.org/get-started/locally/#start-locally) for the specific install command for your framework.", "source_file": "datasets/installation.md", "section_heading": "Installation", "char_start": 0, "char_end": 525, "token_estimate": 131, "prev_chunk_id": null, "next_chunk_id": 457, "url": "https://huggingface.co/docs/datasets/installation", "doc_title": "Installation" }, { "chunk_id": 457, "text": "## Virtual environment\n\nYou should install \ud83e\udd17 Datasets in a [virtual environment](https://docs.python.org/3/library/venv.html) to keep things tidy and avoid dependency conflicts.\n\n1. Create and navigate to your project directory:\n\n ```bash\n mkdir ~/my-project\n cd ~/my-project\n ```\n\n2. Start a virtual environment inside your directory:\n\n ```bash\n python -m venv .env\n ```\n\n3. Activate and deactivate the virtual environment with the following commands:\n\n ```bash\n # Activate the virtual environment\n source .env/bin/activate\n\n # Deactivate the virtual environment\n source .env/bin/deactivate\n ```\n\nOnce you've created your virtual environment, you can install \ud83e\udd17 Datasets in it.", "source_file": "datasets/installation.md", "section_heading": "Virtual environment", "char_start": 527, "char_end": 1230, "token_estimate": 175, "prev_chunk_id": 456, "next_chunk_id": 458, "url": "https://huggingface.co/docs/datasets/installation", "doc_title": "Installation" }, { "chunk_id": 458, "text": "## pip\n\nThe most straightforward way to install \ud83e\udd17 Datasets is with pip:\n\n```bash\npip install datasets\n```\n\nRun the following command to check if \ud83e\udd17 Datasets has been properly installed:\n\n```bash\npython -c \"from datasets import load_dataset; print(load_dataset('rajpurkar/squad', split='train')[0])\"\n```\n\nThis command downloads version 1 of the [Stanford Question Answering Dataset (SQuAD)](https://rajpurkar.github.io/SQuAD-explorer/), loads the training split, and prints the first training example. You should see:", "source_file": "datasets/installation.md", "section_heading": "pip", "char_start": 1232, "char_end": 1747, "token_estimate": 128, "prev_chunk_id": 457, "next_chunk_id": 459, "url": "https://huggingface.co/docs/datasets/installation", "doc_title": "Installation" }, { "chunk_id": 459, "text": "```python\n{'answers': {'answer_start': [515], 'text': ['Saint Bernadette Soubirous']}, 'context': 'Architecturally, the school has a Catholic character. Atop the Main Building\\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend \"Venite Ad Me Omnes\". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.', 'id': '5733be284776f41900661182', 'question': 'To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?', 'title': 'University_of_Notre_Dame'}\n```", "source_file": "datasets/installation.md", "section_heading": "pip", "char_start": 1749, "char_end": 2708, "token_estimate": 239, "prev_chunk_id": 458, "next_chunk_id": 460, "url": "https://huggingface.co/docs/datasets/installation", "doc_title": "Installation" }, { "chunk_id": 460, "text": "## Audio\n\nTo work with audio datasets, you need to install the [Audio](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Audio) feature as an extra dependency:\n\n```bash\npip install datasets[audio]\n```", "source_file": "datasets/installation.md", "section_heading": "Audio", "char_start": 2710, "char_end": 2925, "token_estimate": 53, "prev_chunk_id": 459, "next_chunk_id": 461, "url": "https://huggingface.co/docs/datasets/installation", "doc_title": "Installation" }, { "chunk_id": 461, "text": "## Vision\n\nTo work with image datasets, you need to install the [Image](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Image) feature as an extra dependency:\n\n```bash\npip install datasets[vision]\n```", "source_file": "datasets/installation.md", "section_heading": "Vision", "char_start": 2927, "char_end": 3144, "token_estimate": 54, "prev_chunk_id": 460, "next_chunk_id": 462, "url": "https://huggingface.co/docs/datasets/installation", "doc_title": "Installation" }, { "chunk_id": 462, "text": "## source\n\nBuilding \ud83e\udd17 Datasets from source lets you make changes to the code base. To install from the source, clone the repository and install with the following commands:\n\n```bash\ngit clone https://github.com/huggingface/datasets.git\ncd datasets\npip install -e .\n```\n\nAgain, you can check if \ud83e\udd17 Datasets was properly installed with the following command:\n\n```bash\npython -c \"from datasets import load_dataset; print(load_dataset('rajpurkar/squad', split='train')[0])\"\n```", "source_file": "datasets/installation.md", "section_heading": "source", "char_start": 3146, "char_end": 3618, "token_estimate": 118, "prev_chunk_id": 461, "next_chunk_id": 463, "url": "https://huggingface.co/docs/datasets/installation", "doc_title": "Installation" }, { "chunk_id": 463, "text": "## conda\n\n\ud83e\udd17 Datasets can also be installed from conda, a package management system:\n\n```bash\nconda install -c huggingface -c conda-forge datasets\n```", "source_file": "datasets/installation.md", "section_heading": "conda", "char_start": 3620, "char_end": 3769, "token_estimate": 37, "prev_chunk_id": 462, "next_chunk_id": null, "url": "https://huggingface.co/docs/datasets/installation", "doc_title": "Installation" }, { "chunk_id": 464, "text": "# Load a dataset from the Hub\n\nFinding high-quality datasets that are reproducible and accessible can be difficult. One of \ud83e\udd17 Datasets main goals is to provide a simple way to load a dataset of any format or type. The easiest way to get started is to discover an existing dataset on the [Hugging Face Hub](https://huggingface.co/datasets) - a community-driven collection of datasets for tasks in NLP, computer vision, and audio - and use \ud83e\udd17 Datasets to download and generate the dataset.\n\nThis tutorial uses the [rotten_tomatoes](https://huggingface.co/datasets/rotten_tomatoes) and [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) datasets, but feel free to load any dataset you want and follow along. Head over to the Hub now and find a dataset for your task!", "source_file": "datasets/load_hub.md", "section_heading": "Load a dataset from the Hub", "char_start": 0, "char_end": 769, "token_estimate": 192, "prev_chunk_id": null, "next_chunk_id": 465, "url": "https://huggingface.co/docs/datasets/load_hub", "doc_title": "Load a dataset from the Hub" }, { "chunk_id": 465, "text": "## Load a dataset\n\nBefore you take the time to download a dataset, it's often helpful to quickly get some general information about a dataset. A dataset's information is stored inside [DatasetInfo](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.DatasetInfo) and can include information such as the dataset description, features, and dataset size. \n\nUse the [load_dataset_builder()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset_builder) function to load a dataset builder and inspect a dataset's attributes without committing to downloading it:\n\n```py\n>>> from datasets import load_dataset_builder\n>>> ds_builder = load_dataset_builder(\"cornell-movie-review-data/rotten_tomatoes\")", "source_file": "datasets/load_hub.md", "section_heading": "Load a dataset", "char_start": 771, "char_end": 1504, "token_estimate": 183, "prev_chunk_id": 464, "next_chunk_id": 466, "url": "https://huggingface.co/docs/datasets/load_hub", "doc_title": "Load a dataset from the Hub" }, { "chunk_id": 466, "text": "# Inspect dataset description\n>>> ds_builder.info.description\nMovie Review Dataset. This is a dataset of containing 5,331 positive and 5,331 negative processed sentences from Rotten Tomatoes movie reviews. This data was first used in Bo Pang and Lillian Lee, ``Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales.'', Proceedings of the ACL, 2005.", "source_file": "datasets/load_hub.md", "section_heading": "Inspect dataset description", "char_start": 1506, "char_end": 1904, "token_estimate": 99, "prev_chunk_id": 465, "next_chunk_id": 467, "url": "https://huggingface.co/docs/datasets/load_hub", "doc_title": "Load a dataset from the Hub" }, { "chunk_id": 467, "text": "# Inspect dataset features\n>>> ds_builder.info.features\n{'label': ClassLabel(names=['neg', 'pos']),\n 'text': Value('string')}\n```\n\nIf you're happy with the dataset, then load it with [load_dataset()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset):\n\n```py\n>>> from datasets import load_dataset\n\n>>> dataset = load_dataset(\"cornell-movie-review-data/rotten_tomatoes\", split=\"train\")\n```", "source_file": "datasets/load_hub.md", "section_heading": "Inspect dataset features", "char_start": 1906, "char_end": 2325, "token_estimate": 104, "prev_chunk_id": 466, "next_chunk_id": 468, "url": "https://huggingface.co/docs/datasets/load_hub", "doc_title": "Load a dataset from the Hub" }, { "chunk_id": 468, "text": "## Splits\n\nA split is a specific subset of a dataset like `train` and `test`. List a dataset's split names with the [get_dataset_split_names()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.get_dataset_split_names) function:\n\n```py\n>>> from datasets import get_dataset_split_names\n\n>>> get_dataset_split_names(\"cornell-movie-review-data/rotten_tomatoes\")\n['train', 'validation', 'test']\n```\n\nThen you can load a specific split with the `split` parameter. Loading a dataset `split` returns a [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) object:\n\n```py\n>>> from datasets import load_dataset\n\n>>> dataset = load_dataset(\"cornell-movie-review-data/rotten_tomatoes\", split=\"train\")\n>>> dataset\nDataset({\n features: ['text', 'label'],\n num_rows: 8530\n})\n```\n\nIf you don't specify a `split`, \ud83e\udd17 Datasets returns a [DatasetDict](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.DatasetDict) object instead:", "source_file": "datasets/load_hub.md", "section_heading": "Splits", "char_start": 2327, "char_end": 3307, "token_estimate": 245, "prev_chunk_id": 467, "next_chunk_id": 469, "url": "https://huggingface.co/docs/datasets/load_hub", "doc_title": "Load a dataset from the Hub" }, { "chunk_id": 469, "text": "```py\n>>> from datasets import load_dataset\n\n>>> dataset = load_dataset(\"cornell-movie-review-data/rotten_tomatoes\")\nDatasetDict({\n train: Dataset({\n features: ['text', 'label'],\n num_rows: 8530\n })\n validation: Dataset({\n features: ['text', 'label'],\n num_rows: 1066\n })\n test: Dataset({\n features: ['text', 'label'],\n num_rows: 1066\n })\n})\n```", "source_file": "datasets/load_hub.md", "section_heading": "Splits", "char_start": 3309, "char_end": 3714, "token_estimate": 101, "prev_chunk_id": 468, "next_chunk_id": 470, "url": "https://huggingface.co/docs/datasets/load_hub", "doc_title": "Load a dataset from the Hub" }, { "chunk_id": 470, "text": "## Configurations\n\nSome datasets contain several sub-datasets. For example, the [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset has several sub-datasets, each one containing audio data in a different language. These sub-datasets are known as *configurations* or *subsets*, and you must explicitly select one when loading the dataset. If you don't provide a configuration name, \ud83e\udd17 Datasets will raise a `ValueError` and remind you to choose a configuration.\n\nUse the [get_dataset_config_names()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.get_dataset_config_names) function to retrieve a list of all the possible configurations available to your dataset:\n\n```py\n>>> from datasets import get_dataset_config_names\n\n>>> configs = get_dataset_config_names(\"PolyAI/minds14\")\n>>> print(configs)\n['cs-CZ', 'de-DE', 'en-AU', 'en-GB', 'en-US', 'es-ES', 'fr-FR', 'it-IT', 'ko-KR', 'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'zh-CN', 'all']\n```\n\nThen load the configuration you want:", "source_file": "datasets/load_hub.md", "section_heading": "Configurations", "char_start": 3716, "char_end": 4723, "token_estimate": 251, "prev_chunk_id": 469, "next_chunk_id": 471, "url": "https://huggingface.co/docs/datasets/load_hub", "doc_title": "Load a dataset from the Hub" }, { "chunk_id": 471, "text": "```py\n>>> from datasets import load_dataset\n\n>>> mindsFR = load_dataset(\"PolyAI/minds14\", \"fr-FR\", split=\"train\")\n```", "source_file": "datasets/load_hub.md", "section_heading": "Configurations", "char_start": 4725, "char_end": 4842, "token_estimate": 29, "prev_chunk_id": 470, "next_chunk_id": null, "url": "https://huggingface.co/docs/datasets/load_hub", "doc_title": "Load a dataset from the Hub" }, { "chunk_id": 472, "text": "# Know your dataset\n\nThere are two types of dataset objects, a regular [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) and then an \u2728 [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) \u2728. A [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) provides fast random access to the rows, and memory-mapping so that loading even large datasets only uses a relatively small amount of device memory. But for really, really big datasets that won't even fit on disk or in memory, an [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) allows you to access and use the dataset without waiting for it to download completely!\n\nThis tutorial will show you how to load and access a [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) and an [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset).", "source_file": "datasets/access.md", "section_heading": "Know your dataset", "char_start": 0, "char_end": 1022, "token_estimate": 255, "prev_chunk_id": null, "next_chunk_id": 473, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 473, "text": "## Dataset\n\nWhen you load a dataset split, you'll get a [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) object. You can do many things with a [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) object, which is why it's important to learn how to manipulate and interact with the data stored inside. \n \nThis tutorial uses the [rotten_tomatoes](https://huggingface.co/datasets/rotten_tomatoes) dataset, but feel free to load any dataset you'd like and follow along!\n\n```py\n>>> from datasets import load_dataset\n\n>>> dataset = load_dataset(\"cornell-movie-review-data/rotten_tomatoes\", split=\"train\")\n```", "source_file": "datasets/access.md", "section_heading": "Dataset", "char_start": 1024, "char_end": 1692, "token_estimate": 167, "prev_chunk_id": 472, "next_chunk_id": 474, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 474, "text": "### Indexing\n\nA [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) contains columns of data, and each column can be a different type of data. The *index*, or axis label, is used to access examples from the dataset. For example, indexing by the row returns a dictionary of an example from the dataset:\n\n```py", "source_file": "datasets/access.md", "section_heading": "Indexing", "char_start": 1694, "char_end": 2034, "token_estimate": 85, "prev_chunk_id": 473, "next_chunk_id": 475, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 475, "text": "# Get the first row in the dataset\n>>> dataset[0]\n{'label': 1,\n 'text': 'the rock is destined to be the 21st century\\'s new \" conan \" and that he\\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}\n```\n\nUse the `-` operator to start from the end of the dataset:\n\n```py", "source_file": "datasets/access.md", "section_heading": "Get the first row in the dataset", "char_start": 2035, "char_end": 2360, "token_estimate": 81, "prev_chunk_id": 474, "next_chunk_id": 476, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 476, "text": "# Get the last row in the dataset\n>>> dataset[-1]\n{'label': 0,\n 'text': 'things really get weird , though not particularly scary : the movie is all portent and no content .'}\n```\n\nIndexing by the column name returns a list of all the values in the column:\n\n```py\n>>> dataset[\"text\"]\n['the rock is destined to be the 21st century\\'s new \" conan \" and that he\\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .',\n 'the gorgeously elaborate continuation of \" the lord of the rings \" trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson\\'s expanded vision of j . r . r . tolkien\\'s middle-earth .',\n 'effective but too-tepid biopic',\n ...,\n 'things really get weird , though not particularly scary : the movie is all portent and no content .']\n```\n\nYou can combine row and column name indexing to return a specific value at a position:\n\n```py\n>>> dataset[0][\"text\"]\n'the rock is destined to be the 21st century\\'s new \" conan \" and that he\\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'\n```\n\nIndexing order doesn't matter. Indexing by the column name first returns a [Column](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Column) object that you can index as usual with row indices:\n\n```py\n>>> import time", "source_file": "datasets/access.md", "section_heading": "Get the last row in the dataset", "char_start": 2361, "char_end": 3747, "token_estimate": 346, "prev_chunk_id": 475, "next_chunk_id": 477, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 477, "text": ">>> start_time = time.time()\n>>> text = dataset[0][\"text\"]\n>>> end_time = time.time()\n>>> print(f\"Elapsed time: {end_time - start_time:.4f} seconds\")\nElapsed time: 0.0031 seconds\n\n>>> start_time = time.time()\n>>> text = dataset[\"text\"][0]\n>>> end_time = time.time()\n>>> print(f\"Elapsed time: {end_time - start_time:.4f} seconds\")\nElapsed time: 0.0042 seconds\n```", "source_file": "datasets/access.md", "section_heading": "Get the last row in the dataset", "char_start": 3749, "char_end": 4111, "token_estimate": 90, "prev_chunk_id": 476, "next_chunk_id": 478, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 478, "text": "### Slicing\n\nSlicing returns a slice - or subset - of the dataset, which is useful for viewing several rows at once. To slice a dataset, use the `:` operator to specify a range of positions. \n\n```py", "source_file": "datasets/access.md", "section_heading": "Slicing", "char_start": 4113, "char_end": 4311, "token_estimate": 49, "prev_chunk_id": 477, "next_chunk_id": 479, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 479, "text": "# Get the first three rows\n>>> dataset[:3]\n{'label': [1, 1, 1],\n 'text': ['the rock is destined to be the 21st century\\'s new \" conan \" and that he\\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .',\n 'the gorgeously elaborate continuation of \" the lord of the rings \" trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson\\'s expanded vision of j . r . r . tolkien\\'s middle-earth .',\n 'effective but too-tepid biopic']}", "source_file": "datasets/access.md", "section_heading": "Get the first three rows", "char_start": 4312, "char_end": 4839, "token_estimate": 131, "prev_chunk_id": 478, "next_chunk_id": 480, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 480, "text": "# Get rows between three and six\n>>> dataset[3:6]\n{'label': [1, 1, 1],\n 'text': ['if you sometimes like to go to the movies to have fun , wasabi is a good place to start .',\n \"emerges as something rare , an issue movie that's so honest and keenly observed that it doesn't feel like one .\",\n 'the film provides some great insight into the neurotic mindset of all comics -- even those who have reached the absolute top of the game .']}\n```", "source_file": "datasets/access.md", "section_heading": "Get rows between three and six", "char_start": 4841, "char_end": 5280, "token_estimate": 109, "prev_chunk_id": 479, "next_chunk_id": 481, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 481, "text": "## IterableDataset\n\nAn [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) is loaded when you set the `streaming` parameter to `True` in [load_dataset()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset):\n\n```py\n>>> from datasets import load_dataset\n\n>>> iterable_dataset = load_dataset(\"ethz/food101\", split=\"train\", streaming=True)\n>>> for example in iterable_dataset:\n... print(example)\n... break\n{'image': , 'label': 6}\n```\n\nYou can also create an [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) from an *existing* [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset), but it is faster than streaming mode because the dataset is streamed from local files:\n\n```py\n>>> from datasets import load_dataset\n\n>>> dataset = load_dataset(\"cornell-movie-review-data/rotten_tomatoes\", split=\"train\")\n>>> iterable_dataset = dataset.to_iterable_dataset()\n```", "source_file": "datasets/access.md", "section_heading": "IterableDataset", "char_start": 5282, "char_end": 6302, "token_estimate": 255, "prev_chunk_id": 480, "next_chunk_id": 482, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 482, "text": "An [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) progressively iterates over a dataset one example at a time, so you don't have to wait for the whole dataset to download before you can use it. As you can imagine, this is quite useful for large datasets you want to use immediately!", "source_file": "datasets/access.md", "section_heading": "IterableDataset", "char_start": 6304, "char_end": 6639, "token_estimate": 83, "prev_chunk_id": 481, "next_chunk_id": 483, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 483, "text": "### Indexing\n\nAn [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset)'s behavior is different from a regular [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset). You don't get random access to examples in an [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset). Instead, you should iterate over its elements, for example, by calling `next(iter())` or with a `for` loop to return the next item from the [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset):\n\n```py\n>>> next(iter(iterable_dataset))\n{'image': ,\n 'label': 6}\n\n>>> for example in iterable_dataset:\n... print(example)\n... break\n{'image': , 'label': 6}\n```\n\nBut an [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) supports column indexing that returns an iterable for the column values:", "source_file": "datasets/access.md", "section_heading": "Indexing", "char_start": 6641, "char_end": 7618, "token_estimate": 244, "prev_chunk_id": 482, "next_chunk_id": 484, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 484, "text": "```py\n>>> next(iter(iterable_dataset[\"label\"]))\n6\n```", "source_file": "datasets/access.md", "section_heading": "Indexing", "char_start": 7620, "char_end": 7673, "token_estimate": 13, "prev_chunk_id": 483, "next_chunk_id": 485, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 485, "text": "### Creating a subset\n\nYou can return a subset of the dataset with a specific number of examples in it with [IterableDataset.take()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.take):\n\n```py", "source_file": "datasets/access.md", "section_heading": "Creating a subset", "char_start": 7675, "char_end": 7902, "token_estimate": 56, "prev_chunk_id": 484, "next_chunk_id": 486, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 486, "text": "# Get first three examples\n>>> list(iterable_dataset.take(3))\n[{'image': ,\n 'label': 6},\n {'image': ,\n 'label': 6},\n {'image': ,\n 'label': 6}]\n```\n\nBut unlike [slicing](access/#slicing), [IterableDataset.take()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.take) creates a new [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset).", "source_file": "datasets/access.md", "section_heading": "Get first three examples", "char_start": 7903, "char_end": 8319, "token_estimate": 104, "prev_chunk_id": 485, "next_chunk_id": 487, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 487, "text": "## Next steps\n\nInterested in learning more about the differences between these two types of datasets? Learn more about them in the [Differences between `Dataset` and `IterableDataset`](about_mapstyle_vs_iterable) conceptual guide.\n\nTo get more hands-on with these datasets types, check out the [Process](process) guide to learn how to preprocess a [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) or the [Stream](stream) guide to learn how to preprocess an [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset).", "source_file": "datasets/access.md", "section_heading": "Next steps", "char_start": 8322, "char_end": 8914, "token_estimate": 148, "prev_chunk_id": 486, "next_chunk_id": null, "url": "https://huggingface.co/docs/datasets/access", "doc_title": "Know your dataset" }, { "chunk_id": 488, "text": "# Process\n\n\ud83e\udd17 Datasets provides many tools for modifying the structure and content of a dataset. These tools are important for tidying up a dataset, creating additional columns, converting between features and formats, and much more.\n\nThis guide will show you how to:\n\n- Reorder rows and split the dataset.\n- Rename and remove columns, and other common column operations.\n- Apply processing functions to each example in a dataset.\n- Concatenate datasets.\n- Apply a custom formatting transform.\n- Save and export processed datasets.\n\nFor more details specific to processing other dataset modalities, take a look at the process audio dataset guide, the process image dataset guide, or the process text dataset guide.\n\nThe examples in this guide use the MRPC dataset, but feel free to load any dataset of your choice and follow along!\n\n```py\n>>> from datasets import load_dataset\n>>> dataset = load_dataset(\"nyu-mll/glue\", \"mrpc\", split=\"train\")\n```", "source_file": "datasets/process.md", "section_heading": "Process", "char_start": 0, "char_end": 945, "token_estimate": 236, "prev_chunk_id": null, "next_chunk_id": 489, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 489, "text": "> [!WARNING]\n> All processing methods in this guide return a new [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) object. Modification is not done in-place. Be careful about overriding your previous dataset!", "source_file": "datasets/process.md", "section_heading": "Process", "char_start": 947, "char_end": 1189, "token_estimate": 60, "prev_chunk_id": 488, "next_chunk_id": 490, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 490, "text": "## Sort, shuffle, select, split, and shard\n\nThere are several functions for rearranging the structure of a dataset.\nThese functions are useful for selecting only the rows you want, creating train and test splits, and sharding very large datasets into smaller chunks.", "source_file": "datasets/process.md", "section_heading": "Sort, shuffle, select, split, and shard", "char_start": 1191, "char_end": 1457, "token_estimate": 66, "prev_chunk_id": 489, "next_chunk_id": 491, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 491, "text": "### Sort\n\nUse [sort()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.sort) to sort column values according to their numerical values. The provided column must be NumPy compatible.\n\n```py\n>>> dataset[\"label\"][:10]\n[1, 0, 1, 0, 1, 1, 0, 1, 0, 0]\n>>> sorted_dataset = dataset.sort(\"label\")\n>>> sorted_dataset[\"label\"][:10]\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n>>> sorted_dataset[\"label\"][-10:]\n[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n```\n\nUnder the hood, this creates a list of indices that is sorted according to values of the column.\nThis indices mapping is then used to access the right rows in the underlying Arrow table.", "source_file": "datasets/process.md", "section_heading": "Sort", "char_start": 1459, "char_end": 2093, "token_estimate": 158, "prev_chunk_id": 490, "next_chunk_id": 492, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 492, "text": "### Shuffle\n\nThe [shuffle()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.shuffle) function randomly rearranges the column values. You can specify the `generator` parameter in this function to use a different `numpy.random.Generator` if you want more control over the algorithm used to shuffle the dataset.\n\n```py\n>>> shuffled_dataset = sorted_dataset.shuffle(seed=42)\n>>> shuffled_dataset[\"label\"][:10]\n[1, 1, 1, 0, 1, 1, 1, 1, 1, 0]\n```", "source_file": "datasets/process.md", "section_heading": "Shuffle", "char_start": 2095, "char_end": 2561, "token_estimate": 116, "prev_chunk_id": 491, "next_chunk_id": 493, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 493, "text": "Shuffling takes the list of indices `[0:len(my_dataset)]` and shuffles it to create an indices mapping.\nHowever as soon as your [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) has an indices mapping, the speed can become 10x slower.\nThis is because there is an extra step to get the row index to read using the indices mapping, and most importantly, you aren't reading contiguous chunks of data anymore.\nTo restore the speed, you'd need to rewrite the entire dataset on your disk again using [Dataset.flatten_indices()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.flatten_indices), which removes the indices mapping.\nAlternatively, you can switch to an [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) and leverage its fast approximate shuffling [IterableDataset.shuffle()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.shuffle):", "source_file": "datasets/process.md", "section_heading": "Shuffle", "char_start": 2563, "char_end": 3543, "token_estimate": 245, "prev_chunk_id": 492, "next_chunk_id": 494, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 494, "text": "```py\n>>> iterable_dataset = dataset.to_iterable_dataset(num_shards=128)\n>>> shuffled_iterable_dataset = iterable_dataset.shuffle(seed=42, buffer_size=1000)\n```", "source_file": "datasets/process.md", "section_heading": "Shuffle", "char_start": 3545, "char_end": 3705, "token_estimate": 40, "prev_chunk_id": 493, "next_chunk_id": 495, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 495, "text": "### Select and Filter\n\nThere are two options for filtering rows in a dataset: [select()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.select) and [filter()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.filter).\n\n- [select()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.select) returns rows according to a list of indices:\n\n```py\n>>> small_dataset = dataset.select([0, 10, 20, 30, 40, 50])\n>>> len(small_dataset)\n6\n```\n\n- [filter()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.filter) returns rows that match a specified condition:", "source_file": "datasets/process.md", "section_heading": "Select and Filter", "char_start": 3707, "char_end": 4351, "token_estimate": 161, "prev_chunk_id": 494, "next_chunk_id": 496, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 496, "text": "```py\n>>> start_with_ar = dataset.filter(lambda example: example[\"sentence1\"].startswith(\"Ar\"))\n>>> len(start_with_ar)\n6\n>>> start_with_ar[\"sentence1\"]\n['Around 0335 GMT , Tab shares were up 19 cents , or 4.4 % , at A $ 4.56 , having earlier set a record high of A $ 4.57 .',\n'Arison said Mann may have been one of the pioneers of the world music movement and he had a deep love of Brazilian music .',\n'Arts helped coach the youth on an eighth-grade football team at Lombardi Middle School in Green Bay .',\n'Around 9 : 00 a.m. EDT ( 1300 GMT ) , the euro was at $ 1.1566 against the dollar , up 0.07 percent on the day .',\n\"Arguing that the case was an isolated example , Canada has threatened a trade backlash if Tokyo 's ban is not justified on scientific grounds .\",\n'Artists are worried the plan would harm those who need help most - performers who have a difficult time lining up shows .'\n]\n```", "source_file": "datasets/process.md", "section_heading": "Select and Filter", "char_start": 4353, "char_end": 5252, "token_estimate": 224, "prev_chunk_id": 495, "next_chunk_id": 497, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 497, "text": "[filter()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.filter) can also filter by indices if you set `with_indices=True`:\n\n```py\n>>> even_dataset = dataset.filter(lambda example, idx: idx % 2 == 0, with_indices=True)\n>>> len(even_dataset)\n1834\n>>> len(dataset) / 2\n1834.0\n```\n\nUnless the list of indices to keep is contiguous, those methods also create an indices mapping under the hood.", "source_file": "datasets/process.md", "section_heading": "Select and Filter", "char_start": 5254, "char_end": 5670, "token_estimate": 104, "prev_chunk_id": 496, "next_chunk_id": 498, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 498, "text": "### Split\n\nThe [train_test_split()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.train_test_split) function creates train and test splits if your dataset doesn't already have them. This allows you to adjust the relative proportions or an absolute number of samples in each split. In the example below, use the `test_size` parameter to create a test split that is 10% of the original dataset:\n\n```py\n>>> dataset.train_test_split(test_size=0.1)\n{'train': Dataset(schema: {'sentence1': 'string', 'sentence2': 'string', 'label': 'int64', 'idx': 'int32'}, num_rows: 3301),\n'test': Dataset(schema: {'sentence1': 'string', 'sentence2': 'string', 'label': 'int64', 'idx': 'int32'}, num_rows: 367)}\n>>> 0.1 * len(dataset)\n366.8\n```\n\nThe splits are shuffled by default, but you can set `shuffle=False` to prevent shuffling.", "source_file": "datasets/process.md", "section_heading": "Split", "char_start": 5672, "char_end": 6513, "token_estimate": 210, "prev_chunk_id": 497, "next_chunk_id": 499, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 499, "text": "### Shard\n\n\ud83e\udd17 Datasets supports sharding to divide a very large dataset into a predefined number of chunks. Specify the `num_shards` parameter in [shard()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.shard) to determine the number of shards to split the dataset into. You'll also need to provide the shard you want to return with the `index` parameter.\n\nFor example, the [stanfordnlp/imdb](https://huggingface.co/datasets/stanfordnlp/imdb) dataset has 25000 examples:\n\n```py\n>>> from datasets import load_dataset\n>>> dataset = load_dataset(\"stanfordnlp/imdb\", split=\"train\")\n>>> print(dataset)\nDataset({\n features: ['text', 'label'],\n num_rows: 25000\n})\n```\n\nAfter sharding the dataset into four chunks, the first shard will only have 6250 examples:\n\n```py\n>>> dataset.shard(num_shards=4, index=0)\nDataset({\n features: ['text', 'label'],\n num_rows: 6250\n})\n>>> print(25000/4)\n6250.0\n```", "source_file": "datasets/process.md", "section_heading": "Shard", "char_start": 6515, "char_end": 7441, "token_estimate": 231, "prev_chunk_id": 498, "next_chunk_id": 500, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 500, "text": "## Rename, remove, cast, and flatten\n\nThe following functions allow you to modify the columns of a dataset. These functions are useful for renaming or removing columns, changing columns to a new set of features, and flattening nested column structures.", "source_file": "datasets/process.md", "section_heading": "Rename, remove, cast, and flatten", "char_start": 7443, "char_end": 7695, "token_estimate": 63, "prev_chunk_id": 499, "next_chunk_id": 501, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 501, "text": "### Rename\n\nUse [rename_column()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.rename_column) when you need to rename a column in your dataset. Features associated with the original column are actually moved under the new column name, instead of just replacing the original column in-place.\n\nProvide [rename_column()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.rename_column) with the name of the original column, and the new column name:\n\n```py\n>>> dataset\nDataset({\n features: ['sentence1', 'sentence2', 'label', 'idx'],\n num_rows: 3668\n})\n>>> dataset = dataset.rename_column(\"sentence1\", \"sentenceA\")\n>>> dataset = dataset.rename_column(\"sentence2\", \"sentenceB\")\n>>> dataset\nDataset({\n features: ['sentenceA', 'sentenceB', 'label', 'idx'],\n num_rows: 3668\n})\n```", "source_file": "datasets/process.md", "section_heading": "Rename", "char_start": 7697, "char_end": 8532, "token_estimate": 208, "prev_chunk_id": 500, "next_chunk_id": 502, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 502, "text": "### Remove\n\nWhen you need to remove one or more columns, provide the column name to remove to the [remove_columns()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.remove_columns) function. Remove more than one column by providing a list of column names:\n\n```py\n>>> dataset = dataset.remove_columns(\"label\")\n>>> dataset\nDataset({\n features: ['sentence1', 'sentence2', 'idx'],\n num_rows: 3668\n})\n>>> dataset = dataset.remove_columns([\"sentence1\", \"sentence2\"])\n>>> dataset\nDataset({\n features: ['idx'],\n num_rows: 3668\n})\n```\n\nConversely, [select_columns()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.select_columns) selects one or more columns to keep and removes the rest. This function takes either one or a list of column names:", "source_file": "datasets/process.md", "section_heading": "Remove", "char_start": 8534, "char_end": 9333, "token_estimate": 199, "prev_chunk_id": 501, "next_chunk_id": 503, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 503, "text": "```py\n>>> dataset\nDataset({\n features: ['sentence1', 'sentence2', 'label', 'idx'],\n num_rows: 3668\n})\n>>> dataset = dataset.select_columns(['sentence1', 'sentence2', 'idx'])\n>>> dataset\nDataset({\n features: ['sentence1', 'sentence2', 'idx'],\n num_rows: 3668\n})\n>>> dataset = dataset.select_columns('idx')\n>>> dataset\nDataset({\n features: ['idx'],\n num_rows: 3668\n})\n```", "source_file": "datasets/process.md", "section_heading": "Remove", "char_start": 9335, "char_end": 9722, "token_estimate": 96, "prev_chunk_id": 502, "next_chunk_id": 504, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 504, "text": "### Cast\n\nThe [cast()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.cast) function transforms the feature type of one or more columns. This function accepts your new [Features](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Features) as its argument. The example below demonstrates how to change the [ClassLabel](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.ClassLabel) and [Value](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Value) features:", "source_file": "datasets/process.md", "section_heading": "Cast", "char_start": 9724, "char_end": 10253, "token_estimate": 132, "prev_chunk_id": 503, "next_chunk_id": 505, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 505, "text": "```py\n>>> dataset.features\n{'sentence1': Value('string'),\n'sentence2': Value('string'),\n'label': ClassLabel(names=['not_equivalent', 'equivalent']),\n'idx': Value('int32')}\n\n>>> from datasets import ClassLabel, Value\n>>> new_features = dataset.features.copy()\n>>> new_features[\"label\"] = ClassLabel(names=[\"negative\", \"positive\"])\n>>> new_features[\"idx\"] = Value(\"int64\")\n>>> dataset = dataset.cast(new_features)\n>>> dataset.features\n{'sentence1': Value('string'),\n'sentence2': Value('string'),\n'label': ClassLabel(names=['negative', 'positive']),\n'idx': Value('int64')}\n```\n\n> [!TIP]\n> Casting only works if the original feature type and new feature type are compatible. For example, you can cast a column with the feature type `Value(\"int32\")` to `Value(\"bool\")` if the original column only contains ones and zeros.", "source_file": "datasets/process.md", "section_heading": "Cast", "char_start": 10255, "char_end": 11071, "token_estimate": 204, "prev_chunk_id": 504, "next_chunk_id": 506, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 506, "text": "Use the [cast_column()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.cast_column) function to change the feature type of a single column. Pass the column name and its new feature type as arguments:\n\n```py\n>>> dataset.features\n{'audio': Audio(sampling_rate=44100, mono=True)}\n\n>>> dataset = dataset.cast_column(\"audio\", Audio(sampling_rate=16000))\n>>> dataset.features\n{'audio': Audio(sampling_rate=16000, mono=True)}\n```", "source_file": "datasets/process.md", "section_heading": "Cast", "char_start": 11073, "char_end": 11521, "token_estimate": 112, "prev_chunk_id": 505, "next_chunk_id": 507, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 507, "text": "### Flatten\n\nSometimes a column can be a nested structure of several types. Take a look at the nested structure below from the SQuAD dataset:\n\n```py\n>>> from datasets import load_dataset\n>>> dataset = load_dataset(\"rajpurkar/squad\", split=\"train\")\n>>> dataset.features\n{'id': Value('string'),\n 'title': Value('string'),\n 'context': Value('string'),\n 'question': Value('string'),\n 'answers': {'text': List(Value('string')),\n 'answer_start': List(Value('int32'))}}\n```\n\nThe `answers` field contains two subfields: `text` and `answer_start`. Use the [flatten()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.flatten) function to extract the subfields into their own separate columns:\n\n```py\n>>> flat_dataset = dataset.flatten()\n>>> flat_dataset\nDataset({\n features: ['id', 'title', 'context', 'question', 'answers.text', 'answers.answer_start'],\n num_rows: 87599\n})\n```\n\nNotice how the subfields are now their own independent columns: `answers.text` and `answers.answer_start`.", "source_file": "datasets/process.md", "section_heading": "Flatten", "char_start": 11523, "char_end": 12528, "token_estimate": 251, "prev_chunk_id": 506, "next_chunk_id": 508, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 508, "text": "## Map\n\nSome of the more powerful applications of \ud83e\udd17 Datasets come from using the [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) function. The primary purpose of [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) is to speed up processing functions. It allows you to apply a processing function to each example in a dataset, independently or in batches. This function can even create new rows and columns.\n\nIn the following example, prefix each `sentence1` value in the dataset with `'My sentence: '`.\n\nStart by creating a function that adds `'My sentence: '` to the beginning of each sentence. The function needs to accept and output a `dict`:\n\n```py\n>>> def add_prefix(example):\n... example[\"sentence1\"] = 'My sentence: ' + example[\"sentence1\"]\n... return example\n```\n\nNow use [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) to apply the `add_prefix` function to the entire dataset:", "source_file": "datasets/process.md", "section_heading": "Map", "char_start": 12530, "char_end": 13533, "token_estimate": 250, "prev_chunk_id": 507, "next_chunk_id": 509, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 509, "text": "```py\n>>> updated_dataset = small_dataset.map(add_prefix)\n>>> updated_dataset[\"sentence1\"][:5]\n['My sentence: Amrozi accused his brother , whom he called \" the witness \" , of deliberately distorting his evidence .',\n\"My sentence: Yucaipa owned Dominick 's before selling the chain to Safeway in 1998 for $ 2.5 billion .\",\n'My sentence: They had published an advertisement on the Internet on June 10 , offering the cargo for sale , he added .',\n'My sentence: Around 0335 GMT , Tab shares were up 19 cents , or 4.4 % , at A $ 4.56 , having earlier set a record high of A $ 4.57 .',\n]\n```\n\nLet's take a look at another example, except this time, you'll remove a column with [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map). When you remove a column, it is only removed after the example has been provided to the mapped function. This allows the mapped function to use the content of the columns before they are removed.", "source_file": "datasets/process.md", "section_heading": "Map", "char_start": 13535, "char_end": 14488, "token_estimate": 238, "prev_chunk_id": 508, "next_chunk_id": 510, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 510, "text": "Specify the column to remove with the `remove_columns` parameter in [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map):\n\n```py\n>>> updated_dataset = dataset.map(lambda example: {\"new_sentence\": example[\"sentence1\"]}, remove_columns=[\"sentence1\"])\n>>> updated_dataset.column_names\n['sentence2', 'label', 'idx', 'new_sentence']\n```\n\n> [!TIP]\n> \ud83e\udd17 Datasets also has a [remove_columns()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.remove_columns) function which is faster because it doesn't copy the data of the remaining columns.\n\nYou can also use [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) with indices if you set `with_indices=True`. The example below adds the index to the beginning of each sentence:", "source_file": "datasets/process.md", "section_heading": "Map", "char_start": 14490, "char_end": 15297, "token_estimate": 201, "prev_chunk_id": 509, "next_chunk_id": 511, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 511, "text": "```py\n>>> updated_dataset = dataset.map(lambda example, idx: {\"sentence2\": f\"{idx}: \" + example[\"sentence2\"]}, with_indices=True)\n>>> updated_dataset[\"sentence2\"][:5]\n['0: Referring to him as only \" the witness \" , Amrozi accused his brother of deliberately distorting his evidence .',\n \"1: Yucaipa bought Dominick 's in 1995 for $ 693 million and sold it to Safeway for $ 1.8 billion in 1998 .\",\n \"2: On June 10 , the ship 's owners had published an advertisement on the Internet , offering the explosives for sale .\",\n '3: Tab shares jumped 20 cents , or 4.6 % , to set a record closing high at A $ 4.57 .',\n '4: PG & E Corp. shares jumped $ 1.63 or 8 percent to $ 21.03 on the New York Stock Exchange on Friday .'\n]\n```", "source_file": "datasets/process.md", "section_heading": "Map", "char_start": 15299, "char_end": 16021, "token_estimate": 180, "prev_chunk_id": 510, "next_chunk_id": 512, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 512, "text": "### Multiprocessing\n\nMultiprocessing significantly speeds up processing by parallelizing processes on the CPU. Set the `num_proc` parameter in [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) to set the number of processes to use:\n\n```py\n>>> updated_dataset = dataset.map(lambda example, idx: {\"sentence2\": f\"{idx}: \" + example[\"sentence2\"]}, with_indices=True, num_proc=4)\n```\n\nThe [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) also works with the rank of the process if you set `with_rank=True`. This is analogous to the `with_indices` parameter. The `with_rank` parameter in the mapped function goes after the `index` one if it is already present.", "source_file": "datasets/process.md", "section_heading": "Multiprocessing", "char_start": 16023, "char_end": 16750, "token_estimate": 181, "prev_chunk_id": 511, "next_chunk_id": 513, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 513, "text": "```py\n>>> import torch\n>>> from multiprocess import set_start_method\n>>> from transformers import AutoTokenizer, AutoModelForCausalLM\n>>> from datasets import load_dataset\n>>>\n>>> # Get an example dataset\n>>> dataset = load_dataset(\"fka/awesome-chatgpt-prompts\", split=\"train\")\n>>>\n>>> # Get an example model and its tokenizer\n>>> model = AutoModelForCausalLM.from_pretrained(\"Qwen/Qwen1.5-0.5B-Chat\").eval()\n>>> tokenizer = AutoTokenizer.from_pretrained(\"Qwen/Qwen1.5-0.5B-Chat\")\n>>>\n>>> def gpu_computation(batch, rank):\n... # Move the model on the right GPU if it's not there already\n... device = f\"cuda:{(rank or 0) % torch.cuda.device_count()}\"\n... model.to(device)\n...\n... # Your big GPU call goes here, for example:\n... chats = [[\n... {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n... {\"role\": \"user\", \"content\": prompt}\n... ] for prompt in batch[\"prompt\"]]\n... texts = [tokenizer.apply_chat_template(\n... chat,\n... tokenize=False,\n... add_generation_prompt=True\n... ) for chat in chats]\n... model_inputs = tokenizer(texts, padding=True, return_tensors=\"pt\").to(device)\n... with torch.no_grad():\n... outputs = model.generate(**model_inputs, max_new_tokens=512)\n... batch[\"output\"] = tokenizer.batch_decode(outputs, skip_special_tokens=True)\n... return batch\n>>>\n>>> if __name__ == \"__main__\":\n... set_start_method(\"spawn\")\n... updated_dataset = dataset.map(\n... gpu_computation,\n... batched=True,\n... batch_size=16,\n... with_rank=True,\n... num_proc=torch.cuda.device_count(), # one process per GPU\n... )\n```", "source_file": "datasets/process.md", "section_heading": "Multiprocessing", "char_start": 16752, "char_end": 18432, "token_estimate": 420, "prev_chunk_id": 512, "next_chunk_id": 514, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 514, "text": "The main use-case for rank is to parallelize computation across several GPUs. This requires setting `multiprocess.set_start_method(\"spawn\")`. If you don't you'll receive the following CUDA error:\n\n```bash\nRuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method.\n```", "source_file": "datasets/process.md", "section_heading": "Multiprocessing", "char_start": 18434, "char_end": 18777, "token_estimate": 85, "prev_chunk_id": 513, "next_chunk_id": 515, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 515, "text": "### Batch processing\n\nThe [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) function supports working with batches of examples. Operate on batches by setting `batched=True`. The default batch size is 1000, but you can adjust it with the `batch_size` parameter. Batch processing enables interesting applications such as splitting long sentences into shorter chunks and data augmentation.", "source_file": "datasets/process.md", "section_heading": "Batch processing", "char_start": 18779, "char_end": 19201, "token_estimate": 105, "prev_chunk_id": 514, "next_chunk_id": 516, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 516, "text": "#### Split long examples\n\nWhen examples are too long, you may want to split them into several smaller chunks. Begin by creating a function that:\n\n1. Splits the `sentence1` field into chunks of 50 characters.\n\n2. Stacks all the chunks together to create the new dataset.\n\n```py\n>>> def chunk_examples(examples):\n... chunks = []\n... for sentence in examples[\"sentence1\"]:\n... chunks += [sentence[i:i + 50] for i in range(0, len(sentence), 50)]\n... return {\"chunks\": chunks}\n```\n\nApply the function with [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map):", "source_file": "datasets/process.md", "section_heading": "Split long examples", "char_start": 19203, "char_end": 19810, "token_estimate": 151, "prev_chunk_id": 515, "next_chunk_id": 517, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 517, "text": "```py\n>>> chunked_dataset = dataset.map(chunk_examples, batched=True, remove_columns=dataset.column_names)\n>>> chunked_dataset[:10]\n{'chunks': ['Amrozi accused his brother , whom he called \" the ',\n 'witness \" , of deliberately distorting his evidenc',\n 'e .',\n \"Yucaipa owned Dominick 's before selling the chain\",\n ' to Safeway in 1998 for $ 2.5 billion .',\n 'They had published an advertisement on the Interne',\n 't on June 10 , offering the cargo for sale , he ad',\n 'ded .',\n 'Around 0335 GMT , Tab shares were up 19 cents , or',\n ' 4.4 % , at A $ 4.56 , having earlier set a record']}\n```\n\nNotice how the sentences are split into shorter chunks now, and there are more rows in the dataset.\n\n```py\n>>> dataset\nDataset({\n features: ['sentence1', 'sentence2', 'label', 'idx'],\n num_rows: 3668\n})\n>>> chunked_dataset\nDataset({\n features: ['chunks'],\n num_rows: 10470\n})\n```", "source_file": "datasets/process.md", "section_heading": "Split long examples", "char_start": 19812, "char_end": 20792, "token_estimate": 245, "prev_chunk_id": 516, "next_chunk_id": 518, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 518, "text": "#### Data augmentation\n\nThe [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) function could also be used for data augmentation. The following example generates additional words for a masked token in a sentence.\n\nLoad and use the [RoBERTA](https://huggingface.co/roberta-base) model in \ud83e\udd17 Transformers' [FillMaskPipeline](https://huggingface.co/transformers/main_classes/pipelines#transformers.FillMaskPipeline):", "source_file": "datasets/process.md", "section_heading": "Data augmentation", "char_start": 20794, "char_end": 21241, "token_estimate": 111, "prev_chunk_id": 517, "next_chunk_id": 519, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 519, "text": "```py\n>>> from random import randint\n>>> from transformers import pipeline\n\n>>> fillmask = pipeline(\"fill-mask\", model=\"roberta-base\")\n>>> mask_token = fillmask.tokenizer.mask_token\n>>> smaller_dataset = dataset.filter(lambda e, i: i>> def augment_data(examples):\n... outputs = []\n... for sentence in examples[\"sentence1\"]:\n... words = sentence.split(' ')\n... K = randint(1, len(words)-1)\n... masked_sentence = \" \".join(words[:K] + [mask_token] + words[K+1:])\n... predictions = fillmask(masked_sentence)\n... augmented_sequences = [predictions[i][\"sequence\"] for i in range(3)]\n... outputs += [sentence] + augmented_sequences\n...\n... return {\"data\": outputs}\n```\n\nUse [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) to apply the function over the whole dataset:", "source_file": "datasets/process.md", "section_heading": "Data augmentation", "char_start": 21243, "char_end": 22102, "token_estimate": 214, "prev_chunk_id": 518, "next_chunk_id": 520, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 520, "text": "```py\n>>> augmented_dataset = smaller_dataset.map(augment_data, batched=True, remove_columns=dataset.column_names, batch_size=8)\n>>> augmented_dataset[:9][\"data\"]\n['Amrozi accused his brother , whom he called \" the witness \" , of deliberately distorting his evidence .',\n 'Amrozi accused his brother, whom he called \" the witness \", of deliberately withholding his evidence.',\n 'Amrozi accused his brother, whom he called \" the witness \", of deliberately suppressing his evidence.',\n 'Amrozi accused his brother, whom he called \" the witness \", of deliberately destroying his evidence.',\n \"Yucaipa owned Dominick 's before selling the chain to Safeway in 1998 for $ 2.5 billion .\",\n 'Yucaipa owned Dominick Stores before selling the chain to Safeway in 1998 for $ 2.5 billion.',\n \"Yucaipa owned Dominick's before selling the chain to Safeway in 1998 for $ 2.5 billion.\",\n 'Yucaipa owned Dominick Pizza before selling the chain to Safeway in 1998 for $ 2.5 billion.'\n]\n```", "source_file": "datasets/process.md", "section_heading": "Data augmentation", "char_start": 22104, "char_end": 23075, "token_estimate": 242, "prev_chunk_id": 519, "next_chunk_id": 521, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 521, "text": "For each original sentence, RoBERTA augmented a random word with three alternatives. The original word `distorting` is supplemented by `withholding`, `suppressing`, and `destroying`.", "source_file": "datasets/process.md", "section_heading": "Data augmentation", "char_start": 23077, "char_end": 23259, "token_estimate": 45, "prev_chunk_id": 520, "next_chunk_id": 522, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 522, "text": "### Asynchronous processing\n\nAsynchronous functions are useful to call API endpoints in parallel, for example to download content like images or call a model endpoint.\n\nYou can define an asynchronous function using the `async` and `await` keywords, here is an example function to call a chat model from Hugging Face:", "source_file": "datasets/process.md", "section_heading": "Asynchronous processing", "char_start": 23261, "char_end": 23577, "token_estimate": 79, "prev_chunk_id": 521, "next_chunk_id": 523, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 523, "text": "```python\n>>> import aiohttp\n>>> import asyncio\n>>> from huggingface_hub import get_token\n>>> sem = asyncio.Semaphore(20) # max number of simultaneous queries\n>>> async def query_model(model, prompt):\n... api_url = f\"https://api-inference.huggingface.co/models/{model}/v1/chat/completions\"\n... headers = {\"Authorization\": f\"Bearer {get_token()}\", \"Content-Type\": \"application/json\"}\n... json = {\"messages\": [{\"role\": \"user\", \"content\": prompt}], \"max_tokens\": 20, \"seed\": 42}\n... async with sem, aiohttp.ClientSession() as session, session.post(api_url, headers=headers, json=json) as response:\n... output = await response.json()\n... return {\"Output\": output[\"choices\"][0][\"message\"][\"content\"]}\n```", "source_file": "datasets/process.md", "section_heading": "Asynchronous processing", "char_start": 23579, "char_end": 24311, "token_estimate": 183, "prev_chunk_id": 522, "next_chunk_id": 524, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 524, "text": "Asynchronous functions run in parallel, which accelerates the process a lot. The same code takes a lot more time if it's run sequentially, because it does nothing while waiting for the model response. It is generally recommended to use `async` / `await` when you function has to wait for a response from an API for example, or if it downloads data and it can take some time.\n\nNote the presence of a `Semaphore`: it sets the maximum number of queries that can run in parallel. It is recommended to use a `Semaphore` when calling APIs to avoid rate limit errors.\n\nLet's use it to call the [microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct) model and ask it to return the main topic of each math problem in the [Maxwell-Jia/AIME_2024](https://huggingface.co/Maxwell-Jia/AIME_2024) dataset:", "source_file": "datasets/process.md", "section_heading": "Asynchronous processing", "char_start": 24313, "char_end": 25140, "token_estimate": 206, "prev_chunk_id": 523, "next_chunk_id": 525, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 525, "text": "````python\n>>> from datasets import load_dataset\n>>> ds = load_dataset(\"Maxwell-Jia/AIME_2024\", split=\"train\")\n>>> model = \"microsoft/Phi-3-mini-4k-instruct\"\n>>> prompt = 'What is this text mainly about ? Here is the text:\\n\\n```\\n{Problem}\\n```\\n\\nReply using one or two words max, e.g. \"The main topic is Linear Algebra\".'\n>>> async def get_topic(example):\n... return await query_model(model, prompt.format(Problem=example['Problem']))\n>>> ds = ds.map(get_topic)\n>>> ds[0]\n{'ID': '2024-II-4',\n 'Problem': 'Let $x,y$ and $z$ be positive real numbers that...',\n 'Solution': 'Denote $\\\\log_2(x) = a$, $\\\\log_2(y) = b$, and...,\n 'Answer': 33,\n 'Output': 'The main topic is Logarithms.'}\n````\n\nHere, [Dataset.map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) runs many `get_topic` function asynchronously so it doesn't have to wait for every single model response which would take a lot of time to do sequentially.", "source_file": "datasets/process.md", "section_heading": "Asynchronous processing", "char_start": 25142, "char_end": 26092, "token_estimate": 237, "prev_chunk_id": 524, "next_chunk_id": 526, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 526, "text": "By default, [Dataset.map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) runs up to one thousand map functions in parallel, so don't forget to set the maximum number of API calls that can run in parallel with a `Semaphore`, otherwise the model could return rate limit errors or overload. For advanced use cases, you can change the maximum number of queries in parallel in `datasets.config`.", "source_file": "datasets/process.md", "section_heading": "Asynchronous processing", "char_start": 26094, "char_end": 26517, "token_estimate": 105, "prev_chunk_id": 525, "next_chunk_id": 527, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 527, "text": "### Process multiple splits\n\nMany datasets have splits that can be processed simultaneously with [DatasetDict.map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.DatasetDict.map). For example, tokenize the `sentence1` field in the train and test split by:\n\n```py\n>>> from datasets import load_dataset", "source_file": "datasets/process.md", "section_heading": "Process multiple splits", "char_start": 26519, "char_end": 26839, "token_estimate": 80, "prev_chunk_id": 526, "next_chunk_id": 528, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 528, "text": "# load all the splits\n>>> dataset = load_dataset('nyu-mll/glue', 'mrpc')\n>>> encoded_dataset = dataset.map(lambda examples: tokenizer(examples[\"sentence1\"]), batched=True)\n>>> encoded_dataset[\"train\"][0]\n{'sentence1': 'Amrozi accused his brother , whom he called \" the witness \" , of deliberately distorting his evidence .',\n'sentence2': 'Referring to him as only \" the witness \" , Amrozi accused his brother of deliberately distorting his evidence .',\n'label': 1,\n'idx': 0,\n'input_ids': [ 101, 7277, 2180, 5303, 4806, 1117, 1711, 117, 2292, 1119, 1270, 107, 1103, 7737, 107, 117, 1104, 9938, 4267, 12223, 21811, 1117, 2554, 119, 102],\n'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n}\n```", "source_file": "datasets/process.md", "section_heading": "load all the splits", "char_start": 26841, "char_end": 27698, "token_estimate": 214, "prev_chunk_id": 527, "next_chunk_id": 529, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 529, "text": "### Distributed usage\n\nWhen you use [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) in a distributed setting, you should also use [torch.distributed.barrier](https://pytorch.org/docs/stable/distributed?highlight=barrier#torch.distributed.barrier). This ensures the main process performs the mapping, while the other processes load the results, thereby avoiding duplicate work.\n\nThe following example shows how you can use `torch.distributed.barrier` to synchronize the processes:\n\n```py\n>>> from datasets import Dataset\n>>> import torch.distributed\n\n>>> dataset1 = Dataset.from_dict({\"a\": [0, 1, 2]})\n\n>>> if training_args.local_rank > 0:\n... print(\"Waiting for main process to perform the mapping\")\n... torch.distributed.barrier()\n\n>>> dataset2 = dataset1.map(lambda x: {\"a\": x[\"a\"] + 1})\n\n>>> if training_args.local_rank == 0:\n... print(\"Loading results from main process\")\n... torch.distributed.barrier()\n```", "source_file": "datasets/process.md", "section_heading": "Distributed usage", "char_start": 27700, "char_end": 28665, "token_estimate": 241, "prev_chunk_id": 528, "next_chunk_id": 530, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 530, "text": "## Batch\n\nThe `batch()` method allows you to group samples from the dataset into batches. This is particularly useful when you want to create batches of data for training or evaluation, especially when working with deep learning models.\n\nHere's an example of how to use the `batch()` method:", "source_file": "datasets/process.md", "section_heading": "Batch", "char_start": 28667, "char_end": 28958, "token_estimate": 72, "prev_chunk_id": 529, "next_chunk_id": 531, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 531, "text": "```python\n>>> from datasets import load_dataset\n>>> dataset = load_dataset(\"cornell-movie-review-data/rotten_tomatoes\", split=\"train\")\n>>> batched_dataset = dataset.batch(batch_size=4)\n>>> batched_dataset[0]\n{'text': ['the rock is destined to be the 21st century\\'s new \" conan \" and that he\\'s going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .',\n 'the gorgeously elaborate continuation of \" the lord of the rings \" trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson\\'s expanded vision of j . r . r . tolkien\\'s middle-earth .',\n 'effective but too-tepid biopic',\n 'if you sometimes like to go to the movies to have fun , wasabi is a good place to start .'],\n'label': [1, 1, 1, 1]}\n```\n\nThe `batch()` method accepts the following parameters:", "source_file": "datasets/process.md", "section_heading": "Batch", "char_start": 28960, "char_end": 29827, "token_estimate": 216, "prev_chunk_id": 530, "next_chunk_id": 532, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 532, "text": "- `batch_size` (`int`): The number of samples in each batch.\n- `drop_last_batch` (`bool`, defaults to `False`): Whether to drop the last incomplete batch if the dataset size is not divisible by the batch size.\n- `num_proc` (`int`, optional, defaults to `None`): The number of processes to use for multiprocessing. If None, no multiprocessing is used. This can significantly speed up batching for large datasets.\n\nNote that `Dataset.batch()` returns a new [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) where each item is a batch of multiple samples from the original dataset. If you want to process data in batches, you should use a batched [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) directly, which applies a function to batches but the output dataset is unbatched.", "source_file": "datasets/process.md", "section_heading": "Batch", "char_start": 29829, "char_end": 30675, "token_estimate": 211, "prev_chunk_id": 531, "next_chunk_id": 533, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 533, "text": "## Concatenate\n\nSeparate datasets can be concatenated if they share the same column types. Concatenate datasets with [concatenate_datasets()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.concatenate_datasets):\n\n```py\n>>> from datasets import concatenate_datasets, load_dataset\n\n>>> stories = load_dataset(\"ajibawa-2023/General-Stories-Collection\", split=\"train\")\n>>> stories = stories.select_columns([\"text\"]) # only keep the 'text' column\n>>> wiki = load_dataset(\"wikimedia/wikipedia\", \"20231101.en\", split=\"train\")\n>>> wiki = wiki.select_columns([\"text\"]) # only keep the 'text' column\n\n>>> assert stories.features.type == wiki.features.type\n>>> bert_dataset = concatenate_datasets([stories, wiki])\n```\n\nYou can also concatenate two datasets horizontally by setting `axis=1` as long as the datasets have the same number of rows:", "source_file": "datasets/process.md", "section_heading": "Concatenate", "char_start": 30677, "char_end": 31529, "token_estimate": 213, "prev_chunk_id": 532, "next_chunk_id": 534, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 534, "text": "```py\n>>> from datasets import Dataset\n>>> stories_ids = Dataset.from_dict({\"ids\": list(range(len(stories)))})\n>>> stories_with_ids = concatenate_datasets([stories, stories_ids], axis=1)\n```", "source_file": "datasets/process.md", "section_heading": "Concatenate", "char_start": 31531, "char_end": 31721, "token_estimate": 47, "prev_chunk_id": 533, "next_chunk_id": 535, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 535, "text": "### Interleave\n\nYou can also mix several datasets together by taking alternating examples from each one to create a new dataset. This is known as _interleaving_, which is enabled by the [interleave_datasets()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.interleave_datasets) function. Both [interleave_datasets()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.interleave_datasets) and [concatenate_datasets()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.concatenate_datasets) work with regular [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) and [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) objects.\nRefer to the [Stream](./stream#interleave) guide for an example of how to interleave [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) objects.", "source_file": "datasets/process.md", "section_heading": "Interleave", "char_start": 31723, "char_end": 32668, "token_estimate": 236, "prev_chunk_id": 534, "next_chunk_id": 536, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 536, "text": "You can define sampling probabilities for each of the original datasets to specify how to interleave the datasets.\nIn this case, the new dataset is constructed by getting examples one by one from a random dataset until one of the datasets runs out of samples.\n\n```py\n>>> from datasets import Dataset, interleave_datasets\n>>> seed = 42\n>>> probabilities = [0.3, 0.5, 0.2]\n>>> d1 = Dataset.from_dict({\"a\": [0, 1, 2]})\n>>> d2 = Dataset.from_dict({\"a\": [10, 11, 12, 13]})\n>>> d3 = Dataset.from_dict({\"a\": [20, 21, 22]})\n>>> dataset = interleave_datasets([d1, d2, d3], probabilities=probabilities, seed=seed)\n>>> dataset[\"a\"]\n[10, 11, 20, 12, 0, 21, 13]\n```", "source_file": "datasets/process.md", "section_heading": "Interleave", "char_start": 32670, "char_end": 33322, "token_estimate": 163, "prev_chunk_id": 535, "next_chunk_id": 537, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 537, "text": "You can also specify the `stopping_strategy`. The default strategy, `first_exhausted`, is a subsampling strategy, i.e the dataset construction is stopped as soon one of the dataset runs out of samples.\nYou can specify `stopping_strategy=all_exhausted` to execute an oversampling strategy. In this case, the dataset construction is stopped as soon as every samples in every dataset has been added at least once. In practice, it means that if a dataset is exhausted, it will return to the beginning of this dataset until the stop criterion has been reached.\nNote that if no sampling probabilities are specified, the new dataset will have `max_length_datasets*nb_dataset samples`.\nThere is also `stopping_strategy=all_exhausted_without_replacement` to ensure that every sample is seen exactly once.", "source_file": "datasets/process.md", "section_heading": "Interleave", "char_start": 33324, "char_end": 34119, "token_estimate": 198, "prev_chunk_id": 536, "next_chunk_id": 538, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 538, "text": "```py\n>>> d1 = Dataset.from_dict({\"a\": [0, 1, 2]})\n>>> d2 = Dataset.from_dict({\"a\": [10, 11, 12, 13]})\n>>> d3 = Dataset.from_dict({\"a\": [20, 21, 22]})\n>>> dataset = interleave_datasets([d1, d2, d3], stopping_strategy=\"all_exhausted\")\n>>> dataset[\"a\"]\n[0, 10, 20, 1, 11, 21, 2, 12, 22, 0, 13, 20]\n```", "source_file": "datasets/process.md", "section_heading": "Interleave", "char_start": 34121, "char_end": 34420, "token_estimate": 74, "prev_chunk_id": 537, "next_chunk_id": 539, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 539, "text": "## Format\n\nThe [with_format()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.with_format) function changes the format of a column to be compatible with some common data formats. Specify the output you'd like in the `type` parameter. You can also choose which the columns you want to format using `columns=`. Formatting is applied on-the-fly.\n\nFor example, create PyTorch tensors by setting `type=\"torch\"`:\n\n```py\n>>> dataset = dataset.with_format(type=\"torch\")\n```\n\nThe [set_format()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.set_format) function also changes the format of a column, except it runs in-place:\n\n```py\n>>> dataset.set_format(type=\"torch\")\n```\n\nIf you need to reset the dataset to its original format, set the format to `None` (or use [reset_format()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.reset_format)):", "source_file": "datasets/process.md", "section_heading": "Format", "char_start": 34422, "char_end": 35334, "token_estimate": 228, "prev_chunk_id": 538, "next_chunk_id": 540, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 540, "text": "```py\n>>> dataset.format\n{'type': 'torch', 'format_kwargs': {}, 'columns': [...], 'output_all_columns': False}\n>>> dataset = dataset.with_format(None)\n>>> dataset.format\n{'type': None, 'format_kwargs': {}, 'columns': [...], 'output_all_columns': False}\n```", "source_file": "datasets/process.md", "section_heading": "Format", "char_start": 35336, "char_end": 35592, "token_estimate": 64, "prev_chunk_id": 539, "next_chunk_id": 541, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 541, "text": "### Tensors formats\n\nSeveral tensors or arrays formats are supported. It is generally recommended to use these formats instead of converting outputs of a dataset to tensors or arrays manually to avoid unnecessary data copies and accelerate data loading.\n\nHere is the list of supported tensors or arrays formats:\n\n- NumPy: format name is \"numpy\", for more information see [Using Datasets with NumPy](use_with_numpy)\n- PyTorch: format name is \"torch\", for more information see [Using Datasets with PyTorch](use_with_pytorch)\n- TensorFlow: format name is \"tensorflow\", for more information see [Using Datasets with TensorFlow](use_with_tensorflow)\n- JAX: format name is \"jax\", for more information see [Using Datasets with JAX](use_with_jax)\n\n> [!TIP]\n> Check out the [Using Datasets with TensorFlow](use_with_tensorflow#using-totfdataset) guide for more details on how to efficiently create a TensorFlow dataset.", "source_file": "datasets/process.md", "section_heading": "Tensors formats", "char_start": 35594, "char_end": 36504, "token_estimate": 227, "prev_chunk_id": 540, "next_chunk_id": 542, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 542, "text": "When a dataset is formatted in a tensor or array format, all the data are formatted as tensors or arrays (except unsupported types like strings for example for PyTorch):\n\n```python\n>>> ds = Dataset.from_dict({\"text\": [\"foo\", \"bar\"], \"tokens\": [[0, 1, 2], [3, 4, 5]]})\n>>> ds = ds.with_format(\"torch\")\n>>> ds[0]\n{'text': 'foo', 'tokens': tensor([0, 1, 2])}\n>>> ds[:2]\n{'text': ['foo', 'bar'],\n 'tokens': tensor([[0, 1, 2],\n [3, 4, 5]])}\n```", "source_file": "datasets/process.md", "section_heading": "Tensors formats", "char_start": 36506, "char_end": 36953, "token_estimate": 111, "prev_chunk_id": 541, "next_chunk_id": 543, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 543, "text": "### Tabular formats\n\nYou can use a dataframes or tables format to optimize data loading and data processing, since they generally offer zero-copy operations and transforms written in low-level languages.\n\nHere is the list of supported dataframes or tables formats:\n\n- Pandas: format name is \"pandas\", for more information see [Using Datasets with Pandas](use_with_pandas)\n- Polars: format name is \"polars\", for more information see [Using Datasets with Polars](use_with_polars)\n- PyArrow: format name is \"arrow\", for more information see [Using Datasets with PyArrow](use_with_tensorflow)\n\nWhen a dataset is formatted in a dataframe or table format, every dataset row or batches of rows is formatted as a dataframe or table, and dataset colums are formatted as a series or array:\n\n```python\n>>> ds = Dataset.from_dict({\"text\": [\"foo\", \"bar\"], \"label\": [0, 1]})\n>>> ds = ds.with_format(\"pandas\")\n>>> ds[:2]\n text label\n0 foo 0\n1 bar 1\n```", "source_file": "datasets/process.md", "section_heading": "Tabular formats", "char_start": 36955, "char_end": 37906, "token_estimate": 237, "prev_chunk_id": 542, "next_chunk_id": 544, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 544, "text": "Those formats make it possible to iterate on the data faster by avoiding data copies, and also enable faster data processing in [map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) or [filter()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.filter):\n\n```python\n>>> ds = ds.map(lambda df: df.assign(upper_text=df.text.str.upper()), batched=True)\n>>> ds[:2]\n text label upper_text\n0 foo 0 FOO\n1 bar 1 BAR\n```", "source_file": "datasets/process.md", "section_heading": "Tabular formats", "char_start": 37908, "char_end": 38402, "token_estimate": 123, "prev_chunk_id": 543, "next_chunk_id": 545, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 545, "text": "### Custom format transform\n\nThe [with_transform()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.with_transform) function applies a custom formatting transform on-the-fly. This function replaces any previously specified format. For example, you can use this function to tokenize and pad tokens on-the-fly. Tokenization is only applied when examples are accessed:\n\n```py\n>>> from transformers import AutoTokenizer\n\n>>> tokenizer = AutoTokenizer.from_pretrained(\"bert-base-uncased\")\n>>> def encode(batch):\n... return tokenizer(batch[\"sentence1\"], batch[\"sentence2\"], padding=\"longest\", truncation=True, max_length=512, return_tensors=\"pt\")\n>>> dataset = dataset.with_transform(encode)\n>>> dataset.format\n{'type': 'custom', 'format_kwargs': {'transform': }, 'columns': ['idx', 'label', 'sentence1', 'sentence2'], 'output_all_columns': False}\n```", "source_file": "datasets/process.md", "section_heading": "Custom format transform", "char_start": 38404, "char_end": 39278, "token_estimate": 218, "prev_chunk_id": 544, "next_chunk_id": 546, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 546, "text": "There is also [set_transform()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.set_transform) which does the same but runs in-place.\n\nYou can also use the [with_transform()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.with_transform) function for custom decoding on [Features](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Features).\n\nThe example below uses the [`pydub`](http://pydub.com/) package as an alternative to `torchcodec` decoding:", "source_file": "datasets/process.md", "section_heading": "Custom format transform", "char_start": 39280, "char_end": 39796, "token_estimate": 129, "prev_chunk_id": 545, "next_chunk_id": 547, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 547, "text": "```py\n>>> import numpy as np\n>>> from pydub import AudioSegment\n\n>>> audio_dataset_amr = Dataset.from_dict({\"audio\": [\"audio_samples/audio.amr\"]})\n\n>>> def decode_audio_with_pydub(batch, sampling_rate=16_000):\n... def pydub_decode_file(audio_path):\n... sound = AudioSegment.from_file(audio_path)\n... if sound.frame_rate != sampling_rate:\n... sound = sound.set_frame_rate(sampling_rate)\n... channel_sounds = sound.split_to_mono()\n... samples = [s.get_array_of_samples() for s in channel_sounds]\n... fp_arr = np.array(samples).T.astype(np.float32)\n... fp_arr /= np.iinfo(samples[0].typecode).max\n... return fp_arr\n...\n... batch[\"audio\"] = [pydub_decode_file(audio_path) for audio_path in batch[\"audio\"]]\n... return batch\n\n>>> audio_dataset_amr.set_transform(decode_audio_with_pydub)\n```", "source_file": "datasets/process.md", "section_heading": "Custom format transform", "char_start": 39798, "char_end": 40662, "token_estimate": 216, "prev_chunk_id": 546, "next_chunk_id": 548, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 548, "text": "## Save\n\nOnce your dataset is ready, you can save it as a Hugging Face Dataset in Parquet format and reuse it later with [load_dataset()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset).\n\nSave your dataset by providing the name of the dataset repository on Hugging Face you wish to save it to to [push_to_hub()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.push_to_hub):\n\n```python\nencoded_dataset.push_to_hub(\"username/my_dataset\")\n```\n\nYou can use multiple processes to upload it in parallel. This is especially useful if you want to speed up the process:\n\n```python\ndataset.push_to_hub(\"username/my_dataset\", num_proc=8)\n```\n\nUse the [load_dataset()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset) function to reload the dataset (in streaming mode or not):\n\n```python\nfrom datasets import load_dataset\nreloaded_dataset = load_dataset(\"username/my_dataset\", streaming=True)\n```", "source_file": "datasets/process.md", "section_heading": "Save", "char_start": 40664, "char_end": 41640, "token_estimate": 244, "prev_chunk_id": 547, "next_chunk_id": 549, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 549, "text": "Alternatively, you can save it locally in Arrow format on disk. Compared to Parquet, Arrow is uncompressed which makes it much faster to reload which is great for local use on disk and ephemeral caching. But since it's larger and with less metadata, it is slower to upload/download/query than Parquet and less suited for long term storage.\n\nUse the [save_to_disk()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.save_to_disk) and [load_from_disk()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_from_disk) function to reload the dataset from your disk:\n\n```py\n>>> encoded_dataset.save_to_disk(\"path/of/my/dataset/directory\")\n>>> # later\n>>> from datasets import load_from_disk\n>>> reloaded_dataset = load_from_disk(\"path/of/my/dataset/directory\")\n```", "source_file": "datasets/process.md", "section_heading": "Save", "char_start": 41642, "char_end": 42446, "token_estimate": 201, "prev_chunk_id": 548, "next_chunk_id": 550, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 550, "text": "## Export\n\n\ud83e\udd17 Datasets supports exporting as well so you can work with your dataset in other applications. The following table shows currently supported file formats you can export to:", "source_file": "datasets/process.md", "section_heading": "Export", "char_start": 42448, "char_end": 42631, "token_estimate": 45, "prev_chunk_id": 549, "next_chunk_id": 551, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 551, "text": "| File type | Export method |\n| ----------------------- | ------------------------------------------------------------------- |\n| CSV | [Dataset.to_csv()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.to_csv) |\n| JSON | [Dataset.to_json()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.to_json) |\n| Parquet | [Dataset.to_parquet()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.to_parquet) |\n| SQL | [Dataset.to_sql()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.to_sql) |\n| In-memory Python object | [Dataset.to_pandas()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.to_pandas), `Dataset.to_polars()` or [Dataset.to_dict()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.to_dict) |", "source_file": "datasets/process.md", "section_heading": "Export", "char_start": 42633, "char_end": 43813, "token_estimate": 295, "prev_chunk_id": 550, "next_chunk_id": 552, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 552, "text": "For example, export your dataset to a CSV file like this:\n\n```py\n>>> encoded_dataset.to_csv(\"path/of/my/dataset.csv\")\n```\n\nUse a `hf://` path to export to a [Dataset repository](https://huggingface.co/docs/hub/datasets-overview) or a [Storage Bucket](https://huggingface.co/docs/hub/storage-buckets) on Hugging Face:\n\n```py\n>>> encoded_dataset.to_csv(\"hf://datasets/username/dataset_name/path/of/my/dataset.csv\")\n>>> encoded_dataset.to_csv(\"hf://buckets/username/raw_data_bucket/path/of/my/dataset.csv\")\n```", "source_file": "datasets/process.md", "section_heading": "Export", "char_start": 43815, "char_end": 44322, "token_estimate": 126, "prev_chunk_id": 551, "next_chunk_id": null, "url": "https://huggingface.co/docs/datasets/process", "doc_title": "Process" }, { "chunk_id": 553, "text": "# Stream\n\nDataset streaming lets you work with a dataset without downloading it.\nThe data is streamed as you iterate over the dataset.\nThis is especially helpful when:\n\n- You don't want to wait for an extremely large dataset to download.\n- The dataset size exceeds the amount of available disk space on your computer.\n- You want to quickly explore just a few samples of a dataset.\n\nFor example, the English split of the [HuggingFaceFW/fineweb](https://huggingface.co/datasets/HuggingFaceFW/fineweb) dataset is 45 terabytes, but you can use it instantly with streaming. Stream a dataset by setting `streaming=True` in [load_dataset()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset) as shown below:", "source_file": "datasets/stream.md", "section_heading": "Stream", "char_start": 0, "char_end": 731, "token_estimate": 182, "prev_chunk_id": null, "next_chunk_id": 554, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 554, "text": "```py\n>>> from datasets import load_dataset\n>>> dataset = load_dataset('HuggingFaceFW/fineweb', split='train', streaming=True)\n>>> print(next(iter(dataset)))\n{'text': 'How AP reported in all formats from tornado-stricken regionsMarch 8, 2012\\nWhen the first serious bout of tornadoes of 2012 blew through middle America in the middle of the night, they touched down in places hours from any AP bureau...', ...,\n 'language_score': 0.9721424579620361, 'token_count': 717}\n```\n\nDataset streaming also lets you work with a dataset made of local files without doing any conversion.\nIn this case, the data is streamed from the local files as you iterate over the dataset.\nThis is especially helpful when:\n\n- You don't want to wait for an extremely large local dataset to be converted to Arrow.\n- The converted files size would exceed the amount of available disk space on your computer.\n- You want to quickly explore just a few samples of a dataset.\n- You want to load only certain columns or efficiently filter a Parquet dataset.", "source_file": "datasets/stream.md", "section_heading": "Stream", "char_start": 744, "char_end": 1768, "token_estimate": 256, "prev_chunk_id": 553, "next_chunk_id": 555, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 555, "text": "For example, you can stream a local dataset of hundreds of compressed JSONL files like [oscar-corpus/OSCAR-2201](https://huggingface.co/datasets/oscar-corpus/OSCAR-2201) to use it instantly:\n\n```py\n>>> from datasets import load_dataset\n>>> data_files = {'train': 'path/to/OSCAR-2201/compressed/en_meta/*.jsonl.gz'}\n>>> dataset = load_dataset('json', data_files=data_files, split='train', streaming=True)\n>>> print(next(iter(dataset)))\n{'id': 0, 'text': 'Founded in 2015, Golden Bees is a leading programmatic recruitment platform dedicated to employers, HR agencies and job boards. The company has developed unique HR-custom technologies and predictive algorithms to identify and attract the best candidates for a job opportunity.', ...\n```", "source_file": "datasets/stream.md", "section_heading": "Stream", "char_start": 1770, "char_end": 2510, "token_estimate": 185, "prev_chunk_id": 554, "next_chunk_id": 556, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 556, "text": "Parquet is a columnar format that allows you to stream and load only a subset of columns and ignore unwanted columns. Parquet also stores metadata such as column statistics (at the file and row group level), enabling efficient filtering. Use the `columns` and `filters` arguments of [datasets.packaged_modules.parquet.ParquetConfig](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.packaged_modules.parquet.ParquetConfig) to stream Parquet datasets, select columns, and apply filters:", "source_file": "datasets/stream.md", "section_heading": "Stream", "char_start": 2512, "char_end": 3015, "token_estimate": 125, "prev_chunk_id": 555, "next_chunk_id": 557, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 557, "text": "```py\n>>> from datasets import load_dataset\n>>> dataset = load_dataset('HuggingFaceFW/fineweb', split='train', streaming=True, columns=[\"url\", \"date\"])\n>>> print(next(iter(dataset)))\n{'url': 'http://%20jwashington@ap.org/Content/Press-Release/2012/How-AP-reported-in-all-formats-from-tornado-stricken-regions', 'date': '2013-05-18T05:48:54Z'}\n>>> dataset = load_dataset('HuggingFaceFW/fineweb', split='train', streaming=True, filters=[(\"language_score\", \">=\", 0.99)])\n>>> print(next(iter(dataset)))\n{'text': 'Everyone wishes for something. And lots of people believe they know how to make their wishes come true with magical thinking.\\nWhat is it? \"Magical thinking is a belief in forms of causation, with no known physical basis,\" said Professor Emily Pronin of Princeton...', ...,\n 'language_score': 0.9900368452072144, 'token_count': 716}\n```", "source_file": "datasets/stream.md", "section_heading": "Stream", "char_start": 3017, "char_end": 3862, "token_estimate": 211, "prev_chunk_id": 556, "next_chunk_id": 558, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 558, "text": "Loading a dataset in streaming mode creates a new dataset type instance (instead of the classic [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) object), known as an [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset).\nThis special type of dataset has its own set of processing methods shown below.\n\n> [!TIP]\n> An [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) is useful for iterative jobs like training a model.\n> You shouldn't use a [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) for jobs that require random access to examples because you have to iterate all over it using a for loop. Getting the last example in an iterable dataset would require you to iterate over all the previous examples.\n> You can find more details in the [Dataset vs. IterableDataset guide](./about_mapstyle_vs_iterable).", "source_file": "datasets/stream.md", "section_heading": "Stream", "char_start": 3864, "char_end": 4851, "token_estimate": 246, "prev_chunk_id": 557, "next_chunk_id": 559, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 559, "text": "## Column indexing\n\nSometimes it is convenient to iterate over values of a specific column. Fortunately, an [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) supports column indexing:\n```python\n>>> from datasets import load_dataset\n>>> dataset = load_dataset(\"allenai/c4\", \"en\", streaming=True, split=\"train\")\n>>> print(next(iter(dataset[\"text\"])))\nBeginners BBQ Class Taking Place in Missoula!...\n```", "source_file": "datasets/stream.md", "section_heading": "Column indexing", "char_start": 4853, "char_end": 5304, "token_estimate": 112, "prev_chunk_id": 558, "next_chunk_id": 560, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 560, "text": "## Convert from a Dataset\n\nIf you have an existing [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) object, you can convert it to an [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) with the [to_iterable_dataset()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.to_iterable_dataset) function. This is actually faster than setting the `streaming=True` argument in [load_dataset()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset) because the data is streamed from local files.\n\n```py\n>>> from datasets import load_dataset", "source_file": "datasets/stream.md", "section_heading": "Convert from a Dataset", "char_start": 5306, "char_end": 5971, "token_estimate": 166, "prev_chunk_id": 559, "next_chunk_id": 561, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 561, "text": "# faster \ud83d\udc07\n>>> dataset = load_dataset(\"ethz/food101\")\n>>> iterable_dataset = dataset.to_iterable_dataset()", "source_file": "datasets/stream.md", "section_heading": "faster \ud83d\udc07", "char_start": 5973, "char_end": 6079, "token_estimate": 26, "prev_chunk_id": 560, "next_chunk_id": 562, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 562, "text": "# slower \ud83d\udc22\n>>> iterable_dataset = load_dataset(\"ethz/food101\", streaming=True)\n```\n\nThe [to_iterable_dataset()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.to_iterable_dataset) function supports sharding when the [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) is instantiated. This is useful when working with big datasets, and you'd like to shuffle the dataset or to enable fast parallel loading with a PyTorch DataLoader.\n\n```py\n>>> import torch\n>>> from datasets import load_dataset\n\n>>> dataset = load_dataset(\"ethz/food101\")\n>>> iterable_dataset = dataset.to_iterable_dataset(num_shards=64) # shard the dataset\n>>> iterable_dataset = iterable_dataset.shuffle(buffer_size=10_000) # shuffles the shards order and use a shuffle buffer when you start iterating\ndataloader = torch.utils.data.DataLoader(iterable_dataset, num_workers=4) # assigns 64 / 4 = 16 shards from the shuffled list of shards to each worker when you start iterating\n```", "source_file": "datasets/stream.md", "section_heading": "slower \ud83d\udc22", "char_start": 6081, "char_end": 7106, "token_estimate": 256, "prev_chunk_id": 561, "next_chunk_id": 563, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 563, "text": "## Shuffle\n\nLike a regular [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset) object, you can also shuffle a [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) with [IterableDataset.shuffle()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.shuffle).\n\nThe `buffer_size` argument controls the size of the buffer to randomly sample examples from. Let's say your dataset has one million examples, and you set the `buffer_size` to ten thousand. [IterableDataset.shuffle()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.shuffle) will randomly select examples from the first ten thousand examples in the buffer. Selected examples in the buffer are replaced with new examples. By default, the buffer size is 1,000.", "source_file": "datasets/stream.md", "section_heading": "Shuffle", "char_start": 7108, "char_end": 7965, "token_estimate": 214, "prev_chunk_id": 562, "next_chunk_id": 564, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 564, "text": "```py\n>>> from datasets import load_dataset\n>>> dataset = load_dataset('HuggingFaceFW/fineweb', split='train', streaming=True)\n>>> shuffled_dataset = dataset.shuffle(seed=42, buffer_size=10_000)\n```\n\n> [!TIP]\n> \n> [IterableDataset.shuffle()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.shuffle) will also shuffle the order of the shards if the dataset is sharded into multiple files.", "source_file": "datasets/stream.md", "section_heading": "Shuffle", "char_start": 7967, "char_end": 8387, "token_estimate": 105, "prev_chunk_id": 563, "next_chunk_id": 565, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 565, "text": "## Reshuffle\n\nSometimes you may want to reshuffle the dataset after each epoch. This will require you to set a different seed for each epoch. Use `IterableDataset.set_epoch()` in between epochs to tell the dataset what epoch you're on.\n\nYour seed effectively becomes: `initial seed + current epoch`.\n\n```py\n>>> for epoch in range(epochs):\n... shuffled_dataset.set_epoch(epoch)\n... for example in shuffled_dataset:\n... ...\n```", "source_file": "datasets/stream.md", "section_heading": "Reshuffle", "char_start": 8389, "char_end": 8830, "token_estimate": 110, "prev_chunk_id": 564, "next_chunk_id": 566, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 566, "text": "## Split dataset\n\nYou can split your dataset one of two ways:\n\n- [IterableDataset.take()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.take) returns the first `n` examples in a dataset:\n\n```py\n>>> dataset = load_dataset('HuggingFaceFW/fineweb', split='train', streaming=True)\n>>> dataset_head = dataset.take(2)\n>>> list(dataset_head)\n[{'text': \"How AP reported in all formats from tor...},\n {'text': 'Did you know you have two little yellow...}]\n```\n\n- [IterableDataset.skip()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.skip) omits the first `n` examples in a dataset and returns the remaining examples:\n\n```py\n>>> train_dataset = shuffled_dataset.skip(1000)\n```\n\n> [!WARNING]\n> `take` and `skip` prevent future calls to `shuffle` because they lock in the order of the shards. You should `shuffle` your dataset before splitting it.", "source_file": "datasets/stream.md", "section_heading": "Split dataset", "char_start": 8832, "char_end": 9738, "token_estimate": 226, "prev_chunk_id": 565, "next_chunk_id": 567, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 567, "text": "### Shard\n\n\ud83e\udd17 Datasets supports sharding to divide a very large dataset into a predefined number of chunks. Specify the `num_shards` parameter in [shard()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.shard) to determine the number of shards to split the dataset into. You'll also need to provide the shard you want to return with the `index` parameter.\n\nFor example, the [amazon_polarity](https://huggingface.co/datasets/fancyzhx/amazon_polarity) dataset has 4 shards (in this case they are 4 Parquet files):\n\n```py\n>>> from datasets import load_dataset\n>>> dataset = load_dataset(\"fancyzhx/amazon_polarity\", split=\"train\", streaming=True)\n>>> print(dataset)\nIterableDataset({\n features: ['label', 'title', 'content'],\n num_shards: 4\n})\n```\n\nAfter sharding the dataset into two chunks, the first one will only have 2 shards:\n\n```py\n>>> dataset.shard(num_shards=2, index=0)\nIterableDataset({\n features: ['label', 'title', 'content'],\n num_shards: 2\n})\n```", "source_file": "datasets/stream.md", "section_heading": "Shard", "char_start": 9740, "char_end": 10742, "token_estimate": 250, "prev_chunk_id": 566, "next_chunk_id": 568, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 568, "text": "To increase the number of shards of a dataset, you can use [IterableDataset.reshard()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.reshard):\n\n```py\n>>> dataset.reshard()\nIterableDataset({\n features: ['label', 'title', 'content'],\n num_shards: 3600\n})\n```\n\nThe resharding mechanism depends on the dataset file format.\nFor example for Parquet, it reshards using row groups instead of having one file per shard.\nSee how it works for every format in [IterableDataset.reshard()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.reshard)'s documentation.\n\nIf your dataset has `dataset.num_shards==1` even after resharding, you should chunk it using [IterableDataset.skip()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.skip) and [IterableDataset.take()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.take) instead.", "source_file": "datasets/stream.md", "section_heading": "Shard", "char_start": 10744, "char_end": 11698, "token_estimate": 238, "prev_chunk_id": 567, "next_chunk_id": 569, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 569, "text": "## Concatenate\n\nSeparate datasets can be concatenated if they share the same column types. Concatenate datasets with [concatenate_datasets()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.concatenate_datasets):\n\n```py\n>>> from datasets import concatenate_datasets, load_dataset\n\n>>> stories = load_dataset(\"ajibawa-2023/General-Stories-Collection\", split=\"train\", streaming=True)\n>>> stories = stories.select_columns([\"text\"]) # only keep the 'text' column\nIterableDataset({\n features: Unknown,\n num_shards: 10\n})\n\n>>> wiki = load_dataset(\"wikimedia/wikipedia\", \"20231101.en\", split=\"train\", streaming=True)\n>>> wiki = wiki.select_columns([\"text\"]) # only keep the 'text' column\nIterableDataset({\n features: ['text'],\n num_shards: 41\n})\n\n>>> bert_dataset = concatenate_datasets([stories, wiki])\nIterableDataset({\n features: ['text'],\n num_shards: 51\n})\n```\n\nThe shards of the concatenated dataset are the shards of the input datasets.", "source_file": "datasets/stream.md", "section_heading": "Concatenate", "char_start": 11700, "char_end": 12673, "token_estimate": 243, "prev_chunk_id": 568, "next_chunk_id": 570, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 570, "text": "You can also concatenate two datasets horizontally by setting `axis=1` as long as the datasets have the same number of rows:\n\n```py\n>>> from datasets import IterableDataset\n>>> stories_ids = IterableDataset.from_dict({\"ids\": list(range(num_stories))})\n>>> stories_with_ids = concatenate_datasets([stories, stories_ids], axis=1)\n```\n\nIn this case, the concatenated dataset only has 1 shard, to avoid ending with unaligned shards from the input datasets.", "source_file": "datasets/stream.md", "section_heading": "Concatenate", "char_start": 12675, "char_end": 13127, "token_estimate": 113, "prev_chunk_id": 569, "next_chunk_id": 571, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 571, "text": "## Interleave\n\n[interleave_datasets()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.interleave_datasets) can combine an [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) with other datasets if they have the same column types. The combined dataset returns alternating examples from each of the original datasets.", "source_file": "datasets/stream.md", "section_heading": "Interleave", "char_start": 13129, "char_end": 13510, "token_estimate": 95, "prev_chunk_id": 570, "next_chunk_id": 572, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 572, "text": "```py\n>>> from datasets import interleave_datasets\n>>> es_dataset = load_dataset('allenai/c4', 'es', split='train', streaming=True)\nIterableDataset({\n features: Unknown,\n num_shards: 2048\n})\n>>> fr_dataset = load_dataset('allenai/c4', 'fr', split='train', streaming=True)\nIterableDataset({\n features: Unknown,\n num_shards: 2048\n})\n\n>>> multilingual_dataset = interleave_datasets([es_dataset, fr_dataset])\nIterableDataset({\n features: ['text', 'timestamp', 'url'],\n num_shards: 2048\n})\n>>> list(multilingual_dataset.take(2))\n[{'text': 'Comprar Zapatillas para ni\u00f1a en chancla con goma por...'},\n {'text': 'Le sacre de philippe ier, 23 mai 1059 - Compte Rendu...'}]\n```\n\nDefine sampling probabilities from each of the original datasets for more control over how each of them are sampled and combined. Set the `probabilities` argument with your desired sampling probabilities:", "source_file": "datasets/stream.md", "section_heading": "Interleave", "char_start": 13512, "char_end": 14403, "token_estimate": 222, "prev_chunk_id": 571, "next_chunk_id": 573, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 573, "text": "```py\n>>> multilingual_dataset_with_oversampling = interleave_datasets([es_dataset, fr_dataset], probabilities=[0.8, 0.2], seed=42)\n>>> list(multilingual_dataset_with_oversampling.take(2))\n[{'text': 'Comprar Zapatillas para ni\u00f1a en chancla con goma por...'},\n {'text': 'Chevrolet Cavalier Usados en Bogota - Carros en Vent...'}]\n```\n\nAround 80% of the final dataset is made of the `es_dataset`, and 20% of the `fr_dataset`.", "source_file": "datasets/stream.md", "section_heading": "Interleave", "char_start": 14405, "char_end": 14828, "token_estimate": 105, "prev_chunk_id": 572, "next_chunk_id": 574, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 574, "text": "You can also specify the `stopping_strategy`. The default strategy, `first_exhausted`, is a subsampling strategy, i.e the dataset construction is stopped as soon one of the dataset runs out of samples.\nYou can specify `stopping_strategy=all_exhausted` to execute an oversampling strategy. In this case, the dataset construction is stopped as soon as every samples in every dataset has been added at least once. In practice, it means that if a dataset is exhausted, it will return to the beginning of this dataset until the stop criterion has been reached.\nNote that if no sampling probabilities are specified, the new dataset will have `max_length_datasets*nb_dataset samples`.\nThere is also `stopping_strategy=all_exhausted_without_replacement` to ensure that every sample is seen exactly once.", "source_file": "datasets/stream.md", "section_heading": "Interleave", "char_start": 14830, "char_end": 15625, "token_estimate": 198, "prev_chunk_id": 573, "next_chunk_id": 575, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 575, "text": "To ensure proper parallelism using sharding, the shards of the interleaved dataset contain at least 1 shard of every input dataset. Therefore the sharding level of the interleaved dataset is the minimum sharding level of the input datasets.\n\nE.g. if the input datasets have respectively 32, 48 and 128 shards, then the interleaved dataset has 32 = min(32, 48, 128) shards, and each new shard has 1 shard from the first dataset, 1-2 shards from the second dataset and 4 shards from the third dataset.", "source_file": "datasets/stream.md", "section_heading": "Interleave", "char_start": 15627, "char_end": 16126, "token_estimate": 124, "prev_chunk_id": 574, "next_chunk_id": 576, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 576, "text": "## Rename, remove, and cast\n\nThe following methods allow you to modify the columns of a dataset. These methods are useful for renaming or removing columns and changing columns to a new set of features.", "source_file": "datasets/stream.md", "section_heading": "Rename, remove, and cast", "char_start": 16128, "char_end": 16329, "token_estimate": 50, "prev_chunk_id": 575, "next_chunk_id": 577, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 577, "text": "### Rename\n\nUse [IterableDataset.rename_column()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.rename_column) when you need to rename a column in your dataset. Features associated with the original column are actually moved under the new column name, instead of just replacing the original column in-place.\n\nProvide [IterableDataset.rename_column()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.rename_column) with the name of the original column, and the new column name:\n\n```py\n>>> from datasets import load_dataset\n>>> dataset = load_dataset('allenai/c4', 'en', streaming=True, split='train')\n>>> dataset = dataset.rename_column(\"text\", \"content\")\n```", "source_file": "datasets/stream.md", "section_heading": "Rename", "char_start": 16331, "char_end": 17057, "token_estimate": 181, "prev_chunk_id": 576, "next_chunk_id": 578, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 578, "text": "### Remove\n\nWhen you need to remove one or more columns, give [IterableDataset.remove_columns()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.remove_columns) the name of the column to remove. Remove more than one column by providing a list of column names:\n\n```py\n>>> from datasets import load_dataset\n>>> dataset = load_dataset('allenai/c4', 'en', streaming=True, split='train')\n>>> dataset = dataset.remove_columns('timestamp')\n```", "source_file": "datasets/stream.md", "section_heading": "Remove", "char_start": 17059, "char_end": 17528, "token_estimate": 117, "prev_chunk_id": 577, "next_chunk_id": 579, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 579, "text": "### Cast\n\n[IterableDataset.cast()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.cast) changes the feature type of one or more columns. This method takes your new `Features` as its argument. The following sample code shows how to change the feature types of `ClassLabel` and `Value`:\n\n```py\n>>> from datasets import load_dataset\n>>> dataset = load_dataset('nyu-mll/glue', 'mrpc', split='train', streaming=True)\n>>> dataset.features\n{'sentence1': Value('string'),\n'sentence2': Value('string'),\n'label': ClassLabel(names=['not_equivalent', 'equivalent']),\n'idx': Value('int32')}\n\n>>> from datasets import ClassLabel, Value\n>>> new_features = dataset.features.copy()\n>>> new_features[\"label\"] = ClassLabel(names=['negative', 'positive'])\n>>> new_features[\"idx\"] = Value('int64')\n>>> dataset = dataset.cast(new_features)\n>>> dataset.features\n{'sentence1': Value('string'),\n'sentence2': Value('string'),\n'label': ClassLabel(names=['negative', 'positive']),\n'idx': Value('int64')}\n```", "source_file": "datasets/stream.md", "section_heading": "Cast", "char_start": 17530, "char_end": 18543, "token_estimate": 253, "prev_chunk_id": 578, "next_chunk_id": 580, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 580, "text": "> [!TIP]\n> Casting only works if the original feature type and new feature type are compatible. For example, you can cast a column with the feature type `Value('int32')` to `Value('bool')` if the original column only contains ones and zeros.\n\nUse [IterableDataset.cast_column()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.cast_column) to change the feature type of just one column. Pass the column name and its new feature type as arguments:\n\n```py\n>>> dataset.features\n{'audio': Audio(sampling_rate=44100, mono=True)}\n\n>>> dataset = dataset.cast_column(\"audio\", Audio(sampling_rate=16000))\n>>> dataset.features\n{'audio': Audio(sampling_rate=16000, mono=True)}\n```", "source_file": "datasets/stream.md", "section_heading": "Cast", "char_start": 18545, "char_end": 19247, "token_estimate": 175, "prev_chunk_id": 579, "next_chunk_id": 581, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 581, "text": "## Map\n\nSimilar to the [Dataset.map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) function for a regular [Dataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset), \ud83e\udd17 Datasets features [IterableDataset.map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.map) for processing an [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset).\n[IterableDataset.map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.map) applies processing on-the-fly when examples are streamed.\n\nIt allows you to apply a processing function to each example in a dataset, independently or in batches. This function can even create new rows and columns.\n\nThe following example demonstrates how to tokenize a [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset). The function needs to accept and output a `dict`:", "source_file": "datasets/stream.md", "section_heading": "Map", "char_start": 19249, "char_end": 20253, "token_estimate": 251, "prev_chunk_id": 580, "next_chunk_id": 582, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 582, "text": "```py\n>>> def add_prefix(example):\n... example['text'] = 'My text: ' + example['text']\n... return example\n```\n\nNext, apply this function to the dataset with [IterableDataset.map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.map):", "source_file": "datasets/stream.md", "section_heading": "Map", "char_start": 20255, "char_end": 20530, "token_estimate": 68, "prev_chunk_id": 581, "next_chunk_id": 583, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 583, "text": "```py\n>>> from datasets import load_dataset\n>>> dataset = load_dataset('allenai/c4', 'en', streaming=True, split='train')\n>>> updated_dataset = dataset.map(add_prefix)\n>>> list(updated_dataset.take(3))\n[{'text': 'My text: Beginners BBQ Class Taking Place in Missoula!\\nDo you want to get better at making...',\n 'timestamp': '2019-04-25 12:57:54',\n 'url': 'https://klyq.com/beginners-bbq-class-taking-place-in-missoula/'},\n {'text': 'My text: Discussion in \\'Mac OS X Lion (10.7)\\' started by axboi87, Jan 20, 2012.\\nI\\'ve go...',\n 'timestamp': '2019-04-21 10:07:13',\n 'url': 'https://forums.macrumors.com/threads/restore-from-larger-disk-to-smaller-disk.1311329/'},\n {'text': 'My text: Foil plaid lycra and spandex shortall with metallic slinky insets. Attached metall...',\n 'timestamp': '2019-04-25 10:40:23',\n 'url': 'https://awishcometrue.com/Catalogs/Clearance/Tweens/V1960-Find-A-Way'}]\n```", "source_file": "datasets/stream.md", "section_heading": "Map", "char_start": 20532, "char_end": 21433, "token_estimate": 225, "prev_chunk_id": 582, "next_chunk_id": 584, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 584, "text": "Let's take a look at another example, except this time, you will remove columns with [IterableDataset.map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.map). When you remove a column, it is only removed after the example has been provided to the mapped function. This allows the mapped function to use the content of the columns before they are removed.\n\nSpecify the column to remove with the `remove_columns` argument in [IterableDataset.map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.map):\n\n```py\n>>> updated_dataset = dataset.map(add_prefix, remove_columns=[\"timestamp\", \"url\"])\n>>> list(updated_dataset.take(3))\n[{'text': 'My text: Beginners BBQ Class Taking Place in Missoula!\\nDo you want to get better at making...'},\n {'text': 'My text: Discussion in \\'Mac OS X Lion (10.7)\\' started by axboi87, Jan 20, 2012.\\nI\\'ve go...'},\n {'text': 'My text: Foil plaid lycra and spandex shortall with metallic slinky insets. Attached metall...'}]\n```", "source_file": "datasets/stream.md", "section_heading": "Map", "char_start": 21435, "char_end": 22460, "token_estimate": 256, "prev_chunk_id": 583, "next_chunk_id": 585, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 585, "text": "### Batch processing\n\n[IterableDataset.map()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.map) also supports working with batches of examples. Operate on batches by setting `batched=True`. The default batch size is 1000, but you can adjust it with the `batch_size` argument. This opens the door to many interesting applications such as tokenization, splitting long sentences into shorter chunks, and data augmentation.", "source_file": "datasets/stream.md", "section_heading": "Batch processing", "char_start": 22462, "char_end": 22917, "token_estimate": 113, "prev_chunk_id": 584, "next_chunk_id": 586, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 586, "text": "#### Tokenization\n\n```py\n>>> from datasets import load_dataset\n>>> from transformers import AutoTokenizer\n>>> dataset = load_dataset(\"allenai/c4\", \"en\", streaming=True, split=\"train\")\n>>> tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased')\n>>> def encode(examples):\n... return tokenizer(examples['text'], truncation=True, padding='max_length')\n>>> dataset = dataset.map(encode, batched=True, remove_columns=[\"text\", \"timestamp\", \"url\"])\n>>> next(iter(dataset))\n{'input_ids': [101, 4088, 16912, 22861, 4160, 2465, 2635, 2173, 1999, 3335, ..., 0, 0, 0],\n'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ..., 0, 0]}\n```\n\n> [!TIP]\n> See other examples of batch processing in the [batched map processing](./process#batch-processing) documentation. They work the same for iterable datasets.", "source_file": "datasets/stream.md", "section_heading": "Tokenization", "char_start": 22919, "char_end": 23748, "token_estimate": 207, "prev_chunk_id": 585, "next_chunk_id": 587, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 587, "text": "### Filter\n\nYou can filter rows in the dataset based on a predicate function using [Dataset.filter()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.filter). It returns rows that match a specified condition:\n\n```py\n>>> from datasets import load_dataset\n>>> dataset = load_dataset('HuggingFaceFW/fineweb', streaming=True, split='train')\n>>> start_with_ar = dataset.filter(lambda example: example['text'].startswith('San Francisco'))\n>>> next(iter(start_with_ar))\n{'text': 'San Francisco 49ers cornerback Shawntae Spencer will miss the rest of the sea...}\n```\n\n[Dataset.filter()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.filter) can also filter by indices if you set `with_indices=True`:", "source_file": "datasets/stream.md", "section_heading": "Filter", "char_start": 23750, "char_end": 24493, "token_estimate": 185, "prev_chunk_id": 586, "next_chunk_id": 588, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 588, "text": "```py\n>>> even_dataset = dataset.filter(lambda example, idx: idx % 2 == 0, with_indices=True)\n>>> list(even_dataset.take(3))\n[{'text': 'How AP reported in all formats from tornado-stricken regionsMarch 8, 2012 Whe...},\n {'text': 'Car Wash For Clara! Now is your chance to help! 2 year old Clara Woodward has...},\n {'text': 'Log In Please enter your ECode to log in. Forgotten your eCode? If you create...}]\n```", "source_file": "datasets/stream.md", "section_heading": "Filter", "char_start": 24495, "char_end": 24905, "token_estimate": 102, "prev_chunk_id": 587, "next_chunk_id": 589, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 589, "text": "## Batch\n\nThe `batch` method transforms your `IterableDataset` into an iterable of batches. This is particularly useful when you want to work with batches in your training loop or when using frameworks that expect batched inputs.\n\n> [!TIP]\n> There is also a \"Batch Processing\" option when using the `map` function to apply a function to batches of data, which is discussed in the [Map section](#map) above. The `batch` method described here is different and provides a more direct way to create batches from your dataset.\n\nYou can use the `batch` method like this:\n\n```python\nfrom datasets import load_dataset", "source_file": "datasets/stream.md", "section_heading": "Batch", "char_start": 24907, "char_end": 25516, "token_estimate": 152, "prev_chunk_id": 588, "next_chunk_id": 590, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 590, "text": "# Load a dataset in streaming mode\ndataset = load_dataset(\"some_dataset\", split=\"train\", streaming=True)", "source_file": "datasets/stream.md", "section_heading": "Load a dataset in streaming mode", "char_start": 25518, "char_end": 25622, "token_estimate": 26, "prev_chunk_id": 589, "next_chunk_id": 591, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 591, "text": "# Create batches of 32 samples\nbatched_dataset = dataset.batch(batch_size=32)", "source_file": "datasets/stream.md", "section_heading": "Create batches of 32 samples", "char_start": 25624, "char_end": 25701, "token_estimate": 19, "prev_chunk_id": 590, "next_chunk_id": 592, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 592, "text": "# Iterate over the batched dataset\nfor batch in batched_dataset:\n print(batch)\n break\n```\n\nIn this example, batched_dataset is still an IterableDataset, but each item yielded is now a batch of 32 samples instead of a single sample.\nThis batching is done on-the-fly as you iterate over the dataset, preserving the memory-efficient nature of IterableDataset.\n\nThe batch method also provides a drop_last_batch parameter. \nWhen set to True, it will discard the last batch if it's smaller than the specified batch_size. \nThis can be useful in scenarios where your downstream processing requires all batches to be of the same size:\n\n```python\nbatched_dataset = dataset.batch(batch_size=32, drop_last_batch=True)\n```", "source_file": "datasets/stream.md", "section_heading": "Iterate over the batched dataset", "char_start": 25703, "char_end": 26418, "token_estimate": 178, "prev_chunk_id": 591, "next_chunk_id": 593, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 593, "text": "## Stream in a training loop\n\n[IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) can be integrated into a training loop. First, shuffle the dataset:\n\n```py\n>>> seed, buffer_size = 42, 10_000\n>>> dataset = dataset.shuffle(seed, buffer_size=buffer_size)\n```\n\nLastly, create a simple training loop and start training:", "source_file": "datasets/stream.md", "section_heading": "Stream in a training loop", "char_start": 26420, "char_end": 26783, "token_estimate": 90, "prev_chunk_id": 592, "next_chunk_id": 594, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 594, "text": "```py\n>>> import torch\n>>> from torch.utils.data import DataLoader\n>>> from transformers import AutoModelForMaskedLM, DataCollatorForLanguageModeling\n>>> from tqdm import tqdm\n>>> dataset = dataset.with_format(\"torch\")\n>>> dataloader = DataLoader(dataset, collate_fn=DataCollatorForLanguageModeling(tokenizer))\n>>> device = 'cuda' if torch.cuda.is_available() else 'cpu' \n>>> model = AutoModelForMaskedLM.from_pretrained(\"distilbert-base-uncased\")\n>>> model.train().to(device)\n>>> optimizer = torch.optim.AdamW(params=model.parameters(), lr=1e-5)\n>>> for epoch in range(3):\n... dataset.set_epoch(epoch)\n... for i, batch in enumerate(tqdm(dataloader, total=5)):\n... if i == 5:\n... break\n... batch = {k: v.to(device) for k, v in batch.items()}\n... outputs = model(**batch)\n... loss = outputs[0]\n... loss.backward()\n... optimizer.step()\n... optimizer.zero_grad()\n... if i % 10 == 0:\n... print(f\"loss: {loss}\")\n```", "source_file": "datasets/stream.md", "section_heading": "Stream in a training loop", "char_start": 26785, "char_end": 27791, "token_estimate": 251, "prev_chunk_id": 593, "next_chunk_id": 595, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 595, "text": "### Save a dataset checkpoint and resume iteration\n\nIf your training loop stops, you may want to restart the training from where it was. To do so you can save a checkpoint of your model and optimizers, as well as your data loader.\n\nIterable datasets don't provide random access to a specific example index to resume from, but you can use [IterableDataset.state_dict()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.state_dict) and [IterableDataset.load_state_dict()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.load_state_dict) to resume from a checkpoint instead, similarly to what you can do for models and optimizers:", "source_file": "datasets/stream.md", "section_heading": "Save a dataset checkpoint and resume iteration", "char_start": 27793, "char_end": 28485, "token_estimate": 173, "prev_chunk_id": 594, "next_chunk_id": 596, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 596, "text": "```python\n>>> iterable_dataset = Dataset.from_dict({\"a\": range(6)}).to_iterable_dataset(num_shards=3)\n>>> for idx, example in enumerate(iterable_dataset):\n... print(example)\n... if idx == 2:\n... state_dict = iterable_dataset.state_dict()\n... print(\"checkpoint\")\n... break\n>>> iterable_dataset.load_state_dict(state_dict)\n>>> print(f\"restart from checkpoint\")\n>>> for example in iterable_dataset:\n... print(example)\n```\n\nReturns:\n\n```\n{'a': 0}\n{'a': 1}\n{'a': 2}\ncheckpoint\nrestart from checkpoint\n{'a': 3}\n{'a': 4}\n{'a': 5}\n```\n\nUnder the hood, the iterable dataset keeps track of the current shard being read and the example index in the current shard and it stores this info in the `state_dict`.\n\nTo resume from a checkpoint, the dataset skips all the shards that were previously read to restart from the current shard. \nThen it reads the shard and skips examples until it reaches the exact example from the checkpoint.", "source_file": "datasets/stream.md", "section_heading": "Save a dataset checkpoint and resume iteration", "char_start": 28487, "char_end": 29443, "token_estimate": 239, "prev_chunk_id": 595, "next_chunk_id": 597, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 597, "text": "Therefore restarting a dataset is quite fast, since it will not re-read the shards that have already been iterated on. Still, resuming a dataset is generally not instantaneous since it has to restart reading from the beginning of the current shard and skip examples until it reaches the checkpoint location.\n\nThis can be used with the `StatefulDataLoader` from `torchdata`:\n\n```python\n>>> from torchdata.stateful_dataloader import StatefulDataLoader\n>>> iterable_dataset = load_dataset(\"deepmind/code_contests\", streaming=True, split=\"train\")\n>>> dataloader = StatefulDataLoader(iterable_dataset, batch_size=32, num_workers=4)\n>>> # checkpoint\n>>> state_dict = dataloader.state_dict() # uses iterable_dataset.state_dict() under the hood\n>>> # resume from checkpoint\n>>> dataloader.load_state_dict(state_dict) # uses iterable_dataset.load_state_dict() under the hood\n```", "source_file": "datasets/stream.md", "section_heading": "Save a dataset checkpoint and resume iteration", "char_start": 29445, "char_end": 30316, "token_estimate": 217, "prev_chunk_id": 596, "next_chunk_id": 598, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 598, "text": "> [!TIP]\n> Resuming returns exactly where the checkpoint was saved except if `.shuffle()` is used: examples from shuffle buffers are lost when resuming and the buffers are refilled with new data.", "source_file": "datasets/stream.md", "section_heading": "Save a dataset checkpoint and resume iteration", "char_start": 30318, "char_end": 30513, "token_estimate": 48, "prev_chunk_id": 597, "next_chunk_id": 599, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 599, "text": "## Save\n\nOnce your iterable dataset is ready, you can save it as a Hugging Face Dataset in Parquet format and reuse it later with [load_dataset()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset).\n\nSave your dataset by providing the name of the dataset repository on Hugging Face you wish to save it to to [push_to_hub()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.push_to_hub). This iterates over the dataset and progressively uploads the data to Hugging Face:\n\n```python\ndataset.push_to_hub(\"username/my_dataset\")\n```\n\nIf the dataset consists of multiple shards (`dataset.num_shards > 1`), you can use multiple processes to upload it in parallel. This is especially useful if you applied `map()` or `filter()` steps since they will run faster in parallel:\n\n```python\ndataset.push_to_hub(\"username/my_dataset\", num_proc=8)\n```", "source_file": "datasets/stream.md", "section_heading": "Save", "char_start": 30515, "char_end": 31405, "token_estimate": 222, "prev_chunk_id": 598, "next_chunk_id": 600, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 600, "text": "Use the [load_dataset()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset) function to reload the dataset:\n\n```python\nfrom datasets import load_dataset\nreloaded_dataset = load_dataset(\"username/my_dataset\")\n```", "source_file": "datasets/stream.md", "section_heading": "Save", "char_start": 31407, "char_end": 31649, "token_estimate": 60, "prev_chunk_id": 599, "next_chunk_id": 601, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 601, "text": "## Export\n\n\ud83e\udd17 Datasets supports exporting as well so you can work with your dataset in other applications. The following table shows currently supported file formats you can export to:", "source_file": "datasets/stream.md", "section_heading": "Export", "char_start": 31651, "char_end": 31834, "token_estimate": 45, "prev_chunk_id": 600, "next_chunk_id": 602, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 602, "text": "| File type | Export method |\n|-------------------------|----------------------------------------------------------------|\n| CSV | [IterableDataset.to_csv()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.to_csv) |\n| JSON | [IterableDataset.to_json()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.to_json) |\n| Parquet | [IterableDataset.to_parquet()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.to_parquet) |\n| SQL | [IterableDataset.to_sql()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.to_sql) |\n| In-memory Python object | [IterableDataset.to_pandas()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.to_pandas), `IterableDataset.to_polars()` or [IterableDataset.to_dict()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset.to_dict) |", "source_file": "datasets/stream.md", "section_heading": "Export", "char_start": 31836, "char_end": 33054, "token_estimate": 304, "prev_chunk_id": 601, "next_chunk_id": 603, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 603, "text": "For example, export your dataset to a CSV file like this:\n\n```py\n>>> dataset.to_csv(\"path/of/my/dataset.csv\")\n```\n\nIf you have a large dataset, you can save one file per shard, e.g.\n\n```py\n>>> num_shards = dataset.num_shards\n>>> for index in range(num_shards):\n... shard = dataset.shard(index, num_shards)\n... shard.to_parquet(f\"path/of/my/dataset/data-{index:05d}.parquet\")\n```", "source_file": "datasets/stream.md", "section_heading": "Export", "char_start": 33056, "char_end": 33442, "token_estimate": 96, "prev_chunk_id": 602, "next_chunk_id": null, "url": "https://huggingface.co/docs/datasets/stream", "doc_title": "Stream" }, { "chunk_id": 604, "text": "# Create a dataset card\n\nEach dataset should have a dataset card to promote responsible usage and inform users of any potential biases within the dataset.\nThis idea was inspired by the Model Cards proposed by [Mitchell, 2018](https://huggingface.co/papers/1810.03993).\nDataset cards help users understand a dataset's contents, the context for using the dataset, how it was created, and any other considerations a user should be aware of.\n\nCreating a dataset card is easy and can be done in just a few steps:\n\n1. Go to your dataset repository on the [Hub](https://hf.co/new-dataset) and click on **Create Dataset Card** to create a new `README.md` file in your repository.\n\n2. Use the **Metadata UI** to select the tags that describe your dataset. You can add a license, language, pretty_name, the task_categories, size_categories, and any other tags that you think are relevant. These tags help users discover and find your dataset on the Hub.", "source_file": "datasets/dataset_card.md", "section_heading": "Create a dataset card", "char_start": 0, "char_end": 943, "token_estimate": 235, "prev_chunk_id": null, "next_chunk_id": 605, "url": "https://huggingface.co/docs/datasets/dataset_card", "doc_title": "Create a dataset card" }, { "chunk_id": 605, "text": "> [!TIP]\n > For a complete, but not required, set of tag options you can also look at the [Dataset Card specifications](https://github.com/huggingface/hub-docs/blob/main/datasetcard.md?plain=1). This'll have a few more tag options like `multilinguality` and `language_creators` which are useful but not absolutely necessary.\n\n3. Click on the **Import dataset card template** link to automatically create a template with all the relevant fields to complete. Fill out the template sections to the best of your ability. Take a look at the [Dataset Card Creation Guide](https://github.com/huggingface/datasets/blob/main/templates/README_guide.md) for more detailed information about what to include in each section of the card. For fields you are unable to complete, you can write **[More Information Needed]**.\n\n4. Once you're done, commit the changes to the `README.md` file and you'll see the completed dataset card on your repository.", "source_file": "datasets/dataset_card.md", "section_heading": "Create a dataset card", "char_start": 958, "char_end": 1893, "token_estimate": 233, "prev_chunk_id": 604, "next_chunk_id": 606, "url": "https://huggingface.co/docs/datasets/dataset_card", "doc_title": "Create a dataset card" }, { "chunk_id": 606, "text": "YAML also allows you to customize the way your dataset is loaded by [defining splits and/or configurations](./repository_structure#define-your-splits-and-subsets-in-yaml) without the need to write any code.\n\nFeel free to take a look at the [SNLI](https://huggingface.co/datasets/stanfordnlp/snli), [CNN/DailyMail](https://huggingface.co/datasets/abisee/cnn_dailymail), and [Allocin\u00e9](https://huggingface.co/datasets/tblard/allocine) dataset cards as examples to help you get started.", "source_file": "datasets/dataset_card.md", "section_heading": "Create a dataset card", "char_start": 1895, "char_end": 2378, "token_estimate": 120, "prev_chunk_id": 605, "next_chunk_id": null, "url": "https://huggingface.co/docs/datasets/dataset_card", "doc_title": "Create a dataset card" }, { "chunk_id": 607, "text": "# Create a dataset\n\nSometimes, you may need to create a dataset if you're working with your own data. Creating a dataset with \ud83e\udd17 Datasets confers all the advantages of the library to your dataset: fast loading and processing, [stream enormous datasets](stream), [memory-mapping](https://huggingface.co/course/chapter5/4?fw=pt#the-magic-of-memory-mapping), and more. You can easily and rapidly create a dataset with \ud83e\udd17 Datasets low-code approaches, reducing the time it takes to start training a model. In many cases, it is as easy as [dragging and dropping](upload_dataset#upload-with-the-hub-ui) your data files into a dataset repository on the Hub.\n\nIn this tutorial, you'll learn how to use \ud83e\udd17 Datasets low-code methods for creating all types of datasets:\n\n- Folder-based builders for quickly creating an image or audio dataset\n- `from_` methods for creating datasets from local files", "source_file": "datasets/create_dataset.md", "section_heading": "Create a dataset", "char_start": 0, "char_end": 884, "token_estimate": 221, "prev_chunk_id": null, "next_chunk_id": 608, "url": "https://huggingface.co/docs/datasets/create_dataset", "doc_title": "Create a dataset" }, { "chunk_id": 608, "text": "## File-based builders\n\n\ud83e\udd17 Datasets supports many common formats such as `csv`, `json/jsonl`, `parquet`, `txt`.\n\nFor example it can read a dataset made up of one or several CSV files (in this case, pass your CSV files as a list):\n\n```py\n>>> from datasets import load_dataset\n>>> dataset = load_dataset(\"csv\", data_files=\"my_file.csv\")\n```\n\nTo get the list of supported formats and code examples, follow this guide [here](https://huggingface.co/docs/datasets/loading#local-and-remote-files).", "source_file": "datasets/create_dataset.md", "section_heading": "File-based builders", "char_start": 886, "char_end": 1375, "token_estimate": 122, "prev_chunk_id": 607, "next_chunk_id": 609, "url": "https://huggingface.co/docs/datasets/create_dataset", "doc_title": "Create a dataset" }, { "chunk_id": 609, "text": "## Folder-based builders\n\nThere are two folder-based builders, `ImageFolder` and `AudioFolder`. These are low-code methods for quickly creating an image or speech and audio dataset with several thousand examples. They are great for rapidly prototyping computer vision and speech models before scaling to a larger dataset. Folder-based builders takes your data and automatically generates the dataset's features, splits, and labels. Under the hood:", "source_file": "datasets/create_dataset.md", "section_heading": "Folder-based builders", "char_start": 1377, "char_end": 1824, "token_estimate": 111, "prev_chunk_id": 608, "next_chunk_id": 610, "url": "https://huggingface.co/docs/datasets/create_dataset", "doc_title": "Create a dataset" }, { "chunk_id": 610, "text": "- `ImageFolder` uses the [Image](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Image) feature to decode an image file. Many image extension formats are supported, such as jpg and png, but other formats are also supported. You can check the complete [list](https://github.com/huggingface/datasets/blob/b5672a956d5de864e6f5550e493527d962d6ae55/src/datasets/packaged_modules/imagefolder/imagefolder.py#L39) of supported image extensions.\n- `AudioFolder` uses the [Audio](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Audio) feature to decode an audio file. Extensions such as wav, mp3, and even mp4 are supported, and you can check the complete [list](https://ffmpeg.org/ffmpeg-formats.html) of supported audio extensions. Decoding is done via ffmpeg.\n\nThe dataset splits are generated from the repository structure, and the label names are automatically inferred from the directory name.\n\nFor example, if your image dataset (it is the same for an audio dataset) is stored like this:", "source_file": "datasets/create_dataset.md", "section_heading": "Folder-based builders", "char_start": 1826, "char_end": 2844, "token_estimate": 254, "prev_chunk_id": 609, "next_chunk_id": 611, "url": "https://huggingface.co/docs/datasets/create_dataset", "doc_title": "Create a dataset" }, { "chunk_id": 611, "text": "```\npokemon/train/grass/bulbasaur.png\npokemon/train/fire/charmander.png\npokemon/train/water/squirtle.png\n\npokemon/test/grass/ivysaur.png\npokemon/test/fire/charmeleon.png\npokemon/test/water/wartortle.png\n```\n\nThen this is how the folder-based builder generates an example:\n\nCreate the image dataset by specifying `imagefolder` in [load_dataset()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset):\n\n```py\n>>> from datasets import load_dataset\n\n>>> dataset = load_dataset(\"imagefolder\", data_dir=\"/path/to/pokemon\")\n```\n\nAn audio dataset is created in the same way, except you specify `audiofolder` in [load_dataset()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset) instead:\n\n```py\n>>> from datasets import load_dataset\n\n>>> dataset = load_dataset(\"audiofolder\", data_dir=\"/path/to/folder\")\n```", "source_file": "datasets/create_dataset.md", "section_heading": "Folder-based builders", "char_start": 0, "char_end": 859, "token_estimate": 214, "prev_chunk_id": 610, "next_chunk_id": 612, "url": "https://huggingface.co/docs/datasets/create_dataset", "doc_title": "Create a dataset" }, { "chunk_id": 612, "text": "Any additional information about your dataset, such as text captions or transcriptions, can be included with a `metadata.csv` file in the folder containing your dataset. The metadata file needs to have a `file_name` column that links the image or audio file to its corresponding metadata:\n\n```\nfile_name, text\nbulbasaur.png, There is a plant seed on its back right from the day this Pok\u00e9mon is born.\ncharmander.png, It has a preference for hot things.\nsquirtle.png, When it retracts its long neck into its shell, it squirts out water with vigorous force.\n```\n\nTo learn more about each of these folder-based builders, check out the and ImageFolder or AudioFolder guides.", "source_file": "datasets/create_dataset.md", "section_heading": "Folder-based builders", "char_start": 3711, "char_end": 4380, "token_estimate": 167, "prev_chunk_id": 611, "next_chunk_id": 613, "url": "https://huggingface.co/docs/datasets/create_dataset", "doc_title": "Create a dataset" }, { "chunk_id": 613, "text": "## From Python dictionaries\n\nYou can also create a dataset from data in Python dictionaries. There are two ways you can create a dataset using the `from_` methods:\n\n * The [from_generator()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.from_generator) method is the most memory-efficient way to create a dataset from a [generator](https://wiki.python.org/moin/Generators) due to a generators iterative behavior. This is especially useful when you're working with a really large dataset that may not fit in memory, since the dataset is generated on disk progressively and then memory-mapped.\n\n ```py\n >>> from datasets import Dataset\n >>> def gen():\n ... yield {\"pokemon\": \"bulbasaur\", \"type\": \"grass\"}\n ... yield {\"pokemon\": \"squirtle\", \"type\": \"water\"}\n >>> ds = Dataset.from_generator(gen)\n >>> ds[0]\n {\"pokemon\": \"bulbasaur\", \"type\": \"grass\"}\n ```", "source_file": "datasets/create_dataset.md", "section_heading": "From Python dictionaries", "char_start": 4382, "char_end": 5298, "token_estimate": 229, "prev_chunk_id": 612, "next_chunk_id": 614, "url": "https://huggingface.co/docs/datasets/create_dataset", "doc_title": "Create a dataset" }, { "chunk_id": 614, "text": "A generator-based [IterableDataset](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.IterableDataset) needs to be iterated over with a `for` loop for example:\n\n ```py\n >>> from datasets import IterableDataset\n >>> ds = IterableDataset.from_generator(gen)\n >>> for example in ds:\n ... print(example)\n {\"pokemon\": \"bulbasaur\", \"type\": \"grass\"}\n {\"pokemon\": \"squirtle\", \"type\": \"water\"}\n ```\n\n * The [from_dict()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.from_dict) method is a straightforward way to create a dataset from a dictionary:\n\n ```py\n >>> from datasets import Dataset\n >>> ds = Dataset.from_dict({\"pokemon\": [\"bulbasaur\", \"squirtle\"], \"type\": [\"grass\", \"water\"]})\n >>> ds[0]\n {\"pokemon\": \"bulbasaur\", \"type\": \"grass\"}\n ```", "source_file": "datasets/create_dataset.md", "section_heading": "From Python dictionaries", "char_start": 5304, "char_end": 6131, "token_estimate": 206, "prev_chunk_id": 613, "next_chunk_id": 615, "url": "https://huggingface.co/docs/datasets/create_dataset", "doc_title": "Create a dataset" }, { "chunk_id": 615, "text": "To create an image or audio dataset, chain the [cast_column()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.cast_column) method with [from_dict()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.from_dict) and specify the column and feature type. For example, to create an audio dataset:\n\n ```py\n >>> audio_dataset = Dataset.from_dict({\"audio\": [\"path/to/audio_1\", ..., \"path/to/audio_n\"]}).cast_column(\"audio\", Audio())\n ```\n\nNow that you know how to create a dataset, consider sharing it on the Hub so the community can also benefit from your work! Go on to the next section to learn how to share your dataset.", "source_file": "datasets/create_dataset.md", "section_heading": "From Python dictionaries", "char_start": 6137, "char_end": 6811, "token_estimate": 168, "prev_chunk_id": 614, "next_chunk_id": null, "url": "https://huggingface.co/docs/datasets/create_dataset", "doc_title": "Create a dataset" }, { "chunk_id": 616, "text": "# Share a dataset to the Hub\n\nThe [Hub](https://huggingface.co/datasets) is home to an extensive collection of community-curated and popular research datasets. We encourage you to share your dataset to the Hub to help grow the ML community and accelerate progress for everyone. All contributions are welcome; adding a dataset is just a drag and drop away!\n\nStart by [creating a Hugging Face Hub account](https://huggingface.co/join) if you don't have one yet.", "source_file": "datasets/upload_dataset.md", "section_heading": "Share a dataset to the Hub", "char_start": 0, "char_end": 459, "token_estimate": 114, "prev_chunk_id": null, "next_chunk_id": 617, "url": "https://huggingface.co/docs/datasets/upload_dataset", "doc_title": "Share a dataset to the Hub" }, { "chunk_id": 617, "text": "## Upload with the Hub UI\n\nThe Hub's web-based interface allows users without any developer experience to upload a dataset.", "source_file": "datasets/upload_dataset.md", "section_heading": "Upload with the Hub UI", "char_start": 461, "char_end": 584, "token_estimate": 30, "prev_chunk_id": 616, "next_chunk_id": 618, "url": "https://huggingface.co/docs/datasets/upload_dataset", "doc_title": "Share a dataset to the Hub" }, { "chunk_id": 618, "text": "### Create a repository\n\nA repository hosts all your dataset files, including the revision history, making storing more than one dataset version possible.\n\n1. Click on your profile and select **New Dataset** to create a new dataset repository. \n2. Pick a name for your dataset, and choose whether it is a public or private dataset. A public dataset is visible to anyone, whereas a private dataset can only be viewed by you or members of your organization.", "source_file": "datasets/upload_dataset.md", "section_heading": "Create a repository", "char_start": 586, "char_end": 1041, "token_estimate": 113, "prev_chunk_id": 617, "next_chunk_id": 619, "url": "https://huggingface.co/docs/datasets/upload_dataset", "doc_title": "Share a dataset to the Hub" }, { "chunk_id": 619, "text": "### Upload dataset\n\n1. Once you've created a repository, navigate to the **Files and versions** tab to add a file. Select **Add file** to upload your dataset files. We support many text, audio, and image data extensions such as `.csv`, `.mp3`, and `.jpg` among many others. For text data extensions like `.csv`, `.json`, `.jsonl`, and `.txt`, we recommend compressing them before uploading to the Hub (to `.zip` or `.gz` file extension for example).\n\n Text file extensions are not tracked by Git LFS by default, and if they're greater than 10MB, they will not be committed and uploaded. Take a look at the `.gitattributes` file in your repository for a complete list of tracked file extensions. For this tutorial, you can use the following sample `.csv` files since they're small: train.csv, test.csv.\n\n \n\n2. Drag and drop your dataset files and add a brief descriptive commit message.\n\n \n\n3. After uploading your dataset files, they are stored in your dataset repository.", "source_file": "datasets/upload_dataset.md", "section_heading": "Upload dataset", "char_start": 1049, "char_end": 2030, "token_estimate": 245, "prev_chunk_id": 618, "next_chunk_id": 620, "url": "https://huggingface.co/docs/datasets/upload_dataset", "doc_title": "Share a dataset to the Hub" }, { "chunk_id": 620, "text": "### Create a Dataset card\n\nAdding a Dataset card is super valuable for helping users find your dataset and understand how to use it responsibly.\n\n1. Click on **Create Dataset Card** to create a Dataset card. This button creates a `README.md` file in your repository.\n\n2. At the top, you'll see the **Metadata UI** with several fields to select from like license, language, and task categories. These are the most important tags for helping users discover your dataset on the Hub. When you select an option from each field, they'll be automatically added to the top of the dataset card.\n\n You can also look at the [Dataset Card specifications](https://github.com/huggingface/hub-docs/blob/main/datasetcard.md?plain=1), which has a complete set of (but not required) tag options like `annotations_creators`, to help you choose the appropriate tags.", "source_file": "datasets/upload_dataset.md", "section_heading": "Create a Dataset card", "char_start": 0, "char_end": 849, "token_estimate": 212, "prev_chunk_id": 619, "next_chunk_id": 621, "url": "https://huggingface.co/docs/datasets/upload_dataset", "doc_title": "Share a dataset to the Hub" }, { "chunk_id": 621, "text": "3. Click on the **Import dataset card template** link at the top of the editor to automatically create a dataset card template. Filling out the template is a great way to introduce your dataset to the community and help users understand how to use it. For a detailed example of what a good Dataset card should look like, take a look at the [CNN DailyMail Dataset card](https://huggingface.co/datasets/cnn_dailymail).", "source_file": "datasets/upload_dataset.md", "section_heading": "Create a Dataset card", "char_start": 2901, "char_end": 3317, "token_estimate": 104, "prev_chunk_id": 620, "next_chunk_id": 622, "url": "https://huggingface.co/docs/datasets/upload_dataset", "doc_title": "Share a dataset to the Hub" }, { "chunk_id": 622, "text": "### Load dataset\n\nOnce your dataset is stored on the Hub, anyone can load it with the [load_dataset()](/docs/datasets/v4.8.4/en/package_reference/loading_methods#datasets.load_dataset) function:\n\n```py\n>>> from datasets import load_dataset\n\n>>> dataset = load_dataset(\"stevhliu/demo\")\n```", "source_file": "datasets/upload_dataset.md", "section_heading": "Load dataset", "char_start": 3319, "char_end": 3607, "token_estimate": 72, "prev_chunk_id": 621, "next_chunk_id": 623, "url": "https://huggingface.co/docs/datasets/upload_dataset", "doc_title": "Share a dataset to the Hub" }, { "chunk_id": 623, "text": "## Upload with Python\n\nUsers who prefer to upload a dataset programmatically can use the [huggingface_hub](https://huggingface.co/docs/huggingface_hub/index) library. This library allows users to interact with the Hub from Python. \n\n1. Begin by installing the library:\n\n```bash\npip install huggingface_hub\n```\n\n2. To upload a dataset on the Hub in Python, you need to log in to your Hugging Face account:\n\n```bash\nhuggingface-cli login\n```\n\n3. Use the [`push_to_hub()`](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.DatasetDict.push_to_hub) function to help you add, commit, and push a file to your repository:\n\n```py\n>>> from datasets import load_dataset\n\n>>> dataset = load_dataset(\"stevhliu/demo\")", "source_file": "datasets/upload_dataset.md", "section_heading": "Upload with Python", "char_start": 3609, "char_end": 4348, "token_estimate": 184, "prev_chunk_id": 622, "next_chunk_id": 624, "url": "https://huggingface.co/docs/datasets/upload_dataset", "doc_title": "Share a dataset to the Hub" }, { "chunk_id": 624, "text": "# dataset = dataset.map(...) # do all your processing here\n>>> dataset.push_to_hub(\"stevhliu/processed_demo\")\n```\n\nTo set your dataset as private, set the `private` parameter to `True`. This parameter will only work if you are creating a repository for the first time.\n\n```py\n>>> dataset.push_to_hub(\"stevhliu/private_processed_demo\", private=True)\n```\n\nTo add a new configuration (or subset) to a dataset or to add a new split (train/validation/test), please refer to the [Dataset.push_to_hub()](/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.push_to_hub) documentation.", "source_file": "datasets/upload_dataset.md", "section_heading": "dataset = dataset.map(...) # do all your processing here", "char_start": 4349, "char_end": 4947, "token_estimate": 149, "prev_chunk_id": 623, "next_chunk_id": 625, "url": "https://huggingface.co/docs/datasets/upload_dataset", "doc_title": "Share a dataset to the Hub" }, { "chunk_id": 625, "text": "### Privacy\n\nA private dataset is only accessible by you. Similarly, if you share a dataset within your organization, then members of the organization can also access the dataset.\n\nLoad a private dataset by providing your authentication token to the `token` parameter:\n\n```py\n>>> from datasets import load_dataset", "source_file": "datasets/upload_dataset.md", "section_heading": "Privacy", "char_start": 4949, "char_end": 5262, "token_estimate": 78, "prev_chunk_id": 624, "next_chunk_id": 626, "url": "https://huggingface.co/docs/datasets/upload_dataset", "doc_title": "Share a dataset to the Hub" }, { "chunk_id": 626, "text": "# Load a private individual dataset\n>>> dataset = load_dataset(\"stevhliu/demo\", token=True)", "source_file": "datasets/upload_dataset.md", "section_heading": "Load a private individual dataset", "char_start": 5264, "char_end": 5355, "token_estimate": 22, "prev_chunk_id": 625, "next_chunk_id": 627, "url": "https://huggingface.co/docs/datasets/upload_dataset", "doc_title": "Share a dataset to the Hub" }, { "chunk_id": 627, "text": "# Load a private organization dataset\n>>> dataset = load_dataset(\"organization/dataset_name\", token=True)\n```", "source_file": "datasets/upload_dataset.md", "section_heading": "Load a private organization dataset", "char_start": 5357, "char_end": 5466, "token_estimate": 27, "prev_chunk_id": 626, "next_chunk_id": 628, "url": "https://huggingface.co/docs/datasets/upload_dataset", "doc_title": "Share a dataset to the Hub" }, { "chunk_id": 628, "text": "## What's next?\n\nCongratulations, you've completed the tutorials! \ud83e\udd73\n\nFrom here, you can go on to:\n\n- Learn more about how to use \ud83e\udd17 Datasets other functions to [process your dataset](process).\n- [Stream large datasets](stream) without downloading it locally.\n- [Define your dataset splits and configurations](repository_structure) and share your dataset with the community.\n\nIf you have any questions about \ud83e\udd17 Datasets, feel free to join and ask the community on our [forum](https://discuss.huggingface.co/c/datasets/10).", "source_file": "datasets/upload_dataset.md", "section_heading": "What's next?", "char_start": 5468, "char_end": 5987, "token_estimate": 129, "prev_chunk_id": 627, "next_chunk_id": null, "url": "https://huggingface.co/docs/datasets/upload_dataset", "doc_title": "Share a dataset to the Hub" } ]