skip to content

In TRL's SFTConfig, how do you switch on packing, which strategy does it use by default, and which attention implementation does it expect?

level: middleimportance: nice to knowfreq 9%

answer

  1. off unless asked
  2. max_length becomes the row length
  3. best-fit decreasing
  4. padding-free comes with it
  5. FlashAttention through model_init_kwargs

basics

~20 s

Set packing=True in SFTConfig; in TRL 1.14 it is off by default, packs to max_length (default 1024) and uses the 'bfd' strategy, which also turns on padding-free batching. Load the model with a FlashAttention implementation, or TRL only warns.

solid answer

~40 s

`SFTConfig(packing=True, max_length=...)` - packing is off by default in TRL 1.14, and once on, `max_length` (default 1024) is the packed row length. `packing_strategy` defaults to `"bfd"`, best-fit decreasing, which drops tokens past `max_length`; `"bfd_split"` splits long examples into chunks first, and `"wrapped"` concatenates everything and cuts fixed blocks mid-example. Both bfd strategies force `padding_free` on, so a batch is one flattened sequence with `position_ids` restarting per example, and only a FlashAttention implementation - `flash_attention_2`, `flash_attention_3` or a `kernels-community` Hub kernel set through `model_init_kwargs={"attn_implementation": ...}` - keeps examples apart. With anything else TRL logs a warning rather than failing. `eval_packing` follows `packing` unless set.

code

python · 16 lines
python
import torch
from trl import SFTConfig, SFTTrainer

args = SFTConfig(
    output_dir="runs/sft-packed",
    max_length=4096,                # length of each packed row
    packing=True,                   # off by default in TRL 1.14
    packing_strategy="bfd_split",   # split long examples instead of dropping their tails
    per_device_train_batch_size=2,
    model_init_kwargs={
        "attn_implementation": "kernels-community/flash-attn2",
        "dtype": torch.bfloat16,
    },
)
trainer = SFTTrainer(model="your-org/your-base-model", args=args, train_dataset=train_ds)
trainer.train()

go deeper

for a junior

Recall that packing is an SFTConfig flag, off by default, and that max_length sets the packed row size.

for a middle

Explain the three strategies, what bfd does to an over-long example, and why the bfd strategies switch padding-free batching on.

for a senior

Check the attention implementation before trusting a packed run, since a non-FlashAttention model only produces a warning, and pick bfd_split when long examples matter.

for a principal

Weigh packing's throughput gain against the setup it demands - specific attention kernels, collator limits - when standardising a team's SFT recipe across models.

## What the flags are **Packing** puts several short training examples into one fixed-length row so the GPU is not spending its time on padding. In TRL it is an `SFTConfig` setting for `SFTTrainer`; what packing does to learning, and the risk of examples leaking into each other, is method material owned elsewhere. Here the subject is the switches. | Flag | Default in TRL 1.14 | Role | |---|---|---| | `packing` | `False` | Turns packing on | | `max_length` | `1024` | Truncation length; with packing on, the length of each packed row | | `packing_strategy` | `"bfd"` | How examples are placed into rows | | `padding_free` | `False` | Flattens a batch into one sequence without padding; forced on by the bfd strategies | | `eval_packing` | `None` | Packs the eval set too; `None` copies `packing` | | `truncation_mode` | `"keep_start"` | The only supported mode; `"keep_end"` is deprecated | ## The three strategies | Strategy | Placement | Over-long examples | |---|---|---| | `"bfd"` | Best-fit decreasing bin packing | Tokens beyond `max_length` are dropped | | `"bfd_split"` | Best-fit decreasing | Split into chunks no longer than `max_length` first, so nothing is dropped | | `"wrapped"` | Concatenate everything, cut fixed blocks | Examples are cut mid-sequence | If every example is shorter than `max_length`, `"bfd"` and `"bfd_split"` behave identically. TRL's docs describe `"wrapped"` as minimising padding at the cost of breaking sequence continuity for much of the data. ## Why the attention implementation matters With `"bfd"` or `"bfd_split"`, the trainer turns `padding_free` on regardless of what you set. A batch then becomes one flattened sequence, and the collator emits `position_ids` that restart at 0 for each example, without an attention mask. Only attention kernels that read those boundaries keep the examples separate. TRL 1.14 treats these as supported: - `flash_attention_2` and `flash_attention_3` - the Hub kernels `kernels-community/flash-attn2`, `kernels-community/flash-attn3` and `kernels-community/vllm-flash-attn3` You choose one with `model_init_kwargs={"attn_implementation": ...}` when `SFTTrainer` loads the model from a string, or when you load the model yourself. With any other implementation, such as the default `sdpa`, TRL **logs a warning** that samples may cross-contaminate - it does not stop the run. That is why a packed run can look healthy and still be wrong. ## Errors and warnings around packing 1. **A custom `data_collator` with padding-free** raises `ValueError`; the trainer must use its own collator. 2. **`padding_free=True` without packing while `max_length` is set** raises `ValueError`, because `max_length` would not be enforced; enable packing, pre-truncate, or set `max_length=None`. 3. **`padding_free` with `"wrapped"`** logs a warning that the combination is not recommended. 4. **`padding_free` with `per_device_train_batch_size=1` and no packing** logs a warning that the setting gains nothing. ## Choosing max_length with packing on With packing, `max_length` stops being only a truncation limit and becomes the row size. Too small, and `"bfd"` throws away the tails of long examples; `"bfd_split"` keeps them as separate chunks instead. Too large, and memory per row grows. TRL's memory guide frames the trade-off the same way: a small value discards tokens, a large one risks running out of memory. ## When to leave packing off - **Vision-language data.** `SFTTrainer` raises `ValueError` when packing is requested for a dataset with images ("Packing is not supported for vision datasets"), and it rejects `padding_free=True` there too. - **A custom collator you cannot give up.** Padding-free mode refuses a user-supplied `data_collator`. - **No FlashAttention on the hardware.** Packing still runs, but only with the warning that examples may see each other; an honest choice is to leave `packing=False` and let ordinary padding do its job. - **Short, uniform examples.** When most rows already sit near the same length, padding wastes little and packing buys little. When packing stays off, `max_length` goes back to being a plain truncation limit, applied while the dataset is prepared; with packing on, the preparation step skips that truncation because packing already shapes rows to `max_length`. ## Interview-level summary - Packing is off by default; `packing=True` turns it on. - The default strategy is `"bfd"`, and it brings padding-free batching with it. - `max_length` is the packed row length. - Load the model with a FlashAttention implementation, or the trainer only warns while examples share attention.

  • Your dataset has a few very long examples. Which packing_strategy keeps all of their tokens?
    `"bfd_split"`. It splits any example longer than `max_length` into chunks before best-fit packing, so nothing is discarded. The default `"bfd"` drops the tokens past `max_length`. If every example already fits, the two behave identically.
  • You enable padding_free=True without packing and keep max_length=1024. What does SFTTrainer do?
    It raises `ValueError`: without packing, padding-free batching does not enforce `max_length`. TRL 1.14 asks you to enable packing (for example the `"bfd"` strategy), supply already truncated inputs, or set `max_length=None`.

  • SFTTrainer packs examples by default to save compute.
  • The default packing strategy concatenates everything and cuts fixed-size blocks.
  • TRL refuses to start a packed run without FlashAttention.
  • max_length stops mattering once packing is switched on.
  • You can pass any custom data collator to a padding-free packed run.

Assumes TRL 1.14 on Transformers v5: packing defaults to False and packing_strategy to 'bfd' in this TRL release.