-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_generator.py
188 lines (165 loc) · 6.46 KB
/
data_generator.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
import h5py
import numpy as np
from PIL import Image as PIL_Image
import torchvision
import torch
import argparse
from argparse import Namespace
from torch.nn.parameter import Parameter
from time import time
from data.coco_dataset import CocoDatasetKarpathy
torch.autograd.set_detect_anomaly(False)
torch.set_num_threads(1)
torch.set_num_interop_threads(1)
import functools
print = functools.partial(print, flush=True)
DEFAULT_RANK = 0
def convert_time_as_hhmmss(ticks):
return str(int(ticks / 60)) + " m " + str(int(ticks) % 60) + " s"
def generate_data(path_args):
coco_dataset = CocoDatasetKarpathy(
images_path=path_args.images_path,
coco_annotations_path=args.captions_path + "dataset_coco.json",
train2014_bboxes_path=args.captions_path + "train2014_instances.json",
val2014_bboxes_path=args.captions_path + "val2014_instances.json",
preproc_images_hdf5_filepath=None,
precalc_features_hdf5_filepath=None,
limited_num_train_images=None,
limited_num_val_images=5000,
)
from models.swin_transformer_mod import SwinTransformer
model = SwinTransformer(
img_size=384,
patch_size=4,
in_chans=3,
embed_dim=192,
depths=[2, 2, 18, 2],
num_heads=[6, 12, 24, 48],
window_size=12,
mlp_ratio=4.0,
qkv_bias=True,
qk_scale=None,
drop_rate=0.0,
attn_drop_rate=0.0,
drop_path_rate=0.0,
norm_layer=torch.nn.LayerNorm,
ape=False,
patch_norm=True,
use_checkpoint=False,
)
def load_backbone_only_from_save(model, state_dict, prefix=None):
own_state = model.state_dict()
for name, param in state_dict.items():
if prefix is not None and name.startswith(prefix):
name = name[len(prefix) :]
if name not in own_state:
print("Not found: " + str(name))
continue
if isinstance(param, Parameter):
param = param.data
own_state[name].copy_(param)
print("Found: " + str(name))
save_model_path = path_args.save_model_path
map_location = {"cuda:%d" % DEFAULT_RANK: "cuda:%d" % DEFAULT_RANK}
checkpoint = torch.load(save_model_path, map_location=map_location)
if "model_state_dict" in checkpoint.keys():
print("Custom save point found")
load_backbone_only_from_save(
model, checkpoint["model_state_dict"], prefix="swin_transf."
)
else:
print("Custom save point not found")
load_backbone_only_from_save(model, checkpoint["model"], prefix=None)
print("Loading phase ended")
model = model.to(DEFAULT_RANK)
test_preprocess_layers_1 = [torchvision.transforms.Resize((384, 384))]
test_preprocess_layers_2 = [
torchvision.transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
]
test_preprocess_1 = torchvision.transforms.Compose(test_preprocess_layers_1)
test_preprocess_2 = torchvision.transforms.Compose(test_preprocess_layers_2)
model.eval()
with torch.no_grad():
hdf5_file = h5py.File(path_args.output_path, "w")
def apply_model(model, file_path):
pil_image = PIL_Image.open(file_path)
if pil_image.mode != "RGB":
pil_image = PIL_Image.new("RGB", pil_image.size)
preprocess_pil_image = test_preprocess_1(pil_image)
tens_image = torchvision.transforms.ToTensor()(preprocess_pil_image)
tens_image = test_preprocess_2(tens_image).to(DEFAULT_RANK)
output = model(tens_image.unsqueeze(0))
return output.squeeze(0)
for i in range(coco_dataset.train_num_images):
img_path, img_id = coco_dataset.get_image_path(
coco_dataset.train_num_images - i - 1, CocoDatasetKarpathy.TrainSet_ID
)
output = apply_model(model, img_path)
hdf5_file.create_dataset(
str(img_id) + "_features", data=np.array(output.cpu())
)
if (i + 1) % 5000 == 0 or (i + 1) == coco_dataset.train_num_images:
print(
"Train "
+ str(i + 1)
+ " / "
+ str(coco_dataset.train_num_images)
+ " completed"
)
for i in range(coco_dataset.test_num_images):
img_path, img_id = coco_dataset.get_image_path(
i, CocoDatasetKarpathy.TestSet_ID
)
output = apply_model(model, img_path)
hdf5_file.create_dataset(
str(img_id) + "_features", data=np.array(output.cpu())
)
if (i + 1) % 2500 == 0 or (i + 1) == coco_dataset.test_num_images:
print(
"Test "
+ str(i + 1)
+ " / "
+ str(coco_dataset.test_num_images)
+ " completed"
)
for i in range(coco_dataset.val_num_images):
img_path, img_id = coco_dataset.get_image_path(
i, CocoDatasetKarpathy.ValidationSet_ID
)
output = apply_model(model, img_path)
hdf5_file.create_dataset(
str(img_id) + "_features", data=np.array(output.cpu())
)
if (i + 1) % 2500 == 0 or (i + 1) == coco_dataset.test_num_images:
print(
"Val "
+ str(i + 1)
+ " / "
+ str(coco_dataset.test_num_images)
+ " completed"
)
print("[GPU: " + str(DEFAULT_RANK) + " ] Closing...")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Image Captioning")
parser.add_argument(
"--save_model_path", type=str, default="./github_ignore_material/saves/"
)
parser.add_argument(
"--output_path",
type=str,
default="./github_ignore_material/raw_data/precalc_features.hdf5",
)
parser.add_argument("--images_path", type=str, default="/tmp/images/")
parser.add_argument(
"--captions_path", type=str, default="./github_ignore_material/raw_data/"
)
args = parser.parse_args()
path_args = Namespace(
save_model_path=args.save_model_path,
output_path=args.output_path,
images_path=args.images_path,
captions_path=args.captions_path,
)
generate_data(path_args=path_args)