-
Notifications
You must be signed in to change notification settings - Fork 32
/
dataset.py
54 lines (40 loc) · 1.53 KB
/
dataset.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
'''
Module contains Dataset class, collate function for DataLoader and loader getter function.
* MiniFlickrDataset loads data from pickle file and returns image embedding and caption.
* cl_fn is used to process batch of data and return tensors.
* get_loader returns DataLoader object.
'''
import pickle
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from transformers import GPT2Tokenizer
class MiniFlickrDataset(Dataset):
def __init__(self, path):
with open(path, 'rb') as f:
self.data = pickle.load(f)
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
return self.data[idx]
# collate_fn for DataLoader
def cl_fn(batch, tokenizer):
batch = list(zip(*batch))
_, img_emb, cap = batch
del batch
img_emb = torch.tensor(np.array(img_emb)) # better to convert list to numpy array first, then to tensor
cap = tokenizer(cap, padding=True, return_tensors='pt')
input_ids, attention_mask = cap['input_ids'], cap['attention_mask']
return img_emb, input_ids, attention_mask
def get_loader(dataset, bs_exp=5, shuffle=True, num_workers=0, pin_memory=False, sampler=None):
tokenizer = GPT2Tokenizer.from_pretrained('gpt2-xl')
tokenizer.pad_token = tokenizer.eos_token
return DataLoader(
dataset,
batch_size=2**bs_exp,
collate_fn=lambda b: cl_fn(b, tokenizer),
shuffle=shuffle,
num_workers=num_workers,
pin_memory=pin_memory,
sampler=sampler
)