-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
19039 lines (14598 loc) · 838 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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Main file to be executed
# NB: current version of the code is not at all optimized;
# e.g., the ACL loss computation can be largely accelerated by batchfying computation
import os
import sys
import json
import time
import hashlib
from datetime import datetime
import argparse
import logging
import numpy as np
import random
from packaging import version
from itertools import cycle
import torch
import torch.nn as nn
import torchvision
from torchvision.transforms import Compose, Resize, Lambda, ToTensor, Normalize
from torchmeta_local.utils.data import BatchMetaDataLoader
from warmup_lr import WarmupWrapper
from model_few_shot import (
ConvLSTMModel, ConvDeltaModel, ConvSRWMModel,
Res12LSTMModel, Res12DeltaModel, Res12SRWMModel,
MixerSRWMModel, SRMixerModel,
CompatStatefulMixerSRWMModel, CompatStatefulSelfModMixerModel,
CompatStatefulConvSRWMModel, StatefulConvDeltaModel)
from utils_few_shot import eval_model_label_sync, eval_acl_ab_model_label_sync
def zero_div(nume, denom):
return nume / denom if denom else 0.0
parser = argparse.ArgumentParser(
description='N-way K-shot learning based on label synchronous '
'seq-processing NNs with only predicting (N*K+1)th image.')
parser.add_argument('--data_dir', type=str,
default='./data', help='location of the data corpus')
parser.add_argument('--name_dataset', type=str, default='omniglot',
choices=['omniglot', 'miniimagenet', 'omniglot_rgb84x84',
'omniglot_rgb84x84_norm', 'omniglot_norm', 'omniglot_32_norm',
'miniimagenet_norm', 'tieredimagenet',
'cifar_fs', 'cifar_fs_norm', 'cifar_fs_rfs',
'miniimagenet_32_norm_cache',
'fc100', 'fc100_norm', 'fc100_rfs', 'miniimagenet_32_norm'])
parser.add_argument('--num_worker', default=12, type=int,
help='for dataloader.')
parser.add_argument('--work_dir', default='save_models', type=str,
help='where to save model ckpt.')
parser.add_argument('--init_model_from', default=None, type=str,
help='e.g. save_models/aaa/best_model.pt.')
parser.add_argument('--init_model_except_output_from', default=None, type=str,
help='e.g. save_models/aaa/best_model.pt.')
parser.add_argument('--init_model_except_output_from_class_incremental', default=None, type=str,
help='e.g. save_models/aaa/best_model.pt.')
parser.add_argument('--model_type', type=str, default='lstm',
choices=['lstm', 'deltanet', 'srwm',
'res12_lstm', 'res12_deltanet', 'res12_srwm',
'mixer_srwm', 'srwm_mixer',
'compat_stateful_srwm_res12', 'compat_stateful_srwm_mixer',
'compat_stateful_self_mod_mixer',
'compat_stateful_srwm', 'stateful_deltanet'],
help='0: LSTM, 1: DeltaNet, 2: SRWM')
parser.add_argument('--seed', default=1, type=int, help='Seed.')
parser.add_argument('--valid_seed', default=0, type=int, help='Seed.')
parser.add_argument('--test_seed', default=0, type=int, help='Seed.')
parser.add_argument('--fixed_valid', action='store_true',
help='use fixed validation set.')
parser.add_argument('--fixed_test', action='store_true',
help='[debug mode] use fixed test set.')
parser.add_argument('--num_test', default=10, type=int,
help='test size.')
parser.add_argument('--total_epoch', default=1, type=int,
help='iterate more than one epoch.')
parser.add_argument('--train_acc_stop', default=120, type=int,
help='stopping based on train acc.')
parser.add_argument('--ood_eval', action='store_true',
help='eval on extra unrelated set.')
parser.add_argument('--ood_eval2', action='store_true',
help='eval on extra unrelated set.')
parser.add_argument('--ood_eval3', action='store_true',
help='eval on extra unrelated set.')
parser.add_argument('--ood_eval5', action='store_true',
help='fashion mnist.')
parser.add_argument('--extra_label', action='store_true',
help='eval on extra unrelated set.')
parser.add_argument('--use_84', action='store_true',
help='eval on extra unrelated set.')
parser.add_argument('--use_cache', action='store_true',
help='eval on extra unrelated set.')
parser.add_argument('--use_fc', action='store_true',
help='use fc100 for ab.')
parser.add_argument('--disable_ct', action='store_true',
help='train in non-sequential mode.')
parser.add_argument('--disable_multi', action='store_true',
help='train in single-task mode.')
parser.add_argument('--loss_scale_task_a', default=1., type=float,
help='multiplier for all losses for TASK A.')
parser.add_argument('--prioritize_last', default=1., type=float,
help='multiplier for all other losses than the last task.')
parser.add_argument('--prioritize_last_factor', default=1., type=float,
help='multiplier for all other losses than the last task.')
parser.add_argument('--ab_acl_scaler', default=1., type=float,
help='multiplier for ab acl losses than the last task.')
parser.add_argument('--scale_first', default=1., type=float,
help='multiplier for the first task.')
parser.add_argument('--drop_last_batch', action='store_true',
help='dataloader.')
parser.add_argument('--cycle_dataloader', action='store_true',
help='cycle dataloader.')
parser.add_argument('--eval_only_dir', default=None,
help='skip training and eval ckpts in dir.')
parser.add_argument('--eval_extra_only', action='store_true',
help='train in single-task mode.')
parser.add_argument('--eval_extra_4_tasks', action='store_true',
help='4 task eval.')
# split mnist
parser.add_argument('--eval_splitmnist', action='store_true',
help='train in single-task mode.')
parser.add_argument('--eval_splitfashion', action='store_true',
help='train in single-task mode.')
parser.add_argument('--eval_splitcifar10', action='store_true',
help='train in single-task mode.')
parser.add_argument('--eval_splitmnist_incremental_class', action='store_true',
help='train in single-task mode.')
parser.add_argument('--eval_splitmnist_incremental_class_2task', action='store_true',
help='train in single-task mode.')
# model hyper-parameters:
parser.add_argument('--num_layer', default=1, type=int,
help='number of layers. for both LSTM and Trafo.')
parser.add_argument('--hidden_size', default=512, type=int,
help='hidden size. for both LSTM and Trafo.')
parser.add_argument('--n_head', default=8, type=int,
help='Transformer number of heads.')
parser.add_argument('--ff_factor', default=4, type=int,
help='Transformer ff dim to hidden dim ratio.')
parser.add_argument('--ff_factor_tk', default=0.5, type=float,
help='mixer token proj ff dim to hidden dim ratio.')
parser.add_argument('--patch_size', default=16, type=int,
help='mixer, patch size.')
parser.add_argument('--dropout', default=0.0, type=float,
help='dropout rate.')
parser.add_argument('--state_dropout', default=0.0, type=float,
help='state reset rate.')
parser.add_argument('--input_dropout', default=0.0, type=float,
help='input dropout rate.')
parser.add_argument('--vision_dropout', default=0.0, type=float,
help='dropout rate in the vision feat extractor.')
parser.add_argument('--dropout_type', type=str, default='base',
choices=['base', 'inblock', '2d', '2d_inblock'])
parser.add_argument('--use_big_res12', action='store_true',
help='use big Res-12.')
parser.add_argument('--not_use_ln', action='store_true',
help='not use layer norm.')
parser.add_argument('--not_use_res', action='store_true',
help='not use residual connections.')
parser.add_argument('--not_use_ff', action='store_true',
help='not use ff block.')
parser.add_argument('--srwm_beta_init', default=0.0, type=float,
help='beta bias for srwm.')
parser.add_argument('--srwm_init_scaler', default=1.0, type=float,
help='init for srwm.')
parser.add_argument('--srwm_q_init_scaler', default=0.01, type=float,
help='q init for srwm.')
parser.add_argument('--unif_init', action='store_true',
help='use unif for init.')
parser.add_argument('--use_input_softmax', action='store_true',
help='input softmax for srwm.')
parser.add_argument('--context_carry_over', action='store_true',
help='state carry over.')
parser.add_argument('--context_carry_over_k', default=1, type=int)
parser.add_argument('--context_carry_over_double', action='store_true',
help='state carry over two segments.')
parser.add_argument('--single_state_training', action='store_true',
help='carry state from batch 0.')
parser.add_argument('--no_softmax_on_y', action='store_true',
help='srwm; apply no softmax on y.')
parser.add_argument('--remove_bn', action='store_true',
help='remove bn in certain models.')
parser.add_argument('--use_instance_norm', action='store_true',
help='use InstanceNorm2d in certain models.')
parser.add_argument('--no_load_optimizer', action='store_true',
help='use InstanceNorm2d in certain models.')
# few shot learning setting
parser.add_argument('--n_way', default=5, type=int,
help='number of possible classes per train/test episode.')
parser.add_argument('--k_shot', default=1, type=int,
help='number of examples in the `train` part of torchmeta')
parser.add_argument('--test_per_class', default=1, type=int,
help='param for torchmeta')
parser.add_argument('--use_fs', action='store_true',
help='auxiliary first shot.')
# use automated continual learning loss
parser.add_argument('--use_ab', action='store_true',
help='in-context-train/test on a then b.')
parser.add_argument('--old_use_ab', action='store_true',
help='in-context-train/test on a then b.')
parser.add_argument('--use_ab_v2', action='store_true',
help='another variant of above.')
parser.add_argument('--use_abc_v2', action='store_true',
help='another variant of above.')
parser.add_argument('--use_b_first', action='store_true',
help='in-context-train/test on b then a.')
parser.add_argument('--use_abab', action='store_true') # TODO
parser.add_argument('--use_acl', action='store_true',
help='use the ACL loss.')
parser.add_argument('--train_splitmnist_style', action='store_true',
help='domain incremental.')
parser.add_argument('--train_splitmnist_style_class_incremental', action='store_true',
help='class incremental.')
parser.add_argument('--metaval_fashion', action='store_true',
help='another variant of above.')
parser.add_argument('--metaval_cifar', action='store_true',
help='another variant of above.')
parser.add_argument('--mix_metafinetuning', action='store_true',
help='use om and im for splitmnist style training.')
# training hyper-parameters:
parser.add_argument('--total_train_steps', default=100000, type=int,
help='Number of training steps to train on')
parser.add_argument('--valid_size', default=100, type=int,
help='Number of valid batches to validate on')
parser.add_argument('--test_size', default=100, type=int,
help='Number of test batches to test on')
parser.add_argument('--batch_size', default=16, type=int,
help='batch size.')
parser.add_argument('--learning_rate', default=1e-3, type=float,
help='batch size.')
parser.add_argument('--warmup_steps', default=5000, type=int)
parser.add_argument('--freeze_after_steps', default=200000, type=int)
parser.add_argument('--freeze_after', action='store_true',
help='freeze the conv stem.')
parser.add_argument('--freeze_out_emb', action='store_true',
help='freeze the output embeddings.')
parser.add_argument('--use_radam', action='store_true',
help='use radam.')
parser.add_argument('--use_sgd', action='store_true',
help='use radam.')
parser.add_argument('--use_adamw', action='store_true',
help='use radam.')
parser.add_argument('--use_dropblock', action='store_true',
help='use dropblock.')
parser.add_argument('--sgd_momentum', default=0.9, type=float)
parser.add_argument('--label_smoothing', default=0.0, type=float)
parser.add_argument('--weight_decay', default=0.0, type=float,
help='weight decay term.')
parser.add_argument('--use_exp', action='store_true',
help='use exp warm up.')
parser.add_argument('--use_warmup', action='store_true',
help='use warmup scheduling.')
parser.add_argument('--grad_cummulate', default=1, type=int,
help='number of gradient accumulation steps.')
parser.add_argument('--report_every', default=100, type=int,
help='Report log every this steps (not used).')
parser.add_argument('--validate_every', default=1000, type=int,
help='Report log every this steps (not used).')
parser.add_argument('--clip', default=0.0, type=float,
help='global norm clipping threshold.')
parser.add_argument('--job_id', default=0, type=int)
# for wandb
parser.add_argument('--project_name', type=str, default=None,
help='project name for wandb.')
parser.add_argument('--job_name', type=str, default=None,
help='job name for wandb.')
parser.add_argument('--use_wandb', action='store_true',
help='use wandb.')
args = parser.parse_args()
model_name = args.model_type
exp_str = ''
for arg_key in vars(args):
exp_str += str(getattr(args, arg_key)) + '-'
# taken from https://stackoverflow.com/questions/16008670/how-to-hash-a-string-into-8-digits
exp_hash = str(int(hashlib.sha1(exp_str.encode("utf-8")).hexdigest(), 16) % (10 ** 8))
job_id = args.job_id
# Set work directory
args.work_dir = os.path.join(
args.work_dir, f"{job_id}-{exp_hash}-{time.strftime('%Y%m%d-%H%M%S')}")
if not os.path.exists(args.work_dir):
os.makedirs(args.work_dir)
work_dir_key = '/'.join(os.path.abspath(args.work_dir).split('/')[-3:])
# logging
log_file_name = f"{args.work_dir}/log.txt"
handlers = [logging.FileHandler(log_file_name), logging.StreamHandler()]
logging.basicConfig(
level=logging.INFO, format='%(message)s', handlers=handlers)
loginf = logging.info
loginf(f"torch version: {torch.__version__}")
loginf(f"Work dir: {args.work_dir}")
# wandb settings
if args.use_wandb: # configure wandb.
import wandb
use_wandb = True
# fix to remove extra HTTPS connection logs
# https://stackoverflow.com/questions/11029717/how-do-i-disable-log-messages-from-the-requests-library
logging.getLogger("requests").setLevel(logging.WARNING)
if args.project_name is None:
project_name = (os.uname()[1]
+ datetime.now().strftime("%Y-%m-%d-%H-%M-%S"))
else:
project_name = args.project_name
wandb.init(
project=project_name, settings=wandb.Settings(start_method='fork'))
# or `settings=wandb.Settings(start_method='thread')`
if args.job_name is None:
wandb.run.name = f"{os.uname()[1]}//" \
f"{model_name}-{args.name_dataset}//" \
f"seed{args.seed}//radam{args.use_radam}/" \
f"wd{args.weight_decay}/ip{args.input_dropout}/" \
f"{args.dropout_type}/ls{args.label_smoothing}/" \
f"adamw{args.use_adamw}/dropb{args.use_dropblock}/" \
f"freeze{args.freeze_after}/e{args.freeze_out_emb}/" \
f"use_warm{args.use_warmup}/exp{args.use_exp}/" \
f"psz{args.patch_size}/tk{args.ff_factor_tk}/" \
f"fzstep{args.freeze_after_steps}/" \
f"{args.test_per_class}-test_per_cl/" \
f"{args.n_way}way-{args.k_shot}shot/" \
f"L{args.num_layer}/h{args.hidden_size}/" \
f"n{args.n_head}/ff{args.ff_factor}/" \
f"d{args.dropout}/vd{args.vision_dropout}/" \
f"bigres{args.use_big_res12}/b{args.batch_size}/" \
f"lr{args.learning_rate}/warm{args.warmup_steps}" \
f"g{args.grad_cummulate}/bias{args.srwm_beta_init}" \
f"softmax{args.use_input_softmax}" \
f"//PATH'{work_dir_key}'//"
else:
wandb.run.name = f"{os.uname()[1]}//{args.job_name}"
config = wandb.config
config.host = os.uname()[1] # host node name
config.seed = args.seed
config.test_per_class = args.test_per_class
config.extra_label = args.extra_label
config.use_ab = args.use_ab
config.use_ab_v2 = args.use_ab_v2
config.use_abc_v2 = args.use_abc_v2
config.disable_ct = args.disable_ct
config.disable_multi = args.disable_multi
config.use_fs = args.use_fs
config.use_fc = args.use_fc
config.use_cache = args.use_cache
config.use_acl = args.use_acl
config.loss_scale_task_a = args.loss_scale_task_a
config.use_b_first = args.use_b_first
config.remove_bn = args.remove_bn
config.use_instance_norm = args.use_instance_norm
config.n_way = args.n_way
config.k_shot = args.k_shot
config.srwm_beta_init = args.srwm_beta_init
config.use_input_softmax = args.use_input_softmax
config.context_carry_over = args.context_carry_over
config.context_carry_over_double = args.context_carry_over_double
config.context_carry_over_k = args.context_carry_over_k
config.single_state_training = args.single_state_training
config.name_dataset = args.name_dataset
config.work_dir = args.work_dir
config.model_type = args.model_type
config.hidden_size = args.hidden_size
config.n_head = args.n_head
config.ff_factor = args.ff_factor
config.dropout = args.dropout
config.vision_dropout = args.vision_dropout
config.use_big_res12 = args.use_big_res12
config.batch_size = args.batch_size
config.learning_rate = args.learning_rate
config.warmup_steps = args.warmup_steps
config.freeze_after = args.freeze_after
config.freeze_out_emb = args.freeze_out_emb
config.freeze_after_steps = args.freeze_after_steps
config.grad_cummulate = args.grad_cummulate
config.use_radam = args.use_radam
config.use_sgd = args.use_sgd
config.use_adamw = args.use_adamw
config.sgd_momentum = args.sgd_momentum
config.input_dropout = args.input_dropout
config.dropout_type = args.dropout_type
config.use_dropblock = args.use_dropblock
config.weight_decay = args.weight_decay
config.label_smoothing = args.label_smoothing
config.report_every = args.report_every
config.not_use_ln = args.not_use_ln
config.not_use_res = args.not_use_res
config.not_use_ff = args.not_use_ff
config.patch_size = args.patch_size
config.ff_factor_tk = args.ff_factor_tk
else:
use_wandb = False
# end wandb
# save args
loginf(f"Command executed: {sys.argv[:]}")
loginf(f"Args: {json.dumps(args.__dict__, indent=2)}")
with open(f'{args.work_dir}/args.txt', 'w') as f:
json.dump(args.__dict__, f, indent=2)
# set seed
loginf(f"Seed: {args.seed}")
seed = args.seed
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
valid_seed = args.valid_seed
test_seed = args.test_seed
loginf(f"Valid seed: {valid_seed}, Test seed: {test_seed}")
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
# torch.backends.cudnn.benchmark = False
# set dataset
batch_size = args.batch_size
n_way = args.n_way
k_shot_train = args.k_shot
test_per_class = args.test_per_class
# Let's hard code this
args.drop_last_batch = True
if args.use_ab or args.use_ab_v2:
if args.use_cache:
if args.use_fc:
if args.use_b_first:
loginf(f"A-B training on miniimagenet_32_norm_cache and fc100_norm")
from torchmeta_local.datasets.helpers import fc100_norm as data_cls_b
from torchmeta_local.datasets.helpers import miniimagenet_32_norm_cache as data_cls_a
else:
loginf(f"A-B training on fc100_norm and miniimagenet_32_norm_cache")
from torchmeta_local.datasets.helpers import fc100_norm as data_cls_a
from torchmeta_local.datasets.helpers import miniimagenet_32_norm_cache as data_cls_b
else:
if args.use_b_first:
loginf(f"A-B training on miniimagenet_32_norm_cache and omniglot_32_norm")
from torchmeta_local.datasets.helpers import omniglot_32_norm as data_cls_b
from torchmeta_local.datasets.helpers import miniimagenet_32_norm_cache as data_cls_a
else:
loginf(f"A-B training on omniglot_32_norm and miniimagenet_32_norm_cache")
from torchmeta_local.datasets.helpers import omniglot_32_norm as data_cls_a
from torchmeta_local.datasets.helpers import miniimagenet_32_norm_cache as data_cls_b
elif args.use_84:
loginf(f"A-B training on omniglot_84_norm and miniimagenet_84_norm")
from torchmeta_local.datasets.helpers import omniglot_rgb84x84_norm as data_cls_a
from torchmeta_local.datasets.helpers import miniimagenet_norm as data_cls_b
else:
if args.use_fc:
loginf(f"A-B training on fc100_norm and miniimagenet_32_norm")
from torchmeta_local.datasets.helpers import fc100_norm as data_cls_a
from torchmeta_local.datasets.helpers import miniimagenet_32_norm as data_cls_b
else:
loginf(f"A-B training on omniglot_32_norm and miniimagenet_32_norm")
from torchmeta_local.datasets.helpers import omniglot_32_norm as data_cls_a
from torchmeta_local.datasets.helpers import miniimagenet_32_norm as data_cls_b
# use first shot loss
use_fs = args.use_fs
if args.use_fs:
assert model_name in [
'compat_stateful_srwm', 'stateful_deltanet', 'compat_stateful_deltanet',
'compat_stateful_srwm_res12', 'compat_stateful_srwm_mixer',
'compat_stateful_self_mod_mixer']
num_samples_per_class = {
'first_shot': 1, 'train': k_shot_train, 'test': test_per_class}
dataset_a = data_cls_a(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed,
num_samples_per_class=num_samples_per_class)
dataset_b = data_cls_b(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed,
num_samples_per_class=num_samples_per_class)
else:
dataset_a = data_cls_a(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed)
dataset_b = data_cls_b(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed)
dataloader_a = BatchMetaDataLoader(
dataset_a, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
dataloader_b = BatchMetaDataLoader(
dataset_b, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
# valid
val_dataset_a = data_cls_a(args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_val=True,
shuffle=True, seed=valid_seed) # fixed validation set
val_dataset_b = data_cls_b(args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_val=True,
shuffle=True, seed=valid_seed) # fixed validation set
val_dataloader_a = BatchMetaDataLoader(
val_dataset_a, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
val_dataloader_b = BatchMetaDataLoader(
val_dataset_b, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
# test
test_dataset_a = data_cls_a(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_test=True,
download=True, shuffle=True, seed=test_seed)
test_dataset_b = data_cls_b(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_test=True,
download=True, shuffle=True, seed=test_seed)
test_dataloader_a = BatchMetaDataLoader(
test_dataset_a, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
test_dataloader_b = BatchMetaDataLoader(
test_dataset_b, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
if args.cycle_dataloader:
zip_dataloader_a_b = zip(cycle(dataloader_a), cycle(dataloader_b))
else:
zip_dataloader_a_b = zip(dataloader_a, dataloader_b)
# end use_ab or use_ab_v2
elif args.use_abc_v2:
loginf(f"A-B-C training on omniglot_32_norm, miniimagenet_32_norm_cache and fc100_norm")
from torchmeta_local.datasets.helpers import omniglot_32_norm as data_cls_a
from torchmeta_local.datasets.helpers import miniimagenet_32_norm_cache as data_cls_b
from torchmeta_local.datasets.helpers import fc100_norm as data_cls_c
# use first shot loss
use_fs = args.use_fs
if args.use_fs:
assert model_name in [
'compat_stateful_srwm', 'stateful_deltanet', 'compat_stateful_deltanet',
'compat_stateful_srwm_res12', 'compat_stateful_srwm_mixer',
'compat_stateful_self_mod_mixer']
num_samples_per_class = {
'first_shot': 1, 'train': k_shot_train, 'test': test_per_class}
dataset_a = data_cls_a(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed,
num_samples_per_class=num_samples_per_class)
dataset_b = data_cls_b(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed,
num_samples_per_class=num_samples_per_class)
dataset_c = data_cls_c(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed,
num_samples_per_class=num_samples_per_class)
else:
dataset_a = data_cls_a(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed)
dataset_b = data_cls_b(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed)
dataset_c = data_cls_c(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed)
dataloader_a = BatchMetaDataLoader(
dataset_a, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
dataloader_b = BatchMetaDataLoader(
dataset_b, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
dataloader_c = BatchMetaDataLoader(
dataset_c, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
# valid
val_dataset_a = data_cls_a(args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_val=True,
shuffle=True, seed=valid_seed) # fixed validation set
val_dataset_b = data_cls_b(args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_val=True,
shuffle=True, seed=valid_seed) # fixed validation set
val_dataset_c = data_cls_c(args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_val=True,
shuffle=True, seed=valid_seed) # fixed validation set
val_dataloader_a = BatchMetaDataLoader(
val_dataset_a, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
val_dataloader_b = BatchMetaDataLoader(
val_dataset_b, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
val_dataloader_c = BatchMetaDataLoader(
val_dataset_c, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
# test
test_dataset_a = data_cls_a(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_test=True,
download=True, shuffle=True, seed=test_seed)
test_dataset_b = data_cls_b(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_test=True,
download=True, shuffle=True, seed=test_seed)
test_dataset_c = data_cls_c(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_test=True,
download=True, shuffle=True, seed=test_seed)
test_dataloader_a = BatchMetaDataLoader(
test_dataset_a, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
test_dataloader_b = BatchMetaDataLoader(
test_dataset_b, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
test_dataloader_c = BatchMetaDataLoader(
test_dataset_c, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
if args.cycle_dataloader:
zip_dataloader_a_b_c = zip(
cycle(dataloader_a), cycle(dataloader_b), cycle(dataloader_c))
else:
zip_dataloader_a_b_c = zip(dataloader_a, dataloader_b, dataloader_c)
elif args.train_splitmnist_style:
# lazy implementation:
# we independently draw 5 2-way tasks; this might end up in an ill-conditioned setting where the
# certain classes are assigned to two different labels within the same sequence.
# Ideally, we should draw one 10-way task instead and split it.
loginf(f"Split-MNIST-like domain-incremental 5-task training")
if args.mix_metafinetuning:
from torchmeta_local.datasets.helpers import omniglot_32_norm as data_cls_a
from torchmeta_local.datasets.helpers import miniimagenet_32_norm_cache as data_cls_b
else:
from torchmeta_local.datasets.helpers import omniglot_32_norm as data_cls_a
# use first shot loss
use_fs = args.use_fs
if args.use_fs:
assert model_name in [
'compat_stateful_srwm', 'stateful_deltanet', 'compat_stateful_deltanet',
'compat_stateful_srwm_res12', 'compat_stateful_srwm_mixer',
'compat_stateful_self_mod_mixer']
num_samples_per_class = {
'first_shot': 1, 'train': k_shot_train, 'test': test_per_class}
dataset_a = data_cls_a(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed,
num_samples_per_class=num_samples_per_class)
if args.mix_metafinetuning:
dataset_b = data_cls_b(
args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed,
num_samples_per_class=num_samples_per_class)
else:
assert False
dataloader_a = BatchMetaDataLoader(
dataset_a, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
if args.mix_metafinetuning:
dataloader_b = BatchMetaDataLoader(
dataset_b, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
elif args.train_splitmnist_style_class_incremental:
# lazy implementation:
# we draw 5 2-way tasks and shift the target labels by task_id * 2
# this might end up in an ill-conditioned setting where certain classes are assigned to
# two different labels within the same sequence.
# Ideally, we should draw one 10-way task instead and split it.
loginf(f"Split-MNIST-like class-incremental 5-task training")
if args.mix_metafinetuning:
from torchmeta_local.datasets.helpers import omniglot_32_norm as data_cls_a
from torchmeta_local.datasets.helpers import miniimagenet_32_norm_cache as data_cls_b
else:
from torchmeta_local.datasets.helpers import omniglot_32_norm as data_cls_a
# use first shot loss
use_fs = args.use_fs
if args.use_fs:
assert model_name in [
'compat_stateful_srwm', 'stateful_deltanet', 'compat_stateful_deltanet',
'compat_stateful_srwm_res12', 'compat_stateful_srwm_mixer',
'compat_stateful_self_mod_mixer']
num_samples_per_class = {
'first_shot': 1, 'train': k_shot_train, 'test': test_per_class}
dataset_a = data_cls_a(
args.data_dir, ways=2, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed,
num_samples_per_class=num_samples_per_class)
if args.mix_metafinetuning:
dataset_b = data_cls_b(
args.data_dir, ways=2, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed,
num_samples_per_class=num_samples_per_class)
else:
assert False
dataloader_a = BatchMetaDataLoader(
dataset_a, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
if args.mix_metafinetuning:
dataloader_b = BatchMetaDataLoader(
dataset_b, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
else:
loginf(f"Dataset/Task: {args.name_dataset}")
if args.name_dataset == 'omniglot':
from torchmeta_local.datasets.helpers import omniglot as data_cls
elif args.name_dataset == 'omniglot_norm':
from torchmeta_local.datasets.helpers import omniglot_norm as data_cls
elif args.name_dataset == 'omniglot_32_norm':
from torchmeta_local.datasets.helpers import omniglot_32_norm as data_cls
elif args.name_dataset == 'miniimagenet':
from torchmeta_local.datasets.helpers import miniimagenet as data_cls
elif args.name_dataset == 'tieredimagenet':
from torchmeta_local.datasets.helpers import tieredimagenet as data_cls
elif args.name_dataset == 'miniimagenet_norm': # mean/std normalized
from torchmeta_local.datasets.helpers import (
miniimagenet_norm as data_cls)
elif args.name_dataset == 'miniimagenet_32_norm':
from torchmeta_local.datasets.helpers import (
miniimagenet_32_norm as data_cls)
elif args.name_dataset == 'miniimagenet_32_norm_cache':
from torchmeta_local.datasets.helpers import (
miniimagenet_32_norm_cache as data_cls)
elif args.name_dataset == 'omniglot_rgb84x84':
from torchmeta_local.datasets.helpers import omniglot_rgb84x84 as data_cls
elif args.name_dataset == 'omniglot_rgb84x84_norm': # mean/std normalized
from torchmeta_local.datasets.helpers import (
omniglot_rgb84x84_norm as data_cls)
elif args.name_dataset == 'fc100':
from torchmeta_local.datasets.helpers import fc100 as data_cls
elif args.name_dataset == 'cifar_fs':
from torchmeta_local.datasets.helpers import cifar_fs as data_cls
elif args.name_dataset == 'cifar_fs_norm':
from torchmeta_local.datasets.helpers import cifar_fs_norm as data_cls
elif args.name_dataset == 'cifar_fs_rfs':
from torchmeta_local.datasets.helpers import cifar_fs_rfs as data_cls
elif args.name_dataset == 'fc100_norm':
from torchmeta_local.datasets.helpers import fc100_norm as data_cls
elif args.name_dataset == 'fc100_rfs':
from torchmeta_local.datasets.helpers import fc100_rfs as data_cls
else:
assert False, f'Unknown dataset: {args.name_dataset}'
# use first shot loss
use_fs = args.use_fs
if args.use_fs:
assert model_name in [
'compat_stateful_srwm', 'stateful_deltanet', 'compat_stateful_deltanet',
'compat_stateful_srwm_res12', 'compat_stateful_srwm_mixer',
'compat_stateful_self_mod_mixer']
num_samples_per_class = {
'first_shot': 1, 'train': k_shot_train, 'test': test_per_class}
dataset = data_cls(args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed,
num_samples_per_class=num_samples_per_class)
else:
dataset = data_cls(args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_train=True,
download=True, shuffle=True, seed=seed)
dataloader = BatchMetaDataLoader(
dataset, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
if args.name_dataset == 'fc100_rfs':
from torchmeta_local.datasets.helpers import fc100_norm as data_cls
if args.name_dataset == 'cifar_fs_rfs':
from torchmeta_local.datasets.helpers import cifar_fs_norm as data_cls
val_dataset = data_cls(args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_val=True,
shuffle=True, seed=valid_seed) # fixed validation set
if args.fixed_valid:
# https://github.com/tristandeleu/pytorch-meta/issues/132
valid_class_size = len(val_dataset.dataset) # num classes in valid
# `dataset` here is torchmeta ClassDataset
import itertools
from torch.utils.data import Subset
cls_indices = np.array(range(valid_class_size))
all_indices = []
for subset in itertools.combinations(cls_indices, args.n_way):
all_indices.append(subset)
val_total_size = args.valid_size * batch_size
val_indices = random.sample(all_indices, val_total_size)
val_dataset = Subset(val_dataset, val_indices)
val_dataloader = BatchMetaDataLoader(
val_dataset, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
test_dataset = data_cls(args.data_dir, ways=n_way, shots=k_shot_train,
test_shots=test_per_class, meta_test=True,
download=True, shuffle=True, seed=test_seed)
if args.fixed_test:
# https://github.com/tristandeleu/pytorch-meta/issues/132
test_class_size = len(test_dataset.dataset) # num classes in valid
# `dataset` here is torchmeta ClassDataset
import itertools
from torch.utils.data import Subset
cls_indices = np.array(range(test_class_size))
all_indices = []
for subset in itertools.combinations(cls_indices, args.n_way):
all_indices.append(subset)
test_total_size = args.test_size * batch_size
test_indices = random.sample(all_indices, test_total_size)
test_dataset = Subset(test_dataset, test_indices)
test_dataloader = BatchMetaDataLoader(
test_dataset, batch_size=batch_size, num_workers=args.num_worker,
pin_memory=True, drop_last=args.drop_last_batch)
device = 'cuda'
# setting model
hidden_size = args.hidden_size
num_classes = args.n_way
num_layer = args.num_layer
n_head = args.n_head
dim_head = hidden_size // n_head
dim_ff = hidden_size * args.ff_factor
dropout_rate = args.dropout
vision_dropout = args.vision_dropout
# is_imagenet = args.name_dataset != 'omniglot'
is_imagenet = args.name_dataset not in ['omniglot', 'omniglot_norm']
is_fc100 = False
if args.name_dataset in ['fc100', 'fc100_norm', 'fc100_rfs', 'cifar_fs', 'cifar_fs_norm', 'cifar_fs_rfs',
'miniimagenet_32_norm', 'miniimagenet_32_norm_cache', 'omniglot_32_norm']:
is_fc100 = True
is_imagenet = False
if model_name == 'lstm': # conv lstm
loginf("Model: LSTM")
model = ConvLSTMModel(hidden_size, num_classes, num_layer=num_layer,
vision_dropout=vision_dropout,
imagenet=is_imagenet, fc100=is_fc100)
elif model_name == 'deltanet':
loginf("Model: DeltaNet")
model = ConvDeltaModel(hidden_size=hidden_size, num_layers=num_layer,
num_head=n_head, dim_head=dim_head, dim_ff=dim_ff,
dropout=dropout_rate, num_classes=num_classes,
vision_dropout=vision_dropout,
imagenet=is_imagenet, fc100=is_fc100)
elif model_name in ['stateful_deltanet', 'compat_stateful_deltanet']:
loginf("Model: Stateful DeltaNet")
model = StatefulConvDeltaModel(hidden_size=hidden_size, num_layers=num_layer,
num_head=n_head, dim_head=dim_head, dim_ff=dim_ff,
dropout=dropout_rate, num_classes=num_classes,
vision_dropout=vision_dropout,
imagenet=is_imagenet, fc100=is_fc100,
single_state_training=args.single_state_training,
extra_label=args.extra_label,
remove_bn=args.remove_bn,
use_instance_norm=args.use_instance_norm)
elif model_name == 'srwm':
loginf("Model: Self-Referential learning")
model = ConvSRWMModel(hidden_size=hidden_size, num_layers=num_layer,
num_head=n_head, dim_head=dim_head, dim_ff=dim_ff,
dropout=dropout_rate, num_classes=num_classes,
vision_dropout=vision_dropout,
use_ln=True, beta_init=args.srwm_beta_init,
use_input_softmax=args.use_input_softmax,
input_dropout=args.input_dropout,
dropout_type=args.dropout_type,
imagenet=is_imagenet, fc100=is_fc100,
init_scaler=args.srwm_init_scaler,
q_init_scaler=args.srwm_q_init_scaler,
unif_init=args.unif_init,
no_softmax_on_y=args.no_softmax_on_y,
remove_bn=args.remove_bn,
use_instance_norm=args.use_instance_norm)
elif model_name == 'compat_stateful_srwm':
loginf("Model: Self-Referential learning")
model = CompatStatefulConvSRWMModel(hidden_size=hidden_size, num_layers=num_layer,
num_head=n_head, dim_head=dim_head, dim_ff=dim_ff,
dropout=dropout_rate, num_classes=num_classes,
vision_dropout=vision_dropout,
use_ln=True, beta_init=args.srwm_beta_init,
use_input_softmax=args.use_input_softmax,
input_dropout=args.input_dropout,
dropout_type=args.dropout_type,
imagenet=is_imagenet, fc100=is_fc100,
init_scaler=args.srwm_init_scaler,
q_init_scaler=args.srwm_q_init_scaler,
unif_init=args.unif_init,
single_state_training=args.single_state_training,
no_softmax_on_y=args.no_softmax_on_y,
extra_label=args.extra_label,
remove_bn=args.remove_bn,
use_instance_norm=args.use_instance_norm)
elif model_name == 'compat_stateful_srwm_mixer':
loginf("Model: Mixer, Self-Referential learning")
model = CompatStatefulMixerSRWMModel(hidden_size=hidden_size, num_layers=num_layer,
num_head=n_head, dim_head=dim_head, dim_ff=dim_ff,
dropout=dropout_rate, num_classes=num_classes,
vision_dropout=vision_dropout,
use_ln=True, beta_init=args.srwm_beta_init,
use_input_softmax=args.use_input_softmax,
input_dropout=args.input_dropout,
dropout_type=args.dropout_type,
patch_size=args.patch_size,
expansion_factor=dim_ff,
expansion_factor_token=args.ff_factor_tk,
imagenet=is_imagenet, fc100=is_fc100,
init_scaler=args.srwm_init_scaler,
q_init_scaler=args.srwm_q_init_scaler,
unif_init=args.unif_init,
single_state_training=args.single_state_training,
no_softmax_on_y=args.no_softmax_on_y,
extra_label=args.extra_label)
elif model_name == 'compat_stateful_self_mod_mixer':
loginf("Model: Mixer, Self-Referential learning")
model = CompatStatefulSelfModMixerModel(hidden_size=hidden_size, num_layers=num_layer,
num_head=n_head, dim_head=dim_head, dim_ff=dim_ff,
dropout=dropout_rate, num_classes=num_classes,
vision_dropout=vision_dropout,
use_ln=True, beta_init=args.srwm_beta_init,
use_input_softmax=args.use_input_softmax,
input_dropout=args.input_dropout,
dropout_type=args.dropout_type,
patch_size=args.patch_size,
expansion_factor=dim_ff,
expansion_factor_token=args.ff_factor_tk,
imagenet=is_imagenet, fc100=is_fc100,
init_scaler=args.srwm_init_scaler,
q_init_scaler=args.srwm_q_init_scaler,
unif_init=args.unif_init,
single_state_training=args.single_state_training,
no_softmax_on_y=args.no_softmax_on_y,
extra_label=args.extra_label)
elif model_name == 'mixer_srwm':
loginf("Model: Self-Referential learning")
model = MixerSRWMModel(hidden_size=hidden_size, num_layers=num_layer,
num_head=n_head, dim_head=dim_head, dim_ff=dim_ff,
dropout=dropout_rate, num_classes=num_classes,