Skip to content

A straightforward method for training your LLM, from downloading data to generating text.

fix: preserve preference responses when truncating

Iams4kura6cd3f8d2648e
diff --git a/data_loader/preference_dataset.py b/data_loader/preference_dataset.py
index 50b939a..2a2abca 100644
--- a/data_loader/preference_dataset.py
+++ b/data_loader/preference_dataset.py
@@ -16,6 +16,7 @@ positions in the loss.
from __future__ import annotations
import json
+from itertools import zip_longest
from typing import Iterator
import numpy as np
@@ -24,15 +25,58 @@ import torch
from src.post_training.chat_template import EOT_ID, encode_chat
-def _encode_side(prompt: str, response: str, max_len: int) -> tuple[list[int], list[int]]:
- ids, mask = encode_chat([{"role": "user", "content": prompt},
- {"role": "assistant", "content": response}])
- return ids[:max_len], mask[:max_len]
+def _encode_response(response: str) -> list[int]:
+ """Encode assistant content plus its EOT, without duplicating the role header."""
+ ids, mask = encode_chat([{"role": "assistant", "content": response}])
+ start = mask.index(1) # non-empty responses and the EOT always provide a target
+ return ids[start:]
+
+
+def _encode_pair(prompt: str, chosen: str, rejected: str, max_len: int):
+ """Truncate a pair over one shared prompt while retaining response targets."""
+ prompt_ids, _ = encode_chat(
+ [{"role": "user", "content": prompt}], add_generation_prompt=True,
+ )
+ assistant_header, _ = encode_chat([], add_generation_prompt=True)
+ chosen_ids = _encode_response(chosen)
+ rejected_ids = _encode_response(rejected)
+
+ difference_at = next(
+ (i for i, pair in enumerate(zip_longest(chosen_ids, rejected_ids)) if pair[0] != pair[1]),
+ None,
+ )
+ if difference_at is None:
+ raise ValueError("chosen and rejected responses encode identically")
+
+ # Keep the complete assistant header plus the prompt's EOT and at least one prompt
+ # token. Preserve both responses in full when they fit beside that shared context;
+ # otherwise shorten the prompt only enough to retain the first differing target.
+ min_shared_prompt = min(len(prompt_ids), len(assistant_header) + 2)
+ required_response = difference_at + 1
+ max_response_with_context = max_len - min_shared_prompt
+ if required_response > max_response_with_context:
+ raise ValueError(
+ f"max_len={max_len} cannot retain shared prompt context and distinguish responses"
+ )
+ longest_response = max(len(chosen_ids), len(rejected_ids))
+ reserved_response = (
+ longest_response if longest_response <= max_response_with_context else required_response
+ )
+ prompt_budget = min(len(prompt_ids), max_len - reserved_response)
+ shared_prompt = prompt_ids[-prompt_budget:]
+ response_budget = max_len - len(shared_prompt)
+
+ def side(response_ids: list[int]) -> tuple[list[int], list[int]]:
+ response_ids = response_ids[:response_budget]
+ ids = shared_prompt + response_ids
+ mask = [0] * len(shared_prompt) + [1] * len(response_ids)
+ return ids, mask
+
+ return side(chosen_ids), side(rejected_ids)
def _collate(rows: list[dict], max_len: int, device: str) -> dict:
- enc = [( _encode_side(r["prompt"], r["chosen"], max_len),
- _encode_side(r["prompt"], r["rejected"], max_len)) for r in rows]
+ enc = [_encode_pair(r["prompt"], r["chosen"], r["rejected"], max_len) for r in rows]
# Pad chosen and rejected to a single common length so they can share one forward.
L = max(max(len(c[0]), len(j[0])) for c, j in enc)
diff --git a/tests/test_post_training_smoke.py b/tests/test_post_training_smoke.py
index 64725f2..30949a7 100644
--- a/tests/test_post_training_smoke.py
+++ b/tests/test_post_training_smoke.py
@@ -9,6 +9,7 @@ Run from the repo root:
import torch
import torch.nn.functional as F
+from data_loader.preference_dataset import _collate
from src.models.transformer import Transformer
from src.post_training import chat_template as ct
from src.post_training.rollout import (
@@ -125,6 +126,38 @@ def test_reward_parsing():
print("ok reward parsing + verifier scoring")
+def test_preference_truncation_preserves_responses():
+ row = {
+ "prompt": "Explain every step in detail. " * 100,
+ "chosen": "Shared response prefix, followed by the preferred ending.",
+ "rejected": "Shared response prefix, followed by the rejected ending.",
+ }
+ batch = _collate([row], max_len=32, device="cpu")
+ chosen_mask = batch["chosen_mask"][0].bool()
+ rejected_mask = batch["rejected_mask"][0].bool()
+
+ assert chosen_mask.any(), "truncation must retain chosen completion targets"
+ assert rejected_mask.any(), "truncation must retain rejected completion targets"
+
+ chosen_start = chosen_mask.nonzero()[0, 0]
+ rejected_start = rejected_mask.nonzero()[0, 0]
+ assert chosen_start == rejected_start, "both sides must keep the same prompt length"
+ assert torch.equal(
+ batch["chosen_ids"][0, :chosen_start],
+ batch["rejected_ids"][0, :rejected_start],
+ ), "both sides must be conditioned on the same truncated prompt"
+ assert batch["chosen_ids"][0].tolist() != batch["rejected_ids"][0].tolist(), (
+ "truncation must retain enough response tokens to distinguish the pair"
+ )
+ chosen_full_mask = ct.encode_chat([{"role": "assistant", "content": row["chosen"]}])[1]
+ rejected_full_mask = ct.encode_chat([{"role": "assistant", "content": row["rejected"]}])[1]
+ assert chosen_mask.sum().item() == sum(chosen_full_mask)
+ assert rejected_mask.sum().item() == sum(rejected_full_mask)
+ assert batch["chosen_ids"][0, chosen_mask][-1].item() == ct.EOT_ID
+ assert batch["rejected_ids"][0, rejected_mask][-1].item() == ct.EOT_ID
+ print("ok preference truncation retains responses over a shared prompt")
+
+
def test_build_from_config():
from config.post_training_config import smoke, SFTConfig
cfg = smoke(SFTConfig)
@@ -143,5 +176,6 @@ if __name__ == "__main__":
test_frozen_copy_and_reductions()
test_chat_template_masking()
test_reward_parsing()
+ test_preference_truncation_preserves_responses()
test_build_from_config()
print("\nALL SMOKE TESTS PASSED")