|
| 1 | +import torch |
| 2 | +import yaml |
| 3 | +from torch.utils.data import Dataset |
| 4 | +from PIL import Image |
| 5 | +import json |
| 6 | +import llama.utils |
| 7 | +from llama import Tokenizer |
| 8 | +import copy |
| 9 | +import torchvision.transforms as transforms |
| 10 | +import pandas as pd |
| 11 | +import random |
| 12 | +import cv2 |
| 13 | + |
| 14 | +try: |
| 15 | + from torchvision.transforms import InterpolationMode |
| 16 | + BICUBIC = InterpolationMode.BICUBIC |
| 17 | +except ImportError: |
| 18 | + BICUBIC = Image.BICUBIC |
| 19 | + |
| 20 | + |
| 21 | +PROMPT_DICT = { |
| 22 | + "prompt_input": ( |
| 23 | + "Below is an instruction that describes a task, paired with an input that provides further context. " |
| 24 | + "Write a response that appropriately completes the request.\n\n" |
| 25 | + "### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:" |
| 26 | + ), |
| 27 | + "prompt_no_input": ( |
| 28 | + "Below is an instruction that describes a task. " |
| 29 | + "Write a response that appropriately completes the request.\n\n" |
| 30 | + "### Instruction:\n{instruction}\n\n### Response:" |
| 31 | + ), |
| 32 | +} |
| 33 | + |
| 34 | +# create data |
| 35 | +transform_train = transforms.Compose([ |
| 36 | + transforms.RandomResizedCrop(size=(224, 224), scale=(0.9, 1.0), ratio=(0.75, 1.3333), interpolation=BICUBIC, |
| 37 | + antialias=None), # 3 is bicubic |
| 38 | + transforms.ToTensor(), |
| 39 | + transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711])]) |
| 40 | + |
| 41 | +class FinetuneDataset(Dataset): |
| 42 | + def __init__(self, config_path, transform, max_words=30, tokenizer_path=None): |
| 43 | + print(f"read dataset config from {config_path}") |
| 44 | + with open(config_path, 'r') as f: |
| 45 | + self.config = yaml.load(f, Loader=yaml.FullLoader) |
| 46 | + print("DATASET CONFIG:") |
| 47 | + print(self.config) |
| 48 | + ann = [] |
| 49 | + for meta_path in self.config['META']: |
| 50 | + meta_l = json.load(open(meta_path)) |
| 51 | + print(f"{meta_path}: len {len(meta_l)}") |
| 52 | + ann += meta_l |
| 53 | + self.ann = ann |
| 54 | + print(f"total length: {len(self)}") |
| 55 | + self.transform = transform |
| 56 | + self.max_words = max_words |
| 57 | + self.tokenizer = Tokenizer(model_path=tokenizer_path) |
| 58 | + |
| 59 | + def __len__(self): |
| 60 | + return len(self.ann) |
| 61 | + |
| 62 | + def __getitem__(self, index): |
| 63 | + data_item = self.ann[index] |
| 64 | + if 'image' in data_item.keys(): |
| 65 | + filename = data_item['image'] |
| 66 | + question = data_item['conversations'][0]['value'] |
| 67 | + answer = data_item['conversations'][1]['value'] |
| 68 | + |
| 69 | + image = cv2.imread(filename) |
| 70 | + image = Image.fromarray(image) |
| 71 | + image = self.transform(image) |
| 72 | + format_instruction = question |
| 73 | + format_input = None |
| 74 | + else: |
| 75 | + image = torch.zeros(3, 224, 224) |
| 76 | + format_instruction = data_item['instruction'], |
| 77 | + format_input = data_item['input'] |
| 78 | + answer = data_item['output'] |
| 79 | + input1 = llama.utils.format_prompt(format_instruction, format_input) |
| 80 | + input2 = input1 + answer |
| 81 | + input1 = torch.tensor(self.tokenizer.encode(input1, bos=True, eos=False), dtype=torch.int64) |
| 82 | + input2 = torch.tensor(self.tokenizer.encode(input2, bos=True, eos=True), dtype=torch.int64) |
| 83 | + padding = self.max_words - input2.shape[0] |
| 84 | + if padding > 0: |
| 85 | + input2 = torch.cat((input2, torch.zeros(padding, dtype=torch.int64) - 1)) |
| 86 | + elif padding < 0: |
| 87 | + input2 = input2[:self.max_words] |
| 88 | + labels = copy.deepcopy(input2) |
| 89 | + labels[:len(input1)] = -1 |
| 90 | + input2_mask = input2.ge(0) |
| 91 | + label_mask = labels.ge(0) |
| 92 | + input2[~input2_mask] = 0 |
| 93 | + labels[~label_mask] = 0 |
| 94 | + input2_mask = input2_mask.float() |
| 95 | + label_mask = label_mask.float() |
| 96 | + return input2, labels, input2_mask, image |
| 97 | + |
| 98 | + |
| 99 | +class PretrainDataset(Dataset): |
| 100 | + def __init__(self, config_path, transform, max_words=30, tokenizer_path=None): |
| 101 | + print(f"read dataset config from {config_path}") |
| 102 | + with open(config_path, 'r') as f: |
| 103 | + self.config = yaml.load(f, Loader=yaml.FullLoader) |
| 104 | + print("DATASET CONFIG:") |
| 105 | + print(self.config) |
| 106 | + images, captions = [], [] |
| 107 | + for meta_path in self.config['META']: |
| 108 | + images_this_meta, captions_this_meta = [], [] |
| 109 | + for chunk in pd.read_csv(meta_path, sep='\t', lineterminator='\n', chunksize=10 ** 6): |
| 110 | + images_this_meta.extend(chunk['url'].tolist()) |
| 111 | + captions_this_meta.extend(chunk['caption'].tolist()) |
| 112 | + print(f"{meta_path}: len {len(images_this_meta)}") |
| 113 | + images.extend(images_this_meta) |
| 114 | + captions.extend(captions_this_meta) |
| 115 | + |
| 116 | + self.data_list = [] |
| 117 | + for x, y in zip(images, captions): |
| 118 | + self.data_list.append({'url': x, 'caption': y}) |
| 119 | + print(f"total length: {len(self)}") |
| 120 | + self.transform = transform |
| 121 | + self.max_words = max_words |
| 122 | + self.tokenizer = Tokenizer(model_path=tokenizer_path) |
| 123 | + |
| 124 | + def __len__(self): |
| 125 | + return len(self.data_list) |
| 126 | + |
| 127 | + def __getitem__(self, index): |
| 128 | + sample = self.data_list[index] |
| 129 | + image_path, caption = sample['url'], sample['caption'] |
| 130 | + if isinstance(caption, list): |
| 131 | + caption = random.choice(caption) |
| 132 | + caption = str(caption) |
| 133 | + |
| 134 | + image = cv2.imread(image_path) |
| 135 | + image = Image.fromarray(image) |
| 136 | + image = self.transform(image) |
| 137 | + |
| 138 | + format_instruction = "Generate caption of this image" |
| 139 | + input1 = llama.utils.format_prompt(format_instruction, None) |
| 140 | + input2 = input1 + caption |
| 141 | + |
| 142 | + input1 = torch.tensor(self.tokenizer.encode(input1, bos=True, eos=False), dtype=torch.int64) |
| 143 | + input2 = torch.tensor(self.tokenizer.encode(input2, bos=True, eos=True), dtype=torch.int64) |
| 144 | + padding = self.max_words - input2.shape[0] |
| 145 | + if padding > 0: |
| 146 | + input2 = torch.cat((input2, torch.zeros(padding, dtype=torch.int64) - 1)) |
| 147 | + elif padding < 0: |
| 148 | + input2 = input2[:self.max_words] |
| 149 | + labels = copy.deepcopy(input2) |
| 150 | + labels[:len(input1)] = -1 |
| 151 | + input2_mask = input2.ge(0) |
| 152 | + label_mask = labels.ge(0) |
| 153 | + input2[~input2_mask] = 0 |
| 154 | + labels[~label_mask] = 0 |
| 155 | + input2_mask = input2_mask.float() |
| 156 | + label_mask = label_mask.float() |
| 157 | + return input2, labels, input2_mask, image |
0 commit comments