trl icon indicating copy to clipboard operation
trl copied to clipboard

`is_conversational` result depends on `PYTHONHASHSEED`

Open aidless opened this issue 4 weeks ago • 2 comments

System Info

trl main @ d144b88, Python 3.12, transformers 5.17.0

Reproduction

import os
import subprocess
import sys

CHILD = """
from trl.data_utils import is_conversational

example = {
    "prompt": "What color is the sky?",
    "chosen": [{"role": "user", "content": "What color is the sky?"},
               {"role": "assistant", "content": "It is blue."}],
    "rejected": [{"role": "user", "content": "What color is the sky?"},
                 {"role": "assistant", "content": "It is green."}],
}
print(is_conversational(example))
"""

for seed in range(6):
    out = subprocess.run(
        [sys.executable, "-c", CHILD],
        env={**os.environ, "PYTHONHASHSEED": str(seed)},
        capture_output=True,
        text=True,
    )
    print(f"PYTHONHASHSEED={seed} -> {out.stdout.strip()}")

Output (each seed reproduced 3/3 times):

PYTHONHASHSEED=0 -> True
PYTHONHASHSEED=1 -> False
PYTHONHASHSEED=2 -> True
PYTHONHASHSEED=3 -> False
PYTHONHASHSEED=4 -> True
PYTHONHASHSEED=5 -> False

Cause

is_conversational collects the supported keys into a set and pops one arbitrary element:

supported_keys = ["prompt", "chosen", "rejected", "completion", "messages"]
example_keys = {key for key in example.keys() if key in supported_keys}
if example_keys:
    key = example_keys.pop()  # take the first supported key

For examples that mix a string prompt with conversational chosen/rejected (the shape described in maybe_extract_prompt), the popped key decides the result, and the iteration order of a set of strings depends on PYTHONHASHSEED.

Impact

DPOTrainer._prepare_dataset uses this result to decide whether to add EOS (dpo_trainer.py#L1108-L1121). With the example above:

Traceback (most recent call last):
  File "repro.py", line 25, in <module>
    trainer = DPOTrainer(
  File "trl/trainer/dpo_trainer.py", line 901, in __init__
    train_dataset = self._prepare_dataset(train_dataset, processing_class, args, "train")
  File "trl/trainer/dpo_trainer.py", line 1121, in _prepare_dataset
    dataset = dataset.map(add_eos, fn_kwargs={"eos_token": self._tokenizer.eos_token}, **map_kwargs)
  File "datasets/arrow_dataset.py", line 3942, in iter_outputs
    yield i, apply_function(example, i, offset=offset)
  File "datasets/arrow_dataset.py", line 3863, in apply_function
    processed_inputs = function(*fn_args, *additional_args, **fn_kwargs)
  File "trl/trainer/dpo_trainer.py", line 1115, in add_eos
    if not example["chosen"].endswith(eos_token):
AttributeError: 'list' object has no attribute 'endswith'

With PYTHONHASHSEED=0 the same example skips add_eos and instead fails in tokenize_fn with TypeError: can only concatenate str (not "list") to str at dpo_trainer.py#L1141. With a dataset that also has a plain-text completion column, seeds 0/3/5 prepare the dataset successfully while seeds 1/2/4 raise the AttributeError above. With dataset_num_proc > 1, each worker has its own hash seed, so rows of the same dataset can take different branches.

Fix

Iterate over ["messages", "prompt", "chosen", "rejected", "completion"] in a fixed order and return True for the first value that is a non-empty list of message dicts. Happy to open a PR.

aidless avatar Nov 06 '26 04:11 aidless

Please fill in the bug report template In particular "How did you hit this?": what you were training, with which dataset, or say so if you found it by reading the source. And the output of trl env for the system info.

qgallouedec avatar Nov 08 '26 12:11 qgallouedec

Hey @aidless, thanks for the write-up. The key order is indeed hash-dependent, but I ran your example through DPOTrainer on current main and the only thing it changes is which error you get: AttributeError in add_eos on some seeds, TypeError in tokenize_fn on the others. Same with the extra completion column. A fixed order would just pin one of the two crashes, which is the same reasoning as #6636.

To train on a string prompt next to conversational chosen/rejected (e.g. HuggingFaceH4/ultrafeedback_binarized), drop the prompt column so the trainer extracts it from chosen/rejected here:

https://github.com/huggingface/trl/blob/8773d24ff72db11cec960aa022583b61bf0074d9/trl/trainer/dpo_trainer.py#L1119-L1123

Closing, but happy to reopen if you have a real run where one seed trains and another doesn't.

albertvillanova avatar Nov 20 '26 06:11 albertvillanova