-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtrain.py
305 lines (259 loc) · 12.1 KB
/
train.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import collections
import json
import os
import random
import sys
import time
import uuid
from itertools import chain
import numpy as np
import PIL
import torch
import torchvision
import torch.utils.data
from domainbed import datasets
from domainbed import hparams_registry
from domainbed import algorithms
from domainbed.lib import misc
from domainbed.lib.fast_data_loader import InfiniteDataLoader, FastDataLoader, DataParallelPassthrough
from domainbed import model_selection
from domainbed.lib.query import Q
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Domain generalization')
parser.add_argument('--data_dir', type=str, default='/data2/yifan.zhang/datasets/DGdata/')
parser.add_argument('--dataset', type=str, default="ColoredMNIST")
parser.add_argument('--algorithm', type=str, default="KNN")
parser.add_argument('--task', type=str, default="domain_generalization",
help='domain_generalization | domain_adaptation')
parser.add_argument('--hparams', type=str,
help='JSON-serialized hparams dict')
parser.add_argument('--hparams_seed', type=int, default=0,
help='Seed for random hparams (0 means "default hparams")')
parser.add_argument('--trial_seed', type=int, default=0,
help='Trial number (used for seeding split_dataset and '
'random_hparams).')
parser.add_argument('--seed', type=int, default=0,
help='Seed for everything else')
parser.add_argument('--steps', type=int, default=None,
help='Number of steps. Default is dataset-dependent.')
parser.add_argument('--checkpoint_freq', type=int, default=None,
help='Checkpoint every N steps. Default is dataset-dependent.')
parser.add_argument('--test_envs', type=int, nargs='+', default=[0])
parser.add_argument('--output_dir', type=str, default="train_output")
parser.add_argument('--holdout_fraction', type=float, default=0.2)
parser.add_argument('--uda_holdout_fraction', type=float, default=0)
parser.add_argument('--skip_model_save', action='store_true')
parser.add_argument('--save_model_every_checkpoint', action='store_true')
args = parser.parse_args()
# If we ever want to implement checkpointing, just persist these values
# every once in a while, and then load them from disk here.
start_step = 0
algorithm_dict = None
os.makedirs(args.output_dir, exist_ok=True)
sys.stdout = misc.Tee(os.path.join(args.output_dir, 'out.txt'))
sys.stderr = misc.Tee(os.path.join(args.output_dir, 'err.txt'))
print("Environment:")
print("\tPython: {}".format(sys.version.split(" ")[0]))
print("\tPyTorch: {}".format(torch.__version__))
print("\tTorchvision: {}".format(torchvision.__version__))
print("\tCUDA: {}".format(torch.version.cuda))
print("\tCUDNN: {}".format(torch.backends.cudnn.version()))
print("\tNumPy: {}".format(np.__version__))
print("\tPIL: {}".format(PIL.__version__))
print('Args:')
for k, v in sorted(vars(args).items()):
print('\t{}: {}'.format(k, v))
if args.hparams_seed == 0:
hparams = hparams_registry.default_hparams(args.algorithm, args.dataset)
else:
hparams = hparams_registry.random_hparams(args.algorithm, args.dataset,
misc.seed_hash(args.hparams_seed, args.trial_seed))
if args.hparams:
hparams.update(json.loads(args.hparams))
print('HParams:')
for k, v in sorted(hparams.items()):
print('\t{}: {}'.format(k, v))
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
if torch.cuda.is_available():
device = "cuda"
else:
device = "cpu"
if args.dataset in vars(datasets):
dataset = vars(datasets)[args.dataset](args.data_dir,
args.test_envs, hparams)
else:
raise NotImplementedError
# Split each env into an 'in-split' and an 'out-split'. We'll train on
# each in-split except the test envs, and evaluate on all splits.
# To allow unsupervised domain adaptation experiments, we split each test
# env into 'in-split', 'uda-split' and 'out-split'. The 'in-split' is used
# by collect_results.py to compute classification accuracies. The
# 'out-split' is used by the Oracle model selectino method. The unlabeled
# samples in 'uda-split' are passed to the algorithm at training time if
# args.task == "domain_adaptation". If we are interested in comparing
# domain generalization and domain adaptation results, then domain
# generalization algorithms should create the same 'uda-splits', which will
# be discared at training.
in_splits = []
out_splits = []
uda_splits = []
for env_i, env in enumerate(dataset):
uda = []
out, in_ = misc.split_dataset(env,
int(len(env)*args.holdout_fraction),
misc.seed_hash(args.trial_seed, env_i))
if env_i in args.test_envs:
uda, in_ = misc.split_dataset(in_,
int(len(in_)*args.uda_holdout_fraction),
misc.seed_hash(args.trial_seed, env_i))
if hparams['class_balanced']:
in_weights = misc.make_weights_for_balanced_classes(in_)
out_weights = misc.make_weights_for_balanced_classes(out)
if uda is not None:
uda_weights = misc.make_weights_for_balanced_classes(uda)
else:
in_weights, out_weights, uda_weights = None, None, None
in_splits.append((in_, in_weights))
out_splits.append((out, out_weights))
if len(uda):
uda_splits.append((uda, uda_weights))
train_loaders = [InfiniteDataLoader(
dataset=env,
weights=env_weights,
batch_size=hparams['batch_size'],
num_workers=dataset.N_WORKERS)
for i, (env, env_weights) in enumerate(in_splits)
if i not in args.test_envs]
uda_loaders = [InfiniteDataLoader(
dataset=env,
weights=env_weights,
batch_size=hparams['batch_size'],
num_workers=dataset.N_WORKERS)
for i, (env, env_weights) in enumerate(uda_splits)
if i in args.test_envs]
train_loaders_eval = [FastDataLoader(
dataset=env,
batch_size=64,
num_workers=dataset.N_WORKERS)
for i, (env, env_weights) in enumerate(in_splits)
if i not in args.test_envs]
eval_loaders = [FastDataLoader(
dataset=env,
batch_size=64,
num_workers=dataset.N_WORKERS)
for env, _ in (in_splits + out_splits + uda_splits)]
eval_weights = [None for _, weights in (in_splits + out_splits + uda_splits)]
eval_loader_names = ['env{}_in'.format(i)
for i in range(len(in_splits))]
eval_loader_names += ['env{}_out'.format(i)
for i in range(len(out_splits))]
eval_loader_names += ['env{}_uda'.format(i)
for i in range(len(uda_splits))]
algorithm_class = algorithms.get_algorithm_class(args.algorithm)
algorithm = algorithm_class(dataset.input_shape, dataset.num_classes,
len(dataset) - len(args.test_envs), hparams)
if algorithm_dict is not None:
algorithm.load_state_dict(algorithm_dict)
algorithm.to(device)
if hasattr(algorithm, 'network'):
algorithm.network = DataParallelPassthrough(algorithm.network)
else:
for m in algorithm.children():
m = DataParallelPassthrough(m)
if args.algorithm == 'KNN':
from domainbed.knn import MomentumQueue
algorithm.eval_knn = MomentumQueue(algorithm.featurizer.n_outputs, sum([len(loader) for loader in train_loaders_eval]) * 64, 0.1, hparams['k'], dataset.num_classes).cuda()
train_minibatches_iterator = zip(*train_loaders)
uda_minibatches_iterator = zip(*uda_loaders)
checkpoint_vals = collections.defaultdict(lambda: [])
steps_per_epoch = min([len(env)/hparams['batch_size'] for env,_ in in_splits])
n_steps = args.steps or dataset.N_STEPS
checkpoint_freq = args.checkpoint_freq or dataset.CHECKPOINT_FREQ
def save_checkpoint(filename):
if args.skip_model_save:
return
save_dict = {
"args": vars(args),
"model_input_shape": dataset.input_shape,
"model_num_classes": dataset.num_classes,
"model_num_domains": len(dataset) - len(args.test_envs),
"model_hparams": hparams,
"model_dict": algorithm.cpu().state_dict()
}
torch.save(save_dict, os.path.join(args.output_dir, filename))
last_results_keys, best_test_acc = None, 0
for step in range(start_step, n_steps):
step_start_time = time.time()
minibatches_device = [(x.to(device), y.to(device))
for x,y in next(train_minibatches_iterator)]
if args.task == "domain_adaptation":
uda_device = [x.to(device)
for x,_ in next(uda_minibatches_iterator)]
else:
uda_device = None
step_vals = algorithm.update(minibatches_device, uda_device)
checkpoint_vals['step_time'].append(time.time() - step_start_time)
for key, val in step_vals.items():
checkpoint_vals[key].append(val)
if (step % checkpoint_freq == 0) or (step == n_steps - 1):
results = {
'step': step,
'epoch': step / steps_per_epoch,
}
for key, val in checkpoint_vals.items():
results[key] = np.mean(val)
evals = zip(eval_loader_names, eval_loaders, eval_weights)
if args.algorithm == 'KNN':
for loader in train_loaders_eval:
for x,y in loader:
algorithm.eval_knn.update_queue(algorithm.featurizer(x.to(device)), y.to(device))
if step == 0:
algorithm.eval_knn.queue_size = algorithm.eval_knn.memory.shape[0]
for name, loader, weights in evals:
if args.algorithm == 'KNN':
algorithm.eval_knn.memory = algorithm.eval_knn.memory[:algorithm.eval_knn.queue_size,:]# drop last
algorithm.eval_knn.memory_label = algorithm.eval_knn.memory_label[:algorithm.eval_knn.queue_size]
acc = misc.accuracy(algorithm, loader, weights, device)
else:
acc = misc.accuracy(algorithm, loader, weights, device)
results[name+'_acc'] = acc
if 'in' in name and str(args.test_envs[0]) in name and acc > best_test_acc:
best_test_acc = acc
save_checkpoint("OOD_best.pkl")
algorithm.to(device)
results_keys = sorted(results.keys())
if results_keys != last_results_keys:
misc.print_row(results_keys, colwidth=12)
last_results_keys = results_keys
misc.print_row([results[key] for key in results_keys],
colwidth=12)
results.update({
'hparams': hparams,
'args': vars(args)
})
epochs_path = os.path.join(args.output_dir, 'results.jsonl')
with open(epochs_path, 'a') as f:
f.write(json.dumps(results, sort_keys=True) + "\n")
algorithm_dict = algorithm.state_dict()
start_step = step + 1
checkpoint_vals = collections.defaultdict(lambda: [])
records = []
with open(epochs_path, 'r') as f:
for line in f:
records.append(json.loads(line[:-1]))
records = Q(records)
scores = records.map(model_selection.IIDAccuracySelectionMethod._step_acc)
if scores[-1] == scores.argmax('val_acc'):
save_checkpoint('IID_best.pkl')
algorithm.to(device)
if args.save_model_every_checkpoint:
save_checkpoint(f'model_step{step}.pkl')
save_checkpoint('model.pkl')
with open(os.path.join(args.output_dir, 'done'), 'w') as f:
f.write('done')