-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_blocks.py
More file actions
1503 lines (1216 loc) · 54 KB
/
basic_blocks.py
File metadata and controls
1503 lines (1216 loc) · 54 KB
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
'''
Copyright (C) 2010-2021 Alibaba Group Holding Limited.
'''
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
import uuid
from PlainNet import _get_right_parentheses_index_, _create_netblock_list_from_str_
class PlainNetBasicBlockClass(nn.Module):
def __init__(self, in_channels=None, out_channels=None, stride=1, no_create=False, block_name=None, **kwargs):
super(PlainNetBasicBlockClass, self).__init__(**kwargs)
self.in_channels = in_channels
self.out_channels = out_channels
self.stride = stride
self.no_create = no_create
self.block_name = block_name
if self.block_name is None:
self.block_name = 'uuid{}'.format(uuid.uuid4().hex)
def forward(self, x):
raise RuntimeError('Not implemented')
def __str__(self):
return type(self).__name__ + '({},{},{})'.format(self.in_channels, self.out_channels, self.stride)
def __repr__(self):
return type(self).__name__ + '({}|{},{},{})'.format(self.block_name, self.in_channels, self.out_channels, self.stride)
def get_output_resolution(self, input_resolution):
raise RuntimeError('Not implemented')
def get_FLOPs(self, input_resolution):
raise RuntimeError('Not implemented')
def get_model_size(self):
raise RuntimeError('Not implemented')
def set_in_channels(self, c):
raise RuntimeError('Not implemented')
@classmethod
def create_from_str(cls, s, no_create=False, **kwargs):
assert PlainNetBasicBlockClass.is_instance_from_str(s)
idx = _get_right_parentheses_index_(s)
assert idx is not None
param_str = s[len(cls.__name__ + '('):idx]
# find block_name
tmp_idx = param_str.find('|')
if tmp_idx < 0:
tmp_block_name = 'uuid{}'.format(uuid.uuid4().hex)
else:
tmp_block_name = param_str[0:tmp_idx]
param_str = param_str[tmp_idx + 1:]
param_str_split = param_str.split(',')
in_channels = int(param_str_split[0])
out_channels = int(param_str_split[1])
stride = int(param_str_split[2])
return cls(in_channels=in_channels, out_channels=out_channels, stride=stride,
block_name=tmp_block_name, no_create=no_create), s[idx + 1:]
@classmethod
def is_instance_from_str(cls, s):
if s.startswith(cls.__name__ + '(') and s[-1] == ')':
return True
else:
return False
class AdaptiveAvgPool(PlainNetBasicBlockClass):
def __init__(self, out_channels, output_size, no_create=False, **kwargs):
super(AdaptiveAvgPool, self).__init__(**kwargs)
self.in_channels = out_channels
self.out_channels = out_channels
self.output_size = output_size
self.no_create = no_create
if not no_create:
self.netblock = nn.AdaptiveAvgPool2d(output_size=(self.output_size, self.output_size))
def forward(self, x):
return self.netblock(x)
def __str__(self):
return type(self).__name__ + '({},{})'.format(self.out_channels // self.output_size**2, self.output_size)
def __repr__(self):
return type(self).__name__ + '({}|{},{})'.format(self.block_name,
self.out_channels // self.output_size ** 2, self.output_size)
def get_output_resolution(self, input_resolution):
return self.output_size
def get_FLOPs(self, input_resolution):
return 0
def get_model_size(self):
return 0
def set_in_channels(self, c):
self.in_channels = c
self.out_channels = c
@classmethod
def create_from_str(cls, s, no_create=False, **kwargs):
assert AdaptiveAvgPool.is_instance_from_str(s)
idx = _get_right_parentheses_index_(s)
assert idx is not None
param_str = s[len('AdaptiveAvgPool('):idx]
# find block_name
tmp_idx = param_str.find('|')
if tmp_idx < 0:
tmp_block_name = 'uuid{}'.format(uuid.uuid4().hex)
else:
tmp_block_name = param_str[0:tmp_idx]
param_str = param_str[tmp_idx + 1:]
param_str_split = param_str.split(',')
out_channels = int(param_str_split[0])
output_size = int(param_str_split[1])
return AdaptiveAvgPool(out_channels=out_channels, output_size=output_size,
block_name=tmp_block_name, no_create=no_create), s[idx + 1:]
class BN(PlainNetBasicBlockClass):
def __init__(self, out_channels=None, copy_from=None, no_create=False, **kwargs):
super(BN, self).__init__(**kwargs)
self.no_create = no_create
if copy_from is not None:
assert isinstance(copy_from, nn.BatchNorm2d)
self.in_channels = copy_from.weight.shape[0]
self.out_channels = copy_from.weight.shape[0]
assert out_channels is None or out_channels == self.out_channels
self.netblock = copy_from
else:
self.in_channels = out_channels
self.out_channels = out_channels
if no_create:
return
else:
self.netblock = nn.BatchNorm2d(num_features=self.out_channels)
def forward(self, x):
return self.netblock(x)
def __str__(self):
return 'BN({})'.format(self.out_channels)
def __repr__(self):
return 'BN({}|{})'.format(self.block_name, self.out_channels)
def get_output_resolution(self, input_resolution):
return input_resolution
def get_FLOPs(self, input_resolution):
return input_resolution ** 2 * self.out_channels
def get_model_size(self):
return self.out_channels
def set_in_channels(self, c):
self.in_channels = c
self.out_channels = c
if not self.no_create:
self.netblock = nn.BatchNorm2d(num_features=self.out_channels)
self.netblock.train()
self.netblock.requires_grad_(True)
@classmethod
def create_from_str(cls, s, no_create=False, **kwargs):
assert BN.is_instance_from_str(s)
idx = _get_right_parentheses_index_(s)
assert idx is not None
param_str = s[len('BN('):idx]
# find block_name
tmp_idx = param_str.find('|')
if tmp_idx < 0:
tmp_block_name = 'uuid{}'.format(uuid.uuid4().hex)
else:
tmp_block_name = param_str[0:tmp_idx]
param_str = param_str[tmp_idx + 1:]
out_channels = int(param_str)
return BN(out_channels=out_channels, block_name=tmp_block_name, no_create=no_create), s[idx + 1:]
class ConvKX(PlainNetBasicBlockClass):
def __init__(self, in_channels=None, out_channels=None, kernel_size=None, stride=None, groups=1, copy_from=None,
no_create=False, **kwargs):
super(ConvKX, self).__init__(**kwargs)
self.no_create = no_create
if copy_from is not None:
assert isinstance(copy_from, nn.Conv2d)
self.in_channels = copy_from.in_channels
self.out_channels = copy_from.out_channels
self.kernel_size = copy_from.kernel_size[0]
self.stride = copy_from.stride[0]
self.groups = copy_from.groups
assert in_channels is None or in_channels == self.in_channels
assert out_channels is None or out_channels == self.out_channels
assert kernel_size is None or kernel_size == self.kernel_size
assert stride is None or stride == self.stride
self.netblock = copy_from
else:
self.in_channels = in_channels
self.out_channels = out_channels
self.stride = stride
self.groups = groups
self.kernel_size = kernel_size
self.padding = (self.kernel_size - 1) // 2
if no_create or self.in_channels == 0 or self.out_channels == 0 or self.kernel_size == 0 \
or self.stride == 0:
return
else:
self.netblock = nn.Conv2d(in_channels=self.in_channels, out_channels=self.out_channels,
kernel_size=self.kernel_size, stride=self.stride,
padding=self.padding, bias=False, groups=self.groups)
def forward(self, x):
return self.netblock(x)
def __str__(self):
return type(self).__name__ + '({},{},{},{})'.format(self.in_channels, self.out_channels, self.kernel_size, self.stride)
def __repr__(self):
return type(self).__name__ + '({}|{},{},{},{})'.format(self.block_name, self.in_channels, self.out_channels, self.kernel_size, self.stride)
def get_output_resolution(self, input_resolution):
return input_resolution // self.stride
def get_FLOPs(self, input_resolution):
return self.in_channels * self.out_channels * self.kernel_size ** 2 * input_resolution ** 2 // self.stride ** 2 // self.groups
def get_model_size(self):
return self.in_channels * self.out_channels * self.kernel_size ** 2 // self.groups
def set_in_channels(self, c):
self.in_channels = c
if not self.no_create:
self.netblock = nn.Conv2d(in_channels=self.in_channels, out_channels=self.out_channels,
kernel_size=self.kernel_size, stride=self.stride,
padding=self.padding, bias=False)
self.netblock.train()
self.netblock.requires_grad_(True)
@classmethod
def create_from_str(cls, s, no_create=False, **kwargs):
assert cls.is_instance_from_str(s)
idx = _get_right_parentheses_index_(s)
assert idx is not None
param_str = s[len(cls.__name__ + '('):idx]
# find block_name
tmp_idx = param_str.find('|')
if tmp_idx < 0:
tmp_block_name = 'uuid{}'.format(uuid.uuid4().hex)
else:
tmp_block_name = param_str[0:tmp_idx]
param_str = param_str[tmp_idx + 1:]
split_str = param_str.split(',')
in_channels = int(split_str[0])
out_channels = int(split_str[1])
kernel_size = int(split_str[2])
stride = int(split_str[3])
return cls(in_channels=in_channels, out_channels=out_channels,
kernel_size=kernel_size, stride=stride, no_create=no_create, block_name=tmp_block_name), s[idx + 1:]
class ConvDW(PlainNetBasicBlockClass):
def __init__(self, out_channels=None, kernel_size=None, stride=None, copy_from=None,
no_create=False, **kwargs):
super(ConvDW, self).__init__(**kwargs)
self.no_create = no_create
if copy_from is not None:
assert isinstance(copy_from, nn.Conv2d)
self.in_channels = copy_from.in_channels
self.out_channels = copy_from.out_channels
self.kernel_size = copy_from.kernel_size[0]
self.stride = copy_from.stride[0]
assert self.in_channels == self.out_channels
assert out_channels is None or out_channels == self.out_channels
assert kernel_size is None or kernel_size == self.kernel_size
assert stride is None or stride == self.stride
self.netblock = copy_from
else:
self.in_channels = out_channels
self.out_channels = out_channels
self.stride = stride
self.kernel_size = kernel_size
self.padding = (self.kernel_size - 1) // 2
if no_create or self.in_channels == 0 or self.out_channels == 0 or self.kernel_size == 0 \
or self.stride == 0:
return
else:
self.netblock = nn.Conv2d(in_channels=self.in_channels, out_channels=self.out_channels,
kernel_size=self.kernel_size, stride=self.stride,
padding=self.padding, bias=False, groups=self.in_channels)
def forward(self, x):
return self.netblock(x)
def __str__(self):
return 'ConvDW({},{},{})'.format(self.out_channels, self.kernel_size, self.stride)
def __repr__(self):
return 'ConvDW({}|{},{},{})'.format(self.block_name, self.out_channels, self.kernel_size, self.stride)
def get_output_resolution(self, input_resolution):
return input_resolution // self.stride
def get_FLOPs(self, input_resolution):
return self.out_channels * self.kernel_size ** 2 * input_resolution ** 2 // self.stride ** 2
def get_model_size(self):
return self.out_channels * self.kernel_size ** 2
def set_in_channels(self, c):
self.in_channels = c
self.out_channels=self.in_channels
if not self.no_create:
self.netblock = nn.Conv2d(in_channels=self.in_channels, out_channels=self.out_channels,
kernel_size=self.kernel_size, stride=self.stride,
padding=self.padding, bias=False, groups=self.in_channels)
self.netblock.train()
self.netblock.requires_grad_(True)
@classmethod
def create_from_str(cls, s, no_create=False, **kwargs):
assert ConvDW.is_instance_from_str(s)
idx = _get_right_parentheses_index_(s)
assert idx is not None
param_str = s[len('ConvDW('):idx]
# find block_name
tmp_idx = param_str.find('|')
if tmp_idx < 0:
tmp_block_name = 'uuid{}'.format(uuid.uuid4().hex)
else:
tmp_block_name = param_str[0:tmp_idx]
param_str = param_str[tmp_idx + 1:]
split_str = param_str.split(',')
out_channels = int(split_str[0])
kernel_size = int(split_str[1])
stride = int(split_str[2])
return ConvDW(out_channels=out_channels,
kernel_size=kernel_size, stride=stride, no_create=no_create, block_name=tmp_block_name), s[idx + 1:]
class ConvKXG2(ConvKX):
def __init__(self, in_channels=None, out_channels=None, kernel_size=None, stride=None, copy_from=None,
no_create=False, **kwargs):
super(ConvKXG2, self).__init__(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,
stride=stride, copy_from=copy_from, no_create=no_create,
groups=2, **kwargs)
class ConvKXG4(ConvKX):
def __init__(self, in_channels=None, out_channels=None, kernel_size=None, stride=None, copy_from=None,
no_create=False, **kwargs):
super(ConvKXG4, self).__init__(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,
stride=stride, copy_from=copy_from, no_create=no_create,
groups=4, **kwargs)
class ConvKXG8(ConvKX):
def __init__(self, in_channels=None, out_channels=None, kernel_size=None, stride=None, copy_from=None,
no_create=False, **kwargs):
super(ConvKXG8, self).__init__(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,
stride=stride, copy_from=copy_from, no_create=no_create,
groups=8, **kwargs)
class ConvKXG16(ConvKX):
def __init__(self, in_channels=None, out_channels=None, kernel_size=None, stride=None, copy_from=None,
no_create=False, **kwargs):
super(ConvKXG16, self).__init__(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,
stride=stride, copy_from=copy_from, no_create=no_create,
groups=16, **kwargs)
class ConvKXG32(ConvKX):
def __init__(self, in_channels=None, out_channels=None, kernel_size=None, stride=None, copy_from=None,
no_create=False, **kwargs):
super(ConvKXG32, self).__init__(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,
stride=stride, copy_from=copy_from, no_create=no_create,
groups=32, **kwargs)
class Flatten(PlainNetBasicBlockClass):
def __init__(self, out_channels, no_create=False, **kwargs):
super(Flatten, self).__init__(**kwargs)
self.in_channels = out_channels
self.out_channels = out_channels
self.no_create = no_create
def forward(self, x):
return torch.flatten(x, 1)
def __str__(self):
return 'Flatten({})'.format(self.out_channels)
def __repr__(self):
return 'Flatten({}|{})'.format(self.block_name, self.out_channels)
def get_output_resolution(self, input_resolution):
return 1
def get_FLOPs(self, input_resolution):
return 0
def get_model_size(self):
return 0
def set_in_channels(self, c):
self.in_channels = c
self.out_channels = c
@classmethod
def create_from_str(cls, s, no_create=False, **kwargs):
assert Flatten.is_instance_from_str(s)
idx = _get_right_parentheses_index_(s)
assert idx is not None
param_str = s[len('Flatten('):idx]
# find block_name
tmp_idx = param_str.find('|')
if tmp_idx < 0:
tmp_block_name = 'uuid{}'.format(uuid.uuid4().hex)
else:
tmp_block_name = param_str[0:tmp_idx]
param_str = param_str[tmp_idx + 1:]
out_channels = int(param_str)
return Flatten(out_channels=out_channels, no_create=no_create, block_name=tmp_block_name), s[idx + 1:]
class Linear(PlainNetBasicBlockClass):
def __init__(self, in_channels=None, out_channels=None, bias=True, copy_from=None,
no_create=False, **kwargs):
super(Linear, self).__init__(**kwargs)
self.no_create = no_create
if copy_from is not None:
assert isinstance(copy_from, nn.Linear)
self.in_channels = copy_from.weight.shape[1]
self.out_channels = copy_from.weight.shape[0]
self.use_bias = copy_from.bias is not None
assert in_channels is None or in_channels == self.in_channels
assert out_channels is None or out_channels == self.out_channels
self.netblock = copy_from
else:
self.in_channels = in_channels
self.out_channels = out_channels
self.use_bias = bias
if not no_create:
self.netblock = nn.Linear(self.in_channels, self.out_channels,
bias=self.use_bias)
def forward(self, x):
return self.netblock(x)
def __str__(self):
return 'Linear({},{},{})'.format(self.in_channels, self.out_channels, int(self.use_bias))
def __repr__(self):
return 'Linear({}|{},{},{})'.format(self.block_name, self.in_channels, self.out_channels, int(self.use_bias))
def get_output_resolution(self, input_resolution):
assert input_resolution == 1
return 1
def get_FLOPs(self, input_resolution):
return self.in_channels * self.out_channels
def get_model_size(self):
return self.in_channels * self.out_channels + int(self.use_bias)
def set_in_channels(self, c):
self.in_channels = c
if not self.no_create:
self.netblock = nn.Linear(self.in_channels, self.out_channels,
bias=self.use_bias)
self.netblock.train()
self.netblock.requires_grad_(True)
@classmethod
def create_from_str(cls, s, no_create=False, **kwargs):
assert Linear.is_instance_from_str(s)
idx = _get_right_parentheses_index_(s)
assert idx is not None
param_str = s[len('Linear('):idx]
# find block_name
tmp_idx = param_str.find('|')
if tmp_idx < 0:
tmp_block_name = 'uuid{}'.format(uuid.uuid4().hex)
else:
tmp_block_name = param_str[0:tmp_idx]
param_str = param_str[tmp_idx + 1:]
split_str = param_str.split(',')
in_channels = int(split_str[0])
out_channels = int(split_str[1])
use_bias = int(split_str[2])
return Linear(in_channels=in_channels, out_channels=out_channels, bias=use_bias == 1,
block_name=tmp_block_name, no_create=no_create), s[idx+1 :]
class MaxPool(PlainNetBasicBlockClass):
def __init__(self, out_channels, kernel_size, stride, no_create=False, **kwargs):
super(MaxPool, self).__init__(**kwargs)
self.in_channels = out_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = (kernel_size - 1) // 2
self.no_create = no_create
if not no_create:
self.netblock = nn.MaxPool2d(kernel_size=self.kernel_size, stride=self.stride, padding=self.padding)
def forward(self, x):
return self.netblock(x)
def __str__(self):
return 'MaxPool({},{},{})'.format(self.out_channels, self.kernel_size, self.stride)
def __repr__(self):
return 'MaxPool({}|{},{},{})'.format(self.block_name, self.out_channels, self.kernel_size, self.stride)
def get_output_resolution(self, input_resolution):
return input_resolution // self.stride
def get_FLOPs(self, input_resolution):
return 0
def get_model_size(self):
return 0
def set_in_channels(self, c):
self.in_channels = c
self.out_channels = c
if not self.no_create:
self.netblock = nn.MaxPool2d(kernel_size=self.kernel_size, stride=self.stride, padding=self.padding)
@classmethod
def create_from_str(cls, s, no_create=False, **kwargs):
assert MaxPool.is_instance_from_str(s)
idx = _get_right_parentheses_index_(s)
assert idx is not None
param_str = s[len('MaxPool('):idx]
# find block_name
tmp_idx = param_str.find('|')
if tmp_idx < 0:
tmp_block_name = 'uuid{}'.format(uuid.uuid4().hex)
else:
tmp_block_name = param_str[0:tmp_idx]
param_str = param_str[tmp_idx + 1:]
param_str_split = param_str.split(',')
out_channels = int(param_str_split[0])
kernel_size = int(param_str_split[1])
stride = int(param_str_split[2])
return MaxPool(out_channels=out_channels, kernel_size=kernel_size, stride=stride, no_create=no_create,
block_name=tmp_block_name), s[idx + 1:]
class Sequential(PlainNetBasicBlockClass):
def __init__(self, block_list, no_create=False, **kwargs):
super(Sequential, self).__init__(**kwargs)
self.block_list = block_list
if not no_create:
self.module_list = nn.ModuleList(block_list)
self.in_channels = block_list[0].in_channels
self.out_channels = block_list[-1].out_channels
self.no_create = no_create
res = 1024
for block in self.block_list:
res = block.get_output_resolution(res)
self.stride = 1024 // res
def forward(self, x):
output = x
for inner_block in self.block_list:
output = inner_block(output)
return output
def __str__(self):
s = 'Sequential('
for inner_block in self.block_list:
s += str(inner_block)
s += ')'
return s
def __repr__(self):
return str(self)
def get_output_resolution(self, input_resolution):
the_res = input_resolution
for the_block in self.block_list:
the_res = the_block.get_output_resolution(the_res)
return the_res
def get_FLOPs(self, input_resolution):
the_res = input_resolution
the_flops = 0
for the_block in self.block_list:
the_flops += the_block.get_FLOPs(the_res)
the_res = the_block.get_output_resolution(the_res)
return the_flops
def get_model_size(self):
the_size = 0
for the_block in self.block_list:
the_size += the_block.get_model_size()
return the_size
def set_in_channels(self, c):
self.in_channels = c
if len(self.block_list) == 0:
self.out_channels = c
return
self.block_list[0].set_in_channels(c)
last_channels = self.block_list[0].out_channels
if len(self.block_list) >= 2 and isinstance(self.block_list[1], BN):
self.block_list[1].set_in_channels(last_channels)
@classmethod
def create_from_str(cls, s, no_create=False, **kwargs):
assert Sequential.is_instance_from_str(s)
the_right_paraen_idx = _get_right_parentheses_index_(s)
param_str = s[len('Sequential(')+1:the_right_paraen_idx]
# find block_name
tmp_idx = param_str.find('|')
if tmp_idx < 0:
tmp_block_name = 'uuid{}'.format(uuid.uuid4().hex)
else:
tmp_block_name = param_str[0:tmp_idx]
param_str = param_str[tmp_idx + 1:]
the_block_list, remaining_s = _create_netblock_list_from_str_(param_str, no_create=no_create)
assert len(remaining_s) == 0
if the_block_list is None or len(the_block_list) == 0:
return None, ''
return Sequential(block_list=the_block_list, no_create=no_create, block_name=tmp_block_name), ''
class MultiSumBlock(PlainNetBasicBlockClass):
def __init__(self, block_list, no_create=False, **kwargs):
super(MultiSumBlock, self).__init__(**kwargs)
self.block_list = block_list
if not no_create:
self.module_list = nn.ModuleList(block_list)
self.in_channels = np.max([x.in_channels for x in block_list])
self.out_channels = np.max([x.out_channels for x in block_list])
self.no_create = no_create
res = 1024
res = self.block_list[0].get_output_resolution(res)
self.stride = 1024 // res
def forward(self, x):
output = self.block_list[0](x)
for inner_block in self.block_list[1:]:
output2 = inner_block(x)
output = output + output2
return output
def __str__(self):
s = 'MultiSumBlock({}|'.format(self.block_name)
for inner_block in self.block_list:
s += str(inner_block) + ';'
s = s[:-1]
s += ')'
return s
def __repr__(self):
return str(self)
def get_output_resolution(self, input_resolution):
the_res = self.block_list[0].get_output_resolution(input_resolution)
for the_block in self.block_list:
assert the_res == the_block.get_output_resolution(input_resolution)
return the_res
def get_FLOPs(self, input_resolution):
the_flops = 0
for the_block in self.block_list:
the_flops += the_block.get_FLOPs(input_resolution)
return the_flops
def get_model_size(self):
the_size = 0
for the_block in self.block_list:
the_size += the_block.get_model_size()
return the_size
def set_in_channels(self, c):
self.in_channels = c
for the_block in self.block_list:
the_block.set_in_channels(c)
@classmethod
def create_from_str(cls, s, no_create=False, **kwargs):
assert MultiSumBlock.is_instance_from_str(s)
idx = _get_right_parentheses_index_(s)
assert idx is not None
param_str = s[len('MultiSumBlock('):idx]
# find block_name
tmp_idx = param_str.find('|')
if tmp_idx < 0:
tmp_block_name = 'uuid{}'.format(uuid.uuid4().hex)
else:
tmp_block_name = param_str[0:tmp_idx]
param_str = param_str[tmp_idx + 1:]
the_s = param_str
the_block_list = []
while len(the_s) > 0:
tmp_block_list, remaining_s = _create_netblock_list_from_str_(the_s, no_create=no_create)
the_s = remaining_s
if tmp_block_list is None:
pass
elif len(tmp_block_list) == 1:
the_block_list.append(tmp_block_list[0])
else:
the_block_list.append(Sequential(block_list=tmp_block_list, no_create=no_create))
pass # end while
if len(the_block_list) == 0:
return None, s[idx+1:]
return MultiSumBlock(block_list=the_block_list, block_name=tmp_block_name, no_create=no_create), s[idx+1:]
class MultiCatBlock(PlainNetBasicBlockClass):
def __init__(self, block_list, no_create=False, **kwargs):
super(MultiCatBlock, self).__init__(**kwargs)
self.block_list = block_list
if not no_create:
self.module_list = nn.ModuleList(block_list)
self.in_channels = np.max([x.in_channels for x in block_list])
self.out_channels = np.sum([x.out_channels for x in block_list])
self.no_create = no_create
res = 1024
res = self.block_list[0].get_output_resolution(res)
self.stride = 1024 // res
def forward(self, x):
output_list = []
for inner_block in self.block_list:
output = inner_block(x)
output_list.append(output)
return torch.cat(output_list, dim=1)
def __str__(self):
s = 'MultiCatBlock({}|'.format(self.block_name)
for inner_block in self.block_list:
s += str(inner_block) + ';'
s = s[:-1]
s += ')'
return s
def __repr__(self):
return str(self)
def get_output_resolution(self, input_resolution):
the_res = self.block_list[0].get_output_resolution(input_resolution)
for the_block in self.block_list:
assert the_res == the_block.get_output_resolution(input_resolution)
return the_res
def get_FLOPs(self, input_resolution):
the_flops = 0
for the_block in self.block_list:
the_flops += the_block.get_FLOPs(input_resolution)
return the_flops
def get_model_size(self):
the_size = 0
for the_block in self.block_list:
the_size += the_block.get_model_size()
return the_size
def set_in_channels(self, c):
self.in_channels = c
for the_block in self.block_list:
the_block.set_in_channels(c)
self.out_channels = np.sum([x.out_channels for x in self.block_list])
@classmethod
def create_from_str(cls, s, no_create=False, **kwargs):
assert MultiCatBlock.is_instance_from_str(s)
idx = _get_right_parentheses_index_(s)
assert idx is not None
param_str = s[len('MultiCatBlock('):idx]
# find block_name
tmp_idx = param_str.find('|')
if tmp_idx < 0:
tmp_block_name = 'uuid{}'.format(uuid.uuid4().hex)
else:
tmp_block_name = param_str[0:tmp_idx]
param_str = param_str[tmp_idx + 1:]
the_s = param_str
the_block_list = []
while len(the_s) > 0:
tmp_block_list, remaining_s = _create_netblock_list_from_str_(the_s, no_create=no_create)
the_s = remaining_s
if tmp_block_list is None:
pass
elif len(tmp_block_list) == 1:
the_block_list.append(tmp_block_list[0])
else:
the_block_list.append(Sequential(block_list=tmp_block_list, no_create=no_create))
pass # end if
pass # end while
if len(the_block_list) == 0:
return None, s[idx+1:]
return MultiCatBlock(block_list=the_block_list, block_name=tmp_block_name,
no_create=no_create), s[idx + 1:]
class RELU(PlainNetBasicBlockClass):
def __init__(self, out_channels, no_create=False, **kwargs):
super(RELU, self).__init__(**kwargs)
self.in_channels = out_channels
self.out_channels = out_channels
self.no_create = no_create
def forward(self, x):
return F.relu(x)
def __str__(self):
return 'RELU({})'.format(self.out_channels)
def __repr__(self):
return 'RELU({}|{})'.format(self.block_name, self.out_channels)
def get_output_resolution(self, input_resolution):
return input_resolution
def get_FLOPs(self, input_resolution):
return 0
def get_model_size(self):
return 0
def set_in_channels(self, c):
self.in_channels = c
self.out_channels = c
@classmethod
def create_from_str(cls, s, no_create=False, **kwargs):
assert RELU.is_instance_from_str(s)
idx = _get_right_parentheses_index_(s)
assert idx is not None
param_str = s[len('RELU('):idx]
# find block_name
tmp_idx = param_str.find('|')
if tmp_idx < 0:
tmp_block_name = 'uuid{}'.format(uuid.uuid4().hex)
else:
tmp_block_name = param_str[0:tmp_idx]
param_str = param_str[tmp_idx + 1:]
out_channels = int(param_str)
return RELU(out_channels=out_channels, no_create=no_create, block_name=tmp_block_name), s[idx+1:]
class ResBlock(PlainNetBasicBlockClass):
'''
ResBlock(in_channles, inner_blocks_str). If in_channels is missing, use block_list[0].in_channels as in_channels
'''
def __init__(self, block_list, in_channels=None, stride=None, no_create=False, **kwargs):
super(ResBlock, self).__init__(**kwargs)
self.block_list = block_list
self.stride = stride
self.no_create = no_create
if not no_create:
self.module_list = nn.ModuleList(block_list)
if in_channels is None:
self.in_channels = block_list[0].in_channels
else:
self.in_channels = in_channels
self.out_channels = block_list[-1].out_channels
if self.stride is None:
tmp_input_res = 1024
tmp_output_res = self.get_output_resolution(tmp_input_res)
self.stride = tmp_input_res // tmp_output_res
self.proj = None
if self.stride > 1 or self.in_channels != self.out_channels:
self.proj = nn.Sequential(
nn.Conv2d(self.in_channels, self.out_channels, 1, self.stride),
nn.BatchNorm2d(self.out_channels),
)
def forward(self, x):
if len(self.block_list) == 0:
return x
output = x
for inner_block in self.block_list:
output = inner_block(output)
if self.proj is not None:
output = output + self.proj(x)
else:
output = output + x
return output
def __str__(self):
s = 'ResBlock({},{},'.format(self.in_channels, self.stride)
for inner_block in self.block_list:
s += str(inner_block)
s += ')'
return s
def __repr__(self):
s = 'ResBlock({}|{},{},'.format(self.block_name, self.in_channels, self.stride)
for inner_block in self.block_list:
s += str(inner_block)
s += ')'
return s
def get_output_resolution(self, input_resolution):
the_res = input_resolution
for the_block in self.block_list:
the_res = the_block.get_output_resolution(the_res)
return the_res
def get_FLOPs(self, input_resolution):
the_res = input_resolution
the_flops = 0
for the_block in self.block_list:
the_flops += the_block.get_FLOPs(the_res)
the_res = the_block.get_output_resolution(the_res)
if self.proj is not None:
the_flops += self.in_channels * self.out_channels * (the_res / self.stride) ** 2 + \
(the_res / self.stride) ** 2 * self.out_channels
return the_flops
def get_model_size(self):
the_size = 0
for the_block in self.block_list:
the_size += the_block.get_model_size()
if self.proj is not None:
the_size += self.in_channels * self.out_channels + self.out_channels
return the_size
def set_in_channels(self, c):
self.in_channels = c
if len(self.block_list) == 0:
self.out_channels = c
return