|
| 1 | +from typing import Iterable, Dict, List, Union, Any, Callable |
| 2 | +from functools import partial |
| 3 | +from tqdm import tqdm |
| 4 | +from torch.utils.data import Dataset |
| 5 | +from torch.distributed import get_rank |
| 6 | +import torch |
| 7 | +import torch.nn.functional as F |
| 8 | + |
| 9 | + |
| 10 | +def zero_pad_sequences(sequences: List[torch.Tensor], side: str = "left", value: int = 0) -> torch.Tensor: |
| 11 | + assert side in ("left", "right") |
| 12 | + max_len = max(seq.size(-1) for seq in sequences) |
| 13 | + padded_sequences = [] |
| 14 | + for seq in sequences: |
| 15 | + pad_len = max_len - seq.size(-1) |
| 16 | + padding = (pad_len, 0) if side == "left" else (0, pad_len) |
| 17 | + padded_sequences.append(F.pad(seq, padding, value=value)) |
| 18 | + return torch.stack(padded_sequences, dim=0) |
| 19 | + |
| 20 | + |
| 21 | +class OfflineRLDataset(Dataset): |
| 22 | + """ |
| 23 | + Overview: |
| 24 | + PyTorch Dataset for OfflineRL LLM training like KTO and DPO. |
| 25 | + """ |
| 26 | + |
| 27 | + def __init__( |
| 28 | + self, |
| 29 | + dataset: Iterable[Dict], |
| 30 | + tokenizer, |
| 31 | + max_length: int, |
| 32 | + input_key: str = "input", |
| 33 | + output_key: str = "output", |
| 34 | + label_key: str = "label", |
| 35 | + apply_chat_template: bool = False, |
| 36 | + tokenizer_chat_template: str = None, |
| 37 | + input_template: str = None, |
| 38 | + num_processors: int = 8, |
| 39 | + parallel_load: bool = True |
| 40 | + ) -> None: |
| 41 | + super().__init__() |
| 42 | + self.tokenizer = tokenizer |
| 43 | + self.max_length = max_length |
| 44 | + |
| 45 | + if apply_chat_template: |
| 46 | + apply_chat_template = self.tokenizer.apply_chat_template |
| 47 | + if tokenizer_chat_template: |
| 48 | + self.tokenizer.chat_template = tokenizer_chat_template |
| 49 | + |
| 50 | + # Parallel loading datasets |
| 51 | + if parallel_load: |
| 52 | + preprocess_data_fn = partial( |
| 53 | + self._preprocess_data, |
| 54 | + input_template=input_template, |
| 55 | + input_key=input_key, |
| 56 | + output_key=output_key, |
| 57 | + label_key=label_key, |
| 58 | + apply_chat_template=apply_chat_template |
| 59 | + ) |
| 60 | + processed_dataset = dataset.map( |
| 61 | + preprocess_data_fn, remove_columns=dataset.column_names, num_proc=num_processors |
| 62 | + ) |
| 63 | + # preprocess function may return None, so filter out the None |
| 64 | + processed_dataset = processed_dataset.filter(lambda x: x["prompt"] is not None) |
| 65 | + |
| 66 | + self.prompts = processed_dataset["prompt"] |
| 67 | + self.responses = processed_dataset["response"] |
| 68 | + self.labels = processed_dataset["label"] |
| 69 | + self.prompt_ids_lens = processed_dataset["prompt_ids_len"] |
| 70 | + else: |
| 71 | + self.prompts = [] |
| 72 | + self.responses = [] |
| 73 | + self.labels = [] |
| 74 | + self.prompt_ids_lens = [] |
| 75 | + for data in tqdm(dataset, desc="Preprocessing data", disable=not get_rank() == 0): |
| 76 | + processed_data = self._preprocess_data(data) |
| 77 | + if processed_data["prompt"] is not None: |
| 78 | + self.prompts.append(processed_data["prompt"]) |
| 79 | + self.responses.append(processed_data["response"]) |
| 80 | + self.labels.append(processed_data["label"]) |
| 81 | + self.prompt_ids_lens.append(processed_data["prompt_ids_len"]) |
| 82 | + |
| 83 | + def _preprocess_data( |
| 84 | + self, |
| 85 | + data: Dict[str, Any], |
| 86 | + input_template: str = None, |
| 87 | + input_key: str = "input", |
| 88 | + output_key: str = "output", |
| 89 | + label_key: str = "label", |
| 90 | + apply_chat_template: Union[bool, Callable] = False, |
| 91 | + ) -> str: |
| 92 | + label = data[label_key] |
| 93 | + |
| 94 | + if apply_chat_template: |
| 95 | + if output_key: |
| 96 | + prompt = apply_chat_template(data[input_key], tokenize=False, add_generation_prompt=True) |
| 97 | + response = apply_chat_template(data[input_key] + data[output_key], tokenize=False)[len(prompt):] |
| 98 | + else: |
| 99 | + prompt = apply_chat_template(data[input_key][:-1], tokenize=False, add_generation_prompt=True) |
| 100 | + response = apply_chat_template(data[input_key], tokenize=False)[len(prompt):] |
| 101 | + else: |
| 102 | + prompt = data[input_key] |
| 103 | + response = data[output_key] |
| 104 | + if input_template: |
| 105 | + prompt = input_template.format(prompt) |
| 106 | + |
| 107 | + prompt_token = self.tokenizer( |
| 108 | + prompt, |
| 109 | + max_length=self.max_length, |
| 110 | + # use the batch max length (in `collate_fn`) to pad rather than the global max length |
| 111 | + padding=False, |
| 112 | + truncation=True, |
| 113 | + return_tensors="pt", |
| 114 | + # add special tokens for the prompt in `collate_fn` |
| 115 | + add_special_tokens=False, |
| 116 | + ) |
| 117 | + prompt_ids_len = prompt_token["attention_mask"].int().sum().item() |
| 118 | + |
| 119 | + # filter the sample whose length is greater than max_length (2 for answer length) |
| 120 | + if prompt_ids_len >= self.max_length - 2: |
| 121 | + prompt = None |
| 122 | + |
| 123 | + return {"prompt": prompt, "response": response, "label": label, "prompt_ids_len": prompt_ids_len} |
| 124 | + |
| 125 | + def __len__(self) -> int: |
| 126 | + """ |
| 127 | + Overview: |
| 128 | + Get the length of the dataset. |
| 129 | + Returns: |
| 130 | + - length (int): The length of the dataset. |
| 131 | + """ |
| 132 | + return len(self.prompts) |
| 133 | + |
| 134 | + def __getitem__(self, idx: int) -> Dict[str, Union[torch.Tensor, int]]: |
| 135 | + """ |
| 136 | + Overview: |
| 137 | + Get the item at the given index. |
| 138 | + Returns: |
| 139 | + - item (Dict[str, Union[torch.Tensor, int]]): The item at the given index. |
| 140 | + """ |
| 141 | + return { |
| 142 | + "prompt": self.prompts[idx], |
| 143 | + "response": self.responses[idx], |
| 144 | + "label": self.labels[idx], |
| 145 | + "prompt_ids_len": self.prompt_ids_lens[idx] |
| 146 | + } |
| 147 | + |
| 148 | + def collate_fn(self, item_list: List[Dict[str, Union[torch.Tensor, int]]]): |
| 149 | + |
| 150 | + def tokenizer(prompt: str, response: str): |
| 151 | + text = (prompt + response).rstrip("\n") |
| 152 | + if not text.endswith(self.tokenizer.eos_token): |
| 153 | + text += " " + self.tokenizer.eos_token |
| 154 | + inputs = self.tokenizer( |
| 155 | + text, |
| 156 | + max_length=self.max_length, |
| 157 | + padding=False, |
| 158 | + truncation=True, |
| 159 | + return_tensors="pt", |
| 160 | + add_special_tokens=False, |
| 161 | + ) |
| 162 | + |
| 163 | + inputs["input_ids"][0][-1] = self.tokenizer.eos_token_id |
| 164 | + inputs["attention_mask"][0][-1] = True |
| 165 | + return inputs["input_ids"], inputs["attention_mask"] |
| 166 | + |
| 167 | + tot_ids, tot_masks, tot_labels, prompt_ids_lens = [], [], [], [] |
| 168 | + for item in item_list: |
| 169 | + input_ids, attention_mask = tokenizer(item["prompt"], item["response"]) |
| 170 | + tot_ids.append(input_ids) |
| 171 | + tot_masks.append(attention_mask) |
| 172 | + tot_labels.append(item["label"]) |
| 173 | + prompt_ids_lens.append(item["prompt_ids_len"]) |
| 174 | + |
| 175 | + # add unmatched y'| x (used to estimate the KL divergence between policy and reference) |
| 176 | + for idx in range(len(item_list)): |
| 177 | + next_idx = (idx + 1) % len(item_list) |
| 178 | + input_ids, attention_mask = tokenizer(item_list[idx]["prompt"], item_list[next_idx]["response"]) |
| 179 | + tot_ids.append(input_ids) |
| 180 | + tot_masks.append(attention_mask) |
| 181 | + tot_labels.append(-1) |
| 182 | + prompt_ids_lens.append(item_list[idx]["prompt_ids_len"]) |
| 183 | + |
| 184 | + input_ids = zero_pad_sequences(tot_ids, side="right", value=self.tokenizer.pad_token_id) |
| 185 | + attention_mask = zero_pad_sequences(tot_masks, side="right") |
| 186 | + return input_ids, attention_mask, torch.LongTensor(tot_labels), prompt_ids_lens |
0 commit comments