#
Supervised Fine-tuning Trainer

Supervised fine-tuning (SFT) is the most common step in post-training foundation models, and also one of the most effective. In TRL, we provide a simple API to train models with SFT in a few lines of code; for a complete training script, check out `trl/scripts/sft.py`. Experimental support for Vision Language Models is also included in `examples/scripts/sft_vlm.py`.

##
Quickstart

If you have a dataset hosted on the 🤗 Hub, you can easily fine-tune your SFT model using SFTTrainer from TRL. Let us assume your dataset is `imdb`, the text you want to predict is inside the `text` field of the dataset, and you want to fine-tune the `facebook/opt-350m` model. The following code-snippet takes care of all the data pre-processing and training for you:

    from datasets import load_dataset
    from trl import SFTConfig, SFTTrainer

    dataset = load_dataset("stanfordnlp/imdb", split="train")

    training_args = SFTConfig(
        max_length=512,
        output_dir="/tmp",
    )
    trainer = SFTTrainer(
        "facebook/opt-350m",
        train_dataset=dataset,
        args=training_args,
    )
    trainer.train()

Make sure to pass the correct value for `max_length` as the default value will be set to `min(tokenizer.model_max_length, 1024)`.

You can also construct a model outside of the trainer and pass it as follows:

    from transformers import AutoModelForCausalLM
    from datasets import load_dataset
    from trl import SFTConfig, SFTTrainer

    dataset = load_dataset("stanfordnlp/imdb", split="train")

    model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")

    training_args = SFTConfig(output_dir="/tmp")

    trainer = SFTTrainer(
        model,
        train_dataset=dataset,
        args=training_args,
    )

    trainer.train()

The above snippets will use the default training arguments from the SFTConfig class. If you want to modify the defaults pass in your modification to the `SFTConfig` constructor and pass them to the trainer via the `args` argument.

##
Advanced usage

###
Train on completions only

To train on completions only, simply use a prompt-completion dataset. In this mode, loss is computed solely on the completion part.

If you’d like to compute loss on both the prompt and the completion while still using a prompt-completion dataset, set `completion_only_loss=False` in the SFTConfig. This is equivalent to converting the dataset to a language modeling format.

###
Add Special Tokens for Chat Format

Adding special tokens to a language model is crucial for training chat models. These tokens are added between the different roles in a conversation, such as the user, assistant, and system and help the model recognize the structure and flow of a conversation. This setup is essential for enabling the model to generate coherent and contextually appropriate responses in a chat environment. The `setup_chat_format()` function in `trl` easily sets up a model and tokenizer for conversational AI tasks. This function:

- Adds special tokens to the tokenizer, e.g. `<|im_start|>` and `<|im_end|>`, to indicate the start and end of a conversation.
- Resizes the model’s embedding layer to accommodate the new tokens.
- Sets the `chat_template` of the tokenizer, which is used to format the input data into a chat-like format. The default is `chatml` from OpenAI.
- optionally you can pass `resize_to_multiple_of` to resize the embedding layer to a multiple of the `resize_to_multiple_of` argument, e.g. 64. If you want to see more formats being supported in the future, please open a GitHub issue on trl

    from transformers import AutoModelForCausalLM, AutoTokenizer
    from trl import setup_chat_format

    # Load model and tokenizer
    model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
    tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")

    # Set up the chat format with default 'chatml' format
    model, tokenizer = setup_chat_format(model, tokenizer)

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 `setup_chat_format()`, 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`; for example, for `Qwen/Qwen2.5-1.5B` one should set `eos_token="<|im_end|>"`.

With our model and tokenizer set up, we can now fine-tune our model on a conversational dataset. Below is an example of how a dataset can be formatted for fine-tuning.

###
Dataset format support

The SFTTrainer supports popular dataset formats. This allows you to pass the dataset to the trainer without any pre-processing directly. The following formats are supported:

- conversational format

    {"messages": [{"role": "system", "content": "You are helpful"}, {"role": "user", "content": "What's the capital of France?"}, {"role": "assistant", "content": "..."}]}
    {"messages": [{"role": "system", "content": "You are helpful"}, {"role": "user", "content": "Who wrote 'Romeo and Juliet'?"}, {"role": "assistant", "content": "..."}]}
    {"messages": [{"role": "system", "content": "You are helpful"}, {"role": "user", "content": "How far is the Moon from Earth?"}, {"role": "assistant", "content": "..."}]}

- instruction format

    {"prompt": "<prompt text>", "completion": "<ideal generated text>"}
    {"prompt": "<prompt text>", "completion": "<ideal generated text>"}
    {"prompt": "<prompt text>", "completion": "<ideal generated text>"}

If your dataset uses one of the above formats, you can directly pass it to the trainer without pre-processing. The SFTTrainer will then format the dataset for you using the defined format from the model’s tokenizer with the apply_chat_template method.

    from datasets import load_dataset
    from trl import SFTConfig, SFTTrainer

    ...

    # load jsonl dataset
    dataset = load_dataset("json", data_files="path/to/dataset.jsonl", split="train")
    # load dataset from the HuggingFace Hub
    dataset = load_dataset("philschmid/dolly-15k-oai-style", split="train")

    ...

    training_args = SFTConfig(packing=True)
    trainer = SFTTrainer(
        "facebook/opt-350m",
        args=training_args,
        train_dataset=dataset,
    )

If the dataset is not in one of those format you can either preprocess the dataset to match the formatting or pass a formatting function to the SFTTrainer to do it for you. Let’s have a look.

###
Format your input prompts

For instruction fine-tuning, it is quite common to have two columns inside the dataset: one for the prompt & the other for the response. This allows people to format examples like Stanford-Alpaca did as follows:

    Below is an instruction ...

    ### Instruction
    {prompt}

    ### Response:
    {completion}

Let us assume your dataset has two fields, `question` and `answer`. Therefore you can just run:

    ...
    def formatting_prompts_func(example):
        return f"### Question: {example['question']}\n ### Answer: {example['answer']}"

    trainer = SFTTrainer(
        model,
        args=training_args,
        train_dataset=dataset,
        formatting_func=formatting_prompt_func,
    )

    trainer.train()

To properly format your input make sure to process all the examples by looping over them and returning a list of processed text. Check out a full example of how to use SFTTrainer on alpaca dataset here

###
Packing dataset

SFTTrainer supports example packing, where multiple short examples are packed in the same input sequence to increase training efficiency. To enable the usage of this dataset class, simply pass `packing=True` to the SFTConfig constructor.

    ...
    training_args = SFTConfig(packing=True)

    trainer = SFTTrainer(
        "facebook/opt-350m",
        train_dataset=dataset,
        args=training_args
    )

    trainer.train()

Note that if you use a packed dataset and if you pass `max_steps` in the training arguments you will probably train your models for more than few epochs, depending on the way you have configured the packed dataset and the training protocol. Double check that you know and understand what you are doing. If you don’t want to pack your `eval_dataset`, you can pass `eval_packing=False` to the `SFTConfig` init method.

####
Customize your prompts using packed dataset

If your dataset has several fields that you want to combine, for example if the dataset has `question` and `answer` fields and you want to combine them, you can pass a formatting function to the trainer that will take care of that. For example:

    def formatting_func(example):
        text = f"### Question: {example['question']}\n ### Answer: {example['answer']}"
        return text

    training_args = SFTConfig(packing=True)
    trainer = SFTTrainer(
        "facebook/opt-350m",
        train_dataset=dataset,
        args=training_args,
        formatting_func=formatting_func
    )

    trainer.train()

###
Control over the pretrained model

You can directly pass the kwargs of the `from_pretrained()` method to the SFTConfig. For example, if you want to load a model in a different precision, analogous to

    model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m", torch_dtype=torch.bfloat16)

    ...

    training_args = SFTConfig(
        model_init_kwargs={
            "torch_dtype": "bfloat16",
        },
        output_dir="/tmp",
    )
    trainer = SFTTrainer(
        "facebook/opt-350m",
        train_dataset=dataset,
        args=training_args,
    )

    trainer.train()

Note that all keyword arguments of `from_pretrained()` are supported.

###
Training adapters

We also support tight integration with 🤗 PEFT library so that any user can conveniently train adapters and share them on the Hub instead of training the entire model.

    from datasets import load_dataset
    from trl import SFTConfig, SFTTrainer
    from peft import LoraConfig

    dataset = load_dataset("trl-lib/Capybara", split="train")

    peft_config = LoraConfig(
        r=16,
        lora_alpha=32,
        lora_dropout=0.05,
        target_modules="all-linear",
        modules_to_save=["lm_head", "embed_token"],
        task_type="CAUSAL_LM",
    )

    trainer = SFTTrainer(
        "Qwen/Qwen2.5-0.5B",
        train_dataset=dataset,
        args=SFTConfig(output_dir="Qwen2.5-0.5B-SFT"),
        peft_config=peft_config
    )

    trainer.train()

If the chat template contains special tokens like `<|im_start|>` (ChatML) or `<|eot_id|>` (Llama), the embedding layer and LM head must be included in the trainable parameters via the `modules_to_save` argument. Without this, the fine-tuned model will produce unbounded or nonsense generations. If the chat template doesn’t contain special tokens (e.g. Alpaca), then the `modules_to_save` argument can be ignored or set to `None`.

You can also continue training your `PeftModel`. For that, first load a `PeftModel` outside `SFTTrainer` and pass it directly to the trainer without the `peft_config` argument being passed.

###
Training adapters with base 8 bit models

For that, you need to first load your 8 bit model outside the Trainer and pass a `PeftConfig` to the trainer. For example:

    ...

    peft_config = LoraConfig(
        r=16,
        lora_alpha=32,
        lora_dropout=0.05,
        bias="none",
        task_type="CAUSAL_LM",
    )

    model = AutoModelForCausalLM.from_pretrained(
        "EleutherAI/gpt-neo-125m",
        load_in_8bit=True,
        device_map="auto",
    )

    trainer = SFTTrainer(
        model,
        train_dataset=dataset,
        args=SFTConfig(),
        peft_config=peft_config,
    )

    trainer.train()

##
Using Flash Attention and Flash Attention 2

You can benefit from Flash Attention 1 & 2 using SFTTrainer out of the box with minimal changes of code. First, to make sure you have all the latest features from transformers, install transformers from source

    pip install -U git+https://github.com/huggingface/transformers.git

Note that Flash Attention only works on GPU now and under half-precision regime (when using adapters, base model loaded in half-precision) Note also both features are perfectly compatible with other tools such as quantization.

###
Using Flash-Attention 1

For Flash Attention 1 you can use the `BetterTransformer` API and force-dispatch the API to use Flash Attention kernel. First, install the latest optimum package:

    pip install -U optimum

Once you have loaded your model, wrap the `trainer.train()` call under the `with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False):` context manager:

    ...

    + with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False):
        trainer.train()

Note that you cannot train your model using Flash Attention 1 on an arbitrary dataset as `torch.scaled_dot_product_attention` does not support training with padding tokens if you use Flash Attention kernels. Therefore you can only use that feature with `packing=True`. If your dataset contains padding tokens, consider switching to Flash Attention 2 integration.

Below are some numbers you can get in terms of speedup and memory efficiency, using Flash Attention 1, on a single NVIDIA-T4 16GB.

use_flash_attn_1 | model_name | max_seq_len | batch_size | time per training step
--- | --- | --- | --- | ---
✓ | facebook/opt-350m | 2048 | 8 | ~59.1s
| facebook/opt-350m | 2048 | 8 | OOM
✓ | facebook/opt-350m | 2048 | 4 | ~30.3s
| facebook/opt-350m | 2048 | 4 | ~148.9s

###
Using Flash Attention-2

To use Flash Attention 2, first install the latest `flash-attn` package:

    pip install -U flash-attn

And add `attn_implementation="flash_attention_2"` when calling `from_pretrained`:

    model = AutoModelForCausalLM.from_pretrained(
        model_id,
        load_in_4bit=True,
        attn_implementation="flash_attention_2"
    )

If you don’t use quantization, make sure your model is loaded in half-precision and dispatch your model on a supported GPU device. After loading your model, you can either train it as it is, or attach adapters and train adapters on it in case your model is quantized.

In contrast to Flash Attention 1, the integration makes it possible to train your model on an arbitrary dataset that also includes padding tokens.

###
Using model creation utility

We included a utility function to create your model.

###
class trl.ModelConfig

< source >

( model_name_or_path: typing.Optional[str] = None model_revision: str = 'main' torch_dtype: typing.Optional[str] = None trust_remote_code: bool = False attn_implementation: typing.Optional[str] = None use_peft: bool = False lora_r: int = 16 lora_alpha: int = 32 lora_dropout: float = 0.05 lora_target_modules: typing.Optional[list[str]] = None lora_modules_to_save: typing.Optional[list[str]] = None lora_task_type: str = 'CAUSAL_LM' use_rslora: bool = False use_dora: bool = False load_in_8bit: bool = False load_in_4bit: bool = False bnb_4bit_quant_type: str = 'nf4' use_bnb_nested_quant: bool = False )

Parameters

- model_name_or_path (`str` or `None`, optional, defaults to `None`) — Model checkpoint for weights initialization.
- model_revision (`str`, optional, defaults to `"main"`) — Specific model version to use. It can be a branch name, a tag name, or a commit id.
- torch_dtype (`Literal["auto", "bfloat16", "float16", "float32"]` or `None`, optional, defaults to `None`) — Override the default `torch.dtype` and load the model under this dtype. Possible values are
  - `"bfloat16"`: `torch.bfloat16`
  - `"float16"`: `torch.float16`
  - `"float32"`: `torch.float32`
  - `"auto"`: Automatically derive the dtype from the model’s weights.
- trust_remote_code (`bool`, optional, defaults to `False`) — Whether to allow for custom models defined on the Hub in their own modeling files. This option should only be set to `True` for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine.
- attn_implementation (`str` or `None`, optional, defaults to `None`) — Which attention implementation to use. You can run `--attn_implementation=flash_attention_2`, in which case you must install this manually by running `pip install flash-attn --no-build-isolation`.
- use_peft (`bool`, optional, defaults to `False`) — Whether to use PEFT for training.
- lora_r (`int`, optional, defaults to `16`) — LoRA R value.
- lora_alpha (`int`, optional, defaults to `32`) — LoRA alpha.
- lora_dropout (`float`, optional, defaults to `0.05`) — LoRA dropout.
- lora_target_modules (`Union[str, list[str]]` or `None`, optional, defaults to `None`) — LoRA target modules.
- lora_modules_to_save (`list[str]` or `None`, optional, defaults to `None`) — Model layers to unfreeze & train.
- lora_task_type (`str`, optional, defaults to `"CAUSAL_LM"`) — Task type to pass for LoRA (use `"SEQ_CLS"` for reward modeling).
- use_rslora (`bool`, optional, defaults to `False`) — Whether to use Rank-Stabilized LoRA, which sets the adapter scaling factor to `lora_alpha/√r`, instead of the original default value of `lora_alpha/r`.
- use_dora (`bool`, optional, defaults to `False`) — Enable Weight-Decomposed Low-Rank Adaptation (DoRA). This technique decomposes the updates of the weights into two parts, magnitude and direction. Direction is handled by normal LoRA, whereas the magnitude is handled by a separate learnable parameter. This can improve the performance of LoRA, especially at low ranks. Right now, DoRA only supports linear and Conv2D layers. DoRA introduces a bigger overhead than pure LoRA, so it is recommended to merge weights for inference.
- load_in_8bit (`bool`, optional, defaults to `False`) — Whether to use 8 bit precision for the base model. Works only with LoRA.
- load_in_4bit (`bool`, optional, defaults to `False`) — Whether to use 4 bit precision for the base model. Works only with LoRA.
- bnb_4bit_quant_type (`str`, optional, defaults to `"nf4"`) — Quantization type (`"fp4"` or `"nf4"`).
- use_bnb_nested_quant (`bool`, optional, defaults to `False`) — Whether to use nested quantization.

Configuration class for the models.

Using HfArgumentParser we can turn this class into argparse arguments that can be specified on the command line.

    from trl import ModelConfig, SFTTrainer, get_kbit_device_map, get_peft_config, get_quantization_config
    model_args = ModelConfig(
        model_name_or_path="facebook/opt-350m"
        attn_implementation=None, # or "flash_attention_2"
    )
    torch_dtype = (
        model_args.torch_dtype
        if model_args.torch_dtype in ["auto", None]
        else getattr(torch, model_args.torch_dtype)
    )
    quantization_config = get_quantization_config(model_args)
    model_kwargs = dict(
        revision=model_args.model_revision,
        trust_remote_code=model_args.trust_remote_code,
        attn_implementation=model_args.attn_implementation,
        torch_dtype=torch_dtype,
        use_cache=False if training_args.gradient_checkpointing else True,
        device_map=get_kbit_device_map() if quantization_config is not None else None,
        quantization_config=quantization_config,
    )
    model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs)
    trainer = SFTTrainer(
        ...,
        model=model_args.model_name_or_path,
        peft_config=get_peft_config(model_args),
    )

###
Enhance the model’s performances using NEFTune

NEFTune is a technique to boost the performance of chat models and was introduced by the paper “NEFTune: Noisy Embeddings Improve Instruction Finetuning” from Jain et al. it consists of adding noise to the embedding vectors during training. According to the abstract of the paper:

> Standard finetuning of LLaMA-2-7B using Alpaca achieves 29.79% on AlpacaEval, which rises to 64.69% using noisy embeddings. NEFTune also improves over strong baselines on modern instruction datasets. Models trained with Evol-Instruct see a 10% improvement, with ShareGPT an 8% improvement, and with OpenPlatypus an 8% improvement. Even powerful models further refined with RLHF such as LLaMA-2-Chat benefit from additional training with NEFTune.

To use it in `SFTTrainer` simply pass `neftune_noise_alpha` when creating your `SFTConfig` instance. Note that to avoid any surprising behaviour, NEFTune is disabled after training to retrieve back the original behaviour of the embedding layer.

    from datasets import load_dataset
    from trl import SFTConfig, SFTTrainer

    dataset = load_dataset("stanfordnlp/imdb", split="train")

    training_args = SFTConfig(
        neftune_noise_alpha=5,
    )
    trainer = SFTTrainer(
        "facebook/opt-350m",
        train_dataset=dataset,
        args=training_args,
    )
    trainer.train()

We have tested NEFTune by training `mistralai/Mistral-7B-v0.1` on the OpenAssistant dataset and validated that using NEFTune led to a performance boost of ~25% on MT Bench.

Note however, that the amount of performance gain is dataset dependent and in particular, applying NEFTune on synthetic datasets like UltraChat typically produces smaller gains.

###
Accelerate fine-tuning 2x using unsloth

You can further accelerate QLoRA / LoRA (2x faster, 60% less memory) using the `unsloth` library that is fully compatible with `SFTTrainer`. Currently `unsloth` supports only Llama (Yi, TinyLlama, Qwen, Deepseek etc) and Mistral architectures. Some benchmarks on 1x A100 listed below:

1 A100 40GB | Dataset | 🤗 | 🤗 + Flash Attention 2 | 🦥 Unsloth | 🦥 VRAM saved
--- | --- | --- | --- | --- | ---
Code Llama 34b | Slim Orca | 1x | 1.01x | 1.94x | -22.7%
Llama-2 7b | Slim Orca | 1x | 0.96x | 1.87x | -39.3%
Mistral 7b | Slim Orca | 1x | 1.17x | 1.88x | -65.9%
Tiny Llama 1.1b | Alpaca | 1x | 1.55x | 2.74x | -57.8%

First install `unsloth` according to the official documentation. Once installed, you can incorporate unsloth into your workflow in a very simple manner; instead of loading `AutoModelForCausalLM`, you just need to load a `FastLanguageModel` as follows:

    import torch
    from trl import SFTConfig, SFTTrainer
    from unsloth import FastLanguageModel

    max_length = 2048 # Supports automatic RoPE Scaling, so choose any number

    # Load model
    model, tokenizer = FastLanguageModel.from_pretrained(
        model_name="unsloth/mistral-7b",
        max_seq_length=max_length,
        dtype=None,  # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
        load_in_4bit=True,  # Use 4bit quantization to reduce memory usage. Can be False
        # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf
    )

    # Do model patching and add fast LoRA weights
    model = FastLanguageModel.get_peft_model(
        model,
        r=16,
        target_modules=[
            "q_proj",
            "k_proj",
            "v_proj",
            "o_proj",
            "gate_proj",
            "up_proj",
            "down_proj",
        ],
        lora_alpha=16,
        lora_dropout=0,  # Dropout = 0 is currently optimized
        bias="none",  # Bias = "none" is currently optimized
        use_gradient_checkpointing=True,
        random_state=3407,
    )

    training_args = SFTConfig(output_dir="./output", max_length=max_length)

    trainer = SFTTrainer(
        model=model,
        args=training_args,
        train_dataset=dataset,
    )
    trainer.train()

The saved model is fully compatible with Hugging Face’s transformers library. Learn more about unsloth in their official repository.

##
Liger-Kernel: Increase 20% throughput and reduces 60% memory for multi-GPU training

Liger Kernel is a collection of Triton kernels designed specifically for LLM training. It can effectively increase multi-GPU training throughput by 20% and reduces memory usage by 60%. That way, we can 4x our context length, as described in the benchmark below. They have implemented Hugging Face Compatible `RMSNorm`, `RoPE`, `SwiGLU`, `CrossEntropy`, `FusedLinearCrossEntropy`, and more to come. The kernel works out of the box with Flash Attention, PyTorch FSDP, and Microsoft DeepSpeed.

With great memory reduction, you can potentially turn off cpu_offloading or gradient checkpointing to further boost the performance.

Speed Up | Memory Reduction
--- | ---

1. To use Liger-Kernel in SFTTrainer, first install by

    pip install liger-kernel

2. Once installed, set `use_liger_kernel` in SFTConfig. No other changes are needed!

    training_args = SFTConfig(
      use_liger_kernel=True
    )

To learn more about Liger-Kernel, visit their official repository.

##
Best practices

Pay attention to the following best practices when training a model with that trainer:

- SFTTrainer always truncates by default the sequences to the `max_length` argument of the SFTConfig. If none is passed, the trainer will retrieve that value from the tokenizer. Some tokenizers do not provide a default value, so there is a check to retrieve the minimum between 1024 and that value. Make sure to check it before training.
- For training adapters in 8bit, you might need to tweak the arguments of the `prepare_model_for_kbit_training` method from PEFT, hence we advise users to use `prepare_in_int8_kwargs` field, or create the `PeftModel` outside the SFTTrainer and pass it.
- For a more memory-efficient training using adapters, you can load the base model in 8bit, for that simply add `load_in_8bit` argument when creating the SFTTrainer, or create a base model in 8bit outside the trainer and pass it.
- If you create a model outside the trainer, make sure to not pass to the trainer any additional keyword arguments that are relative to `from_pretrained()` method.

##
Multi-GPU Training

Trainer (and thus SFTTrainer) supports multi-GPU training. If you run your script with `python script.py` it will default to using DP as the strategy, which may be slower than expected. To use DDP (which is generally recommended, see here for more info) you must launch the script with `python -m torch.distributed.launch script.py` or `accelerate launch script.py`. For DDP to work you must also check the following:

- If you’re using gradient_checkpointing, add the following to the TrainingArguments: `gradient_checkpointing_kwargs={'use_reentrant':False}` (more info here
- Ensure that the model is placed on the correct device:

    from accelerate import PartialState
    device_string = PartialState().process_index
    model = AutoModelForCausalLM.from_pretrained(
         ...
        device_map={'':device_string}
    )

##
GPTQ Conversion

You may experience some issues with GPTQ Quantization after completing training. Lowering `gradient_accumulation_steps` to `4` will resolve most issues during the quantization process to GPTQ format.

##
Extending SFTTrainer for Vision Language Models

`SFTTrainer` does not inherently support vision-language data. However, we provide a guide on how to tweak the trainer to support vision-language data. Specifically, you need to use a custom data collator that is compatible with vision-language data. This guide outlines the steps to make these adjustments. For a concrete example, refer to the script `examples/scripts/sft_vlm.py` which demonstrates how to fine-tune the LLaVA 1.5 model on the HuggingFaceH4/llava-instruct-mix-vsft dataset.

###
Preparing the Data

The data format is flexible, provided it is compatible with the custom collator that we will define later. A common approach is to use conversational data. Given that the data includes both text and images, the format needs to be adjusted accordingly. Below is an example of a conversational data format involving both text and images:

    images = ["obama.png"]
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Who is this?"},
                {"type": "image"}
            ]
        },
        {
            "role": "assistant",
            "content": [
                {"type": "text", "text": "Barack Obama"}
            ]
        },
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What is he famous for?"}
            ]
        },
        {
            "role": "assistant",
            "content": [
                {"type": "text", "text": "He is the 44th President of the United States."}
            ]
        }
    ]

To illustrate how this data format will be processed using the LLaVA model, you can use the following code:

    from transformers import AutoProcessor

    processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
    print(processor.apply_chat_template(messages, tokenize=False))

The output will be formatted as follows:

    Who is this? ASSISTANT: Barack Obama USER: What is he famous for? ASSISTANT: He is the 44th President of the United States.

###
A custom collator for processing multi-modal data

Unlike the default behavior of `SFTTrainer`, processing multi-modal data is done on the fly during the data collation process. To do this, you need to define a custom collator that processes both the text and images. This collator must take a list of examples as input (see the previous section for an example of the data format) and return a batch of processed data. Below is an example of such a collator:

    def collate_fn(examples):
        # Get the texts and images, and apply the chat template
        texts = [processor.apply_chat_template(example["messages"], tokenize=False) for example in examples]
        images = [example["images"][0] for example in examples]

        # Tokenize the texts and process the images
        batch = processor(texts, images, return_tensors="pt", padding=True)

        # The labels are the input_ids, and we mask the padding tokens in the loss computation
        labels = batch["input_ids"].clone()
        labels[labels == processor.tokenizer.pad_token_id] = -100
        batch["labels"] = labels

        return batch

We can verify that the collator works as expected by running the following code:

    from datasets import load_dataset

    dataset = load_dataset("HuggingFaceH4/llava-instruct-mix-vsft", split="train")
    examples = [dataset[0], dataset[1]]  # Just two examples for the sake of the example
    collated_data = collate_fn(examples)
    print(collated_data.keys())  # dict_keys(['input_ids', 'attention_mask', 'pixel_values', 'labels'])

###
Training the vision-language model

Now that we have prepared the data and defined the collator, we can proceed with training the model. To ensure that the data is not processed as text-only, we need to set a couple of arguments in the `SFTConfig`, specifically `remove_unused_columns` and `skip_prepare_dataset` to `True` to avoid the default processing of the dataset. Below is an example of how to set up the `SFTTrainer`.

    training_args.remove_unused_columns = False
    training_args.dataset_kwargs = {"skip_prepare_dataset": True}

    trainer = SFTTrainer(
        model=model,
        args=training_args,
        data_collator=collate_fn,
        train_dataset=train_dataset,
        processing_class=processor.tokenizer,
    )

A full example of training LLaVa 1.5 on the HuggingFaceH4/llava-instruct-mix-vsft dataset can be found in the script `examples/scripts/sft_vlm.py`.

- Experiment tracking
- Trained model

##
SFTTrainer

###
class trl.SFTTrainer

< source >

( model: typing.Union[str, torch.nn.modules.module.Module, transformers.modeling_utils.PreTrainedModel] args: typing.Union[trl.trainer.sft_config.SFTConfig, transformers.training_args.TrainingArguments, NoneType] = None data_collator: typing.Optional[transformers.data.data_collator.DataCollator] = None train_dataset: typing.Union[datasets.arrow_dataset.Dataset, datasets.iterable_dataset.IterableDataset, NoneType] = None eval_dataset: typing.Union[datasets.arrow_dataset.Dataset, dict[str, datasets.arrow_dataset.Dataset], NoneType] = None processing_class: typing.Union[transformers.tokenization_utils_base.PreTrainedTokenizerBase, transformers.image_processing_utils.BaseImageProcessor, transformers.feature_extraction_utils.FeatureExtractionMixin, transformers.processing_utils.ProcessorMixin, NoneType] = None compute_loss_func: typing.Optional[typing.Callable] = None compute_metrics: typing.Optional[typing.Callable[[transformers.trainer_utils.EvalPrediction], dict]] = None callbacks: typing.Optional[list[transformers.trainer_callback.TrainerCallback]] = None optimizers: tuple = (None, None) optimizer_cls_and_kwargs: typing.Optional[tuple[type[torch.optim.optimizer.Optimizer], dict[str, typing.Any]]] = None preprocess_logits_for_metrics: typing.Optional[typing.Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None peft_config: typing.Optional[ForwardRef('PeftConfig')] = None formatting_func: typing.Union[typing.Callable[[dict], str], typing.Callable[[dict], list[str]], NoneType] = None )

Parameters

- model (`Union[str, PreTrainedModel]`) — 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, e.g., `'./my_model_directory/'`. The model is loaded using from_pretrained with the keywork arguments in `args.model_init_kwargs`.
  - A PreTrainedModel object. Only causal language models are supported.
- args (SFTConfig, optional, defaults to `None`) — Configuration for this trainer. If `None`, a default configuration is used.
- data_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 default_data_collator if no `processing_class` is provided, an instance of DataCollatorWithPadding otherwise if the processing_class is a feature extractor or tokenizer.
- train_dataset (Dataset or IterableDataset) — Dataset to use for training. SFT supports both language modeling type and prompt-completion type. The format of the samples can be either:
  - Standard: Each sample contains plain text.
  - 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.

- eval_dataset (Dataset, IterableDataset or `dict[str, Union[Dataset, IterableDataset]]`) — Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
- processing_class (PreTrainedTokenizerBase, optional, defaults to `None`) — Processing class used to process the data. If `None`, the processing class is loaded from the model’s name with from_pretrained.
- callbacks (list of TrainerCallback, optional, defaults to `None`) — List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed in here.

  If you want to remove one of the default callbacks used, use the remove_callback method.

- optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, 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` controlled by `args`.
- optimizer_cls_and_kwargs (`Tuple[Type[torch.optim.Optimizer], Dict[str, Any]]`, optional, defaults to `None`) — 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.

- preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, optional, defaults to `None`) — 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.

- peft_config (`~peft.PeftConfig`, optional, defaults to `None`) — PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
- formatting_func (`Optional[Callable]`) — Formatting function applied to the dataset before tokenization. Applying the formatting function explicitly converts the dataset into a language modeling type.

Trainer for Supervised Fine-Tuning (SFT) method.

This class is a wrapper around the transformers.Trainer class and inherits all of its attributes and methods.

Example:

    from datasets import load_dataset
    from trl import SFTTrainer

    dataset = load_dataset("roneneldan/TinyStories", split="train[:1%]")

    trainer = SFTTrainer(model="Qwen/Qwen2-0.5B-Instruct", train_dataset=dataset)
    trainer.train()

####
compute_loss

< source >

( model inputs return_outputs = False num_items_in_batch = None )

Compute training loss and additionally compute token accuracies

####
create_model_card

< source >

( model_name: typing.Optional[str] = None dataset_name: typing.Optional[str] = None tags: typing.Union[str, list[str], NoneType] = None )

Parameters

- model_name (`str` or `None`, optional, defaults to `None`) — Name of the model.
- dataset_name (`str` or `None`, optional, defaults to `None`) — Name of the dataset used for training.
- tags (`str`, `list[str]` or `None`, optional, defaults to `None`) — Tags to be associated with the model card.

Creates a draft of a model card using the information available to the `Trainer`.

##
SFTConfig

###
class trl.SFTConfig

< source >

( output_dir: typing.Optional[str] = None overwrite_output_dir: bool = False do_train: bool = False do_eval: bool = False do_predict: bool = False eval_strategy: typing.Union[transformers.trainer_utils.IntervalStrategy, str] = 'no' prediction_loss_only: bool = False per_device_train_batch_size: int = 8 per_device_eval_batch_size: int = 8 per_gpu_train_batch_size: typing.Optional[int] = None per_gpu_eval_batch_size: typing.Optional[int] = None gradient_accumulation_steps: int = 1 eval_accumulation_steps: typing.Optional[int] = None eval_delay: typing.Optional[float] = 0 torch_empty_cache_steps: typing.Optional[int] = None learning_rate: float = 2e-05 weight_decay: float = 0.0 adam_beta1: float = 0.9 adam_beta2: float = 0.999 adam_epsilon: float = 1e-08 max_grad_norm: float = 1.0 num_train_epochs: float = 3.0 max_steps: int = -1 lr_scheduler_type: typing.Union[transformers.trainer_utils.SchedulerType, str] = 'linear' lr_scheduler_kwargs: typing.Union[dict, str, NoneType] = <factory> warmup_ratio: float = 0.0 warmup_steps: int = 0 log_level: typing.Optional[str] = 'passive' log_level_replica: typing.Optional[str] = 'warning' log_on_each_node: bool = True logging_dir: typing.Optional[str] = None logging_strategy: typing.Union[transformers.trainer_utils.IntervalStrategy, str] = 'steps' logging_first_step: bool = False logging_steps: float = 500 logging_nan_inf_filter: bool = True save_strategy: typing.Union[transformers.trainer_utils.SaveStrategy, str] = 'steps' save_steps: float = 500 save_total_limit: typing.Optional[int] = None save_safetensors: typing.Optional[bool] = True save_on_each_node: bool = False save_only_model: bool = False restore_callback_states_from_checkpoint: bool = False no_cuda: bool = False use_cpu: bool = False use_mps_device: bool = False seed: int = 42 data_seed: typing.Optional[int] = None jit_mode_eval: bool = False use_ipex: bool = False bf16: bool = False fp16: bool = False fp16_opt_level: str = 'O1' half_precision_backend: str = 'auto' bf16_full_eval: bool = False fp16_full_eval: bool = False tf32: typing.Optional[bool] = None local_rank: int = -1 ddp_backend: typing.Optional[str] = None tpu_num_cores: typing.Optional[int] = None tpu_metrics_debug: bool = False debug: typing.Union[str, list[transformers.debug_utils.DebugOption]] = '' dataloader_drop_last: bool = False eval_steps: typing.Optional[float] = None dataloader_num_workers: int = 0 dataloader_prefetch_factor: typing.Optional[int] = None past_index: int = -1 run_name: typing.Optional[str] = None disable_tqdm: typing.Optional[bool] = None remove_unused_columns: typing.Optional[bool] = True label_names: typing.Optional[list[str]] = None load_best_model_at_end: typing.Optional[bool] = False metric_for_best_model: typing.Optional[str] = None greater_is_better: typing.Optional[bool] = None ignore_data_skip: bool = False fsdp: typing.Union[list[transformers.trainer_utils.FSDPOption], str, NoneType] = '' fsdp_min_num_params: int = 0 fsdp_config: typing.Union[dict, str, NoneType] = None fsdp_transformer_layer_cls_to_wrap: typing.Optional[str] = None accelerator_config: typing.Union[dict, str, NoneType] = None deepspeed: typing.Union[dict, str, NoneType] = None label_smoothing_factor: float = 0.0 optim: typing.Union[transformers.training_args.OptimizerNames, str] = 'adamw_torch' optim_args: typing.Optional[str] = None adafactor: bool = False group_by_length: bool = False length_column_name: typing.Optional[str] = 'length' report_to: typing.Union[NoneType, str, list[str]] = None ddp_find_unused_parameters: typing.Optional[bool] = None ddp_bucket_cap_mb: typing.Optional[int] = None ddp_broadcast_buffers: typing.Optional[bool] = None dataloader_pin_memory: bool = True dataloader_persistent_workers: bool = False skip_memory_metrics: bool = True use_legacy_prediction_loop: bool = False push_to_hub: bool = False resume_from_checkpoint: typing.Optional[str] = None hub_model_id: typing.Optional[str] = None hub_strategy: typing.Union[transformers.trainer_utils.HubStrategy, str] = 'every_save' hub_token: typing.Optional[str] = None hub_private_repo: typing.Optional[bool] = None hub_always_push: bool = False gradient_checkpointing: bool = False gradient_checkpointing_kwargs: typing.Union[dict, str, NoneType] = None include_inputs_for_metrics: bool = False include_for_metrics: list = <factory> eval_do_concat_batches: bool = True fp16_backend: str = 'auto' push_to_hub_model_id: typing.Optional[str] = None push_to_hub_organization: typing.Optional[str] = None push_to_hub_token: typing.Optional[str] = None mp_parameters: str = '' auto_find_batch_size: bool = False full_determinism: bool = False torchdynamo: typing.Optional[str] = None ray_scope: typing.Optional[str] = 'last' ddp_timeout: typing.Optional[int] = 1800 torch_compile: bool = False torch_compile_backend: typing.Optional[str] = None torch_compile_mode: typing.Optional[str] = None include_tokens_per_second: typing.Optional[bool] = False include_num_input_tokens_seen: typing.Optional[bool] = False neftune_noise_alpha: typing.Optional[float] = None optim_target_modules: typing.Union[NoneType, str, list[str]] = None batch_eval_metrics: bool = False eval_on_start: bool = False use_liger_kernel: typing.Optional[bool] = False eval_use_gather_object: typing.Optional[bool] = False average_tokens_across_devices: typing.Optional[bool] = False model_init_kwargs: typing.Optional[dict[str, typing.Any]] = None dataset_text_field: str = 'text' dataset_kwargs: typing.Optional[dict[str, typing.Any]] = None dataset_num_proc: typing.Optional[int] = None eos_token: typing.Optional[str] = None pad_token: typing.Optional[str] = None max_length: typing.Optional[int] = 1024 packing: bool = False padding_free: bool = False pad_to_multiple_of: typing.Optional[int] = None eval_packing: typing.Optional[bool] = None completion_only_loss: typing.Optional[bool] = None max_seq_length: typing.Optional[int] = None )

Parameters that control the model

- model_init_kwargs (`dict[str, Any]` or `None`, optional, defaults to `None`) — Keyword arguments for from_pretrained, used when the `model` argument of the SFTTrainer is provided as a string.

Parameters that control the data preprocessing

- dataset_text_field (`str`, optional, defaults to `"text"`) — Name of the column that contains text data in the dataset.
- dataset_kwargs (`dict[str, Any]` or `None`, optional, defaults to `None`) — Dictionary of optional keyword arguments for the dataset preparation. The only supported key is `skip_prepare_dataset`.
- dataset_num_proc (`int` or `None`, optional, defaults to `None`) — Number of processes to use for processing the dataset.
- eos_token (`str` or `None`, optional, defaults to `None`) — Token used to indicate the end of a turn or sequence. If `None`, it defaults to `processing_class.eos_token`.
- pad_token (`int` or `None`, optional, defaults to `None`) — Token used for padding. If `None`, it defaults to `processing_class.pad_token`, or if that is also `None`, it falls back to `processing_class.eos_token`.
- max_length (`int` or `None`, optional, defaults to `1024`) — Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from the right. If `None`, no truncation is applied. When packing is enabled, this value sets the sequence length.
- packing (`bool`, optional, defaults to `False`) — Whether to pack multiple sequences into a fixed-length format. Uses `max_length` to define sequence length.
- padding_free (`bool`, optional, defaults to `False`) — Whether to perform forward passes without padding by flattening all sequences in the batch into a single continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this is only supported with the `flash_attention_2` attention implementation, which can efficiently handle the flattened batch structure.
- pad_to_multiple_of (`int` or `None`, optional, defaults to `None`) — If set, the sequences will be padded to a multiple of this value.
- eval_packing (`bool` or `None`, optional, defaults to `None`) — Whether to pack the eval dataset. If `None`, uses the same value as `packing`.

Parameters that control the training

- learning_rate (`float`, optional, defaults to `2e-5`) — Initial learning rate for `AdamW` optimizer. The default value replaces that of TrainingArguments.
- completion_only_loss (`bool` or `None`, optional, defaults to `None`) — Whether to compute loss only on the completion part of the sequence. If set to `True`, loss is computed only on the completion, which is supported only for prompt-completion datasets. If `False`, loss is computed on the entire sequence. If `None` (default), the behavior depends on the dataset: loss is computed on the completion for prompt-completion datasets, and on the full sequence for language modeling datasets.

Configuration class for the SFTTrainer.

Only the parameters specific to SFT training are listed here. For details on other parameters, refer to the TrainingArguments documentation.

Using HfArgumentParser we can turn this class into argparse arguments that can be specified on the command line.

##
Datasets

In the SFTTrainer we smartly support `datasets.IterableDataset` in addition to other style datasets. This is useful if you are using large corpora that you do not want to save all to disk. The data will be tokenized and processed on the fly, even when packing is enabled.

Additionally, in the SFTTrainer, we support pre-tokenized datasets if they are `datasets.Dataset` or `datasets.IterableDataset`. In other words, if such a dataset has a column of `input_ids`, no further processing (tokenization or packing) will be done, and the dataset will be used as-is. This can be useful if you have pretokenized your dataset outside of this script and want to re-use it directly.

< > Update on GitHub