trl icon indicating copy to clipboard operation
trl copied to clipboard

[CPO/SimPO] Truncation in CPOTrainer can silently produce empty completions -> NaN loss with loss_type="simpo"

Open ninjafrmtjk opened this issue 4 months ago • 7 comments

Reproduction

Description

In trl/experimental/cpo/cpo_trainer.py, the response truncation logic in tokenize_row truncates both responses using the length of the longer response of the pair:

longer_response_length = max(len(chosen_tokens["input_ids"]), len(rejected_tokens["input_ids"]))

# if combined sequence is too long, truncate the response
for answer_tokens in [chosen_tokens, rejected_tokens]:
    if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length:
        for k in ["input_ids", "attention_mask"]:
            answer_tokens[k] = answer_tokens[k][: self.max_length - longer_response_length]

(https://github.com/huggingface/trl/blob/4708879046dde897bdb84667a97e781bfc1965d2/trl/experimental/cpo/cpo_trainer.py#L554-L560)

When longer_response_length > self.max_length, the slice bound self.max_length - longer_response_length is negative, so lst[:negative] cuts from the end. If the shorter response of the pair has fewer tokens than that negative offset, it is truncated to an empty sequence (0 completion tokens, all labels are -100).

Consequences:

  • With loss_type="simpo", log-probs are length-normalized, so an empty completion produces a 0/0 division -> NaN in logps, which propagates to the loss and destroys all model weights after the first optimizer step. Training metrics show loss = 0, grad_norm = nan, all rewards/logps nan.
  • With other loss types the empty completion contributes a silent logp = 0, which is incorrect but does not crash — arguably worse, since it corrupts training without any visible symptom.

This is easy to hit in practice with self-generated preference data (e.g., math reasoning), where response lengths are heavy-tailed: a single pair with one very long response (> max_length) and one normal-length response triggers it.

Reproduction

Pure-Python demonstration of the slicing logic (3 lines):

max_length = 2048
chosen = list(range(5000))    # long response, > max_length
rejected = list(range(600))   # normal short response

longer = max(len(chosen), len(rejected))          # 5000
print(len(chosen[: max_length - longer]))         # 2048  (truncated, survives)
print(len(rejected[: max_length - longer]))       # 0     (silently EMPTY)

End-to-end reproduction through the trainer (any small public model):

import torch
from datasets import Dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
from trl.experimental.cpo import CPOTrainer, CPOConfig

model_id = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float32)

pair = {
    "prompt": "Question: what is 2+2?\nAnswer:",
    "chosen": " step" * 5000,          # ~5000 tokens, exceeds max_length
    "rejected": " The answer is 4.",   # ~7 tokens, healthy short response
}

def count_completion_tokens(max_length):
    args = CPOConfig(
        output_dir="/tmp/cpo_repro",
        loss_type="simpo",
        cpo_alpha=0.0,
        beta=0.1,
        max_length=max_length,
        per_device_train_batch_size=1,
        report_to="none",
    )
    trainer = CPOTrainer(
        model=model,
        args=args,
        train_dataset=Dataset.from_list([pair]),
        processing_class=tokenizer,
    )
    row = trainer.train_dataset[0]
    n_chosen = sum(t != -100 for t in row["chosen_labels"])
    n_rejected = sum(t != -100 for t in row["rejected_labels"])
    return n_chosen, n_rejected

print("max_length=2048:", count_completion_tokens(2048))
# -> (2048, 0)   rejected is EMPTY -> NaN loss with loss_type="simpo"

print("max_length=8192:", count_completion_tokens(8192))
# -> (5001, 7)   control: everything fits, both responses intact

Same data, only max_length differs: the short response is destroyed exactly when the other response exceeds max_length.

Expected behavior

Each response should be truncated based on its own length, e.g.:

for answer_tokens in [chosen_tokens, rejected_tokens]:
    if len(answer_tokens["prompt_input_ids"]) + len(answer_tokens["input_ids"]) > self.max_length:
        for k in ["input_ids", "attention_mask"]:
            answer_tokens[k] = answer_tokens[k][
                : max(0, self.max_length - len(answer_tokens["prompt_input_ids"]))
            ]

so that a short response is never emptied because its pair partner is long. Additionally, a guard (warning or error) when a completion ends up with zero tokens after truncation would make failures like the SimPO NaN immediately diagnosable instead of silent.

System Info

  • Platform: Linux-6.8.0-124-generic-x86_64-with-glibc2.39
  • Python version: 3.12.3
  • TRL version: 1.6.0
  • PyTorch version: 2.11.0+cu130
  • accelerator(s): NVIDIA L40S, NVIDIA L40S
  • Transformers version: 5.12.1
  • Accelerate version: 1.14.0
  • Accelerate config:
    • compute_environment: LOCAL_MACHINE
    • distributed_type: FSDP
    • mixed_precision: bf16
    • use_cpu: False
    • debug: False
    • num_processes: 2
    • machine_rank: 0
    • num_machines: 1
    • rdzv_backend: static
    • same_network: True
    • main_training_function: main
    • enable_cpu_affinity: False
    • fsdp_config: {'fsdp_activation_checkpointing': False, 'fsdp_auto_wrap_policy': 'TRANSFORMER_BASED_WRAP', 'fsdp_backward_prefetch': 'BACKWARD_PRE', 'fsdp_cpu_ram_efficient_loading': True, 'fsdp_forward_prefetch': False, 'fsdp_offload_params': False, 'fsdp_sharding_strategy': 'FULL_SHARD', 'fsdp_state_dict_type': 'SHARDED_STATE_DICT', 'fsdp_sync_module_states': True, 'fsdp_use_orig_params': False, 'fsdp_version': 1}
    • downcast_bf16: yes
    • tpu_use_cluster: False
    • tpu_use_sudo: False
    • tpu_env: []
  • Datasets version: 5.0.0
  • HF Hub version: 1.23.0
  • bitsandbytes version: 0.49.2
  • DeepSpeed version: not installed
  • Liger-Kernel version: not installed
  • PEFT version: 0.19.1
  • vLLM version: 0.23.0

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

ninjafrmtjk avatar Jul 26 '26 18:07 ninjafrmtjk

Hey! I'd love to work on this issue if it's available.

RohanMali2003 avatar Jul 26 '26 20:07 RohanMali2003

Reproduced on 8d19a36. Adding a few things I ran into while digging, since they change what the fix has to cover.

The same block is in ORPO, byte for byte. trl/experimental/orpo/orpo_trainer.py#L540-L546. Whatever lands in cpo_trainer.py should land there too, otherwise ORPO keeps the bug.

The bound is wrong even when it doesn't go negative. max_length - longer_response_length is only the correct budget when longer_response_length == len(prompt_input_ids). The budget for a response is max_length - len(prompt_input_ids); the length of the other member of the pair has nothing to do with it. So the pair gets over-truncated whenever the longer response is longer than the prompt, which for reasoning data is the normal case, not the edge case:

case                                    prompt  chosen    rej  max_len |        current       expected
over-truncation, bound still positive       20      40     30       50 |       [10, 10]       [30, 30]
negative bound, short response emptied      20    5000    600     2048 |      [2048, 0]    [2028, 600]
negative bound, both survive partially      20    5000   4000     2048 |   [2048, 1048]   [2028, 2028]
no truncation needed (control)              20      20     15      128 |       [20, 15]       [20, 15]

Row 1 is the part I hadn't seen mentioned: no negative slice, no empty completion, no NaN, and both responses still lose 20 tokens of supervision each for no reason. That one is invisible in the metrics.

When the bound does go negative, the truncation doesn't actually enforce max_length either. Row 3 above: chosen comes out at 2048 tokens, so prompt_input_ids + input_ids is 2068, over a max_length of 2048. The slice cuts longer_response_length - max_length tokens off the end of each response, which has no relationship to the budget, so the sequence that the branch was supposed to shrink can still overflow by len(prompt_input_ids).

DPOTrainer already solved this and is worth copying rather than re-deriving. The collator slices the concatenated prompt + completion with slice(None, max_length) / slice(-max_length, None), which can't go negative, and then the dataset pass drops the examples where truncation would leave nothing behind: dpo_trainer.py#L1077-L1083

# Drop examples whose prompt alone fills `max_length`: with `keep_start` truncation the collator would
# remove every completion token, leaving no learning signal. `keep_end` keeps the completion end, so
# nothing is dropped there.
if args.max_length is not None and args.truncation_mode == "keep_start":
    ...
    dataset = dataset.filter(lambda example: len(example["prompt_ids"]) < args.max_length, **map_kwargs)

That comment describes exactly the failure mode in this issue, so the "empty completion" half is a solved problem in the stable trainer and the experimental ones just never picked it up.

Related but not the same bug, in BCO. bco_trainer.py#L296-L299 uses answer[: max_length - len(prompt_input_ids)]. There is no longer_response_length there, but there is also no max_prompt_length anywhere in BCOTrainer, so a prompt longer than max_length makes that bound negative too. Running _process_tokens directly with a stub tokenizer:

  prompt=  10 answer= 10 max_length=  32 -> completion_len=  22 (budget 32)  answer_tokens_kept=11
  prompt=  28 answer= 10 max_length=  32 -> completion_len=  32 (budget 32)  answer_tokens_kept=3
  prompt=  60 answer= 10 max_length=  32 -> completion_len=  62 (budget 32)  answer_tokens_kept=1
  prompt=1000 answer= 10 max_length=  32 -> completion_len=1002 (budget 32)  answer_tokens_kept=1

The last two keep only the appended EOS, so the example carries zero real completion tokens, and the sequence is still way over max_length. I'll send that one as its own PR since it's a different code path and I don't want to step on this issue.

@RohanMali2003 no objection from me on you taking this one, the above is just so you don't have to rediscover it. Happy to review whatever you put up.

ErenAta16 avatar Jul 28 '26 21:07 ErenAta16

Hi @RohanMali2003 ? I saw that you are interested in working on this issue. I have not started any code changes yet. After reviewing the current main implementation and @ErenAta16's analysis, I think the fix should have two parts.

First, the truncation logic should be corrected in both CPOTrainer and ORPOTrainer. Instead of truncating both completions according to the longer response in the pair, each completion should use its own available budget:

completion_budget = max(0, self.max_length - prompt_length)

This preserves a shorter completion when only the other completion is too long and ensures that each prompt-completion sequence is handled independently.

Second, if truncation leaves either the chosen or rejected side with no supervised completion tokens, the entire decoder-only preference pair should be dropped after tokenization. This follows the behavior recently added to DPO and KTO in #6321 and prevents empty completions from reaching the loss calculation.

For regression coverage, I propose adding matching parameterized tests for CPO and ORPO covering:

  • no truncation;
  • over-truncation while the old slice bound is still positive;
  • one long and one short completion;
  • two long completions;
  • a prompt that fills the entire max_length budget.

The tests would verify that each sequence respects max_length, the shorter completion is preserved, and every retained pair has supervised tokens on both sides. For CPO, I would also add a small one-step SimPO test to confirm that the loss and gradients remain finite.

The related BCO behavior would remain out of scope because it uses a different preprocessing path.

Does this approach sound reasonable to you? Are you already working on an implementation? If so, would you be open to collaborating so that we can divide the trainer changes and regression tests without duplicating work? If you have not started yet, I would be happy to coordinate and work on it together.

YAO-001 avatar Jul 30 '26 09:07 YAO-001

Hi @YAO-001 !

I had actually started working on the implementation a while ago, but I didn't have the chance to review how DPO Trainer did it yet, apart from what Eren's comment outlines. I can leave that part to you, if you're open to collaboration.

I've just pushed a branch that implements the first part of your proposal: correcting the truncation logic for both CPOTrainer and ORPOTrainer. It applies the independent budget math that you also mentioned: (max(0, self.max_length - prompt_length)) to prevent the negative slicing and adds a logger warning if a completion is emptied.

I haven't yet implemented the dataset filtering part yet, and since you mentioned you haven't started coding yet, I am going to open a Draft PR with these core fixes right now, and we can collaborate on that PR to add the second part (dataset filtering/dropping logic as is done in dpotrainer) and the regression tests you outlined? I have not done that and I'm happy to grant you edit access to the branch so we can tag-team it, or if you prefer, I can help write some of the tests too. Let me know what works best for you!

RohanMali2003 avatar Jul 30 '26 11:07 RohanMali2003

Hey @YAO-001, just a quick thought while we're setting this up!

I was looking over Eren's BCO PR and noticed he intentionally left the .filter() out because dropping rows could skew BCO's desirable-to-undesirable ratio.

Since CPO and ORPO train on strict chosen and rejected pairs just like DPO, dropping the fully truncated rows will cleanly remove the pairs without skewing the data distribution. So I think DPO trainer's logic should apply without any problems, but would be cool if you could check that once. Thanks!

RohanMali2003 avatar Jul 30 '26 11:07 RohanMali2003

Hi @RohanMali2003, thanks for the detailed update and for opening #6588. I'd be happy to collaborate on it.

I checked the current DPOTrainer implementation as you suggested. With keep_start truncation, DPO drops a preference row when the tokenized prompt alone reaches max_length, because the collator would otherwise remove all completion tokens. CPO and ORPO have the same paired structure and likewise preserve the prompt while truncating the completions. Therefore, filtering the entire row when either side has no supervised completion tokens is the corresponding behavior here. It removes one chosen and one rejected completion together, so it does not introduce the desirable-to-undesirable imbalance that is relevant to BCO.

Since leaving my earlier comment, I have done some local validation of the proposed filtering behavior and regression coverage. To avoid duplicating implementation effort, I can adapt the non-overlapping parts onto your Draft PR. Specifically, I can take care of:

  • filtering fully truncated pairs from both the training and evaluation datasets in CPO and ORPO;
  • matching regression tests for the independent truncation cases in both trainers;
  • a one-step CPO SimPO test confirming that the loss and gradients remain finite.

If that division works for you, please let me know whether you would prefer to add me (@YAO-001) as a collaborator on the fix-cpo-truncation branch or have me open a PR against that branch. Either option works for me.

Thanks again for coordinating this — I'm looking forward to working on it together.

YAO-001 avatar Jul 30 '26 17:07 YAO-001

yeah, @YAO-001, that sounds perfect to me! I think the easiest approach is for you to just push directly to the branch. I've already sent you a collaborator invitation for my fork so you can push the filtering logic and tests straight to the fix-cpo-truncation branch of my repo. Once you're done, we'll finalize the draft and mark it as ready for review. Let me know if you don't see the invite or run into any issues accessing my fork/my branch, in that case we can try the alternative. Thanks!

RohanMali2003 avatar Jul 30 '26 18:07 RohanMali2003