-
Notifications
You must be signed in to change notification settings - Fork 7
/
dataloader.py
206 lines (165 loc) · 7.71 KB
/
dataloader.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
from PIL import Image
import clip
import webdataset as wds
from torch.utils.data import DataLoader, Dataset
import io
import random
import argparse
import pandas as pd
from tqdm import tqdm
import os
import time
import torch
from torchvision.utils import save_image
from torchvision.transforms import ToTensor, Compose
Image.MAX_IMAGE_PIXELS = None
def build_ordinary_dataset_dataloader(pub11_intermediate_path, pub11_img_dir, preproc, batch_size, num_worker):
class RS5MDataset(Dataset):
def __init__(self, img_dir, intermediate_path, transform):
self.metainfo = pd.read_csv(intermediate_path)
self.img_dir = img_dir
self.transform = transform
def __len__(self):
return len(self.metainfo)
def __getitem__(self, idx):
img_name = self.metainfo.iloc[idx, 0]
img_path = os.path.join(self.img_dir, img_name)
image = Image.open(img_path)
image = self.transform(image)
caption = self.metainfo.iloc[idx, 1]
return img_name, image, caption
val_dataset = RS5MDataset(pub11_img_dir, pub11_intermediate_path, preproc)
val_dataloader = DataLoader(
val_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=num_worker,
pin_memory=True,
)
return val_dataloader
def get_wds_loader(train_dir, val_dir, num_workers, batch_size, num_shuffle, preproc):
def byte_decode(x):
return x.decode("utf-8")
train_url = os.path.join(train_dir, "{pub11,rs3}-train-{0000..0031}.tar")
val_url = os.path.join(val_dir, "{pub11,rs3}-val-{0000..0031}.tar")
# train_url = os.path.join(train_dir, "pub11-train-{0000..0031}.tar")
# val_url = os.path.join(val_dir, "pub11-val-{0000..0031}.tar")
# train_url = os.path.join(train_dir, "rs3-train-{0000..0031}.tar")
# val_url = os.path.join(val_dir, "rs3-val-{0000..0031}.tar")
def my_decoder(key, value):
if key.endswith(".img_content"):
assert isinstance(value, bytes)
value = Image.open(io.BytesIO(value))
value = preproc(value)
elif key.endswith(".img_name") or key.endswith(".caption"):
value = byte_decode(value)
return value
train_dataset = wds.WebDataset(train_url).shuffle(num_shuffle).decode(my_decoder)
train_dataloader = DataLoader(train_dataset, num_workers=num_workers, batch_size=batch_size)
val_dataset = wds.WebDataset(val_url).shuffle(num_shuffle).decode(my_decoder)
val_dataloader = DataLoader(val_dataset, num_workers=num_workers, batch_size=batch_size)
return train_dataloader, val_dataloader
def get_rs3_loader(val_dir, num_workers, batch_size, num_shuffle, preproc):
def byte_decode(x):
return x.decode("utf-8")
val_url = os.path.join(val_dir, "rs3-val-{0000..0031}.tar")
def my_decoder(key, value):
if key.endswith(".img_content"):
assert isinstance(value, bytes)
value = Image.open(io.BytesIO(value))
value = preproc(value)
elif key.endswith(".img_name") or key.endswith(".caption"):
value = byte_decode(value)
return value
val_dataset = wds.WebDataset(val_url).shuffle(num_shuffle).decode(my_decoder)
val_dataloader = DataLoader(val_dataset, num_workers=num_workers, batch_size=batch_size)
return val_dataloader
def run_wds_dataloader(train_dataloader, val_dataloader, num_worker, N_stop):
start = time.perf_counter()
total_batch_size = 0
for idx, items in enumerate(train_dataloader):
img_names, imgs, captions = items["img_name"], items["img_content"], items["caption"]
batch_size = len(img_names)
total_batch_size += batch_size
if total_batch_size > N_stop:
end = time.perf_counter()
time_cost = end - start
print(f"wds dataloader: num_workers={num_worker}, fps={total_batch_size / time_cost:.2f}")
break
def run_ordinary_dataset(ordinary_dataset_dataloader, num_worker, N_stop):
start = time.perf_counter()
total_batch_size = 0
for index, batch in tqdm(enumerate(ordinary_dataset_dataloader)):
names, image, caption = batch
batch_size = len(names)
total_batch_size += batch_size
if total_batch_size > N_stop:
end = time.perf_counter()
time_cost = end - start
print(f"ordinary dataloader: num_workers={num_worker}, fps={total_batch_size / time_cost:.2f}")
break
def dump_from_wds_dataloader(val_dataloader, num_worker, N_stop):
start = time.perf_counter()
name_list = []
caption_list = []
total_batch_size = 0
for idx, items in tqdm(enumerate(val_dataloader)):
img_names, imgs, captions = items["img_name"], items["img_content"], items["caption"]
batch_size = len(img_names)
total_batch_size += batch_size
name_list += img_names
caption_list += captions
for (name, img) in zip(img_names, imgs):
save_path = os.path.join("statics", name)
save_image(img, save_path)
if total_batch_size > N_stop:
end = time.perf_counter()
time_cost = end - start
df = pd.DataFrame({
"name": name_list,
"caption": caption_list
})
df.to_csv("rs3_dump.csv", index=False)
print(f"wds dataloader: num_workers={num_worker}, fps={total_batch_size / time_cost:.2f}")
break
def main():
random.seed(2023)
parser = argparse.ArgumentParser()
parser.add_argument("--train_dir", type=str,
default="/Volumes/Tipro7000/RS5M_v5/data/train",
help='RS5M webdataset train dir')
parser.add_argument("--val_dir", type=str,
default="/Volumes/Tipro7000/RS5M_v5/data/val",
help='RS5M webdataset val dir')
parser.add_argument("--pub11_intermediate_path", type=str,
default="/media/zilun/mx500/RS5M/tools/pub11_val_intermediate.csv",
help='pub11 intermediate file path')
parser.add_argument("--pub11_img_dir", type=str,
default="/home/zilun/RS5M_processing_v2/pub11_img/img",
help='pub11 image dir')
parser.add_argument("--num_worker", type=int,
default=20,
help='number of workers')
parser.add_argument("--batch_size", type=int,
default=400,
help='batch size')
parser.add_argument("--num_shuffle", type=int,
default=10000,
help='number of shuffle (for webdataset)')
args = parser.parse_args()
model, preprocess = clip.load("ViT-B/32", device="cpu", jit=False)
ordinary_dataset_dataloader = build_ordinary_dataset_dataloader(args.pub11_intermediate_path, args.pub11_img_dir,
preprocess, args.batch_size, args.num_worker)
run_ordinary_dataset(ordinary_dataset_dataloader, args.num_worker, N_stop=10000)
train_dataloader, val_dataloader = get_wds_loader(args.train_dir, args.val_dir, args.num_worker, args.batch_size,
args.num_shuffle, preprocess)
run_wds_dataloader(train_dataloader, val_dataloader, args.num_worker, N_stop=10000)
# # Uncomment if you want to dump data for visualization
# dump_preprocess = Compose(
# [ToTensor()]
# )
# rs3_val_dataloader = get_rs3_loader(args.val_dir, 0, 1, args.num_shuffle, dump_preprocess)
# os.makedirs("statics", exist_ok=True)
# dump_from_wds_dataloader(rs3_val_dataloader, 0, N_stop=10000)
if __name__ == "__main__":
main()