forked from amazon-science/mm-cot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_data.py
228 lines (197 loc) · 7.83 KB
/
utils_data.py
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
import os
from torch.utils.data import Dataset
import os
import json
import numpy as np
import torch
from utils_prompt import *
img_shape = {
"resnet": (512, 2048),
"clip": (49, 2048),
"detr": (100, 256),
}
def load_data_std(args):
problems = json.load(open(os.path.join(args.data_root, 'scienceqa/problems.json')))
pid_splits = json.load(open(os.path.join(args.data_root, 'scienceqa/pid_splits.json')))
captions = json.load(open(args.caption_file))["captions"]
for qid in problems:
problems[qid]['caption'] = captions[qid] if qid in captions else ""
train_qids = pid_splits['%s' % (args.train_split)]
val_qids = pid_splits['%s' % (args.val_split)]
test_qids = pid_splits['%s' % (args.test_split)]
print(f"number of train problems: {len(train_qids)}\n")
print(f"number of val problems: {len(val_qids)}\n")
print(f"number of test problems: {len(test_qids)}\n")
qids = {'train': train_qids, 'val':val_qids,'test':test_qids}
return problems, qids,
def load_data_img(args):
problems = json.load(open(os.path.join(args.data_root, 'scienceqa/problems.json')))
pid_splits = json.load(open(os.path.join(args.data_root, 'scienceqa/pid_splits.json')))
captions = json.load(open(args.caption_file))["captions"]
name_maps = json.load(open('vision_features/name_map.json'))
# check
if args.img_type == "resnet":
image_features = np.load('vision_features/resnet.npy')
image_features = np.expand_dims(image_features, axis=1)
image_features = image_features.repeat(512, axis=1)
elif args.img_type == "clip":
image_features = np.load('vision_features/clip.npy')
elif args.img_type == "detr":
image_features = np.load('vision_features/detr.npy')
else:
image_features = np.load('vision_features/detr.npy')
print("img_features size: ", image_features.shape)
for qid in problems:
problems[qid]['caption'] = captions[qid] if qid in captions else ""
train_qids = pid_splits['%s' % (args.train_split)]
val_qids = pid_splits['%s' % (args.val_split)]
test_qids = pid_splits['%s' % (args.test_split)]
print(f"number of train problems: {len(train_qids)}\n")
print(f"number of val problems: {len(val_qids)}\n")
print(f"number of test problems: {len(test_qids)}\n")
qids = {'train': train_qids, 'val':val_qids,'test':test_qids}
return problems, qids, name_maps, image_features
class ScienceQADatasetStd(Dataset):
"""
Creating a custom dataset for reading the dataset and
loading it into the dataloader to pass it to the
neural network for finetuning the model
"""
def __init__(
self, problems, qids, tokenizer, source_len, target_len, args, test_le=None
):
self.tokenizer = tokenizer
self.data = {qid : problems[qid] for qid in qids}
self.source_len = source_len
self.summ_len = target_len
self.target_text = []
self.source_text = []
if test_le is not None:
test_le_data =json.load(open(test_le))["preds"]
else:
test_le_data = None
idx = 0
for qid in self.data:
if test_le_data is not None:
curr_le_data = test_le_data[idx]
idx += 1
else:
curr_le_data = None
prompt, target = build_train_pair(problems, qid, args, curr_le_data)
self.target_text.append(target)
self.source_text.append(prompt)
def __len__(self):
return len(self.target_text)
def __getitem__(self, index):
source_text = str(self.source_text[index])
target_text = str(self.target_text[index])
# cleaning data so as to ensure data is in string type
source_text = " ".join(source_text.split())
target_text = " ".join(target_text.split())
source = self.tokenizer.batch_encode_plus(
[source_text],
max_length=self.source_len,
pad_to_max_length=True,
truncation=True,
padding="max_length",
return_tensors="pt",
)
target = self.tokenizer.batch_encode_plus(
[target_text],
max_length=self.summ_len,
pad_to_max_length=True,
truncation=True,
padding="max_length",
return_tensors="pt",
)
source_ids = source["input_ids"].squeeze()
source_mask = source["attention_mask"].squeeze()
target_ids = target["input_ids"].squeeze().tolist()
return {
"input_ids": source_ids,
"attention_mask": source_mask,
"labels": target_ids,
}
class ScienceQADatasetImg(Dataset):
"""
Creating a custom dataset for reading the dataset and
loading it into the dataloader to pass it to the
neural network for finetuning the model
"""
def __init__(
self, problems, qids, name_maps, tokenizer, source_len, target_len, args, image_features, test_le=None
):
"""
Initializes a Dataset class
Args:
dataframe (pandas.DataFrame): Input dataframe
tokenizer (transformers.tokenizer): Transformers tokenizer
source_len (int): Max length of source text
target_len (int): Max length of target text
source_text (str): column name of source text
target_text (str): column name of target text
"""
self.tokenizer = tokenizer
self.data = {qid : problems[qid] for qid in qids}
self.source_len = source_len
self.summ_len = target_len
self.target_text = []
self.source_text = []
self.image_ids = []
if test_le is not None:
test_le_data =json.load(open(test_le))["preds"]
else:
test_le_data = None
idx = 0
for qid in self.data:
if test_le_data is not None:
curr_le_data = test_le_data[idx]
idx += 1
else:
curr_le_data = None
prompt, target = build_train_pair(problems, qid, args, curr_le_data)
self.target_text.append(target)
self.source_text.append(prompt)
if str(qid) in name_maps:
i_vectors = image_features[int(name_maps[str(qid)])]
self.image_ids.append(i_vectors)
else:
shape = img_shape[args.img_type]
self.image_ids.append(np.zeros(shape))
def __len__(self):
"""returns the length of dataframe"""
return len(self.target_text)
def __getitem__(self, index):
"""return the input ids, attention masks and target ids"""
source_text = str(self.source_text[index])
target_text = str(self.target_text[index])
image_ids = self.image_ids[index]
# cleaning data so as to ensure data is in string type
source_text = " ".join(source_text.split())
target_text = " ".join(target_text.split())
source = self.tokenizer.batch_encode_plus(
[source_text],
max_length=self.source_len,
pad_to_max_length=True,
truncation=True,
padding="max_length",
return_tensors="pt",
)
target = self.tokenizer.batch_encode_plus(
[target_text],
max_length=self.summ_len,
pad_to_max_length=True,
truncation=True,
padding="max_length",
return_tensors="pt",
)
source_ids = source["input_ids"].squeeze()
source_mask = source["attention_mask"].squeeze()
target_ids = target["input_ids"].squeeze().tolist()
image_ids = torch.tensor(image_ids).squeeze()
return {
"input_ids": source_ids,
"attention_mask": source_mask,
"image_ids": image_ids,
"labels": target_ids,
}