-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.py
270 lines (241 loc) · 9.44 KB
/
main.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import argparse
import json
import os
import random
from collections import defaultdict
from pathlib import Path
import numpy as np
import pandas
import torch
import torch.backends.cudnn as cudnn
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from imagenetv2_pytorch import ImageNetV2Dataset
from torchvision import transforms
import wandb
from inference.imagenet_x import run_imagenetx
from inference.invariance import run_invariance
from inference.pug_imagenet import run_pug_imagenet
from inference.robustness import run_robustness
from utils.misc import (ImageFolderWithPaths, get_world_size,
load_model_transform, resolve_name)
def get_args_parser():
parser = argparse.ArgumentParser("Beyond ImageNet accuracy")
parser.add_argument(
"--batch_size",
default=512,
type=int,
help="Batch size per GPU (effective batch size is batch_size * # gpus",
)
parser.add_argument("--model",
type=str,
metavar="MODEL",
help="name of model")
parser.add_argument("--experiment",
default="scale",
type=str,
help="Name of model to train")
parser.add_argument("--scale_factor", type=float, help="scale factor")
parser.add_argument("--shift_x", type=int, default=0, help="Shift X")
parser.add_argument("--shift_y", type=int, default=0, help="Shift Y")
parser.add_argument("--data_path",
type=str,
default="",
help="dataset path")
parser.add_argument("--pretrained_dir",
type=str,
default="pretrained",
help="pretrained directory")
parser.add_argument(
"--nb_classes",
default=1000,
type=int,
help="number of the classification types",
)
parser.add_argument("--image_size",
default=224,
type=int,
help="image size")
parser.add_argument(
"--output_dir",
default="./outputs",
help="path where to save, empty for no saving",
)
parser.add_argument("--device",
default="cuda",
help="device to use for training / testing")
parser.add_argument("--seed", default=0, type=int)
parser.add_argument("--num_workers", default=10, type=int)
parser.add_argument(
"--pin_mem",
action="store_true",
help=
"Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.",
)
parser.set_defaults(pin_mem=True)
parser.add_argument(
"--num_runs",
default=1,
type=int,
help="number of how many repeated runs of experiment",
)
parser.add_argument("--n_bins",
default=15,
type=int,
help="number of bins in ECE calculation")
parser.add_argument("--run_name", type=str, default="")
parser.add_argument("--dataset", type=str, default="")
parser.add_argument("--debug", action="store_true")
return parser
def main(args):
print("job dir: {}".format(os.path.dirname(os.path.realpath(__file__))))
print("{}".format(args).replace(", ", ",\n"))
device = torch.device(args.device)
seed = args.seed
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
cudnn.benchmark = True
model_name = None
transform_val = None
data_loader_val = None
model, transform_val = load_model_transform(args.model,
args.pretrained_dir,
args.image_size)
if transform_val is None:
transform_val = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
])
print(transform_val)
if args.experiment == "imagenetx" or args.experiment == "pug_imagenet":
dataset_val = ImageFolderWithPaths(root=args.data_path,
transform=transform_val)
else:
if "imagenetv2" in args.data_path:
dataset_val = ImageNetV2Dataset("matched-frequency",
transform=transform_val,
location=args.data_path)
elif "imagenet-r" in args.data_path:
dataset_val = datasets.ImageFolder(os.path.join(args.data_path),
transform=transform_val)
elif "imagenet" in args.data_path:
dataset_val = datasets.ImageFolder(os.path.join(args.data_path),
transform=transform_val)
if args.experiment != "robustness":
data_loader_val = torch.utils.data.DataLoader(
dataset_val,
batch_size=args.batch_size,
num_workers=args.num_workers,
pin_memory=True,
shuffle=False,
)
model.to(device)
model.eval()
model_without_ddp = model
n_parameters = sum(p.numel() for p in model.parameters()
if p.requires_grad)
print("Model = %s" % str(model_without_ddp))
print(args.model)
print("number of params (M): %.2f" % (n_parameters / 1.0e6))
eff_batch_size = args.batch_size * get_world_size()
print("effective batch size: %d" % eff_batch_size)
if data_loader_val is not None:
print(data_loader_val.dataset)
if (args.experiment == "scale" or args.experiment == "shift_xy"
or args.experiment == "resolution"):
return run_invariance(data_loader_val, model, device)
elif args.experiment == "robustness":
return run_robustness(model, args.data_path, transform_val, args)
elif args.experiment == "imagenetx":
return run_imagenetx(data_loader_val, model, device, model_name)
elif args.experiment == "pug_imagenet":
return run_pug_imagenet(model, args.data_path, transform_val)
return
if __name__ == "__main__":
args = get_args_parser()
args = args.parse_args()
if args.output_dir:
Path(args.output_dir).mkdir(parents=True, exist_ok=True)
seed_vals = [0, 50, 1000]
metrics_dict = defaultdict(list)
name = resolve_name(args)
run = wandb.init(
name=name,
mode="disabled" if args.debug else "online",
project="beyond-imagenet-accuracy",
)
args.run_name = name
if args.experiment in ["scale", "shift_x", "shift_xy", "resolution"]:
correct_prob_list = []
accuracy_list = []
if args.experiment == "scale":
transform_vals = [1, 1.25, 1.5, 2, 3]
for x in transform_vals:
args.scale_factor = x
d = main(args)
correct_prob_list.append(d["correct_class_prob"])
accuracy_list.append(d["top1_accuracy"])
run.log({
"transform_val": x,
"correct_class_prob": d["correct_class_prob"],
"accuracy": d["top1_accuracy"],
})
elif args.experiment == "shift_xy":
transform_vals = [0, 5, 30, 75, 100]
for x in transform_vals:
args.shift_x = x
args.shift_y = x
d = main(args)
correct_prob_list.append(d["correct_class_prob"])
accuracy_list.append(d["top1_accuracy"])
run.log({
"transform_val": x,
"correct_class_prob": d["correct_class_prob"],
"accuracy": d["top1_accuracy"],
})
elif args.experiment == "resolution":
transform_vals = [112, 224, 336, 512, 640]
for x in transform_vals:
args.image_size = x
print(args)
d = main(args)
correct_prob_list.append(d["correct_class_prob"])
accuracy_list.append(d["top1_accuracy"])
run.log({
"transform_val": x,
"correct_class_prob": d["correct_class_prob"],
"accuracy": d["top1_accuracy"],
})
data = {
"transform_val": transform_vals,
"correct_class_prob": correct_prob_list,
"accuracy": accuracy_list,
}
with open(f"./scale_shift_reso/{name}.json", "w") as json_file:
json.dump(data, json_file)
run.finish()
exit(0)
for i in range(args.num_runs):
args.seed = seed_vals[i]
results = main(args)
if isinstance(results, pandas.Series) or isinstance(
results, pandas.DataFrame):
results = results.loc["preds"].to_dict()
for key, value in results.items():
if run is not None:
run.log({f"{key}_run_{i}": value})
metrics_dict[key].append(value)
mean_std_metrics = {}
for key, values in metrics_dict.items():
mean_value = np.mean(values)
std_value = np.std(values)
mean_std_metrics[f"{key}_mean"] = mean_value
mean_std_metrics[f"{key}_std"] = std_value
print(mean_std_metrics)
if run is not None:
run.log(mean_std_metrics)
run.finish()