max_length causing training loss issues not found in v0.19.1
Reproduction
Problem description
When training using trl versions 0.20.0 and above and using max_length, I seem to get into a situation where the total loss during fine-tuning training is stagnant (image attached below. However, when using max_seq_length, training loss is decreasing as normal.
Doing some research, #2895 seems to have a relation to the variable name change, but it is only that, a variable name change, unless a max_seq_length was missed somewhere or max_length not added somewhere.
Please also note, I did test trl 0.21.0 to over 1000 epochs to see if it was an error on my end, however I still obtained stagnant results, which are completely the opposite at 10 epochs for version 0.19.1.
Versions TRL: 0.19.1 (The one that works), =>0.20.0 ( The one that has issues)
Configuration
sft_config = SFTConfig(
## GROUP 1: Memory usage
# These arguments will squeeze the most out of your GPU's RAM
# Checkpointing
gradient_checkpointing=True, # this saves a LOT of memory
# Set this to avoid exceptions in newer versions of PyTorch
gradient_checkpointing_kwargs={'use_reentrant': False},
# Gradient Accumulation / Batch size
# Actual batch (for updating) is same (1x) as micro-batch size
gradient_accumulation_steps=1,
# The initial (micro) batch size to start off with
per_device_train_batch_size=16,
# If batch size would cause OOM, halves its size until it works
auto_find_batch_size=True,
## GROUP 2: Dataset-related
max_seq_length=64,
# Dataset
# packing a dataset means no padding is needed
packing=True,
## GROUP 3: These are typical training parameters
num_train_epochs=10,
learning_rate=3e-4,
# Optimizer
# 8-bit Adam optimizer - doesn't help much if you're using LoRA!
optim='paged_adamw_8bit',
## GROUP 4: Logging parameters
logging_steps=10,
logging_dir='./logs',
output_dir='./llms/best-friend-llm',
report_to='none'
)
Outputs
Before changing to max_length:
Output after changing to max_length:
System Info
- Platform: Windows-10-10.0.19045-SP0
- Python version: 3.13.5
- TRL version: 0.19.1
- PyTorch version: 2.8.0+cu128
- accelerator(s): NVIDIA GeForce RTX 3060
- Transformers version: 4.55.2
- Accelerate version: 1.10.0
- Accelerate config: not found
- Datasets version: 4.0.0
- HF Hub version: 0.34.4
- bitsandbytes version: 0.47.0
- DeepSpeed version: not installed
- Diffusers version: not installed
- Liger-Kernel version: not installed
- LLM-Blender version: not installed
- OpenAI version: not installed
- PEFT version: 0.17.0
- vLLM version: not installed
Checklist
- [x] I have checked that my issue isn't already filed (see open issues)
- [x] I have included my system information
- [x] Any code provided is minimal, complete, and reproducible (more on MREs)
- [x] Any code provided is properly formatted in code blocks, (no screenshot, more on code blocks)
- [x] Any traceback provided is complete
Thanks, Please share a reproducible example, it's hard to answer without knowing the dataset used
@qgallouedec Here's a reproduction:
from datasets import Dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
from trl import SFTTrainer, SFTConfig
dataset = Dataset.from_list([
{"text": f"Question: What is {i} + {i}? Answer: {i*2}."}
for i in range(100)
])
model = AutoModelForCausalLM.from_pretrained("gpt2")
tokenizer = AutoTokenizer.from_pretrained("gpt2")
tokenizer.pad_token = tokenizer.eos_token
# This fails in v0.20.0+
config = SFTConfig(
max_seq_length=128, # <- breaks here
output_dir="./test",
packing=True,
)
Error:
TypeError: SFTConfig.__init__() got an unexpected keyword argument 'max_seq_length'
The parameter was renamed from max_seq_length to max_length but backward compatibility was removed. That's why training appears stagnant - it never starts due to the parameter error.
I don't understand. Do you encounter different training results with different trl version (considering the param renaming) or is your issue only about this renaming that causes an expected key error?
Have the same loss problem with 0.22.0.dev0
Thanks, Please share a reproducible example, it's hard to answer without knowing the dataset used
I will try when possible, all the har AI stuff has made my hdd give up and I won't be able to get a new one until Sep.
I don't understand. Do you encounter different training results with different trl version (considering the param renaming) or is your issue only about this renaming that causes an expected key error?
Hi, was this to me or someone else?
What dataset do you use @AmazingGabriel16?
This isn't a trl bug — it's the torch_dtype default change in transformers v5.0.0.
Pinning trl at v0.19.1 and varying only transformers (reporter's config trimmed to SmolLM-135M + alpaca + 200 steps, seed=42):
| transformers | torch_dtype |
last_loss @ 200 |
|---|---|---|
| 4.57.6 | default (= float32) | 1.06 |
| 5.12.1 | default (= "auto", model native dtype) | 1.76 |
| 5.12.1 | explicit torch.float32 |
1.10 |
git bisect between v5.0.0rc0 (good) and v5.0.0rc1 (bad), 134 commits, points at:
6217adc6c8 Default auto (#42805) — huggingface/transformers#42805
An intentional breaking change (flagged with sirens in the PR title) that flips from_pretrained default from torch_dtype=float32 to torch_dtype="auto". With max_length=64 + packing=True + paged_adamw_8bit, the low-precision default hurts convergence on small models more than it would on a normal config.
Same numbers reproduce across trl v0.19.1, v0.20.0, v0.21.0, v0.22.0, and main — trl version doesn't matter.
Workaround:
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float32)
Probably worth a docs note in SFTTrainer that the trainer inherits the loaded model dtype, so explicit torch_dtype matters under transformers >= 5.0.0. Happy to open that PR if useful; otherwise I think this can be closed as upstream.
Independently confirming @AloysJehwin's bisect: transformers#42805 ("Default auto", merge commit 6217adc) is a real, merged PR, and its description does flip from_pretrained's default torch_dtype from float32 to "auto" (i.e. the checkpoint's stored dtype) starting in transformers 5.0.0. So the root-cause analysis checks out — this isn't a trl regression, trl version genuinely doesn't matter here, as demonstrated.
On the "probably worth a docs note" suggestion: docs/source/sft_trainer.md's existing "Model initialization" section (around the model_init_kwargs={"dtype": ...} example) looks like the natural spot, since it already documents how to control the loaded dtype but doesn't currently mention that omitting it means the trainer inherits whatever dtype from_pretrained picks by default, which is now version-dependent (float32 pre-5.0, checkpoint-native "auto" from 5.0 on). A one-line callout there would have made this diagnosable without a bisect.
@AloysJehwin since you already have the full story and the fix ready to write up — feel free to open that docs PR.
Hey @AmazingGabriel16 — sorry this one has been open so long, and thanks to @AloysJehwin and @DaoyuanLi2816 for the deep dives. The torch_dtype="auto" change they found (transformers >= 5.0) is real, but it cannot be what you originally hit: your trl env shows transformers 4.55.2, which predates 5.0, so the dtype default was still float32 on both the 0.19.1 and 0.20.0 runs you compared.
The more likely culprit on your setup is packing. With packing=True and the default bfd strategy, TRL enables padding-free training, which flattens your examples into one sequence and relies on FlashAttention-2 to stop them from attending across each other (see the warning it emits: https://github.com/huggingface/trl/blob/8db673e40d81a2851b5f57931ce81c68a3849aa3/trl/trainer/sft_trainer.py#L1211-L1219 ). On Windows + an RTX 3060, FA2 is almost certainly not installed, so the packed examples cross-contaminate and the loss barely moves — which fits your "stagnant even after 1000 epochs" result.
Could you confirm your attn_implementation, and try either (a) packing=False, or (b) installing flash-attn with attn_implementation="flash_attention_2"? If the loss recovers, that pins it down. (Aside: the TypeError from max_seq_length earlier is expected — that arg was renamed to max_length and the alias was removed in 0.20.0, so it is unrelated to the loss.)
:mag: Investigation
I measured the packing hypothesis from @albertvillanova's last message, since it was the leading explanation and had not been tested.
The code path is exactly as described. packing=True with the default bfd strategy does silently enable padding-free training (sft_trainer.py#L1155), and TRL warns when FlashAttention is absent (L1156-L1171).
But it does not stagnate the loss. Same seed, same data, same steps; only packing varies. No FlashAttention installed. I varied the attention backend and the model size so the result does not hinge on either:
| model | attn | packing | padding_free | first loss | final loss |
|---|---|---|---|---|---|
| pythia-160m | sdpa | True | True | 2.8470 | 0.9132 |
| pythia-160m | sdpa | False | False | 2.9310 | 0.7948 |
| pythia-160m | eager | True | True | 3.6470 | 0.9756 |
| pythia-160m | eager | False | False | 2.9620 | 0.8276 |
| pythia-410m | sdpa | True | True | 4.4735 | 0.5044 |
| pythia-410m | sdpa | False | False | 4.2069 | 0.4729 |
Every packed run learns. The cost of packing without FlashAttention is roughly 0.03 to 0.15 in final loss, consistently, and it shows up on both sdpa and eager and at both model sizes. That is a mild penalty, not the "stagnant even after 1000 epochs" behaviour in the original report. So padding-free cross-contamination is real but bounded, and on this evidence it does not by itself explain @AmazingGabriel16's result.
Caveat so this is not over-read: these are small pretrained models on CPU with a synthetic dataset, not Llama-3.2-3B on Windows with an RTX 3060. A negative result here does not prove the reporter's specific run was healthy. What it does show is that "packing without FA2 leads to a stagnant loss" is not a general property of the current code.
For completeness, the torch_dtype="auto" finding by @AloysJehwin and @DaoyuanLi2816 is real but, as @albertvillanova already noted, cannot apply to the original report either, since the reporter was on transformers 4.55.2, which predates the 5.0 default change.
Both leading explanations therefore look ruled out for the original configuration. Unless @AmazingGabriel16 can still reproduce on a current version, this looks like a candidate for closing as not reproducible.
One thing I ran into while testing that may be relevant to anyone else chasing a "loss that will not move": if every label in a batch ends up masked, SFTTrainer reports loss: 0.0 and finishes normally even though the underlying forward loss is NaN. That failure mode looks exactly like a stagnant loss from the outside. #5826 addresses the same class for DPO and TPO but does not touch sft_trainer.py. I will open that separately with a minimal reproduction rather than derail this thread.
cc @albertvillanova @qgallouedec
@albertvillanova is right and my July comment was too strong. I verified that transformers#42805 is real and that it flips the from_pretrained dtype default in 5.0.0, then wrote "the root-cause analysis checks out" as if that explained this report — without checking the reporter's environment, which was in the issue body the whole time:
- TRL version: 0.19.1
- Transformers version: 4.55.2
4.55.2 predates the 5.0 default change, so that mechanism cannot have been active on either of the runs @AmazingGabriel16 compared. I confirmed one link in the chain and endorsed the whole chain.
@behroozazarkhalili's measurements look like the right way to settle the other hypothesis — varying only packing while holding seed, data and steps, across two attention backends and two model sizes, is what turns "plausible mechanism" into "bounded 0.03–0.15 penalty, not stagnation".
One thing worth keeping separate from the closing decision: the docs gap is still real on its own terms. From transformers 5.0 on, omitting dtype in model_init_kwargs means the trainer silently inherits the checkpoint's dtype instead of float32, and that is version-dependent behaviour a user cannot see. That is worth the one-line callout in the "Model initialization" section regardless of what happened here — it just isn't this report's cause. It would be a shame to drop the valid half along with the part that turned out not to apply.
No objection to closing as not reproducible unless @AmazingGabriel16 can still reproduce on a current version.
No objection to closing as not reproducible unless @AmazingGabriel16 can still reproduce on a current version.
Hello, my apologies that I have not replied for so long. I ended up going on with the working version of TRL, the 0.19.1 version. At the moment I believe it's best we close this as I will not be able to reproduce the issue anymore in the same environment as I have since changed to ROCm with a 9070XT.
I do apologise, I was not aware that this issue was still up and I thank you all for your patience in the matter.
Thank you, Gabriel