MCPcopy Create free account
hub / github.com/AMAP-ML/EMF / DataCollatorForSupervisedDataset

Class DataCollatorForSupervisedDataset

blip3o/data/dataset.py:355–393  ·  view source on GitHub ↗

Collate examples for supervised fine-tuning.

Source from the content-addressed store, hash-verified

353
354@dataclass
355class DataCollatorForSupervisedDataset(object):
356 """Collate examples for supervised fine-tuning."""
357
358 tokenizer: transformers.PreTrainedTokenizer
359
360 def pad_sequence(self, input_ids, batch_first, padding_value):
361 if self.tokenizer.padding_side == "left":
362 input_ids = [torch.flip(_input_ids, [0]) for _input_ids in input_ids]
363 input_ids = torch.nn.utils.rnn.pad_sequence(input_ids, batch_first=batch_first, padding_value=padding_value)
364 if self.tokenizer.padding_side == "left":
365 input_ids = torch.flip(input_ids, [1])
366 return input_ids
367
368 def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
369 input_ids, labels = tuple([instance[key] for instance in instances] for key in ("input_ids", "labels"))
370 input_ids = [_input_ids[: self.tokenizer.model_max_length] for _input_ids in input_ids]
371 labels = [_labels[: self.tokenizer.model_max_length] for _labels in labels]
372 if self.tokenizer.pad_token_id is None:
373 self.tokenizer.pad_token_id = 0 # This gets the best result. Don't know why.
374 input_ids = self.pad_sequence(input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id)
375 labels = self.pad_sequence(labels, batch_first=True, padding_value=IGNORE_INDEX)
376 batch = dict(input_ids=input_ids, labels=labels.long() if labels.dtype == torch.int32 else labels, attention_mask=input_ids.ne(self.tokenizer.pad_token_id))
377 if "image" in instances[0]:
378 images = [instance["image"] for instance in instances]
379
380 batch["image_sizes"] = [im[1] for im_list in images for im in im_list]
381 batch["modalities"] = [im[2] for im_list in images for im in im_list]
382 images = [im[0] for im_list in images for im in im_list]
383
384 batch["images"] = images
385
386 target_images = [instance["target_image"][0] for instance in instances]
387 target_images = torch.stack(target_images, dim=0) if target_images else None
388 batch["target_images"] = target_images
389
390
391 if "prompt" in instances[0]:
392 batch["prompts"] = [instance["prompt"] for instance in instances]
393 return batch
394
395def get_dataset_cls(name):
396

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected