-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmodel_few_shot.py
1830 lines (1479 loc) · 69.9 KB
/
model_few_shot.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
from operator import xor
import torch
import torch.nn as nn
from layer import FastFFlayer, TransformerFFlayers, SRWMlayer
from utils_other.resnet_impl import resnet12_base
from utils_other.resnet_dropblock_impl import resnet12_dropblock
from utils_other.mlpmixer_impl import MLPMixer, FeedForward, PreNormResidual
from einops.layers.torch import Rearrange, Reduce
pair = lambda x: x if isinstance(x, tuple) else (x, x)
class BaseModel(nn.Module):
def __init__(self):
super().__init__()
# return number of parameters
def num_params(self):
return sum(p.numel() for p in self.parameters() if p.requires_grad)
def reset_grad(self):
# More efficient than optimizer.zero_grad() according to:
# Szymon Migacz "PYTORCH PERFORMANCE TUNING GUIDE" at GTC-21.
# - doesn't execute memset for every parameter
# - memory is zeroed-out by the allocator in a more efficient way
# - backward pass updates gradients with "=" operator (write) (unlike
# zero_grad() which would result in "+=").
# In PyT >= 1.7, one can do `model.zero_grad(set_to_none=True)`
for p in self.parameters():
p.grad = None
def print_params(self):
for p in self.named_parameters():
print(p)
# set batch norm in eval mode (preventing mean/var updates)
def set_bn_in_eval_mode(self):
for _, module in self.named_modules():
if isinstance(module, nn.BatchNorm2d):
module.eval()
def set_bn_in_train_mode(self):
for _, module in self.named_modules():
if isinstance(module, nn.BatchNorm2d):
module.train()
class LSTMModel(BaseModel):
def __init__(self, input_size, hidden_size, num_classes, emb_dim=10, imagenet=False):
super(LSTMModel, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.out_layer = nn.Linear(hidden_size, num_classes)
self.rnn = nn.LSTM(hidden_size + emb_dim, hidden_size)
# plus one for the dummy token
self.fb_emb = nn.Embedding(num_classes + 1, emb_dim)
self.activation = nn.ReLU(inplace=True)
def forward(self, x, fb, state=None):
# Assume linealized input: here `images.view(−1, 28*28)`.
x = self.fc1(x)
emb = self.fb_emb(fb)
out = torch.cat([x, emb], dim=-1)
# out = self.activation(out) # or F.relu.
out, _ = self.rnn(out, state)
out = self.out_layer(out)
return out, None
# Conv4 by Vynials et al:
# '''
# We used a simple yet powerful CNN as the embedding function – consisting of a stack of modules,
# each of which is a 3 × 3 convolution with 64 filters followed by batch normalization [10], a Relu
# non-linearity and 2 × 2 max-pooling. We resized all the images to 28 × 28 so that, when we stack 4
# modules, the resulting feature map is 1 × 1 × 64, resulting in our embedding function f(x).
# '''
class ConvLSTMModel(BaseModel):
def __init__(self, hidden_size, num_classes, num_layer=1, imagenet=False,
fc100=False, vision_dropout=0.0, bn_momentum=0.1):
super(ConvLSTMModel, self).__init__()
num_conv_blocks = 4
if imagenet: # mini-imagenet
input_channels = 3
out_num_channel = 32
self.conv_feature_final_size = 32 * 5 * 5 # (B, 32, 5, 5)
elif fc100:
input_channels = 3
out_num_channel = 32
self.conv_feature_final_size = 32 * 2 * 2 # (B, 32, 2, 2)
else: # onmiglot
input_channels = 1
out_num_channel = 64
self.conv_feature_final_size = 64 # final feat shape (B, 64, 1, 1)
self.input_channels = input_channels
self.num_classes = num_classes
list_conv_layers = []
for i in range(num_conv_blocks):
conv_block = []
conv_block.append(
nn.Conv2d(
in_channels=input_channels,
out_channels=out_num_channel,
kernel_size=3,
stride=1,
padding=1,
)
)
conv_block.append(nn.BatchNorm2d(
out_num_channel, momentum=bn_momentum))
conv_block.append(nn.MaxPool2d(kernel_size=2, stride=2, padding=0))
conv_block.append(nn.Dropout(vision_dropout))
conv_block.append(nn.ReLU(inplace=True))
list_conv_layers.append(nn.Sequential(*conv_block))
input_channels = out_num_channel
self.conv_layers = nn.ModuleList(list_conv_layers)
# self.fc1 = nn.Linear(conv_feature_final_size, hidden_size)
self.rnn = nn.LSTM(self.conv_feature_final_size + num_classes,
hidden_size, num_layers=num_layer)
# self.rnn = nn.LSTM(self.conv_feature_final_size + emb_dim, hidden_size)
# plus one for the dummy token
# self.fb_emb = nn.Embedding(num_classes + 1, emb_dim)
self.activation = nn.ReLU(inplace=True)
self.out_layer = nn.Linear(hidden_size, num_classes)
def forward(self, x, fb, state=None):
# Assume input of shape (len, B, 1, 28, 28)
slen, bsz, _, hs, ws = x.shape
x = x.reshape(slen * bsz, self.input_channels, hs, ws)
for conv_layer in self.conv_layers:
x = conv_layer(x)
x = x.reshape(slen, bsz, self.conv_feature_final_size)
emb = torch.nn.functional.one_hot(fb, num_classes=self.num_classes)
# emb = self.fb_emb(fb)
out = torch.cat([x, emb], dim=-1)
# out = self.activation(out) # or F.relu.
out, _ = self.rnn(out, state)
out = self.out_layer(out)
return out, None
# Linear Transformer with the delta update rule.
class DeltaNetModel(BaseModel):
def __init__(self, input_size, hidden_size, num_classes,
num_layers, num_head, dim_head, dim_ff,
dropout, emb_dim=10, imagenet=False):
super(DeltaNetModel, self).__init__()
assert num_head * dim_head == hidden_size
self.fc1 = nn.Linear(input_size, hidden_size)
self.feedback_emb = nn.Embedding(num_classes , emb_dim)
# input projection takes both image and feedback
self.input_proj = nn.Linear(hidden_size + emb_dim, hidden_size)
layers = []
for _ in range(num_layers): # each "layer" consists of two sub-layers
layers.append(
FastFFlayer(num_head, dim_head, hidden_size, dropout))
layers.append(
TransformerFFlayers(dim_ff, hidden_size, dropout))
self.layers = nn.Sequential(*layers)
self.out_layer = nn.Linear(hidden_size, num_classes)
def forward(self, x, fb, state=None):
x = self.fc1(x)
emb = self.feedback_emb(fb)
out = torch.cat([x, emb], dim=-1)
out = self.input_proj(out)
out = self.layers(out)
out = self.out_layer(out)
return out, state
class ConvDeltaModel(BaseModel):
def __init__(self, hidden_size, num_classes, num_layers, num_head,
dim_head, dim_ff, dropout, vision_dropout=0.0, emb_dim=10,
imagenet=False, fc100=False, bn_momentum=0.1, use_pytorch=False):
super(ConvDeltaModel, self).__init__()
num_conv_blocks = 4
if imagenet: # mini-imagenet
input_channels = 3
out_num_channel = 32
self.conv_feature_final_size = 32 * 5 * 5 # (B, 32, 5, 5)
elif fc100:
input_channels = 3
out_num_channel = 32
self.conv_feature_final_size = 32 * 2 * 2 # (B, 32, 5, 5)
else: # onmiglot
input_channels = 1
out_num_channel = 64
self.conv_feature_final_size = 64 # final feat shape (B, 64, 1, 1)
self.input_channels = input_channels
self.num_classes = num_classes
list_conv_layers = []
for _ in range(num_conv_blocks):
conv_block = []
conv_block.append(
nn.Conv2d(
in_channels=input_channels,
out_channels=out_num_channel,
kernel_size=3,
stride=1,
padding=1,
)
)
conv_block.append(nn.BatchNorm2d(
out_num_channel, momentum=bn_momentum))
conv_block.append(nn.MaxPool2d(kernel_size=2, stride=2, padding=0))
conv_block.append(nn.Dropout(vision_dropout))
conv_block.append(nn.ReLU(inplace=True))
list_conv_layers.append(nn.Sequential(*conv_block))
input_channels = out_num_channel
self.conv_layers = nn.ModuleList(list_conv_layers)
self.input_proj = nn.Linear(
self.conv_feature_final_size + num_classes, hidden_size)
layers = []
for _ in range(num_layers): # each "layer" consists of two sub-layers
layers.append(
FastFFlayer(num_head, dim_head, hidden_size, dropout))
layers.append(
TransformerFFlayers(dim_ff, hidden_size, dropout))
self.layers = nn.Sequential(*layers)
self.activation = nn.ReLU(inplace=True)
self.out_layer = nn.Linear(hidden_size, num_classes)
def forward(self, x, fb, state=None):
# Assume input of shape (len, B, 1, 28, 28)
slen, bsz, _, hs, ws = x.shape
x = x.reshape(slen * bsz, self.input_channels, hs, ws)
for conv_layer in self.conv_layers:
x = conv_layer(x)
x = x.reshape(slen, bsz, self.conv_feature_final_size)
emb = torch.nn.functional.one_hot(fb, num_classes=self.num_classes)
# emb = self.fb_emb(fb)
out = torch.cat([x, emb], dim=-1)
# out = self.activation(out) # or F.relu.
out = self.input_proj(out)
out = self.layers(out)
out = self.out_layer(out)
return out, None
class StatefulConvDeltaModel(BaseModel):
def __init__(self, hidden_size, num_classes, num_layers, num_head,
dim_head, dim_ff, dropout, vision_dropout=0.0, emb_dim=10,
imagenet=False, fc100=False, bn_momentum=0.1, use_pytorch=False,
single_state_training=False, extra_label=False,
remove_bn=False, use_instance_norm=False):
super(StatefulConvDeltaModel, self).__init__()
num_conv_blocks = 4
if imagenet: # mini-imagenet
input_channels = 3
out_num_channel = 32
self.conv_feature_final_size = 32 * 5 * 5 # (B, 32, 5, 5)
elif fc100:
input_channels = 3
out_num_channel = 32
self.conv_feature_final_size = 32 * 2 * 2 # (B, 32, 5, 5)
else: # onmiglot
input_channels = 1
out_num_channel = 64
self.conv_feature_final_size = 64 # final feat shape (B, 64, 1, 1)
self.input_channels = input_channels
self.num_classes = num_classes
self.extra_label = extra_label
if extra_label:
self.num_input_classes = num_classes + 1
else:
self.num_input_classes = num_classes
list_conv_layers = []
for _ in range(num_conv_blocks):
conv_block = []
conv_block.append(
nn.Conv2d(
in_channels=input_channels,
out_channels=out_num_channel,
kernel_size=3,
stride=1,
padding=1,
)
)
if use_instance_norm:
conv_block.append(nn.InstanceNorm2d(
out_num_channel, affine=True))
elif not remove_bn:
conv_block.append(nn.BatchNorm2d(
out_num_channel, momentum=bn_momentum))
conv_block.append(nn.MaxPool2d(kernel_size=2, stride=2, padding=0))
conv_block.append(nn.Dropout(vision_dropout))
conv_block.append(nn.ReLU(inplace=True))
list_conv_layers.append(nn.Sequential(*conv_block))
input_channels = out_num_channel
self.conv_layers = nn.ModuleList(list_conv_layers)
self.input_proj = nn.Linear(
self.conv_feature_final_size + self.num_input_classes, hidden_size)
layers = []
assert not use_pytorch, 'not implemented.'
self.num_layers = num_layers
for _ in range(num_layers): # each "layer" consists of two sub-layers
layers.append(
FastFFlayer(num_head, dim_head, hidden_size, dropout, stateful=True,
single_state_training=single_state_training))
layers.append(
TransformerFFlayers(dim_ff, hidden_size, dropout))
self.layers = nn.ModuleList(layers)
self.activation = nn.ReLU(inplace=True)
self.out_layer = nn.Linear(hidden_size, num_classes)
def clone_state_drop(self, state, drop2d_layer):
W_state = state
B, H, D, _ = W_state[0].shape
W_state_list = []
for i in range(self.num_layers):
W_state_list.append(drop2d_layer(W_state[i].clone().detach().reshape(B, 1, H*D, -1).transpose(0, 1)).transpose(0, 1).reshape(B, H, D, -1))
W_state_tuple = tuple(W_state_list)
return W_state_tuple
def clone_state(self, state, detach=False):
W_state = state
B, H, D, _ = W_state[0].shape
W_state_list = []
for i in range(self.num_layers):
if detach:
W_state_list.append(W_state[i].detach().clone())
else:
W_state_list.append(W_state[i].clone())
W_state_tuple = tuple(W_state_list)
return W_state_tuple
def forward(self, x, fb, state=None):
# Assume input of shape (len, B, 1, 28, 28)
slen, bsz, _, hs, ws = x.shape
x = x.reshape(slen * bsz, self.input_channels, hs, ws)
for conv_layer in self.conv_layers:
x = conv_layer(x)
x = x.reshape(slen, bsz, self.conv_feature_final_size)
emb = torch.nn.functional.one_hot(fb, num_classes=self.num_input_classes)
# emb = self.fb_emb(fb)
out = torch.cat([x, emb], dim=-1)
# out = self.activation(out) # or F.relu.
out = self.input_proj(out)
# forward main layers
W_state_list = []
if state is not None:
W = state
for i in range(self.num_layers):
if state is not None:
out, out_state = self.layers[2 * i](
out,
state=W[i],
get_state=True)
else:
out, out_state = self.layers[2 * i](
out,
get_state=True)
W_state_list.append(out_state)
out = self.layers[2 * i + 1](out)
out = self.out_layer(out)
W_state_tuple = tuple(W_state_list)
return out, W_state_tuple
class ConvSRWMModel(BaseModel):
def __init__(self, hidden_size, num_classes,
num_layers, num_head, dim_head, dim_ff,
dropout, vision_dropout=0.0, emb_dim=10, use_ln=True, use_input_softmax=False,
beta_init=0., imagenet=False, fc100=False, bn_momentum=0.1,
input_dropout=0.0, dropout_type='base', init_scaler=1., q_init_scaler=0.01,
unif_init=False, no_softmax_on_y=False, remove_bn=False,
use_instance_norm=False):
super(ConvSRWMModel, self).__init__()
num_conv_blocks = 4
if imagenet: # mini-imagenet
input_channels = 3
out_num_channel = 32
self.conv_feature_final_size = 32 * 5 * 5 # (B, 32, 5, 5)
elif fc100:
input_channels = 3
out_num_channel = 32
self.conv_feature_final_size = 32 * 2 * 2 # (B, 32, 5, 5)
else: # onmiglot
input_channels = 1
out_num_channel = 64
self.conv_feature_final_size = 64 # final feat shape (B, 64, 1, 1)
self.input_channels = input_channels
self.num_classes = num_classes
list_conv_layers = []
for _ in range(num_conv_blocks):
conv_block = []
conv_block.append(
nn.Conv2d(
in_channels=input_channels,
out_channels=out_num_channel,
kernel_size=3,
stride=1,
padding=1,
)
)
if use_instance_norm:
conv_block.append(nn.InstanceNorm2d(
out_num_channel, affine=True))
elif not remove_bn:
conv_block.append(nn.BatchNorm2d(
out_num_channel, momentum=bn_momentum))
conv_block.append(nn.MaxPool2d(kernel_size=2, stride=2, padding=0))
if '2d' in dropout_type:
conv_block.append(nn.Dropout2d(vision_dropout))
else:
conv_block.append(nn.Dropout(vision_dropout))
conv_block.append(nn.ReLU(inplace=True))
list_conv_layers.append(nn.Sequential(*conv_block))
input_channels = out_num_channel
self.conv_layers = nn.ModuleList(list_conv_layers)
self.input_proj = nn.Linear(
self.conv_feature_final_size + num_classes, hidden_size)
# self.input_layer_norm = nn.LayerNorm(self.conv_feature_final_size)
layers = []
for _ in range(num_layers): # each "layer" consists of two sub-layers
layers.append(
SRWMlayer(num_head, dim_head, hidden_size, dropout, use_ln,
use_input_softmax, beta_init,
init_scaler=init_scaler, q_init_scaler=q_init_scaler,
unif_init=unif_init, no_softmax_on_y=no_softmax_on_y))
layers.append(
TransformerFFlayers(dim_ff, hidden_size, dropout))
self.layers = nn.Sequential(*layers)
self.activation = nn.ReLU(inplace=True)
self.out_layer = nn.Linear(hidden_size, num_classes)
if dropout_type == 'base':
self.input_drop = nn.Dropout(input_dropout)
else:
self.input_drop = nn.Dropout2d(input_dropout)
def forward(self, x, fb, state=None):
# Assume input of shape (len, B, 1, 28, 28)
slen, bsz, _, hs, ws = x.shape
x = x.reshape(slen * bsz, self.input_channels, hs, ws)
x = self.input_drop(x)
for conv_layer in self.conv_layers:
x = conv_layer(x)
x = x.reshape(slen, bsz, self.conv_feature_final_size)
# TODO remove?
# x = self.input_layer_norm(x)
emb = torch.nn.functional.one_hot(fb, num_classes=self.num_classes)
# emb = self.fb_emb(fb)
out = torch.cat([x, emb], dim=-1)
# out = self.activation(out) # or F.relu.
out = self.input_proj(out)
out = self.layers(out)
out = self.out_layer(out)
return out, None
class CompatStatefulConvSRWMModel(BaseModel):
def __init__(self, hidden_size, num_classes,
num_layers, num_head, dim_head, dim_ff,
dropout, vision_dropout=0.0, emb_dim=10, use_ln=True,
use_input_softmax=False,
beta_init=0., imagenet=False, fc100=False, bn_momentum=0.1,
input_dropout=0.0, dropout_type='base',
init_scaler=1., q_init_scaler=0.01,
unif_init=False, single_state_training=False,
no_softmax_on_y=False, extra_label=False, remove_bn=False,
use_instance_norm=False):
super().__init__()
num_conv_blocks = 4
if imagenet: # mini-imagenet
input_channels = 3
out_num_channel = 32
self.conv_feature_final_size = 32 * 5 * 5 # (B, 32, 5, 5)
elif fc100:
input_channels = 3
out_num_channel = 32
self.conv_feature_final_size = 32 * 2 * 2 # (B, 32, 5, 5)
else: # onmiglot
input_channels = 1
out_num_channel = 64
self.conv_feature_final_size = 64 # final feat shape (B, 64, 1, 1)
self.input_channels = input_channels
self.num_classes = num_classes
self.extra_label = extra_label
if extra_label:
self.num_input_classes = num_classes + 1
else:
self.num_input_classes = num_classes
list_conv_layers = []
for _ in range(num_conv_blocks):
conv_block = []
conv_block.append(
nn.Conv2d(
in_channels=input_channels,
out_channels=out_num_channel,
kernel_size=3,
stride=1,
padding=1,
)
)
if use_instance_norm:
conv_block.append(nn.InstanceNorm2d(
out_num_channel, affine=True))
elif not remove_bn:
conv_block.append(nn.BatchNorm2d(
out_num_channel, momentum=bn_momentum))
conv_block.append(nn.MaxPool2d(kernel_size=2, stride=2, padding=0))
if '2d' in dropout_type:
conv_block.append(nn.Dropout2d(vision_dropout))
else:
conv_block.append(nn.Dropout(vision_dropout))
conv_block.append(nn.ReLU(inplace=True))
list_conv_layers.append(nn.Sequential(*conv_block))
input_channels = out_num_channel
self.conv_layers = nn.ModuleList(list_conv_layers)
self.input_proj = nn.Linear(
self.conv_feature_final_size + self.num_input_classes, hidden_size)
# self.input_layer_norm = nn.LayerNorm(self.conv_feature_final_size)
layers = []
self.num_layers = num_layers
for _ in range(num_layers): # each "layer" consists of two sub-layers
layers.append(
SRWMlayer(num_head, dim_head, hidden_size, dropout, use_ln,
use_input_softmax, beta_init, stateful=True,
init_scaler=init_scaler, q_init_scaler=q_init_scaler,
unif_init=unif_init,
single_state_training=single_state_training,
no_softmax_on_y=no_softmax_on_y))
layers.append(
TransformerFFlayers(dim_ff, hidden_size, dropout))
self.layers = nn.ModuleList(layers)
self.activation = nn.ReLU(inplace=True)
self.out_layer = nn.Linear(hidden_size, num_classes)
if dropout_type == 'base':
self.input_drop = nn.Dropout(input_dropout)
else:
self.input_drop = nn.Dropout2d(input_dropout)
# return clone of input state
def clone_state(self, state, detach=False):
Wy_states, Wq_states, Wk_states, wb_states = state
Wy_state_list = []
Wq_state_list = []
Wk_state_list = []
wb_state_list = []
for i in range(self.num_layers):
if detach:
Wy_state_list.append(Wy_states[i].detach().clone())
Wq_state_list.append(Wq_states[i].detach().clone())
Wk_state_list.append(Wk_states[i].detach().clone())
wb_state_list.append(wb_states[i].detach().clone())
else:
Wy_state_list.append(Wy_states[i].clone())
Wq_state_list.append(Wq_states[i].clone())
Wk_state_list.append(Wk_states[i].clone())
wb_state_list.append(wb_states[i].clone())
Wy_state_tuple = tuple(Wy_state_list)
Wq_state_tuple = tuple(Wq_state_list)
Wk_state_tuple = tuple(Wk_state_list)
wb_state_tuple = tuple(wb_state_list)
state_tuple = (
Wy_state_tuple, Wq_state_tuple, Wk_state_tuple, wb_state_tuple)
return state_tuple
# return clone of input state, with drop certain batch
def clone_state_drop(self, state, drop2d_layer):
Wy_states, Wq_states, Wk_states, wb_states = state
Wy_state_list = []
Wq_state_list = []
Wk_state_list = []
wb_state_list = []
B, H, D, _ = Wy_states[0].shape
for i in range(self.num_layers):
Wy_state_list.append(drop2d_layer(Wy_states[i].clone().detach().reshape(B, 1, H*D, -1).transpose(0, 1)).transpose(0, 1).reshape(B, H, D, -1))
Wq_state_list.append(drop2d_layer(Wq_states[i].clone().detach().reshape(B, 1, H*D, -1).transpose(0, 1)).transpose(0, 1).reshape(B, H, D, -1))
Wk_state_list.append(drop2d_layer(Wk_states[i].clone().detach().reshape(B, 1, H*D, -1).transpose(0, 1)).transpose(0, 1).reshape(B, H, D, -1))
wb_state_list.append(drop2d_layer(wb_states[i].clone().detach().reshape(B, 1, H*D, -1).transpose(0, 1)).transpose(0, 1).reshape(B, H, D, -1))
# Wy_state_list.append(Wy_states[i].clone())
# Wq_state_list.append(Wq_states[i].clone())
# Wk_state_list.append(Wk_states[i].clone())
# wb_state_list.append(wb_states[i].clone())
Wy_state_tuple = tuple(Wy_state_list)
Wq_state_tuple = tuple(Wq_state_list)
Wk_state_tuple = tuple(Wk_state_list)
wb_state_tuple = tuple(wb_state_list)
state_tuple = (
Wy_state_tuple, Wq_state_tuple, Wk_state_tuple, wb_state_tuple)
return state_tuple
def forward(self, x, fb, state=None):
# Assume input of shape (len, B, 1, 28, 28)
slen, bsz, _, hs, ws = x.shape
x = x.reshape(slen * bsz, self.input_channels, hs, ws)
x = self.input_drop(x)
for conv_layer in self.conv_layers:
x = conv_layer(x)
x = x.reshape(slen, bsz, self.conv_feature_final_size)
emb = torch.nn.functional.one_hot(fb, num_classes=self.num_input_classes)
out = torch.cat([x, emb], dim=-1)
out = self.input_proj(out)
# forward main layers
Wy_state_list = []
Wq_state_list = []
Wk_state_list = []
wb_state_list = []
if state is not None:
Wy_states, Wq_states, Wk_states, wb_states = state
for i in range(self.num_layers):
if state is not None:
out, out_state = self.layers[2 * i](
out,
state=(Wy_states[i], Wq_states[i],
Wk_states[i], wb_states[i]),
get_state=True)
else:
out, out_state = self.layers[2 * i](
out,
get_state=True)
# no cloning here. We do it outside where needed
Wy_state_list.append(out_state[0])
Wq_state_list.append(out_state[1])
Wk_state_list.append(out_state[2])
wb_state_list.append(out_state[3])
# Wy_state_list.append(out_state[0].unsqueeze(0))
# Wq_state_list.append(out_state[1].unsqueeze(0))
# Wk_state_list.append(out_state[2].unsqueeze(0))
# wb_state_list.append(out_state[3].unsqueeze(0))
out = self.layers[2 * i + 1](out)
out = self.out_layer(out)
Wy_state_tuple = tuple(Wy_state_list)
Wq_state_tuple = tuple(Wq_state_list)
Wk_state_tuple = tuple(Wk_state_list)
wb_state_tuple = tuple(wb_state_list)
state_tuple = (
Wy_state_tuple, Wq_state_tuple, Wk_state_tuple, wb_state_tuple)
return out, state_tuple
class CompatStatefulRes12SRWMModel(BaseModel):
def __init__(self, hidden_size, num_classes,
num_layers, num_head, dim_head, dim_ff,
dropout, vision_dropout=0.0, emb_dim=10, use_ln=True,
use_input_softmax=False,
beta_init=0., imagenet=False, fc100=False, bn_momentum=0.1,
input_dropout=0.0, dropout_type='base',
use_dropblock=False, use_big=False,
init_scaler=1., q_init_scaler=0.01,
unif_init=False, single_state_training=False,
no_softmax_on_y=False, extra_label=False, use_instance_norm=False):
super().__init__()
self.input_channels = 3
self.num_classes = num_classes
self.extra_label = extra_label
if extra_label:
self.num_input_classes = num_classes + 1
else:
self.num_input_classes = num_classes
if use_dropblock:
dropblock = 5 if imagenet else 2
self.stem_resnet12 = resnet12_dropblock(
use_big=use_big, drop_rate=vision_dropout,
dropblock_size=dropblock)
if use_big:
self.conv_feature_final_size = 2560 if imagenet else 640
else:
self.conv_feature_final_size = 1024 if imagenet else 256
else:
self.stem_resnet12 = resnet12_base(
vision_dropout, use_big, dropout_type,
instance_norm=use_instance_norm)
if use_big:
self.conv_feature_final_size = 512
else:
self.conv_feature_final_size = 256
self.input_proj = nn.Linear(
self.conv_feature_final_size + self.num_input_classes, hidden_size)
# self.input_layer_norm = nn.LayerNorm(self.conv_feature_final_size)
layers = []
self.num_layers = num_layers
for _ in range(num_layers): # each "layer" consists of two sub-layers
layers.append(
SRWMlayer(num_head, dim_head, hidden_size, dropout, use_ln,
use_input_softmax, beta_init, stateful=True,
init_scaler=init_scaler, q_init_scaler=q_init_scaler,
unif_init=unif_init,
single_state_training=single_state_training,
no_softmax_on_y=no_softmax_on_y))
layers.append(
TransformerFFlayers(dim_ff, hidden_size, dropout))
self.layers = nn.ModuleList(layers)
self.activation = nn.ReLU(inplace=True)
self.out_layer = nn.Linear(hidden_size, num_classes)
if dropout_type == 'base':
self.input_drop = nn.Dropout(input_dropout)
else:
self.input_drop = nn.Dropout2d(input_dropout)
# return clone of input state
def clone_state(self, state, detach=False):
Wy_states, Wq_states, Wk_states, wb_states = state
Wy_state_list = []
Wq_state_list = []
Wk_state_list = []
wb_state_list = []
for i in range(self.num_layers):
if detach:
Wy_state_list.append(Wy_states[i].detach().clone())
Wq_state_list.append(Wq_states[i].detach().clone())
Wk_state_list.append(Wk_states[i].detach().clone())
wb_state_list.append(wb_states[i].detach().clone())
else:
Wy_state_list.append(Wy_states[i].clone())
Wq_state_list.append(Wq_states[i].clone())
Wk_state_list.append(Wk_states[i].clone())
wb_state_list.append(wb_states[i].clone())
Wy_state_tuple = tuple(Wy_state_list)
Wq_state_tuple = tuple(Wq_state_list)
Wk_state_tuple = tuple(Wk_state_list)
wb_state_tuple = tuple(wb_state_list)
state_tuple = (
Wy_state_tuple, Wq_state_tuple, Wk_state_tuple, wb_state_tuple)
return state_tuple
# return clone of input state, with drop certain batch
def clone_state_drop(self, state, drop2d_layer):
Wy_states, Wq_states, Wk_states, wb_states = state
Wy_state_list = []
Wq_state_list = []
Wk_state_list = []
wb_state_list = []
B, H, D, _ = Wy_states[0].shape
for i in range(self.num_layers):
Wy_state_list.append(drop2d_layer(Wy_states[i].clone().detach().reshape(B, 1, H*D, -1).transpose(0, 1)).transpose(0, 1).reshape(B, H, D, -1))
Wq_state_list.append(drop2d_layer(Wq_states[i].clone().detach().reshape(B, 1, H*D, -1).transpose(0, 1)).transpose(0, 1).reshape(B, H, D, -1))
Wk_state_list.append(drop2d_layer(Wk_states[i].clone().detach().reshape(B, 1, H*D, -1).transpose(0, 1)).transpose(0, 1).reshape(B, H, D, -1))
wb_state_list.append(drop2d_layer(wb_states[i].clone().detach().reshape(B, 1, H*D, -1).transpose(0, 1)).transpose(0, 1).reshape(B, H, D, -1))
# Wy_state_list.append(Wy_states[i].clone())
# Wq_state_list.append(Wq_states[i].clone())
# Wk_state_list.append(Wk_states[i].clone())
# wb_state_list.append(wb_states[i].clone())
Wy_state_tuple = tuple(Wy_state_list)
Wq_state_tuple = tuple(Wq_state_list)
Wk_state_tuple = tuple(Wk_state_list)
wb_state_tuple = tuple(wb_state_list)
state_tuple = (
Wy_state_tuple, Wq_state_tuple, Wk_state_tuple, wb_state_tuple)
return state_tuple
def forward(self, x, fb, state=None):
# Assume input of shape (len, B, 1, 28, 28)
slen, bsz, _, hs, ws = x.shape
x = x.reshape(slen * bsz, self.input_channels, hs, ws)
x = self.input_drop(x)
x = self.stem_resnet12(x)
x = x.reshape(slen, bsz, self.conv_feature_final_size)
emb = torch.nn.functional.one_hot(fb, num_classes=self.num_input_classes)
out = torch.cat([x, emb], dim=-1)
out = self.input_proj(out)
# forward main layers
Wy_state_list = []
Wq_state_list = []
Wk_state_list = []
wb_state_list = []
if state is not None:
Wy_states, Wq_states, Wk_states, wb_states = state
for i in range(self.num_layers):
if state is not None:
out, out_state = self.layers[2 * i](
out,
state=(Wy_states[i], Wq_states[i],
Wk_states[i], wb_states[i]),
get_state=True)
else:
out, out_state = self.layers[2 * i](
out,
get_state=True)
# no cloning here. We do it outside where needed
Wy_state_list.append(out_state[0])
Wq_state_list.append(out_state[1])
Wk_state_list.append(out_state[2])
wb_state_list.append(out_state[3])
# Wy_state_list.append(out_state[0].unsqueeze(0))
# Wq_state_list.append(out_state[1].unsqueeze(0))
# Wk_state_list.append(out_state[2].unsqueeze(0))
# wb_state_list.append(out_state[3].unsqueeze(0))
out = self.layers[2 * i + 1](out)
out = self.out_layer(out)
Wy_state_tuple = tuple(Wy_state_list)
Wq_state_tuple = tuple(Wq_state_list)
Wk_state_tuple = tuple(Wk_state_list)
wb_state_tuple = tuple(wb_state_list)
state_tuple = (
Wy_state_tuple, Wq_state_tuple, Wk_state_tuple, wb_state_tuple)
return out, state_tuple
class CompatStatefulMixerSRWMModel(BaseModel):
def __init__(self, hidden_size, num_classes,
num_layers, num_head, dim_head, dim_ff,
dropout, vision_dropout=0.0, emb_dim=10, use_ln=True,
use_input_softmax=False,
beta_init=0., imagenet=False, fc100=False, bn_momentum=0.1,
patch_size=16, expansion_factor = 4, expansion_factor_token = 0.5,
input_dropout=0.0, dropout_type='base',
init_scaler=1., q_init_scaler=0.01,
unif_init=False, single_state_training=False,
no_softmax_on_y=False, extra_label=False):
super().__init__()
self.num_classes = num_classes
self.extra_label = extra_label
if extra_label:
self.num_input_classes = num_classes + 1
else:
self.num_input_classes = num_classes
if imagenet: # mini-imagenet
input_channels = 3
out_num_channel = 32
image_size = 84
self.conv_feature_final_size = 32 * 5 * 5 # (B, 32, 5, 5)
elif fc100:
input_channels = 3
out_num_channel = 32
image_size = 32
self.conv_feature_final_size = 32 * 2 * 2 # (B, 32, 5, 5)
else: # onmiglot
input_channels = 1
out_num_channel = 64
image_size = 28
self.conv_feature_final_size = 64 # final feat shape (B, 64, 1, 1)
self.input_channels = input_channels
self.vision_model = MLPMixer(
image_size = image_size,
channels = input_channels,
patch_size = patch_size,
dim = 32,
depth = 4,
expansion_factor = expansion_factor,
expansion_factor_token = expansion_factor_token,
dropout = vision_dropout,
num_classes = self.conv_feature_final_size # just to make it similar to conv baseline
)
self.input_proj = nn.Linear(
self.conv_feature_final_size + self.num_input_classes, hidden_size)
# self.input_layer_norm = nn.LayerNorm(self.conv_feature_final_size)
layers = []
self.num_layers = num_layers
for _ in range(num_layers): # each "layer" consists of two sub-layers
layers.append(
SRWMlayer(num_head, dim_head, hidden_size, dropout, use_ln,
use_input_softmax, beta_init, stateful=True,
init_scaler=init_scaler, q_init_scaler=q_init_scaler,
unif_init=unif_init,
single_state_training=single_state_training,
no_softmax_on_y=no_softmax_on_y))
layers.append(
TransformerFFlayers(dim_ff, hidden_size, dropout))
self.layers = nn.ModuleList(layers)