-
Notifications
You must be signed in to change notification settings - Fork 22
/
main.py
677 lines (636 loc) · 29.2 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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
import os
import json
import argparse
import torch
import numpy as np
from tensorboardX import SummaryWriter
from maml.datasets.omniglot import OmniglotMetaDataset
from maml.datasets.miniimagenet import MiniimagenetMetaDataset
from maml.datasets.cifar100 import Cifar100MetaDataset
from maml.datasets.bird import BirdMetaDataset
from maml.datasets.aircraft import AircraftMetaDataset
from maml.datasets.multimodal_few_shot import MultimodalFewShotDataset
from maml.models.fully_connected import FullyConnectedModel, MultiFullyConnectedModel
from maml.models.conv_net import ConvModel
from maml.models.gated_conv_net import GatedConvModel
from maml.models.gated_net import GatedNet
from maml.models.simple_embedding_model import SimpleEmbeddingModel
from maml.models.lstm_embedding_model import LSTMEmbeddingModel
from maml.models.gru_embedding_model import GRUEmbeddingModel
from maml.models.conv_embedding_model import ConvEmbeddingModel
from maml.metalearner import MetaLearner
from maml.trainer import Trainer
from maml.utils import optimizer_to_device, get_git_revision_hash
def main(args):
is_training = not args.eval
run_name = 'train' if is_training else 'eval'
if is_training:
writer = SummaryWriter('./train_dir/{0}/{1}'.format(
args.output_folder, run_name))
with open('./train_dir/{}/config.txt'.format(
args.output_folder), 'w') as config_txt:
for k, v in sorted(vars(args).items()):
config_txt.write('{}: {}\n'.format(k, v))
else:
writer = None
save_folder = './train_dir/{0}'.format(args.output_folder)
if not os.path.exists(save_folder):
os.makedirs(save_folder)
config_name = '{0}_config.json'.format(run_name)
with open(os.path.join(save_folder, config_name), 'w') as f:
config = {k: v for (k, v) in vars(args).items() if k != 'device'}
config.update(device=args.device.type)
try:
config.update({'git_hash': get_git_revision_hash()})
except:
pass
json.dump(config, f, indent=2)
_num_tasks = 1
if args.dataset == 'omniglot':
dataset = OmniglotMetaDataset(
root='data',
img_side_len=28, # args.img_side_len,
num_classes_per_batch=args.num_classes_per_batch,
num_samples_per_class=args.num_samples_per_class,
num_total_batches=args.num_batches,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
train=is_training,
num_train_classes=args.num_train_classes,
num_workers=args.num_workers,
device=args.device)
loss_func = torch.nn.CrossEntropyLoss()
collect_accuracies = True
elif args.dataset == 'cifar':
dataset = Cifar100MetaDataset(
root='data',
img_side_len=32,
num_classes_per_batch=args.num_classes_per_batch,
num_samples_per_class=args.num_samples_per_class,
num_total_batches=args.num_batches,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
train=is_training,
num_train_classes=args.num_train_classes,
num_workers=args.num_workers,
device=args.device)
loss_func = torch.nn.CrossEntropyLoss()
collect_accuracies = True
elif args.dataset == 'multimodal_few_shot':
dataset_list = []
if 'omniglot' in args.multimodal_few_shot:
dataset_list.append(OmniglotMetaDataset(
root='data',
img_side_len=args.common_img_side_len,
img_channel=args.common_img_channel,
num_classes_per_batch=args.num_classes_per_batch,
num_samples_per_class=args.num_samples_per_class,
num_total_batches=args.num_batches,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
train=is_training,
num_train_classes=args.num_train_classes,
num_workers=args.num_workers,
device=args.device)
)
if 'miniimagenet' in args.multimodal_few_shot:
dataset_list.append( MiniimagenetMetaDataset(
root='data',
img_side_len=args.common_img_side_len,
img_channel=args.common_img_channel,
num_classes_per_batch=args.num_classes_per_batch,
num_samples_per_class=args.num_samples_per_class,
num_total_batches=args.num_batches,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
train=is_training,
num_train_classes=args.num_train_classes,
num_workers=args.num_workers,
device=args.device)
)
if 'cifar' in args.multimodal_few_shot:
dataset_list.append(Cifar100MetaDataset(
root='data',
img_side_len=args.common_img_side_len,
img_channel=args.common_img_channel,
num_classes_per_batch=args.num_classes_per_batch,
num_samples_per_class=args.num_samples_per_class,
num_total_batches=args.num_batches,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
train=is_training,
num_train_classes=args.num_train_classes,
num_workers=args.num_workers,
device=args.device)
)
if 'doublemnist' in args.multimodal_few_shot:
dataset_list.append( DoubleMNISTMetaDataset(
root='data',
img_side_len=args.common_img_side_len,
img_channel=args.common_img_channel,
num_classes_per_batch=args.num_classes_per_batch,
num_samples_per_class=args.num_samples_per_class,
num_total_batches=args.num_batches,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
train=is_training,
num_train_classes=args.num_train_classes,
num_workers=args.num_workers,
device=args.device)
)
if 'triplemnist' in args.multimodal_few_shot:
dataset_list.append( TripleMNISTMetaDataset(
root='data',
img_side_len=args.common_img_side_len,
img_channel=args.common_img_channel,
num_classes_per_batch=args.num_classes_per_batch,
num_samples_per_class=args.num_samples_per_class,
num_total_batches=args.num_batches,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
train=is_training,
num_train_classes=args.num_train_classes,
num_workers=args.num_workers,
device=args.device)
)
if 'bird' in args.multimodal_few_shot:
dataset_list.append( BirdMetaDataset(
root='data',
img_side_len=args.common_img_side_len,
img_channel=args.common_img_channel,
num_classes_per_batch=args.num_classes_per_batch,
num_samples_per_class=args.num_samples_per_class,
num_total_batches=args.num_batches,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
train=is_training,
num_train_classes=args.num_train_classes,
num_workers=args.num_workers,
device=args.device)
)
if 'aircraft' in args.multimodal_few_shot:
dataset_list.append( AircraftMetaDataset(
root='data',
img_side_len=args.common_img_side_len,
img_channel=args.common_img_channel,
num_classes_per_batch=args.num_classes_per_batch,
num_samples_per_class=args.num_samples_per_class,
num_total_batches=args.num_batches,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
train=is_training,
num_train_classes=args.num_train_classes,
num_workers=args.num_workers,
device=args.device)
)
assert len(dataset_list) > 0
print('Multimodal Few Shot Datasets: {}'.format(
' '.join([dataset.name for dataset in dataset_list])))
dataset = MultimodalFewShotDataset(
dataset_list,
num_total_batches=args.num_batches,
mix_meta_batch=args.mix_meta_batch,
mix_mini_batch=args.mix_mini_batch,
txt_file=args.sample_embedding_file+'.txt' if args.num_sample_embedding > 0 else None,
train=is_training,
)
loss_func = torch.nn.CrossEntropyLoss()
collect_accuracies = True
elif args.dataset == 'doublemnist':
dataset = DoubleMNISTMetaDataset(
root='data',
img_side_len=64,
num_classes_per_batch=args.num_classes_per_batch,
num_samples_per_class=args.num_samples_per_class,
num_total_batches=args.num_batches,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
train=is_training,
num_train_classes=args.num_train_classes,
num_workers=args.num_workers,
device=args.device)
loss_func = torch.nn.CrossEntropyLoss()
collect_accuracies = True
elif args.dataset == 'triplemnist':
dataset = TripleMNISTMetaDataset(
root='data',
img_side_len=84,
num_classes_per_batch=args.num_classes_per_batch,
num_samples_per_class=args.num_samples_per_class,
num_total_batches=args.num_batches,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
train=is_training,
num_train_classes=args.num_train_classes,
num_workers=args.num_workers,
device=args.device)
loss_func = torch.nn.CrossEntropyLoss()
collect_accuracies = True
elif args.dataset == 'miniimagenet':
dataset = MiniimagenetMetaDataset(
root='data',
img_side_len=84,
num_classes_per_batch=args.num_classes_per_batch,
num_samples_per_class=args.num_samples_per_class,
num_total_batches=args.num_batches,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
train=is_training,
num_train_classes=args.num_train_classes,
num_workers=args.num_workers,
device=args.device)
loss_func = torch.nn.CrossEntropyLoss()
collect_accuracies = True
elif args.dataset == 'sinusoid':
dataset = SinusoidMetaDataset(
num_total_batches=args.num_batches,
num_samples_per_function=args.num_samples_per_class,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
amp_range=args.amp_range,
phase_range=args.phase_range,
input_range=args.input_range,
oracle=args.oracle,
train=is_training,
device=args.device)
loss_func = torch.nn.MSELoss()
collect_accuracies = False
elif args.dataset == 'linear':
dataset = LinearMetaDataset(
num_total_batches=args.num_batches,
num_samples_per_function=args.num_samples_per_class,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
slope_range=args.slope_range,
intersect_range=args.intersect_range,
input_range=args.input_range,
oracle=args.oracle,
train=is_training,
device=args.device)
loss_func = torch.nn.MSELoss()
collect_accuracies = False
elif args.dataset == 'mixed':
dataset = MixedFunctionsMetaDataset(
num_total_batches=args.num_batches,
num_samples_per_function=args.num_samples_per_class,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
amp_range=args.amp_range,
phase_range=args.phase_range,
slope_range=args.slope_range,
intersect_range=args.intersect_range,
input_range=args.input_range,
noise_std=args.noise_std,
oracle=args.oracle,
task_oracle=args.task_oracle,
train=is_training,
device=args.device)
loss_func = torch.nn.MSELoss()
collect_accuracies = False
_num_tasks=2
elif args.dataset == 'many':
dataset = ManyFunctionsMetaDataset(
num_total_batches=args.num_batches,
num_samples_per_function=args.num_samples_per_class,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
amp_range=args.amp_range,
phase_range=args.phase_range,
slope_range=args.slope_range,
intersect_range=args.intersect_range,
input_range=args.input_range,
noise_std=args.noise_std,
oracle=args.oracle,
task_oracle=args.task_oracle,
train=is_training,
device=args.device)
loss_func = torch.nn.MSELoss()
collect_accuracies = False
_num_tasks=3
elif args.dataset == 'multisinusoids':
dataset = MultiSinusoidsMetaDataset(
num_total_batches=args.num_batches,
num_samples_per_function=args.num_samples_per_class,
num_val_samples=args.num_val_samples,
meta_batch_size=args.meta_batch_size,
amp_range=args.amp_range,
phase_range=args.phase_range,
slope_range=args.slope_range,
intersect_range=args.intersect_range,
input_range=args.input_range,
noise_std=args.noise_std,
oracle=args.oracle,
task_oracle=args.task_oracle,
train=is_training,
device=args.device)
loss_func = torch.nn.MSELoss()
collect_accuracies = False
else:
raise ValueError('Unrecognized dataset {}'.format(args.dataset))
embedding_model = None
if args.model_type == 'fc':
model = FullyConnectedModel(
input_size=np.prod(dataset.input_size),
output_size=dataset.output_size,
hidden_sizes=args.hidden_sizes,
disable_norm=args.disable_norm,
bias_transformation_size=args.bias_transformation_size)
elif args.model_type == 'multi':
model = MultiFullyConnectedModel(
input_size=np.prod(dataset.input_size),
output_size=dataset.output_size,
hidden_sizes=args.hidden_sizes,
disable_norm=args.disable_norm,
num_tasks=_num_tasks,
bias_transformation_size=args.bias_transformation_size)
elif args.model_type == 'conv':
model = ConvModel(
input_channels=dataset.input_size[0],
output_size=dataset.output_size,
num_channels=args.num_channels,
img_side_len=dataset.input_size[1],
use_max_pool=args.use_max_pool,
verbose=args.verbose)
elif args.model_type == 'gatedconv':
model = GatedConvModel(
input_channels=dataset.input_size[0],
output_size=dataset.output_size,
use_max_pool=args.use_max_pool,
num_channels=args.num_channels,
img_side_len=dataset.input_size[1],
condition_type=args.condition_type,
condition_order=args.condition_order,
verbose=args.verbose)
elif args.model_type == 'gated':
model = GatedNet(
input_size=np.prod(dataset.input_size),
output_size=dataset.output_size,
hidden_sizes=args.hidden_sizes,
condition_type=args.condition_type,
condition_order=args.condition_order)
else:
raise ValueError('Unrecognized model type {}'.format(args.model_type))
model_parameters = list(model.parameters())
if args.embedding_type == '':
embedding_model = None
elif args.embedding_type == 'simple':
embedding_model = SimpleEmbeddingModel(
num_embeddings=dataset.num_tasks,
embedding_dims=args.embedding_dims)
embedding_parameters = list(embedding_model.parameters())
elif args.embedding_type == 'GRU':
embedding_model = GRUEmbeddingModel(
input_size=np.prod(dataset.input_size),
output_size=dataset.output_size,
embedding_dims=args.embedding_dims,
hidden_size=args.embedding_hidden_size,
num_layers=args.embedding_num_layers)
embedding_parameters = list(embedding_model.parameters())
elif args.embedding_type == 'LSTM':
embedding_model = LSTMEmbeddingModel(
input_size=np.prod(dataset.input_size),
output_size=dataset.output_size,
embedding_dims=args.embedding_dims,
hidden_size=args.embedding_hidden_size,
num_layers=args.embedding_num_layers)
embedding_parameters = list(embedding_model.parameters())
elif args.embedding_type == 'ConvGRU':
embedding_model = ConvEmbeddingModel(
input_size=np.prod(dataset.input_size),
output_size=dataset.output_size,
embedding_dims=args.embedding_dims,
hidden_size=args.embedding_hidden_size,
num_layers=args.embedding_num_layers,
convolutional=args.conv_embedding,
num_conv=args.num_conv_embedding_layer,
num_channels=args.num_channels,
rnn_aggregation=(not args.no_rnn_aggregation),
embedding_pooling=args.embedding_pooling,
batch_norm=args.conv_embedding_batch_norm,
avgpool_after_conv=args.conv_embedding_avgpool_after_conv,
linear_before_rnn=args.linear_before_rnn,
num_sample_embedding=args.num_sample_embedding,
sample_embedding_file=args.sample_embedding_file+'.'+args.sample_embedding_file_type,
img_size=dataset.input_size,
verbose=args.verbose)
embedding_parameters = list(embedding_model.parameters())
else:
raise ValueError('Unrecognized embedding type {}'.format(
args.embedding_type))
optimizers = None
if embedding_model:
optimizers = ( torch.optim.Adam(model_parameters, lr=args.slow_lr),
torch.optim.Adam(embedding_parameters, lr=args.slow_lr) )
else:
optimizers = ( torch.optim.Adam(model_parameters, lr=args.slow_lr), )
if args.checkpoint != '':
checkpoint = torch.load(args.checkpoint)
model.load_state_dict(checkpoint['model_state_dict'])
model.to(args.device)
if 'optimizer' in checkpoint:
pass
else:
optimizers[0].load_state_dict(checkpoint['optimizers'][0])
optimizer_to_device(optimizers[0], args.device)
if embedding_model:
embedding_model.load_state_dict(
checkpoint['embedding_model_state_dict'])
optimizers[1].load_state_dict(checkpoint['optimizers'][1])
optimizer_to_device(optimizers[1], args.device)
meta_learner = MetaLearner(
model, embedding_model, optimizers, fast_lr=args.fast_lr,
loss_func=loss_func, first_order=args.first_order,
num_updates=args.num_updates,
inner_loop_grad_clip=args.inner_loop_grad_clip,
collect_accuracies=collect_accuracies, device=args.device,
alternating=args.alternating, embedding_schedule=args.embedding_schedule,
classifier_schedule=args.classifier_schedule, embedding_grad_clip=args.embedding_grad_clip)
trainer = Trainer(
meta_learner=meta_learner, meta_dataset=dataset, writer=writer,
log_interval=args.log_interval, save_interval=args.save_interval,
model_type=args.model_type, save_folder=save_folder,
total_iter=args.num_batches//args.meta_batch_size
)
if is_training:
trainer.train()
else:
trainer.eval()
if __name__ == '__main__':
def str2bool(arg):
return arg.lower() == 'true'
parser = argparse.ArgumentParser(
description='Model-Agnostic Meta-Learning (MAML)')
parser.add_argument('--mmaml-model', type=str2bool, default=False,
help='gated_conv + ConvGRU')
parser.add_argument('--maml-model', type=str2bool, default=False,
help='conv')
# Model
parser.add_argument('--hidden-sizes', type=int,
default=[256, 128, 64, 64], nargs='+',
help='number of hidden units per layer')
parser.add_argument('--model-type', type=str, default='gatedconv',
help='type of the model')
parser.add_argument('--condition-type', type=str, default='affine',
choices=['affine', 'sigmoid', 'softmax'],
help='type of the conditional layers')
parser.add_argument('--condition-order', type=str, default='low2high',
help='order of the conditional layers to be used')
parser.add_argument('--use-max-pool', type=str2bool, default=False,
help='choose whether to use max pooling with convolutional model')
parser.add_argument('--num-channels', type=int, default=32,
help='number of channels in convolutional layers')
parser.add_argument('--disable-norm', action='store_true',
help='disable batchnorm after linear layers in a fully connected model')
parser.add_argument('--bias-transformation-size', type=int, default=0,
help='size of bias transformation vector that is concatenated with '
'input')
# Embedding
parser.add_argument('--embedding-type', type=str, default='',
help='type of the embedding')
parser.add_argument('--embedding-hidden-size', type=int, default=128,
help='number of hidden units per layer in recurrent embedding model')
parser.add_argument('--embedding-num-layers', type=int, default=2,
help='number of layers in recurrent embedding model')
parser.add_argument('--embedding-dims', type=int, nargs='+', default=0,
help='dimensions of the embeddings')
# Randomly sampled embedding vectors
parser.add_argument('--num-sample-embedding', type=int, default=0,
help='number of randomly sampled embedding vectors')
parser.add_argument(
'--sample-embedding-file', type=str, default='embeddings',
help='the file name of randomly sampled embedding vectors')
parser.add_argument(
'--sample-embedding-file-type', type=str, default='hdf5')
# Inner loop
parser.add_argument('--first-order', action='store_true',
help='use the first-order approximation of MAML')
parser.add_argument('--fast-lr', type=float, default=0.05,
help='learning rate for the 1-step gradient update of MAML')
parser.add_argument('--inner-loop-grad-clip', type=float, default=20.0,
help='enable gradient clipping in the inner loop')
parser.add_argument('--num-updates', type=int, default=5,
help='how many update steps in the inner loop')
# Optimization
parser.add_argument('--num-batches', type=int, default=1920000,
help='number of batches')
parser.add_argument('--meta-batch-size', type=int, default=10,
help='number of tasks per batch')
parser.add_argument('--slow-lr', type=float, default=0.001,
help='learning rate for the global update of MAML')
# Miscellaneous
parser.add_argument('--output-folder', type=str, default='maml',
help='name of the output folder')
parser.add_argument('--device', type=str, default='cuda',
help='set the device (cpu or cuda)')
parser.add_argument('--num-workers', type=int, default=4,
help='how many DataLoader workers to use')
parser.add_argument('--log-interval', type=int, default=100,
help='number of batches between tensorboard writes')
parser.add_argument('--save-interval', type=int, default=1000,
help='number of batches between model saves')
parser.add_argument('--eval', action='store_true', default=False,
help='evaluate model')
parser.add_argument('--checkpoint', type=str, default='',
help='path to saved parameters.')
# Dataset
parser.add_argument('--dataset', type=str, default='multimodal_few_shot',
help='which dataset to use')
parser.add_argument('--data-root', type=str, default='data',
help='path to store datasets')
parser.add_argument('--num-train-classes', type=int, default=1100,
help='how many classes for training')
parser.add_argument('--num-classes-per-batch', type=int, default=5,
help='how many classes per task')
parser.add_argument('--num-samples-per-class', type=int, default=1,
help='how many samples per class for training')
parser.add_argument('--num-val-samples', type=int, default=15,
help='how many samples per class for validation')
parser.add_argument('--img-side-len', type=int, default=28,
help='width and height of the input images')
parser.add_argument('--input-range', type=float, default=[-5.0, 5.0],
nargs='+', help='input range of simple functions')
parser.add_argument('--phase-range', type=float, default=[0, np.pi],
nargs='+', help='phase range of sinusoids')
parser.add_argument('--amp-range', type=float, default=[0.1, 5.0],
nargs='+', help='amp range of sinusoids')
parser.add_argument('--slope-range', type=float, default=[-3.0, 3.0],
nargs='+', help='slope range of linear functions')
parser.add_argument('--intersect-range', type=float, default=[-3.0, 3.0],
nargs='+', help='intersect range of linear functions')
parser.add_argument('--noise-std', type=float, default=0.0,
help='add gaussian noise to mixed functions')
parser.add_argument('--oracle', action='store_true',
help='concatenate phase and amp to sinusoid inputs')
parser.add_argument('--task-oracle', action='store_true',
help='uses task id for prediction in some models')
# Combine few-shot learning datasets
parser.add_argument('--multimodal_few_shot', type=str,
default=['omniglot', 'cifar', 'miniimagenet', 'doublemnist', 'triplemnist'],
choices=['omniglot', 'cifar', 'miniimagenet', 'doublemnist', 'triplemnist',
'bird', 'aircraft'],
nargs='+')
parser.add_argument('--common-img-side-len', type=int, default=84)
parser.add_argument('--common-img-channel', type=int, default=3,
help='3 for RGB and 1 for grayscale')
parser.add_argument('--mix-meta-batch', type=str2bool, default=True)
parser.add_argument('--mix-mini-batch', type=str2bool, default=False)
parser.add_argument('--alternating', action='store_true',
help='')
parser.add_argument('--classifier-schedule', type=int, default=10,
help='')
parser.add_argument('--embedding-schedule', type=int, default=10,
help='')
parser.add_argument('--conv-embedding', type=str2bool, default=True,
help='')
parser.add_argument('--conv-embedding-batch-norm', type=str2bool, default=True,
help='')
parser.add_argument('--conv-embedding-avgpool-after-conv', type=str2bool, default=True,
help='')
parser.add_argument('--num-conv-embedding-layer', type=int, default=4,
help='')
parser.add_argument('--no-rnn-aggregation', type=str2bool, default=True,
help='')
parser.add_argument('--embedding-pooling', type=str,
choices=['avg', 'max'], default='avg', help='')
parser.add_argument('--linear-before-rnn', action='store_true',
help='')
parser.add_argument('--embedding-grad-clip', type=float, default=0.0,
help='')
parser.add_argument('--verbose', type=str2bool, default=False,
help='')
args = parser.parse_args()
# Create logs and saves folder if they don't exist
if not os.path.exists('./train_dir'):
os.makedirs('./train_dir')
# Make sure num sample embedding < num sample tasks
args.num_sample_embedding = min(args.num_sample_embedding, args.num_batches)
# computer embedding dims
num_gated_conv_layers = 4
if args.embedding_dims == 0:
args.embedding_dims = []
for i in range(num_gated_conv_layers):
embedding_dim = args.num_channels*2**i
if args.condition_type == 'affine':
embedding_dim *= 2
args.embedding_dims.append(embedding_dim)
assert not (args.mmaml_model and args.maml_model)
# mmaml model: gated conv + convGRU
if args.mmaml_model is True:
print('Use MMAML')
args.model_type = 'gatedconv'
args.embedding_type = 'ConvGRU'
# maml model: conv
if args.maml_model is True:
print('Use vanilla MAML')
args.model_type = 'conv'
args.embedding_type = ''
# Device
args.device = torch.device(args.device
if torch.cuda.is_available() else 'cpu')
# print args
if args.verbose:
print('='*10 + ' ARGS ' + '='*10)
for k, v in sorted(vars(args).items()):
print('{}: {}'.format(k, v))
print('='*26)
main(args)