DFT loss turns every weight into NaN on a batch with no trainable tokens
What
With loss_type="dft", a training step on a batch where every label is -100 makes all model weights non-finite, while the reported loss is 0:
import torch
from datasets import load_dataset
from trl import SFTConfig, SFTTrainer
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_completion", split="train")
training_args = SFTConfig(
loss_type="dft",
max_length=33, # keeps the image, truncates away the completion of the first example
per_device_train_batch_size=1,
max_steps=1,
bf16=False,
report_to="none",
)
trainer = SFTTrainer(
model="trl-internal-testing/tiny-Qwen2VLForConditionalGeneration", args=training_args, train_dataset=dataset
)
trainer.train()
print(trainer.state.log_history[-1]["train_loss"])
print(all(torch.isfinite(p).all() for p in trainer.model.parameters()))0.0
Falsedft_loss divides the summed per-token loss by the number of trainable tokens, so a batch with none gives 0/0. The loss is NaN (the Trainer's logging_nan_inf_filter hides it from the logs), and since the per-token loss is multiplied by the loss mask, the backward pass computes 0 * inf and the NaN gradients reach every weight. The default loss_type="nll" also returns a NaN loss on such a batch, but its gradients are zero, so the same script ends with finite weights.
Text datasets never produce such a batch, because fully masked examples are dropped during dataset preparation (#6320). Vision datasets are collated on the fly, so an example whose completion is truncated away stays in the batch with all its labels at -100; with per_device_train_batch_size=1, that is the whole batch.
Source: huggingface/trl