-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnets.py
1393 lines (1180 loc) · 64.3 KB
/
nets.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
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import typing
from torchinfo import summary
from utils import get_act_function
import torchvision
from typing import Optional, List, Tuple
import torch.nn as nn
import time
import math
from fov_conv2d_cont import FovConv2dCont, LinearMiddleBiasOne
from fov_conv2d_reg import FovConv2dReg
class Foveate2d(nn.Module):
def __init__(self,
regions: int,
regions_radius: List[int],
region_valid_idx: List,
region_type: str,
in_channels: int,
out_channels: int,
kernel_size_list: List[int],
stride_list: List[int],
padding_list: List[int],
w: int,
h: int,
outmost_global: bool,
device,
# transposed: bool,
# output_padding: List[int, ...],
padding_mode: str = 'zeros', # TODO: refine this type
dilation_list: List[int] = None,
debug=False,
compute_region_indexes=False
):
super(Foveate2d, self).__init__()
self.module_list = nn.ModuleList()
self.conv_regions = regions
self.index_regions = len(regions_radius) - 1 # 0 radius was added at the beginning
self.regions_radius = regions_radius
self.region_type = region_type
self.region_valid_idx = region_valid_idx
self.in_channels = in_channels
self.out_channels = out_channels
self.w = w
self.h = h
self.upsample = nn.Upsample(size=[h, w], mode='nearest')
self.device = device
self.zero_tensor = torch.tensor([0], device=self.device, requires_grad=False)
self.compute_region_indexes = compute_region_indexes
# if last region has radius -1, select the whole frame as attentended region
self.outmost_global = outmost_global
# a different convolutional layer for each region
for idx in range(self.conv_regions):
if dilation_list is not None:
self.module_list.append(
nn.Conv2d(in_channels=in_channels, out_channels=out_channels, stride=stride_list[idx],
kernel_size=kernel_size_list[idx], padding=padding_list[idx], dilation=dilation_list[idx],
bias=True, padding_mode='replicate'), )
else:
self.module_list.append(
nn.Conv2d(in_channels=in_channels, out_channels=out_channels, stride=stride_list[idx],
kernel_size=kernel_size_list[idx], padding=padding_list[idx],
bias=True, padding_mode='replicate'), )
if debug: # Notice: does not work anymoer in the case of 1 conv region and multiple index regions
with torch.no_grad():
for i in range(len(self.module_list)):
if self.module_list[i].weight is not None:
self.module_list[i].weight *= 0.
mid = int(self.module_list[i].kernel_size[0]) // 2
self.module_list[i].weight[:, :, mid, mid] = 1.
if self.conv_regions > 1:
self.module_list[i].weight[:, :, mid, mid] -= float(i) / float(self.conv_regions)
self.module_list[i].weight /= self.module_list[i].weight.shape[1]
self.module_list[i].bias *= 0
def compose_output(self, list_activations, foa_x, foa_y):
self.b = foa_x.shape[0]
return self.compose_regions(list_activations, foa_y, foa_x) # TODO inverted x and y
def compose_regions(self, list_activations, foa_x, foa_y):
unique_cnn_flag = False
# if last region is -1, hence we want to consider all the remaining of the frame
if self.outmost_global:
layer_output = list_activations[-1] # the outmost region is taken as all the latest activation
considered_list = list_activations[:-1]
# region to consider for the output creation (the outmost one has been already considered)
regions_to_consider = self.index_regions - 1
else:
layer_output = torch.zeros_like(list_activations[-1],
device=list_activations[
-1].device) # the outmost region activation as all 0s
considered_list = list_activations
regions_to_consider = self.index_regions
# Handling specific case of 1 CNN regions and multiple radii
if len(list_activations) == 1:
# the activation list to be considered is always composed by one CNN output
considered_list = layer_output
unique_cnn_flag = True
f = self.out_channels
if self.compute_region_indexes:
if self.regions_radius[-1] == -1:
# indexes for the outmost region when -1
region_idx_global = torch.ones((self.b, f, self.h, self.w), device=list_activations[-1].device) * (
self.index_regions - 1)
else:
# indexes for the outmost region when we do not consider the whole frame
region_idx_global = -torch.ones((self.b, f, self.h, self.w), device=list_activations[-1].device)
# starting = time.time()
z_index = torch.arange(start=0, end=self.b, device=list_activations[-1].device, dtype=torch.long).view(self.b,
1, 1)
f_index = torch.arange(start=0, end=f, device=list_activations[-1].device, dtype=torch.long).view(1, f, 1)
# for idx, el in enumerate(considered_list):
for idx in range(regions_to_consider): #
# handling case of 1 CNN layer
if unique_cnn_flag:
el = considered_list
else:
el = considered_list[idx]
region_x, region_y = self.region_valid_idx[idx]
new_region_x = (region_x + foa_x)
new_region_y = (region_y + foa_y)
inside = (new_region_x >= 0) * (new_region_x < self.h) * (new_region_y >= 0) * (new_region_y < self.w)
################ NEW IMPLEMENTATION #############
first_dim = (new_region_x * self.w + new_region_y).unsqueeze(dim=1)
second_dim = f_index * self.h * self.w + first_dim
third_dim = z_index * f * self.h * self.w + second_dim
region_idx_whole = torch.masked_select(third_dim, inside.view(inside.shape[0], 1, inside.shape[1]))
layer_output.view(-1)[region_idx_whole] = el.view(-1)[region_idx_whole]
if self.compute_region_indexes:
region_idx_global.view(-1)[region_idx_whole] = idx
#####################################################
# end = time.time() - starting
# print(f"For all the regions: {end} sec.")
if self.compute_region_indexes:
# => then select only first channel of features
return layer_output, region_idx_global[:, 0]
# return layer_output, region_idx_global
else:
return layer_output
def forward(self, frame, foa_coordinates):
outlist = []
# forward for every type of kernel/region
# import time
# torch.cuda.synchronize()
# starting = time.time()
for conv_i in self.module_list: # for every conv2d of the various regions,
# process the whole frame with the call method
out = conv_i(frame)
# upsample in case of lower dim obtained - caused by bigger stride
if out.shape[2:] != frame.shape[2:]:
out = self.upsample(out)
outlist.append(out)
# torch.cuda.synchronize()
# end = time.time() - starting
# print(f"Convolutions for loop: {end} sec.")
# call a method on the output of the foveated layer depending on the type of region wanted
foa_x = foa_coordinates[:, 0, None]
foa_y = foa_coordinates[:, 1, None] # TODO check!!! can be removed and also the one on dataloader!
return self.compose_output(outlist, foa_x, foa_y)
class NetFactory:
@staticmethod
def createNet(options, region_valid_idx=None, outmost_global=None):
if options.wrapped_arch == "test":
return BaseEncoder(options, region_valid_idx, outmost_global)
elif options.wrapped_arch == "fnn_reg":
# az = SimpleEncoder(options, region_valid_idx, outmost_global)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return FNN_Reg(options, region_valid_idx, outmost_global)
elif options.wrapped_arch == "last_FL":
return FNN_Back1(options)
elif options.wrapped_arch == "first_FL":
return FNN_Back2(options)
elif options.wrapped_arch == "all_FL":
return FNN_Back3(options)
elif options.wrapped_arch == "first_FL_gaussian":
return Back2_GaussianFirst(options)
elif options.wrapped_arch == "last_FL_gaussian":
return Back2_GaussianLast(options)
elif options.wrapped_arch == "all_FL_gaussian":
return Back3_NetGaussianAll(options)
elif options.wrapped_arch == "first_FL_netmodulated":
return Back2_NetModulatedFirst(options)
elif options.wrapped_arch == "last_FL_netmodulated":
return Back2_NetModulatedLast(options)
elif options.wrapped_arch == "all_FL_netmodulated":
return Back3_NetModulatedAll(options)
elif options.wrapped_arch == "first_FL_netgenerated":
return Back2_NetGeneratedFirst(options)
elif options.wrapped_arch == "last_FL_netgenerated":
return Back2_NetGeneratedLast(options)
elif options.wrapped_arch == "all_FL_netgenerated":
return Back3_NetGeneratedAll(options)
elif options.wrapped_arch == "FNN_one_layerk_5_d_1":
# az = SimpleEncoder(options, region_valid_idx, outmost_global)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return OneLayerFNN(options, region_valid_idx, outmost_global)
elif options.wrapped_arch == "FNN_one_layerk_7_d_1":
# az = SimpleEncoder(options, region_valid_idx, outmost_global)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return OneLayerFNNk_7_d_1(options, region_valid_idx, outmost_global)
elif options.wrapped_arch == "FNN_one_layerk_7_d_3":
# az = SimpleEncoder(options, region_valid_idx, outmost_global)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return OneLayerFNNk_7_d_3(options, region_valid_idx, outmost_global)
elif options.wrapped_arch == "FNN_one_layerk_10_d_1":
# az = SimpleEncoder(options, region_valid_idx, outmost_global)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return OneLayerFNNk_10_d_1(options, region_valid_idx, outmost_global)
elif options.wrapped_arch == "FNN_one_layerk_10_d_3":
# az = SimpleEncoder(options, region_valid_idx, outmost_global)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return OneLayerFNNk_10_d_3(options, region_valid_idx, outmost_global)
elif options.wrapped_arch == "FNN_one_layerk_15_d_3":
# az = SimpleEncoder(options, region_valid_idx, outmost_global)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return OneLayerFNNk_15_d_3(options, region_valid_idx, outmost_global)
elif options.wrapped_arch == "FNN_one_layerk_15_d_1":
# az = SimpleEncoder(options, region_valid_idx, outmost_global)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return OneLayerFNNk_15_d_1(options, region_valid_idx, outmost_global)
elif options.wrapped_arch == "FNN_one_layerk_29_d_1":
# az = SimpleEncoder(options, region_valid_idx, outmost_global)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return OneLayerFNNk_29_d_1(options, region_valid_idx, outmost_global)
elif options.wrapped_arch == "FNN_one_layerk_30_d_1":
# az = SimpleEncoder(options, region_valid_idx, outmost_global)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return OneLayerFNNk_30_d_1(options, region_valid_idx, outmost_global)
elif options.wrapped_arch == "FNN_one_layer_custom":
# az = SimpleEncoder(options, region_valid_idx, outmost_global)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return OneLayerFNN_custom(options, region_valid_idx, outmost_global)
elif options.wrapped_arch == "two_layer":
# az = SimpleEncoder(options, region_valid_idx, outmost_global)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return SimpleEncoder(options, region_valid_idx, outmost_global)
elif options.wrapped_arch == "five":
# az = SimpleEncoder(options, region_valid_idx, outmost_global)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return FiveLayerEncoder(options, region_valid_idx, outmost_global)
elif options.wrapped_arch == "low_param":
# az = LowerParamEncoder(options, region_valid_idx, outmost_global)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return LowerParamEncoder(options, region_valid_idx, outmost_global)
elif options.wrapped_arch == "CNN_A":
# az = CNN_A(options)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return CNN_A(options)
elif options.wrapped_arch == "CNN_A112":
# az = CNN_A(options)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return CNN_A112(options)
elif options.wrapped_arch == "CNN_A100":
# az = CNN_A(options)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return CNN_A100(options)
elif options.wrapped_arch == "CNN_RAM":
# az = CNN_RAM(options)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, 1, options.w, options.h))
# exit()
return CNN_RAM(options)
elif options.wrapped_arch == "FC64":
# az = FC64(options)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, options.w, options.h))
# exit()
return FC64(options)
elif options.wrapped_arch == "FC256":
# az = FC256(options)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, options.w, options.h))
# exit()
return FC256(options)
elif options.wrapped_arch == "vanilla":
# az = VanillaCNN(options)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, options.w, options.h))
# exit()
return VanillaCNN(options)
elif options.wrapped_arch == "CNN_one_layer_64_global":
# az = VanillaCNN(options)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, options.w, options.h))
# exit()
return OneLayerCNN(options)
elif options.wrapped_arch == "CNN_one_layer_custom":
# az = VanillaCNN(options)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, options.w, options.h))
# exit()
return OneLayerCNNCustom(options)
elif options.wrapped_arch == "CNN_one_layer_maxpool":
# az = VanillaCNN(options)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, options.w, options.h))
# exit()
return OneLayerCNN_maxpool(options)
elif options.wrapped_arch == "CNN_one_layer_regionwise":
# az = VanillaCNN(options)
# print(az)
# summary(az.to("cuda:0"), input_size=(1, options.w, options.h))
# exit()
return OneLayerCNNRegionwise(options)
else:
raise AttributeError(f"Architecture {options['architecture']} unknown.")
class BaseEncoder(nn.Module):
def __init__(self, options, region_valid_idx, outmost_global):
super(BaseEncoder, self).__init__()
self.config = options
self.region_valid_idx = region_valid_idx
self.outmost_global = outmost_global
self.device = options.device
self.in_channels = 1 if self.config.grayscale else 3
self.activation = get_act_function(options.act)
self.net_modulelist = nn.ModuleList()
self._architecture()
def _architecture(self):
self.net_modulelist.append(Foveate2d(regions=self.config.regions, regions_radius=self.config.regions_radius,
region_valid_idx=self.region_valid_idx,
region_type=self.config.region_type,
outmost_global=self.outmost_global,
device=self.device,
in_channels=self.in_channels, out_channels=1,
w=self.config.w, h=self.config.h,
kernel_size_list=[1 for i in range(self.config.regions)],
stride_list=[1 for i in range(self.config.regions)],
padding_list=[0 for i in range(self.config.regions)],
debug=True,
compute_region_indexes=True),
)
def forward(self, frame, foa):
temp = frame
for i, module in enumerate(self.net_modulelist):
temp = module(temp, foa)
if i != len(self.net_modulelist) - 1: # do not put activation in last layer
temp = self.activation(temp) # TODO customize activation function
return temp
class FNN_Reg(BaseEncoder):
def _architecture(self):
self.net_modulelist.append(FovConv2dReg(self.in_channels, self.config.output_channels, self.config.kernel,
region_type=self.config.region_type,
method=self.config.reduction_method,
region_sizes=self.config.region_sizes,
reduction_factors=[1.0, self.config.reduction_factor],
banks=self.config.banks,
padding_mode="replicate")
)
class VanillaCNN(nn.Module):
def __init__(self, config, input_dim=1):
super(VanillaCNN, self).__init__()
self.in_channels = 1 if config.grayscale else 3
self.conv1 = nn.Conv2d(self.in_channels, 16, 5, stride=1, padding=2)
self.conv2 = nn.Conv2d(16, 32, 5, stride=1, padding=2)
self.conv3 = nn.Conv2d(32, 64, 3, stride=1, padding=1)
self.conv4 = nn.Conv2d(64, 128, 3, stride=1, padding=1)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.num_classes = config.num_classes
self.fc = nn.Linear(128, self.num_classes)
def forward(self, x):
# x 224 x 224
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2, 2) # 112 x 112
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2, 2) # 56 x 56
x = F.relu(self.conv3(x))
x = F.max_pool2d(x, 2, 2) # 28 x 28
x = F.relu(self.conv4(x))
x = self.avgpool(x) # 1 x 1
x = torch.flatten(x, 1)
x = self.fc(x)
return x
class FNN_Back1(nn.Module):
"""
Last layer is a FL, all others are conv2d
"""
def __init__(self, options):
super(FNN_Back1, self).__init__()
self.config = options
self.device = options.device
self.in_channels = 1 if self.config.grayscale else 3
self.relative_scaling_factor = 28. / 224.
self.conv1 = nn.Conv2d(self.in_channels, 16, 5, stride=1, padding=2)
self.conv2 = nn.Conv2d(16, 32, 5, stride=1, padding=2)
self.conv3 = nn.Conv2d(32, 64, 3, stride=1, padding=1)
self.fl = FovConv2dReg(64, 128, 3,
region_type=self.config.region_type,
method=self.config.reduction_method,
region_sizes=(11, -1),
reduction_factors=(1.0, 0.25),
banks=self.config.banks,
padding_mode="zeros")
def forward(self, x, foa):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2, 2) # 112 x 112
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2, 2) # 56 x 56
x = F.relu(self.conv3(x))
x = F.max_pool2d(x, 2, 2) # 28 x 28
# rescale foa
new_foa = foa * self.relative_scaling_factor
new_foa = torch.floor(new_foa)
x, ind = self.fl(x, new_foa, compute_region_indices=True)
x = F.relu(x)
return x, ind
class FNN_Back2(VanillaCNN):
"""
First layer is a FL, all subsequent are conv2d
"""
def __init__(self, config):
super(FNN_Back2, self).__init__(config)
self.fl = FovConv2dReg(self.in_channels, 16, 5,
region_type=config.region_type,
method=config.reduction_method,
region_sizes=(51, 101, -1),
reduction_factors=(1.0, 0.5, 0.25),
banks=config.banks,
padding_mode="zeros")
def forward(self, x, foa):
x = F.relu(self.fl(x, foa, compute_region_indices=False))
x = F.max_pool2d(x, 2, 2) # 112 x 112
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2, 2) # 56 x 56
x = F.relu(self.conv3(x))
x = F.max_pool2d(x, 2, 2) # 28 x 28
x = F.relu(self.conv4(x))
x = self.avgpool(x) # 1 x 1
x = torch.flatten(x, 1)
x = self.fc(x)
return x
class Back2_GaussianFirst(FNN_Back2):
"""
First layer is FL Gaussian Modulated, all subsequent are conv2d
"""
def __init__(self, options):
super(Back2_GaussianFirst, self).__init__(options)
self.fl = FovConv2dCont(self.in_channels, 16, 5, kernel_type='gaussian_modulated',
gaussian_kernel_size=7, sigma_min=0.01, sigma_max=10.0, sigma_function='exponential')
class Back2_NetModulatedFirst(Back2_GaussianFirst):
"""
First layer is FL Net-Modulated, all subsequent are conv2d
"""
def __init__(self, options):
super(Back2_NetModulatedFirst, self).__init__(options)
self.fl = FovConv2dCont(self.in_channels, 16, 5, kernel_type='net_modulated',
kernel_net=torch.nn.Sequential(torch.nn.Linear(2, 10, bias=False), torch.nn.Tanh(),
LinearMiddleBiasOne(10, 7 * 7)))
class Back2_NetGeneratedFirst(Back2_GaussianFirst):
"""
First layer is FL Net-Generated, all subsequent are conv2d
"""
def __init__(self, options):
super(Back2_NetGeneratedFirst, self).__init__(options)
out_channels = 16
in_channels = self.in_channels
kernel_size = 5
self.fl = FovConv2dCont(in_channels, out_channels, kernel_size, kernel_type='net_generated',
padding_mode='zeros',
kernel_net=torch.nn.Sequential(torch.nn.Linear(2, 10, bias=True), torch.nn.Tanh(),
torch.nn.Linear(10, out_channels * in_channels * (
kernel_size ** 2))))
class Back2_GaussianLast(VanillaCNN):
"""
Only last layer is FL gaussian-modulated; gaussian kernel reduced to 5
"""
def __init__(self, options):
super(Back2_GaussianLast, self).__init__(options)
self.conv4 = FovConv2dCont(64, 128, 3, kernel_type='gaussian_modulated',
gaussian_kernel_size=5, sigma_min=0.01, sigma_max=10.0, sigma_function='exponential')
self.relative_scaling_factor = 28. / 224.
def forward(self, x, foa):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2, 2) # 112 x 112
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2, 2) # 56 x 56
x = F.relu(self.conv3(x))
x = F.max_pool2d(x, 2, 2) # 28 x 28
# rescale foa
new_foa = foa * self.relative_scaling_factor
new_foa = torch.floor(new_foa)
x = F.relu(self.conv4(x, new_foa))
x = self.avgpool(x) # 1 x 1
x = torch.flatten(x, 1)
x = self.fc(x)
return x
class Back2_NetModulatedLast(Back2_GaussianLast):
"""
Only last layer is FL net-modulated;
"""
def __init__(self, options):
super(Back2_NetModulatedLast, self).__init__(options)
out_channels = 128
in_channels = 64
kernel_size = 3
self.conv4 = FovConv2dCont(in_channels, out_channels, kernel_size, kernel_type='net_modulated',
kernel_net=torch.nn.Sequential(torch.nn.Linear(2, 10, bias=False), torch.nn.Tanh(),
LinearMiddleBiasOne(10, 5 * 5)))
class Back2_NetGeneratedLast(Back2_GaussianLast):
"""
Only last layer is FL net-generated;
"""
def __init__(self, options):
super(Back2_NetGeneratedLast, self).__init__(options)
out_channels = 128
in_channels = 64
kernel_size = 3
self.conv4 = FovConv2dCont(in_channels, out_channels, kernel_size, kernel_type='net_generated',
padding_mode='zeros',
kernel_net=torch.nn.Sequential(torch.nn.Linear(2, 10, bias=True), torch.nn.Tanh(),
torch.nn.Linear(10, out_channels * in_channels * (
kernel_size ** 2))))
class FNN_Back3(nn.Module):
"""
All FL layers
"""
def __init__(self, options):
super(FNN_Back3, self).__init__()
self.config = options
self.device = options.device
self.in_channels = 1 if self.config.grayscale else 3
self.relative_scaling_factor2 = 112. / 224.
self.relative_scaling_factor3 = 56. / 224.
self.relative_scaling_factor4 = 28. / 224.
# input 224
self.fl1 = FovConv2dReg(self.in_channels, 16, 5,
region_type=self.config.region_type,
method=self.config.reduction_method,
region_sizes=(51, 101, -1),
reduction_factors=(1.0, 0.5, 0.25),
banks=self.config.banks,
padding_mode="zeros")
# input 112
self.fl2 = FovConv2dReg(16, 32, 5,
region_type=self.config.region_type,
method=self.config.reduction_method,
region_sizes=(25, 51, -1),
reduction_factors=(1.0, 0.5, 0.25),
banks=self.config.banks,
padding_mode="zeros")
# input 56
self.fl3 = FovConv2dReg(32, 64, 3,
region_type=self.config.region_type,
method=self.config.reduction_method,
region_sizes=(25, -1),
reduction_factors=(1.0, 0.25),
banks=self.config.banks,
padding_mode="zeros")
# input 28
self.fl = FovConv2dReg(64, 128, 3,
region_type=self.config.region_type,
method=self.config.reduction_method,
region_sizes=(11, -1),
reduction_factors=(1.0, 0.25),
banks=self.config.banks,
padding_mode="zeros")
def forward(self, x, foa):
x = F.relu(self.fl1(x, foa, compute_region_indices=False))
x = F.max_pool2d(x, 2, 2) # 112 x 112
# rescale foa
new_foa2 = foa * self.relative_scaling_factor2
new_foa2 = torch.floor(new_foa2)
x = F.relu(self.fl2(x, new_foa2, compute_region_indices=False))
x = F.max_pool2d(x, 2, 2) # 56 x 56
# rescale foa
new_foa3 = foa * self.relative_scaling_factor3
new_foa3 = torch.floor(new_foa3)
x = F.relu(self.fl3(x, new_foa3, compute_region_indices=False))
x = F.max_pool2d(x, 2, 2) # 28 x 28
# rescale foa
new_foa4 = foa * self.relative_scaling_factor4
new_foa4 = torch.floor(new_foa4)
x, ind = self.fl(x, new_foa4, compute_region_indices=True)
x = F.relu(x)
return x, ind
class Back3_NetGaussianAll(FNN_Back3):
"""
All FL layers gaussian-modulated
"""
def __init__(self, options):
super(Back3_NetGaussianAll, self).__init__(options)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.num_classes = options.num_classes
self.fc = nn.Linear(128, self.num_classes)
# input 224
self.fl1 = FovConv2dCont(self.in_channels, 16, 5, kernel_type='gaussian_modulated',
gaussian_kernel_size=7, sigma_min=0.01, sigma_max=10.0, sigma_function='exponential')
# input 112
self.fl2 = FovConv2dCont(16, 32, 5, kernel_type='gaussian_modulated',
gaussian_kernel_size=7, sigma_min=0.01, sigma_max=10.0, sigma_function='exponential')
# input 56
self.fl3 = FovConv2dCont(32, 64, 3, kernel_type='gaussian_modulated',
gaussian_kernel_size=5, sigma_min=0.01, sigma_max=10.0, sigma_function='exponential')
# input 28
self.fl = FovConv2dCont(64, 128, 3, kernel_type='gaussian_modulated',
gaussian_kernel_size=3, sigma_min=0.01, sigma_max=10.0, sigma_function='exponential')
def forward(self, x, foa):
x = F.relu(self.fl1(x, foa, compute_region_indices=False))
x = F.max_pool2d(x, 2, 2) # 112 x 112
# rescale foa
new_foa2 = foa * self.relative_scaling_factor2
new_foa2 = torch.floor(new_foa2)
x = F.relu(self.fl2(x, new_foa2, compute_region_indices=False))
x = F.max_pool2d(x, 2, 2) # 56 x 56
# rescale foa
new_foa3 = foa * self.relative_scaling_factor3
new_foa3 = torch.floor(new_foa3)
x = F.relu(self.fl3(x, new_foa3, compute_region_indices=False))
x = F.max_pool2d(x, 2, 2) # 28 x 28
# rescale foa
new_foa4 = foa * self.relative_scaling_factor4
new_foa4 = torch.floor(new_foa4)
x = F.relu(self.fl(x, new_foa4, compute_region_indices=False))
x = self.avgpool(x) # 1 x 1
x = torch.flatten(x, 1)
x = self.fc(x)
return x
class Back3_NetModulatedAll(Back3_NetGaussianAll):
"""
All FL layers net-modulated
"""
def __init__(self, options):
super(Back3_NetModulatedAll, self).__init__(options)
# input 224
self.fl1 = FovConv2dCont(self.in_channels, 16, 5, kernel_type='net_modulated',
kernel_net=torch.nn.Sequential(torch.nn.Linear(2, 10, bias=False), torch.nn.Tanh(),
LinearMiddleBiasOne(10, 7 * 7)))
# input 112
self.fl2 = FovConv2dCont(16, 32, 5, kernel_type='net_modulated',
kernel_net=torch.nn.Sequential(torch.nn.Linear(2, 10, bias=False), torch.nn.Tanh(),
LinearMiddleBiasOne(10, 7 * 7)))
# input 56
self.fl3 = FovConv2dCont(32, 64, 3, kernel_type='net_modulated',
kernel_net=torch.nn.Sequential(torch.nn.Linear(2, 10, bias=False), torch.nn.Tanh(),
LinearMiddleBiasOne(10, 5 * 5)))
# input 28
self.fl = FovConv2dCont(64, 128, 3, kernel_type='net_modulated',
kernel_net=torch.nn.Sequential(torch.nn.Linear(2, 10, bias=False), torch.nn.Tanh(),
LinearMiddleBiasOne(10, 3 * 3)))
class Back3_NetGeneratedAll(Back3_NetGaussianAll):
"""
All FL layers net-generated
"""
def __init__(self, options):
super(Back3_NetGeneratedAll, self).__init__(options)
# input 224
self.fl1 = FovConv2dCont(self.in_channels, 16, 5, kernel_type='net_generated',
padding_mode='zeros',
kernel_net=torch.nn.Sequential(torch.nn.Linear(2, 10, bias=True), torch.nn.Tanh(),
torch.nn.Linear(10, 16 * self.in_channels * (5 ** 2))))
# input 112
self.fl2 = FovConv2dCont(16, 32, 5, kernel_type='net_generated',
padding_mode='zeros',
kernel_net=torch.nn.Sequential(torch.nn.Linear(2, 10, bias=True), torch.nn.Tanh(),
torch.nn.Linear(10, 32 * 16 * (5 ** 2))))
# input 56
self.fl3 = FovConv2dCont(32, 64, 3, kernel_type='net_generated',
padding_mode='zeros',
kernel_net=torch.nn.Sequential(torch.nn.Linear(2, 10, bias=True), torch.nn.Tanh(),
torch.nn.Linear(10, 64 * 32 * (3 ** 2))))
# input 28
self.fl = FovConv2dCont(64, 128, 3, kernel_type='net_generated',
padding_mode='zeros',
kernel_net=torch.nn.Sequential(torch.nn.Linear(2, 10, bias=True), torch.nn.Tanh(),
torch.nn.Linear(10, 128 * 64 * (3 ** 2))))
class OneLayerFNN(BaseEncoder):
def _architecture(self):
self.net_modulelist.append(Foveate2d(regions=self.config.regions, regions_radius=self.config.regions_radius,
in_channels=1, out_channels=self.config.output_channels,
region_type=self.config.region_type,
region_valid_idx=self.region_valid_idx,
outmost_global=self.outmost_global,
w=self.config.w, h=self.config.h,
device=self.device,
kernel_size_list=[5, 5],
stride_list=[1, 1],
padding_list=[5 // 2, 5 // 2],
compute_region_indexes=True),
)
class OneLayerFNNk_7_d_1(BaseEncoder):
def _architecture(self):
self.net_modulelist.append(Foveate2d(regions=self.config.regions, regions_radius=self.config.regions_radius,
in_channels=self.in_channels, out_channels=self.config.output_channels,
region_type=self.config.region_type,
region_valid_idx=self.region_valid_idx,
outmost_global=self.outmost_global,
w=self.config.w, h=self.config.h,
device=self.device,
kernel_size_list=[7, 7],
stride_list=[1, 1],
padding_list=[7 // 2, 7 // 2],
dilation_list=[1, 1],
compute_region_indexes=True),
)
class OneLayerFNNk_7_d_3(BaseEncoder):
def _architecture(self):
self.net_modulelist.append(Foveate2d(regions=self.config.regions, regions_radius=self.config.regions_radius,
in_channels=self.in_channels, out_channels=self.config.output_channels,
region_type=self.config.region_type,
region_valid_idx=self.region_valid_idx,
outmost_global=self.outmost_global,
w=self.config.w, h=self.config.h,
device=self.device,
kernel_size_list=[7, 7],
stride_list=[1, 1],
padding_list=[7 // 2, 7 // 2],
dilation_list=[1, 3],
compute_region_indexes=True),
)
class OneLayerFNNk_10_d_1(BaseEncoder):
def _architecture(self):
self.net_modulelist.append(Foveate2d(regions=self.config.regions, regions_radius=self.config.regions_radius,
in_channels=self.in_channels, out_channels=self.config.output_channels,
region_type=self.config.region_type,
region_valid_idx=self.region_valid_idx,
outmost_global=self.outmost_global,
w=self.config.w, h=self.config.h,
device=self.device,
kernel_size_list=[10, 10],
stride_list=[1, 1],
padding_list=[10 // 2, 10 // 2],
dilation_list=[1, 1],
compute_region_indexes=True),
)
class OneLayerFNNk_10_d_3(BaseEncoder):
def _architecture(self):
self.net_modulelist.append(Foveate2d(regions=self.config.regions, regions_radius=self.config.regions_radius,
in_channels=self.in_channels, out_channels=self.config.output_channels,
region_type=self.config.region_type,
region_valid_idx=self.region_valid_idx,
outmost_global=self.outmost_global,
w=self.config.w, h=self.config.h,
device=self.device,
kernel_size_list=[10, 10],
stride_list=[1, 1],
padding_list=[10 // 2, 10 // 2],
dilation_list=[1, 3],
compute_region_indexes=True),
)
class OneLayerFNNk_15_d_3(BaseEncoder):
def _architecture(self):
self.net_modulelist.append(Foveate2d(regions=self.config.regions, regions_radius=self.config.regions_radius,
in_channels=self.in_channels, out_channels=self.config.output_channels,
region_type=self.config.region_type,
region_valid_idx=self.region_valid_idx,
outmost_global=self.outmost_global,
w=self.config.w, h=self.config.h,
device=self.device,
kernel_size_list=[15, 15],
stride_list=[1, 1],
padding_list=[15 // 2, 15 // 2],
dilation_list=[1, 3],
compute_region_indexes=True),
)
class OneLayerFNNk_15_d_1(BaseEncoder):
def _architecture(self):
self.net_modulelist.append(Foveate2d(regions=self.config.regions, regions_radius=self.config.regions_radius,
in_channels=self.in_channels, out_channels=self.config.output_channels,
region_type=self.config.region_type,
region_valid_idx=self.region_valid_idx,
outmost_global=self.outmost_global,
w=self.config.w, h=self.config.h,
device=self.device,
kernel_size_list=[15, 15],
stride_list=[1, 1],
padding_list=[15 // 2, 15 // 2],
dilation_list=[1, 1],
compute_region_indexes=True),
)
class OneLayerFNNk_29_d_1(BaseEncoder):
def _architecture(self):
self.net_modulelist.append(Foveate2d(regions=self.config.regions, regions_radius=self.config.regions_radius,
in_channels=self.in_channels, out_channels=self.config.output_channels,
region_type=self.config.region_type,
region_valid_idx=self.region_valid_idx,
outmost_global=self.outmost_global,
w=self.config.w, h=self.config.h,
device=self.device,
kernel_size_list=[29, 29],
stride_list=[1, 1],
padding_list=[29 // 2, 29 // 2],
dilation_list=[1, 1, ],
compute_region_indexes=True),
)
class OneLayerFNNk_30_d_1(BaseEncoder):
def _architecture(self):
self.net_modulelist.append(Foveate2d(regions=self.config.regions, regions_radius=self.config.regions_radius,
in_channels=self.in_channels, out_channels=self.config.output_channels,
region_type=self.config.region_type,
region_valid_idx=self.region_valid_idx,
outmost_global=self.outmost_global,
w=self.config.w, h=self.config.h,
device=self.device,
kernel_size_list=[30, 30, 30],
stride_list=[1, 1, 1],
padding_list=[30 // 2, 30 // 2, 30 // 2],
dilation_list=[1, 1, 1],
compute_region_indexes=True),
)
class OneLayerFNN_custom(BaseEncoder):
def _architecture(self):
kernel = self.config.kernel
dilation = self.config.dilation
self.net_modulelist.append(Foveate2d(regions=self.config.regions, regions_radius=self.config.regions_radius,
in_channels=self.in_channels, out_channels=self.config.output_channels,
region_type=self.config.region_type,
region_valid_idx=self.region_valid_idx,
outmost_global=self.outmost_global,
w=self.config.w, h=self.config.h,
device=self.device,
kernel_size_list=[kernel, kernel],
stride_list=[1, 1],
padding_list=[1, 1],
dilation_list=[1, dilation],
compute_region_indexes=True),
)