|
| 1 | +from typing import Dict, List, Optional |
| 2 | + |
| 3 | +import torch |
| 4 | +import torch.nn.functional as F |
| 5 | +from transformers.tokenization_utils_base import PreTrainedTokenizerBase |
| 6 | + |
| 7 | +from xturing.datasets.preference_dataset import PreferenceDatasetMeta |
| 8 | + |
| 9 | + |
| 10 | +class PreferenceDataCollator: |
| 11 | + """Collator for preference datasets used in DPO training. |
| 12 | +
|
| 13 | + For each sample, this collator tokenizes two sequences: |
| 14 | + - ``prompt + chosen`` (the preferred completion) |
| 15 | + - ``prompt + rejected`` (the dispreferred completion) |
| 16 | +
|
| 17 | + The resulting batch contains ``chosen_input_ids``, ``chosen_attention_mask``, |
| 18 | + ``chosen_labels``, and the corresponding ``rejected_*`` tensors. Labels are |
| 19 | + masked so that the loss is only computed over the response tokens (not the |
| 20 | + prompt). |
| 21 | + """ |
| 22 | + |
| 23 | + config_name = "preference_dataset" |
| 24 | + |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + tokenizer: PreTrainedTokenizerBase, |
| 28 | + max_length: Optional[int] = None, |
| 29 | + meta: PreferenceDatasetMeta = PreferenceDatasetMeta(), |
| 30 | + ): |
| 31 | + self.tokenizer = tokenizer |
| 32 | + self.max_length = max_length |
| 33 | + self.meta = meta |
| 34 | + |
| 35 | + def _tokenize_pair(self, prompt: str, response: str): |
| 36 | + """Tokenize a prompt-response pair and return input_ids with a label |
| 37 | + mask that marks only the response tokens as trainable.""" |
| 38 | + prompt_tokens = self.tokenizer(prompt) |
| 39 | + response_tokens = self.tokenizer(response) |
| 40 | + |
| 41 | + input_ids = prompt_tokens["input_ids"] + response_tokens["input_ids"] |
| 42 | + # Labels: -100 for prompt tokens (ignored by loss), actual ids for response |
| 43 | + label_mask = [False] * len(prompt_tokens["input_ids"]) + [True] * len( |
| 44 | + response_tokens["input_ids"] |
| 45 | + ) |
| 46 | + |
| 47 | + # Truncate to max_length - 1 to leave room for eos token |
| 48 | + input_ids = input_ids[: self.max_length - 1] |
| 49 | + input_ids.append(self.tokenizer.eos_token_id) |
| 50 | + attention_mask = [1] * len(input_ids) |
| 51 | + |
| 52 | + label_mask = label_mask[: self.max_length - 1] |
| 53 | + label_mask.append(True) |
| 54 | + |
| 55 | + return { |
| 56 | + "input_ids": torch.tensor(input_ids).long(), |
| 57 | + "attention_mask": torch.tensor(attention_mask).long(), |
| 58 | + "label_mask": label_mask, |
| 59 | + } |
| 60 | + |
| 61 | + def _pad_and_stack(self, samples: List[Dict]): |
| 62 | + """Pad a list of tokenized samples and stack into batch tensors.""" |
| 63 | + padded = self.tokenizer.pad( |
| 64 | + [ |
| 65 | + {"input_ids": s["input_ids"], "attention_mask": s["attention_mask"]} |
| 66 | + for s in samples |
| 67 | + ], |
| 68 | + padding=True, |
| 69 | + max_length=self.max_length, |
| 70 | + return_tensors="pt", |
| 71 | + ) |
| 72 | + |
| 73 | + dim = padded["input_ids"].shape[-1] |
| 74 | + label_masks = torch.stack( |
| 75 | + [ |
| 76 | + F.pad( |
| 77 | + torch.tensor(s["label_mask"]), |
| 78 | + (0, dim - len(s["label_mask"])), |
| 79 | + value=False, |
| 80 | + ) |
| 81 | + for s in samples |
| 82 | + ] |
| 83 | + ) |
| 84 | + |
| 85 | + # Build labels: copy input_ids shifted by 1, masked with -100 for prompt tokens |
| 86 | + labels = padded["input_ids"].clone() |
| 87 | + labels[~label_masks] = -100 |
| 88 | + |
| 89 | + return { |
| 90 | + "input_ids": padded["input_ids"], |
| 91 | + "attention_mask": padded["attention_mask"], |
| 92 | + "labels": labels, |
| 93 | + } |
| 94 | + |
| 95 | + def __call__(self, batches: List[Dict]): |
| 96 | + chosen_samples = [] |
| 97 | + rejected_samples = [] |
| 98 | + |
| 99 | + for sample in batches: |
| 100 | + chosen_samples.append( |
| 101 | + self._tokenize_pair(sample["prompt"], sample["chosen"]) |
| 102 | + ) |
| 103 | + rejected_samples.append( |
| 104 | + self._tokenize_pair(sample["prompt"], sample["rejected"]) |
| 105 | + ) |
| 106 | + |
| 107 | + chosen_batch = self._pad_and_stack(chosen_samples) |
| 108 | + rejected_batch = self._pad_and_stack(rejected_samples) |
| 109 | + |
| 110 | + return { |
| 111 | + "chosen_input_ids": chosen_batch["input_ids"], |
| 112 | + "chosen_attention_mask": chosen_batch["attention_mask"], |
| 113 | + "chosen_labels": chosen_batch["labels"], |
| 114 | + "rejected_input_ids": rejected_batch["input_ids"], |
| 115 | + "rejected_attention_mask": rejected_batch["attention_mask"], |
| 116 | + "rejected_labels": rejected_batch["labels"], |
| 117 | + } |
0 commit comments