1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
| class LazySupervisedDataset(Dataset): """Dataset for supervised fine-tuning."""
def __init__(self, dataset_use, image_processor, tokenizer, chat_template, default_system_message): super(LazySupervisedDataset, self).__init__() dataset_names = dataset_use.split(",") dataset_config_list = get_dataset_config_list(dataset_names) list_data_dict = load_datasets(dataset_config_list)
self.list_data_dict = list_data_dict self.image_processor = image_processor self.tokenizer = copy.deepcopy(tokenizer) self.tokenizer.chat_template = chat_template self.default_system_message = default_system_message self.get_rope_index = get_rope_index_25
def __len__(self): return len(self.list_data_dict)
def __getitem__(self, idx): num_base_retries = 3 for attempt_idx in range(num_base_retries): try: sample = self._get_item(idx) return sample except Exception as e: print(f"[Try #{attempt_idx}] Failed to fetch sample {idx}. Exception:", e) for attempt_idx in range(num_base_retries): try: next_index = (idx + 1) % len(self.list_data_dict) sample = self._get_item(next_index) return sample except Exception as e: print(f"[Try other #{attempt_idx}] Failed to fetch sample {next_index}. Exception:", e,) try: sample = self._get_item(idx) return sample except Exception as e: raise e def process_single_image(self, image_file:str): image = Image.open(image_file).convert("RGB") visual_processed = self.image_processor.preprocess(image, return_tensors="pt") image_tensor = visual_processed["pixel_values"] if isinstance(image_tensor, List): image_tensor = image_tensor[0] grid_thw = visual_processed["image_grid_thw"][0] return image_tensor, grid_thw
def preprocess_qwen_2_visual(self, chat_sources, image_grid_thw_merged:List = [], video_grid_thw_merged:List = []): while not ( (chat_sources[0]['role'] == 'user') or (len(chat_sources) >=2 and chat_sources[0]['role'] == 'system' and chat_sources[1]['role'] == 'user') ): chat_sources = chat_sources[1:]
if chat_sources[0]['role'] == 'system': assert len(chat_sources) % 2 == 1, "user messages and assistant messages must be paired." for i in range(1, len(chat_sources), 2): assert (chat_sources[i]['role'] == 'user' and chat_sources[i + 1]['role'] == 'assistant'), "user messages and assistant messages must be paired." else: assert len(chat_sources) % 2 == 0, "user messages and assistant messages must be paired." for i in range(0, len(chat_sources), 2): assert (chat_sources[i]['role'] == 'user' and chat_sources[i + 1]['role'] == 'assistant'), "user messages and assistant messages must be paired." chat_sources = [{"role": "system", "content": self.default_system_message}] + chat_sources visual_replicate_index_image = 0 IGNORE_INDEX = -100 input_id, target = [], []
for conv in chat_sources:
role = conv['role'] content = conv['content']
if role == 'user':
if '<image>' in content: parts = content.split('<image>') num_parts = len(parts) new_parts = [] for i in range(num_parts): new_parts.append(parts[i]) if i != num_parts - 1: image_tokens = ( "<|vision_start|>" + "<|image_pad|>" * image_grid_thw_merged[visual_replicate_index_image] + "<|vision_end|>" ) visual_replicate_index_image += 1 new_parts.append(image_tokens)
content = "".join(new_parts)
elif '<video>' in content: pass else: pass
text_conv = [{"role": role, "content": content}] encode_id = self.tokenizer.apply_chat_template(text_conv) input_id += encode_id if role in ["user", "system"]: target += [IGNORE_INDEX] * len(encode_id) else: target_mask = encode_id.copy() target_mask[:3] = [IGNORE_INDEX] * 3 target += target_mask
assert len(input_id) == len(target), \ f"input_id length ({len(input_id)}) != target length ({len(target)})" assert visual_replicate_index_image == len(image_grid_thw_merged), \ f"visual_replicate_index_image ({visual_replicate_index_image}) != len(image_grid_thw_merged) ({len(image_grid_thw_merged)})"
input_ids = torch.tensor([input_id], dtype=torch.long) labels = torch.tensor([target], dtype=torch.long)
return dict( input_ids=input_ids, labels=labels, )
def _get_item(self, idx):
source = self.list_data_dict[idx]
image_grid_thw_merged = [] image_grid_thw_list = [] video_grid_thw_merged = [] video_grid_thw_list = []
if "image" in source: image_folder = source["data_path"] image_file = source["image"] if not isinstance(image_file, List): image_file = [image_file] image_file = [ os.path.join(image_folder, file) for file in image_file ] results = [ self.process_single_image(file) for file in image_file ] image_list, image_grid_thw_list = zip(*results)
image_grid_thw_merged = copy.deepcopy(image_grid_thw_list) image_grid_thw_merged = [ grid_thw.prod() // image_processor.merge_size ** 2 for grid_thw in image_grid_thw_merged ]
if "video" in source: raise NotImplementedError("video is not supported yet") chat_sources = copy.deepcopy(source["conversations"])
if "image" not in source and "video" not in source:
data_dict = self.preprocess_qwen_2_visual( chat_sources, image_grid_thw_merged=[] ) position_ids = ( torch.arange(0, data_dict["input_ids"].size(1)) .view(1, -1) .unsqueeze(0) .expand(3, -1, -1) ) else: data_dict = self.preprocess_qwen_2_visual( chat_sources, image_grid_thw_merged=image_grid_thw_merged if "image" in source else [], video_grid_thw_merged=video_grid_thw_merged if "video" in source else [] )
position_ids, _ = self.get_rope_index( image_processor.merge_size, data_dict["input_ids"], image_grid_thw=torch.stack(image_grid_thw_list, dim=0) if image_grid_thw_list else None, video_grid_thw=None, )
data_dict["position_ids"] = position_ids data_dict["attention_mask"] = torch.ones_like(data_dict["input_ids"], dtype=torch.int) if "image" in source: data_dict["pixel_values"] = torch.cat(image_list, dim=0) data_dict["image_grid_thw"] = torch.cat( [thw.unsqueeze(0) for thw in image_grid_thw_list], dim=0 ) elif "video" in self.list_data_dict[i]: raise NotImplementedError("video is not supported yet")
return data_dict
def pad_and_cat(tensor_list): max_length = max(tensor.shape[2] for tensor in tensor_list)
padded_tensors = [] for tensor in tensor_list: pad_length = max_length - tensor.shape[2] padded_tensor = torch.nn.functional.pad(tensor, (0, pad_length), "constant", 1) padded_tensors.append(padded_tensor)
stacked_tensor = torch.cat(padded_tensors, dim=1)
return stacked_tensor
@dataclass class DataCollatorForSupervisedDataset(object):
tokenizer: PreTrainedTokenizer
def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
input_ids, labels, position_ids, attention_masks = tuple( [instance[key] for instance in instances] for key in ("input_ids", "labels", "position_ids", "attention_mask") ) input_ids = [ids.squeeze(0) for ids in input_ids] labels = [ids.squeeze(0) for ids in labels] attention_masks = [ids.squeeze(0) for ids in attention_masks] input_ids = pad_sequence( input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id ) labels = pad_sequence( labels, batch_first=True, padding_value=-100 ) attention_masks = pad_sequence( attention_masks, batch_first=True, padding_value=0 ) position_ids = pad_and_cat(position_ids)
input_ids = input_ids[:, : self.tokenizer.model_max_length] labels = labels[:, : self.tokenizer.model_max_length] position_ids = position_ids[:, : self.tokenizer.model_max_length] attention_masks = attention_masks[:, : self.tokenizer.model_max_length] batch = dict( input_ids=input_ids, labels=labels, position_ids=position_ids, attention_mask=attention_masks, )
images = list( instance["pixel_values"] for instance in instances if "pixel_values" in instance ) if len(images) != 0: concat_images = torch.cat([image for image in images], dim=0) grid_thw = [ instance["image_grid_thw"] for instance in instances if "image_grid_thw" in instance ] grid_thw = torch.cat(grid_thw, dim=0) else: concat_images = None grid_thw = None
videos = list( instance["pixel_values_videos"] for instance in instances if "pixel_values_videos" in instance ) if len(videos) != 0: raise NotImplementedError("video is not supported yet") else: concat_videos = None video_grid_thw = None
batch["pixel_values"] = concat_images batch["image_grid_thw"] = grid_thw batch["pixel_values_videos"] = concat_videos batch["video_grid_thw"] = video_grid_thw return batch
|