A straightforward method for training your LLM, from downloading data to generating text.
fix(data): never crash or starve answers when truncating preference pairs
FareedKhan-dev65ccf7684774
diff --git a/data_loader/preference_dataset.py b/data_loader/preference_dataset.pyindex 2a2abca..d2c2785 100644--- a/data_loader/preference_dataset.py+++ b/data_loader/preference_dataset.py@@ -11,6 +11,11 @@ so we get, for the chosen and rejected responses to the same prompt:Right-padding is safe here because the model's attention is causal: the last real tokennever attends to padding that comes after it, and the response mask zeros paddedpositions in the loss.++Truncation (when ``prompt + response`` does not fit in ``max_len``) follows the usual+recipe for preference training: both sides share one left-truncated prompt, so the model+always compares the two answers under the same context, and the prompt never takes more+than half of the window when the answers are long too. See :func:`encode_preference_pair`."""from __future__ import annotations@@ -24,6 +29,8 @@ import torchfrom src.post_training.chat_template import EOT_ID, encode_chat+Encoded = tuple[list[int], list[int]] # (token ids, response mask)+def _encode_response(response: str) -> list[int]:"""Encode assistant content plus its EOT, without duplicating the role header."""@@ -32,51 +39,58 @@ def _encode_response(response: str) -> list[int]: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+def _first_difference(a: list[int], b: list[int]) -> int | None:+ """Index of the first token where ``a`` and ``b`` differ (None if they are identical)."""+ return next((i for i, (x, y) in enumerate(zip_longest(a, b)) if x != y), None)+++def encode_preference_pair(prompt: str, chosen: str, rejected: str, max_len: int) -> tuple[Encoded, Encoded]:+ """+ Encode ``prompt + chosen`` and ``prompt + rejected`` into at most ``max_len`` tokens each.++ The rules, in order:++ 1. Both sides share the same prompt tokens, so DPO and the reward model compare the two+ answers under exactly the same context.+ 2. If everything fits, nothing is cut.+ 3. Otherwise the prompt is cut from the left (its end, including the ``<|assistant|>``+ header, is what matters for the answer), but it keeps at least half of the window+ when the answers are long as well. The answers are cut from the right.+ 4. The cut always keeps the first token where the two answers differ, when that is+ possible. A pair that can no longer be told apart carries no learning signal, so it+ just gets identical sides (zero DPO gradient) instead of crashing the run.+ """+ prompt_ids, _ = encode_chat([{"role": "user", "content": prompt}], add_generation_prompt=True)+ header_len = len(encode_chat([], add_generation_prompt=True)[0])+ if max_len <= header_len + 1:+ raise ValueError(f"max_len={max_len} is too small to hold the chat template; use at least 16")+ chosen_ids, rejected_ids = _encode_response(chosen), _encode_response(rejected)+ longest = max(len(chosen_ids), len(rejected_ids))++ # The model must always see the assistant header plus one prompt token.+ min_prompt = min(len(prompt_ids), header_len + 1)+ prompt_keep = min(len(prompt_ids), max(max_len - longest, max_len // 2))+ diff = _first_difference(chosen_ids, rejected_ids)+ if diff is not None:+ prompt_keep = min(prompt_keep, max_len - (diff + 1))+ prompt_keep = max(prompt_keep, min_prompt)++ shared = prompt_ids[len(prompt_ids) - prompt_keep:]+ budget = max(0, max_len - len(shared))++ def side(response_ids: list[int]) -> Encoded:+ kept = response_ids[:budget]+ return shared + kept, [0] * len(shared) + [1] * len(kept)return side(chosen_ids), side(rejected_ids)+# Name used by the original fix in #41; kept so existing imports keep working.+_encode_pair = encode_preference_pair++def _collate(rows: list[dict], max_len: int, device: str) -> dict:- enc = [_encode_pair(r["prompt"], r["chosen"], r["rejected"], max_len) for r in rows]+ enc = [encode_preference_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_preference_truncation.py b/tests/test_preference_truncation.pynew file mode 100644index 0000000..863ef9d--- /dev/null+++ b/tests/test_preference_truncation.py@@ -0,0 +1,93 @@+"""+Truncation of preference pairs (reward model and DPO data).++Background: before #41 each side was encoded on its own and cut to ``max_len``, so a long+prompt could push both answers out of the window. The pair then had identical tokens and+all-zero response masks, and DPO learned nothing from it. These tests pin the current rules+(see ``encode_preference_pair``).+"""++from __future__ import annotations++import random++from data_loader.preference_dataset import _collate, encode_preference_pair+from src.post_training import chat_template as ct+++def _prompt_len(mask: list[int]) -> int:+ return mask.index(1) if 1 in mask else len(mask)+++def test_short_pairs_are_encoded_exactly_like_a_full_conversation() -> None:+ (c_ids, c_mask), (r_ids, r_mask) = encode_preference_pair("What is 2+2?", "4", "5", max_len=128)+ full_ids, full_mask = ct.encode_chat(+ [{"role": "user", "content": "What is 2+2?"}, {"role": "assistant", "content": "4"}]+ )+ assert (c_ids, c_mask) == (full_ids, full_mask)+ assert r_ids[: _prompt_len(r_mask)] == c_ids[: _prompt_len(c_mask)]+++def test_long_prompt_keeps_both_full_answers() -> None:+ prompt = "Explain every step in detail. " * 100+ (c_ids, c_mask), (r_ids, r_mask) = encode_preference_pair(prompt, "The answer is yes.", "The answer is no.", 48)+ assert len(c_ids) <= 48 and len(r_ids) <= 48+ assert sum(c_mask) == sum(ct.encode_chat([{"role": "assistant", "content": "The answer is yes."}])[1])+ assert c_ids[-1] == ct.EOT_ID and r_ids[-1] == ct.EOT_ID+ # the kept prompt is the END of the prompt, so it still finishes with the assistant header+ header = ct.encode_prompt([])+ assert c_ids[: _prompt_len(c_mask)][-len(header):] == header+ assert c_ids[: _prompt_len(c_mask)] == r_ids[: _prompt_len(r_mask)]+++def test_long_prompt_and_long_answers_split_the_window() -> None:+ prompt = "Tell me about the printing press. " * 200+ chosen = "It spread knowledge fast. " * 200+ rejected = "It was invented in 1440. " * 200+ (c_ids, c_mask), (r_ids, r_mask) = encode_preference_pair(prompt, chosen, rejected, max_len=256)+ assert len(c_ids) == 256 and len(r_ids) == 256+ assert _prompt_len(c_mask) == 128, "the prompt keeps half of the window when both are long"+ assert sum(c_mask) == 128 and sum(r_mask) == 128+ assert c_ids != r_ids+++def test_late_difference_is_kept_by_shortening_the_prompt() -> None:+ prompt = "Some long context. " * 100+ prefix = "Let me think about this carefully. " * 8 # ~64 shared answer tokens+ (c_ids, _), (r_ids, _) = encode_preference_pair(prompt, prefix + "Yes.", prefix + "No.", max_len=96)+ assert c_ids != r_ids, "the first differing token must survive truncation"+++def test_indistinguishable_pairs_do_not_crash() -> None:+ same = "Sure! " * 300+ (c_ids, c_mask), (r_ids, r_mask) = encode_preference_pair("Hi", same + "yes", same + "no", max_len=64)+ assert len(c_ids) <= 64 and len(r_ids) <= 64+ assert c_ids == r_ids # no signal left, but training keeps going (zero DPO gradient)+++def test_random_pairs_always_fit_and_share_the_prompt() -> None:+ rng = random.Random(0)+ words = ["alpha", "beta", "gamma", "delta", "the", "a", "model", "token", "\n", "42", "!"]++ def text(n: int) -> str:+ return " ".join(rng.choice(words) for _ in range(n))++ for _ in range(200):+ max_len = rng.choice([16, 24, 64, 128])+ pair = encode_preference_pair(text(rng.randint(0, 120)), text(rng.randint(0, 120)),+ text(rng.randint(0, 120)), max_len)+ (c_ids, c_mask), (r_ids, r_mask) = pair+ assert len(c_ids) == len(c_mask) <= max_len+ assert len(r_ids) == len(r_mask) <= max_len+ assert c_ids[: _prompt_len(c_mask)] == r_ids[: _prompt_len(r_mask)]+++def test_collate_pads_both_sides_to_one_length() -> None:+ rows = [+ {"prompt": "short", "chosen": "a", "rejected": "b c d e"},+ {"prompt": "a much longer prompt " * 20, "chosen": "yes", "rejected": "no"},+ ]+ batch = _collate(rows, max_len=64, device="cpu")+ assert batch["chosen_ids"].shape == batch["rejected_ids"].shape+ assert batch["chosen_mask"].sum(1).min() > 0 and batch["rejected_mask"].sum(1).min() > 0+ assert (batch["chosen_len"] <= 64).all() and (batch["rejected_len"] <= 64).all()