-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClassificationModel.py
1206 lines (1115 loc) · 53.2 KB
/
ClassificationModel.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
# a better version of model constructor
import torch
import torch.nn as nn
import torch.nn.functional as F
import snntorch as snn
from snntorch import surrogate
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import torchvision.models as models
import numpy as np
from snntorch import surrogate
import torch
import torch.nn as nn
import math
# config model style:
'''
CNN layer/ SNN layer: name outchannel kernel stride padding skipfrom skipto residual
Linear layer: name
Reisidual layer: same as CNN layer
'''
class DepthwiseSeparableConv(nn.Module):
'''
basic convolution block
args:
in_channels: number of input channels
out_channels: number of output channels
kernel_size: kernel size
stride: stride
padding: padding
'''
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0):
super(DepthwiseSeparableConv, self).__init__()
self.depthwise = nn.Conv2d(in_channels, in_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=in_channels)
self.pointwise = nn.Conv2d(in_channels, out_channels, kernel_size=1)
def forward(self, x):
x = self.depthwise(x)
x = self.pointwise(x)
return x
class Tmaxpool(nn.Module):
def __init__(self,kernel_size,stride,padding) -> None:
super().__init__()
self.mp = nn.MaxPool2d(kernel_size=kernel_size,stride=stride,padding=padding)
def forward(self,x):
x = x.transpose(0,1)
timerange = x.shape[0]
rec = []
for step in range(timerange):
rec.append(self.mp(x[step]))
x = torch.stack(rec)
x = x.transpose(0,1)
return x
class Cnnbase(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, normalize=nn.BatchNorm2d, activation=nn.ReLU):
"""
Args:
in_channels (int): Number of input channels
out_channels (int): Number of output channels
kernel_size (int): Kernel size of the convolution
stride (int): Stride of the convolution (default: 1)
padding (int): Padding of the convolution (default: 0)
normalize (nn.Module): Normalization layer (default: nn.BatchNorm2d)
activation (nn.Module): Activation function (default: nn.ReLU)
"""
super(Cnnbase, self).__init__()
self.conv = DepthwiseSeparableConv(in_channels, out_channels, kernel_size, stride, padding)
if isinstance(normalize, nn.BatchNorm2d):
self.bn = normalize(out_channels)
else:
self.bn = None
self.relu = activation(inplace=True)
def forward(self, x):
x = self.conv(x)
if self.bn is not None:
x = self.bn(x)
x = self.relu(x)
return x
class TCnnbase(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0,time_step=4, normalize=snn.BatchNormTT2d, activation=nn.ReLU6):
"""
Args:
in_channels (int): Number of input channels
out_channels (int): Number of output channels
kernel_size (int): Kernel size of the convolution
stride (int): Stride of the convolution (default: 1)
padding (int): Padding of the convolution (default: 0)
time_step (int): Number of time steps (default: 4)
normalize (nn.Module or None): Normalization layer (default: snn.BatchNormTT2d)
activation (nn.Module or None): Activation function (default: nn.ReLU6)
"""
super(TCnnbase, self).__init__()
self.conv = DepthwiseSeparableConv(in_channels, out_channels, kernel_size, stride, padding)
if normalize is not None:
self.bn = normalize(out_channels,time_steps=time_step)
else:
self.bn = nn.Identity()
if activation is not None:
self.relu = activation(inplace=True)
else:
self.relu = nn.Identity()
self.time_step = time_step
def forward(self, x):
out = []
x = x.transpose(0,1)
for i in range(self.time_step):
#print(i)
x0 = x[i]
bni = self.bn[i]
x0 = self.conv(x0)
x0 = bni(x0 )
out.append(self.relu(x0 ))
out = torch.stack(out)
#print(out.size())
out = out.transpose(0,1)
#print(out.size())
return out
class LCBV2(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, time_steps, padding,activation = nn.SiLU):
"""
Args:
in_channels (int): Number of input channels
out_channels (int): Number of output channels
kernel_size (int): Kernel size of the convolution
stride (int): Stride of the convolution (default: 1)
time_steps (int): Number of time steps (default: 4)
padding (int): Padding of the convolution (default: 0)
activation (nn.Module or None): Activation function (default: nn.ReLU6)
"""
super().__init__()
self.time_steps = time_steps
self.outchannels = out_channels
self.stride = stride
self.B1 = torch.rand(1)
self.TH = torch.rand(1)
self.gF = torch.rand(1)
self.LIF = snn.Leaky(beta=self.B1, threshold=self.TH, learn_beta=True, learn_threshold=True,
graded_spikes_factor=self.gF,learn_graded_spikes_factor=True)
self.conv = nn.Sequential(
DepthwiseSeparableConv(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding),
)
if activation is not None:
self.act1 = activation(inplace=True)
else:
self.act1 = nn.Identity()
self.inv_LIF = snn.Leaky(beta=self.B1, threshold=self.TH, learn_beta=True, learn_threshold=True,
graded_spikes_factor=self.gF,learn_graded_spikes_factor=True)
self.convM = nn.Sequential(
DepthwiseSeparableConv(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=stride, padding=1),
)
if activation is not None:
self.act2 = activation(inplace=True)
else:
self.act2 = nn.Identity()
self.res = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride)
self.BN = snn.BatchNormTT2d(out_channels, time_steps=time_steps)
def forward(self, x):
x = x.transpose(0, 1)
timerange, batch_size, _, height, width = x.shape
mem = self.LIF.init_leaky()
mem_inv = self.inv_LIF.init_leaky()
final_spk_rec = torch.zeros((timerange, batch_size, self.outchannels, height // self.stride, width // self.stride), device=x.device)
for steps in range(timerange):
invsteps = timerange - steps - 1
bn = self.BN[steps]
bn_inv = self.BN[invsteps]
x0, mem = self.LIF(x[steps], mem)
x0 = self.conv(x0)
x0 = self.act1(x0)
spk = bn(x0)
xinv, mem_inv = self.inv_LIF(x[invsteps], mem_inv)
xinv = self.conv(xinv)
xinv = self.act2(xinv)
spk_inv = bn_inv(xinv)
final_spk_rec[steps] += spk*0.5
final_spk_rec[invsteps] += spk_inv*0.5
x = final_spk_rec.transpose(0, 1)
return x
class LCBV2Small(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, time_steps, padding,activation = nn.SiLU):
"""
Args:
in_channels (int): Number of input channels
out_channels (int): Number of output channels
kernel_size (int): Kernel size of the convolution
stride (int): Stride of the convolution (default: 1)
time_steps (int): Number of time steps (default: 4)
padding (int): Padding of the convolution (default: 0)
activation (nn.Module or None): Activation function (default: nn.SiLU)
"""
super().__init__()
self.timesteps = time_steps
self.outchannels = out_channels
self.stride = stride
self.B1 = torch.rand(1)
self.TH = torch.rand(1)
self.gF = torch.rand(1)
self.LIF = snn.Leaky(beta=self.B1, threshold=self.TH, learn_beta=True, learn_threshold=True,
graded_spikes_factor=self.gF,learn_graded_spikes_factor=True)
self.conv = nn.Sequential(
DepthwiseSeparableConv(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding),
activation(inplace=True) if activation is not None else nn.Identity(),
)
self.res = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride)
self.BN = snn.BatchNormTT2d(out_channels,time_steps)
def forward(self, x):
x = x.transpose(0, 1)
timerange, batch_size, _, height, width = x.shape
mem = self.LIF.init_leaky()
final_spk_rec = torch.zeros((timerange, batch_size, self.outchannels, height // self.stride, width // self.stride), device=x.device)
for steps in range(timerange):
bn = self.BN[steps]
x0, mem = self.LIF(x[steps], mem)
x0 = self.conv(x0)
spk = bn(x0)
final_spk_rec[steps] += spk
x = final_spk_rec.transpose(0, 1)
return x
class MSM2(nn.Module):
def __init__(self, in_channels,out_channels,kernel_size,stride,padding,time_steps,v2f = True,activation = nn.SiLU,activation2 = nn.SiLU):
"""
Args:
in_channels (int): Number of input channels
out_channels (int): Number of output channels
kernel_size (int): Kernel size of the convolution
stride (int): Stride of the convolution (default: 1)
time_steps (int): Number of time steps (default: 4)
padding (int): Padding of the convolution (default: 0)
v2f (bool): Whether to use V2F or not (default: True)
activation (nn.Module or None): Activation function for the first layer (default: nn.SiLU)
activation2 (nn.Module or None): Activation function for the following residual layer (default: nn.SiLU)
"""
super().__init__()
assert in_channels<out_channels
print(time_steps)
if v2f:
self.L = nn.ModuleList(
[
LCBV2(in_channels=in_channels,out_channels=out_channels//2,
kernel_size=kernel_size,stride=stride,
time_steps=time_steps,padding=padding,activation=activation),
LCBV2(in_channels=out_channels//2,out_channels=out_channels,kernel_size=kernel_size,stride=1,
time_steps=time_steps,padding=padding,activation=activation),
]
)
self.RLCB = TCnnbase(in_channels=in_channels,out_channels=out_channels,kernel_size=1,stride=stride,padding=0,time_step=time_steps,)
else:
self.L = nn.ModuleList(
[
LCBV2Small(in_channels=in_channels,out_channels=out_channels//2,
kernel_size=kernel_size,stride=stride,
time_steps=time_steps,padding=padding,activation=activation),
LCBV2Small(in_channels=out_channels//2,out_channels=out_channels,kernel_size=kernel_size,stride=1,
time_steps=time_steps,padding=padding,activation=activation),
]
)
self.RLCB = TCnnbase(in_channels=in_channels,out_channels=out_channels,kernel_size=1,stride=stride,padding=0,time_step=time_steps,)
self.Ms = MS(in_channels=out_channels,kernel_size=kernel_size,stride=1,time_steps=time_steps,
padding=padding,v2f = v2f,activation=activation2)
self.mp = Tmaxpool(kernel_size=kernel_size,stride=stride,padding=padding)
def forward(self,x):
Xl = x
Xr = x
for layer in self.L:
Xl = layer(Xl)
Xr = self.RLCB(Xr)#batch,time,c,w,h
x = Xl + Xr
x = self.Ms(x)
return x
class TCFATestBlockVCSTPN(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding, timesteps, activation=nn.SiLU):
"""
Paper used CBAM combine modula: only channel attention and spatial attention
Args:
in_channels (int): Number of input channels
out_channels (int): Number of output channels
kernel_size (int): Kernel size of the convolution
stride (int): Stride of the convolution (default: 1)
padding (int): Padding of the convolution (default: 0)
timesteps (int): Number of time steps (default: 4)
activation (nn.Module or None): Activation function (default: nn.SiLU)
"""
super().__init__()
self.timesteps = timesteps
print(f'time_steps:{self.timesteps}')
self.out_channels = out_channels
self.stride = stride
self.B1 = torch.rand(1)
self.TH = torch.rand(1)
self.gF = torch.rand(1)
self.factor = nn.Parameter(torch.ones(1))
self.LIF = snn.Leaky(beta=self.B1, threshold=self.TH, learn_beta=True, learn_threshold=True, graded_spikes_factor=self.gF, learn_graded_spikes_factor=True)
self.B2 = torch.rand(1)
self.TH2 = torch.rand(1)
self.gF2 = torch.rand(1)
self.factor2 = nn.Parameter(torch.ones(1))
self.LIF2 = snn.Leaky(beta=self.B2, threshold=self.TH2, learn_beta=True, learn_threshold=True, graded_spikes_factor=self.gF2, learn_graded_spikes_factor=True)
self.conv = nn.Sequential(
DepthwiseSeparableConv(
in_channels=in_channels,
out_channels=out_channels//2,
kernel_size=kernel_size,
stride=stride,
padding=padding
),
activation(inplace=True) if activation is not None else nn.Identity(),
)
self.convM = nn.Sequential(
DepthwiseSeparableConv(
in_channels=in_channels,
out_channels=out_channels//2,
kernel_size=1,
stride=stride,
padding=0
),
activation(inplace=True) if activation is not None else nn.Identity(),
)
self.conv2 = nn.Sequential(
DepthwiseSeparableConv(
in_channels=out_channels//2,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding
),
activation(inplace=True) if activation is not None else nn.Identity(),
)
self.BN = snn.BatchNormTT2d(out_channels//2, self.timesteps)
self.BN2 = snn.BatchNormTT2d(out_channels, self.timesteps)
self.Clinear = nn.Sequential(
nn.Linear(out_channels// 2, out_channels // 4),
nn.ReLU6(inplace=True),
nn.BatchNorm1d(out_channels // 4),
nn.Linear(out_channels // 4, out_channels//2),
)
self.Tlinear = nn.Sequential(
nn.Linear(self.timesteps, self.timesteps // 2),
nn.BatchNorm1d(self.timesteps // 2),
nn.ReLU6(inplace=True),
nn.Linear(self.timesteps // 2, self.timesteps),
)
self.spatial_conv = nn.Conv2d(2, 1, kernel_size=7, padding=3)
if in_channels != out_channels:
self.residual = nn.Sequential(
LCBV2(in_channels, out_channels, kernel_size=1, stride=1, time_steps=timesteps,padding=0,activation=activation),
)
else:
self.residual = None
def forward(self, x):
x = x.transpose(0, 1)
time_steps, batch_size, channels, height, width = x.shape
mem = self.LIF.init_leaky()
mem2 = self.LIF2.init_leaky()
mem2
xout = []
mem_rec = []
if self.residual is not None:
x0 = self.residual(x.transpose(0, 1)).transpose(0, 1)
else:
x0 = x
for step in range(self.timesteps):
bn = self.BN[step]
xo = x[step]
xo, mem = self.LIF(xo, mem)
xo = self.conv(xo)
xo = bn(xo)
# Channel Attention
channel_att = torch.mean(xo, dim=[2, 3])
channel_att_max, _ = torch.max(xo, dim=2)
channel_att_max, _ = torch.max(channel_att_max, dim=2)
channel_att = self.Clinear(channel_att)
channel_att_max = self.Clinear(channel_att_max)
channel_att += channel_att_max
channel_att = torch.sigmoid_(channel_att).unsqueeze(-1).unsqueeze(-1)
xo = xo * channel_att
# Spatial Attention
avg_pool = torch.mean(xo, dim=1)
max_pool, _ = torch.max(xo, dim=1)
spatial_att = torch.stack([avg_pool, max_pool], dim=1)
spatial_att = self.spatial_conv(spatial_att)
spatial_att = torch.sigmoid_(spatial_att)
xo = xo * spatial_att
xout.append(xo)
mem_rec.append(self.convM(mem))
x = torch.stack(xout)
xout = []
for step in range(self.timesteps):
bn = self.BN2[step]
xo = x[step]
xo, mem = self.LIF2(xo, mem2)
xo = self.conv2(xo)
xo = bn(xo)
xout.append(xo)
x = torch.stack(xout)
x = x+x0
x = x.transpose(0, 1)
return x
class SnnResidualBlock(nn.Module):
def __init__(self,in_channels,out_channels, time_steps,use_residual=True,num_repeats = 1,activation = nn.SiLU):
"""
Args:
in_channels (int): Number of input channels
out_channels (int): Number of output channels
time_steps (int): Number of time steps
use_residual (bool): Whether to use residual connection (default: True)
num_repeats (int): Number of repeats of the residual block (default: 1)
activation (nn.Module): Activation function (default: nn.SiLU)
"""
super(SnnResidualBlock,self).__init__()
self.layers = nn.ModuleList()
self.residual = nn.Identity()
for _ in range(num_repeats):
self.layers += [
nn.Sequential(
LCBV2Small(in_channels=in_channels,out_channels=out_channels//2,kernel_size=3,padding=1,stride=1,time_steps=time_steps,activation=activation),
LCBV2Small(out_channels//2,out_channels,kernel_size = 3,padding = 1,stride=1,time_steps=time_steps,activation=activation),
)
]
self.use_residual = use_residual
if use_residual and in_channels != out_channels:
self.residual = nn.Sequential(
LCBV2Small(in_channels, out_channels, kernel_size=1, stride=1, time_steps=time_steps,padding=0,activation=activation),
)
self.num_repeats = num_repeats
def forward(self,x):
for layer in self.layers:
if self.use_residual:
x0 = x
x0 = self.residual(x0)
x = layer(x) + x0
else:
x = layer(x)
return x
class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride=1, downsample=None,times=4):
super(ResidualBlock, self).__init__()
self.layers = nn.ModuleList()
for i in range(times):
self.layers+=[
nn.Sequential(
DepthwiseSeparableConv(in_channels, out_channels//2, kernel_size=3, stride=stride, padding=1),
nn.BatchNorm2d(out_channels//2),
nn.ReLU6(inplace=True),
DepthwiseSeparableConv(out_channels//2, out_channels, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(out_channels)),
nn.ReLU6(inplace=True),]
def forward(self, x):
for layer in self.layers:
x = x + layer(x)
return x
class MLPLayer(nn.Module):
def __init__(self, indim, outdim, normalize=nn.BatchNorm1d, activation=nn.ReLU):
"""
Args:
indim (int): Input dimension
outdim (int): Output dimension
normalize (nn.Module or None): Normalization layer (default: nn.BatchNorm1d)
activation (nn.Module or None): Activation function (default: nn.ReLU)
"""
super(MLPLayer, self).__init__()
self.linear = nn.Linear(indim, outdim)
if isinstance(normalize, nn.BatchNorm1d):
self.bn = normalize(outdim)
else:
self.bn = None
if activation is not None:
self.act = activation(inplace=True)
else:
self.act = None
def forward(self, x):
x = self.linear(x)
if self.bn is not None:
x = self.bn(x)
if self.act is not None:
x = self.act(x)
return x
class SnnMLPLayer(nn.Module):
def __init__(self,indim, outdim, time_steps,normalize=snn.BatchNormTT1d, activation=nn.SiLU,outF = False):
"""
Args:
indim (int): Input dimension
outdim (int): Output dimension
time_steps (int): Number of time steps
normalize (nn.Module or None): Normalization layer (default: snn.BatchNormTT1d)
activation (nn.Module or None): Activation function (default: nn.SiLU)
outF (bool): Whether to output the final state (default: False)
"""
super(SnnMLPLayer, self).__init__()
self.linear = nn.ModuleList()
for _ in range(time_steps):
self.linear += [nn.Linear(indim, outdim)]
self.B1 = torch.rand(1)
self.TH = torch.rand(1)
self.outF = outF
self.LIF = snn.Leaky(beta=self.B1,threshold=self.TH,learn_beta=True,learn_threshold=True)
if normalize is not None:
self.bn = normalize(outdim,time_steps)
else:
self.bn = nn.ModuleList()
for i in range(time_steps):
self.bn += [nn.Identity(outdim)]
if activation is not None:
self.act = activation(inplace=True)
else:
self.act = nn.Identity()
def forward(self, x):
mem = self.LIF.init_leaky()
x = x.transpose(0, 1)
spk_rec = []
for st in range(x.shape[0]):
xo = x[st]
bni = self.bn[st]
linear_T = self.linear[st]
xo,mem = self.LIF(xo,mem)
if self.bn is not None:
xo= bni(linear_T(xo))
else:
xo = linear_T(xo)
xo = self.act(xo)
spk_rec.append(xo)
if self.outF:
x = torch.stack(spk_rec)
else:
x = torch.stack(spk_rec)
x = x.transpose(0, 1)
#print(x.shape)
return x
class TFaltten(nn.Module):
def __init__(self):
"""
Initialize the TFaltten layer.
This layer will flatten the input tensor to a 2D tensor, but it will
preserve the time dimension.
"""
super(TFaltten, self).__init__()
self.flatten = nn.Flatten()
def forward(self,x):
x = x.transpose(0,1)
#print(x.shape)
output = []
for i in range(x.shape[0]):
x0 = x[i]
x0 = self.flatten(x0)
output.append(x0)
x = torch.stack(output)
x = x.transpose(0,1)
#print(x.shape)
return x
class MS(nn.Module):
def __init__(self,in_channels,kernel_size,stride ,time_steps,padding,v2f = True,activation=nn.SiLU):
"""
Initialize the MS layer.
This layer will create two sub-layers. The first layer is a LCBV2 layer with
half of the output channels. The second layer is also a LCBV2 layer with the
remaining half of the output channels. The two sub-layers are connected in
series.
Args:
in_channels (int): Number of input channels
kernel_size (int): Kernel size of the convolution
stride (int): Stride of the convolution
time_steps (int): Number of time steps
padding (int): Padding of the convolution
v2f (bool): Whether to use V2F or not (default: True)
activation (nn.Module or None): Activation function for the two sub-layers (default: nn.SiLU)
"""
super().__init__()
self.time_steps = time_steps
if v2f:
self.LCB1 = LCBV2(in_channels=in_channels,out_channels=in_channels//2,
kernel_size=kernel_size,stride=stride,time_steps=time_steps,padding=padding,activation=activation)
self.LCB2 = LCBV2(in_channels=in_channels//2,out_channels=in_channels,
kernel_size=kernel_size,stride=stride,time_steps=time_steps,padding=padding,activation=activation)
else:
self.LCB1 = LCBV2Small(in_channels=in_channels,out_channels=in_channels//2,kernel_size=kernel_size,stride=stride,time_steps=time_steps,padding=padding)
self.LCB2 = LCBV2Small(in_channels=in_channels//2,out_channels=in_channels,kernel_size=kernel_size,stride=stride,time_steps=time_steps,padding=padding)
def forward(self,x):
xo = x
x = self.LCB1(x)
x = self.LCB2(x)
x += xo
return x
class SNNBlockV3M1(nn.Module):
def __init__(self,in_channels,out_channels,kernel_size,stride,padding,time_steps,v2f = True,activation = nn.SiLU):
"""
Initialize the SNNBlockV3M1 module.(EMS M1 residual layer)
This module consists of two branches, L and R, each with a sequence of layers. The choice of layers
is determined by the `v2f` flag. Each branch processes the input data through distinct convolutional
and pooling layers.
"""
super().__init__()
assert in_channels >= out_channels
if v2f:
self.L = nn.ModuleList(
[
LCBV2(in_channels=in_channels,out_channels=out_channels//2,
kernel_size=kernel_size,stride=stride,time_steps=time_steps,padding=padding,activation=activation),
LCBV2(in_channels=out_channels//2,out_channels=out_channels,
kernel_size=3,stride=1,time_steps=time_steps,padding=1,activation=activation),
]
)
self.R = nn.ModuleList(
[
Tmaxpool(kernel_size=kernel_size,stride=stride,padding=padding),
LCBV2(in_channels=in_channels,out_channels=out_channels,
kernel_size=3,stride=1,time_steps=time_steps,padding=1,activation=activation),
]
)
else:
self.L = nn.ModuleList(
[
LCBV2(in_channels=in_channels,out_channels=out_channels//2,
kernel_size=kernel_size,stride=stride,time_steps=time_steps,padding=padding,activation=activation),
LCBV2(in_channels=out_channels//2,out_channels=out_channels,
kernel_size=3,stride=1,time_steps=time_steps,padding=1,activation=activation),
]
)
self.R = nn.ModuleList(
[
Tmaxpool(kernel_size=kernel_size,stride=stride,padding=padding),
LCBV2(in_channels=in_channels,out_channels=out_channels,kernel_size=3,stride=1,time_steps=time_steps,padding=1,activation=activation),
]
)
self.Ms = MS(in_channels=out_channels,kernel_size=kernel_size,stride=1,time_steps=time_steps,padding=padding,v2f = v2f)
def forward(self,x):
xL = x
xR = x
for layer in self.L:
xL = layer(xL)
for layer in self.R:
xR = layer(xR)
x = xL+xR
x = self.Ms(x)
return x
class SNNBlockVS2(nn.Module):
def __init__(self,in_channels,out_channels,kernel_size,stride,padding,time_steps,v2f = True,activation = nn.SiLU,activation2 = nn.SiLU):
"""
Initialize the SNNBlockVS2 layer.
Args:
in_channels (int): Number of input channels
out_channels (int): Number of output channels
kernel_size (int): Kernel size of the convolution
stride (int): Stride of the convolution
time_steps (int): Number of time steps
padding (int): Padding of the convolution
v2f (bool): Whether to use V2F or not (default: True)
activation (nn.Module or None): Activation function for the two sub-layers (default: nn.SiLU)
activation2 (nn.Module or None): Activation function for the following residual layer (default: nn.SiLU)
"""
super().__init__()
assert in_channels<out_channels
R_C = out_channels - in_channels
if v2f:
self.L = nn.ModuleList(
[
LCBV2(in_channels=in_channels,out_channels=out_channels//2,
kernel_size=kernel_size,stride=stride,
time_steps=time_steps,padding=padding,activation=activation),
LCBV2(in_channels=out_channels//2,out_channels=out_channels,kernel_size=kernel_size,stride=1,
time_steps=time_steps,padding=padding,activation=activation),
]
)
self.RLCB = LCBV2(in_channels=in_channels,out_channels=R_C,kernel_size=kernel_size,stride=1,
time_steps=time_steps,padding=1,activation=activation)
else:
self.L = nn.ModuleList(
[
LCBV2Small(in_channels=in_channels,out_channels=out_channels//2,
kernel_size=kernel_size,stride=stride,
time_steps=time_steps,padding=padding),
LCBV2Small(in_channels=out_channels//2,out_channels=out_channels,
kernel_size=kernel_size,stride=1,time_steps=time_steps,padding=padding),
]
)
self.RLCB = LCBV2Small(in_channels=in_channels,out_channels=R_C,kernel_size=kernel_size,stride=1,time_steps=time_steps,padding=1)
self.mp = Tmaxpool(kernel_size=kernel_size,stride=stride,padding=padding)
def forward(self,x):
Xl = x
Xr = x
for layer in self.L:
Xl = layer(Xl)
Xr = self.mp(Xr)
Xr0 = Xr
Xr0 = self.RLCB(Xr0)
Xr = torch.concat([Xr,Xr0],dim=2)
x = Xl + Xr
return x
class SNNBlockV3M2(nn.Module):
def __init__(self,in_channels,out_channels,kernel_size,stride,padding,time_steps,v2f = True,activation = nn.SiLU,activation2 = nn.SiLU):
"""
Initialize the EMS-M2 residual layer.
Args:
in_channels (int): Number of input channels
out_channels (int): Number of output channels
kernel_size (int): Kernel size of the convolution
stride (int): Stride of the convolution
time_steps (int): Number of time steps
padding (int): Padding of the convolution
v2f (bool): Whether to use V2F or not (default: True)
activation (nn.Module or None): Activation function for the two sub-layers (default: nn.SiLU)
activation2 (nn.Module or None): Activation function for the following residual layer (default: nn.SiLU)
"""
super().__init__()
assert in_channels<out_channels
R_C = out_channels - in_channels
if v2f:
self.L = nn.ModuleList(
[
LCBV2(in_channels=in_channels,out_channels=out_channels//2,
kernel_size=kernel_size,stride=stride,
time_steps=time_steps,padding=padding,activation=activation),
LCBV2(in_channels=out_channels//2,out_channels=out_channels,kernel_size=kernel_size,stride=1,
time_steps=time_steps,padding=padding,activation=activation),
]
)
self.mp = Tmaxpool(kernel_size=kernel_size,stride=stride,padding=padding)
self.RLCB = LCBV2(in_channels=in_channels,out_channels=R_C,kernel_size=kernel_size,stride=1,
time_steps=time_steps,padding=1,activation=activation)
else:
self.L = nn.ModuleList(
[
LCBV2Small(in_channels=in_channels,out_channels=out_channels//2,
kernel_size=kernel_size,stride=stride,
time_steps=time_steps,padding=padding),
LCBV2Small(in_channels=out_channels//2,out_channels=out_channels,kernel_size=kernel_size,stride=1,time_steps=time_steps,padding=padding),
]
)
self.RLCB = LCBV2Small(in_channels=in_channels,out_channels=R_C,kernel_size=kernel_size,stride=1,time_steps=time_steps,padding=1)
self.Ms = MS(in_channels=out_channels,kernel_size=kernel_size,stride=1,time_steps=time_steps,
padding=padding,v2f = v2f,activation=activation2)
self.mp = Tmaxpool(kernel_size=kernel_size,stride=stride,padding=padding)
def forward(self,x):
Xl = x
Xr = x
for layer in self.L:
Xl = layer(Xl)
Xr = self.mp(Xr)
Xr0 = Xr
Xr0 = self.RLCB(Xr0)#batch,time,c,w,h
Xr = torch.concat([Xr,Xr0],dim=2)#b,t,c,w,h
x = Xl + Xr
x = self.Ms(x)
return x
class Full_E_RES(nn.Module):
def __init__(self,in_channels,out_channels,kernel_size,stride,padding,timesteps=4,v2f = True,activation = nn.SiLU,):
"""
Initialize the Full spike skip connect adapter.
Args:
in_channels (int): Number of input channels
out_channels (int): Number of output channels
kernel_size (int): Kernel size of the convolution
stride (int): Stride of the convolution
padding (int): Padding of the convolution
timesteps (int): Number of time steps (default: 4)
v2f (bool): Whether to use V2F or not (default: True)
activation (nn.Module or None): Activation function (default: nn.SiLU)
"""
super().__init__()
self.mp = Tmaxpool(kernel_size=kernel_size,stride=stride,padding=padding)
self.RLCB = LCBV2Small(in_channels=in_channels,out_channels=out_channels,kernel_size=kernel_size,stride=1,
time_steps=timesteps,padding=padding,activation=activation)
def forward(self,x):
#print(x.shape)
x = self.mp(x)
x = self.RLCB(x)#batch,time,c,w,h
return x
# define the funtions of all used modual
ConvList = [nn.Conv1d, nn.Conv2d, nn.Conv3d,Cnnbase,ResidualBlock,LCBV2,SNNBlockV3M2,SNNBlockV3M1,TCnnbase,MSM2,TCFATestBlockVCSTPN,SNNBlockVS2]
LinearList = [nn.Linear,MLPLayer,SnnMLPLayer]
ResidualList = [ResidualBlock,SnnResidualBlock]
class ClassificationModel_New_New(nn.Module):
def __init__(self, num_classes, in_channels=3, config_set=None, snnF=False,imageshape=(3, 224, 224),timestpes = 4):
"""
Initialize the ClassificationModel_New_New.
Args:
num_classes (int): Number of output classes
in_channels (int): Number of input channels (default: 3)
config_set (list or None): List of tuples containing the configuration of the layers (default: None)
snnF (bool): Whether to use SNN or not (default: False)
imageshape (tuple): Shape of the input image (default: (3, 224, 224))
timestpes (int): Number of time steps (default: 4)
"""
super(ClassificationModel_New_New, self).__init__()
self.num_classes = num_classes
self.in_channels = in_channels
self.config_set = config_set
self.shape = imageshape
self.layers = nn.ModuleList()
self.skip_convs = nn.ModuleDict()
self.skip_connections = {}
self.snnFlag = snnF
self.timestpes = timestpes
self._create_conv_layers()
def _autoshape(self, in_channels, H, W):
"""
Calculate the size of the flatten layer before the fully connected layer.
Args:
in_channels (int): Number of input channels
H (int): Height of the feature map
W (int): Width of the feature map
Returns:
int: The size of the flatten layer
"""
return in_channels * H * W
def _create_conv_layers(self):
"""
Create convolutional layers based on the configuration set (example is provided in following code).
Attributes:
in_channels (int): Initial number of input channels.
shape (tuple): Tuple containing the initial height and width of input images.
config_set (list): List of tuples specifying layer configurations.
snnFlag (bool): Flag indicating whether to use SNN configurations.
timestpes (int): Number of time steps for SNN layers.
skip_convs (nn.ModuleDict): Dictionary for storing 1x1 convolutions for
skip connection adjustments.
skip_connections (dict): Dictionary for storing skip connection information.
"""
in_channels = self.in_channels
h, w = self.shape[1], self.shape[2]
channels_at_layer = {}
shape_log = []
for idx, config in enumerate(self.config_set):
layer_class = config[0]
layer_params = config[1]
skip_layers = config[2] if len(config) > 2 else []
skip_type = config[3] if len(config) > 3 else None
in_channels_for_layer = in_channels
if skip_layers and skip_type == "concat":
# adapt in_channels_for_layer to skip layers (concat)
adjusted_channels = 0
for skip_layer_idx in skip_layers:
ori_shape = shape_log[skip_layer_idx]
skip_out_channels = channels_at_layer[skip_layer_idx]
if layer_class in ConvList:
h_n,w_n = shape_log[-1]
print(f'conv layer: skip {skip_layer_idx} to {idx} with h {h_n},w{w_n}')
elif layer_class in ResidualList:
h_n,w_n = shape_log[-1]
print(f'residual layer: skip {skip_layer_idx} to {idx} with h {h_n},w{w_n}')
# if the output channels of the skip layer are not equal to the input channels of the current layer
if skip_out_channels != in_channels or ori_shape[0] != h_n or ori_shape[1] != w_n:
adjusted_channels += in_channels
conv_layer_name = f"conv_{skip_layer_idx}_to_{idx}"
ori_shape = shape_log[skip_layer_idx]
print('create transform layer for concat connet')
if ori_shape[0] != h_n or ori_shape[1] != w_n:
print(f'ori_shape: {ori_shape} h: {h} w: {w}')
rate = int(ori_shape[0]/h_n)
print(f'rate: {rate}')
else:
rate =1
# shape adjustment
if self.snnFlag:
print('snnflag')
print(f'ori_shape: {ori_shape} h: {h} w: {w},tps:{self.timestpes}')
self.skip_convs[conv_layer_name] = TCnnbase(skip_out_channels, in_channels, kernel_size=1,stride=rate,padding=0,time_step=self.timestpes, normalize=snn.BatchNormTT2d, activation=nn.SiLU)
else:
self.skip_convs[conv_layer_name] = nn.Conv2d(skip_out_channels, in_channels, kernel_size=1,stride=rate)
else:
adjusted_channels += skip_out_channels
# final in_channels for current layer
in_channels_for_layer = in_channels + adjusted_channels
elif skip_layers and skip_type == "add":
# adapt in_channels_for_layer to skip layers (add)
for skip_layer_idx in skip_layers:
ori_shape = shape_log[skip_layer_idx]
skip_out_channels = channels_at_layer[skip_layer_idx]
if layer_class in ConvList:
h_n,w_n = shape_log[-1]
print(f'conv layer: skip {skip_layer_idx} to {idx} with h {h_n},w{w_n}')
elif layer_class in ResidualList:
h_n,w_n = shape_log[-1]
print(f'residual layer: skip {skip_layer_idx} to {idx} with h {h_n},w{w_n}')
# if not the same, the in_channel of the current layer should be adjusted
if skip_out_channels != in_channels or ori_shape[0] != h_n or ori_shape[1] != w_n:
# create transform layer
conv_layer_name = f"conv_{skip_layer_idx}_to_{idx}"
print('create transform layer for add connet')
if ori_shape[0] != h_n or ori_shape[1] != w_n:
print(f'ori_shape: {ori_shape} h: {h_n} w: {w_n}')
rate = int(ori_shape[0]/h_n)
print(f'rate: {rate}')
else:
rate =1
if self.snnFlag:
# for add skip connection
self.skip_convs[conv_layer_name] = Full_E_RES(skip_out_channels, in_channels, kernel_size=1,stride=rate,padding=0,timesteps=self.timestpes, activation=nn.SiLU)
else:
# for add skip connection
self.skip_convs[conv_layer_name] = nn.Conv2d(skip_out_channels, in_channels, kernel_size=1,stride=rate)
in_channels_for_layer = in_channels
else:
in_channels_for_layer = in_channels # no skip layers
if layer_class in LinearList:
# if previous layer is a linear layer, we need to add one flatten layer before next layer
if isinstance(self.layers[-1], tuple(ConvList)) or isinstance(self.layers[-1], tuple(ResidualList)):
print(f'linear part:')
if layer_class == SnnMLPLayer:
self.layers.append(TFaltten())
print('Tflatten')
else:
self.layers.append(nn.Flatten())
print('flatten')
in_channels = self._autoshape(in_channels, h, w)
h, w = 1, 1 # full connected layer don't have height and width
print(f'linear {layer_class} id: {in_channels} od: {layer_params[0]}')
layer = layer_class(in_channels, *layer_params)
in_channels = layer_params[0] # update in_channels
elif layer_class in ResidualList:
# deal with residual block
out_channels = layer_params[0]
if self.snnFlag:
stride = layer_params[3]
else:
stride = layer_params[1]
in_channels = layer_params[0] # update in_channels
shape_log.append((h,w))
print(f"Residual Block: in_channels={in_channels_for_layer}, out_channels={out_channels}, repeat={stride}")
layer = layer_class(in_channels_for_layer, *layer_params)
in_channels = out_channels # update in_channels
else:
# deal with conv layer
print(f'conv {layer_class} K: {layer_params[1]},S: {layer_params[2]},P: {layer_params[3]}')
print(f'in_C: {in_channels_for_layer},out_C: {layer_params[0]}')
layer = layer_class(in_channels_for_layer, *layer_params)
kernel_size, stride, padding = layer_params[1], layer_params[2], layer_params[3]
h = ((h + 2 * padding - kernel_size) // stride ) + 1
w = ((w + 2 * padding - kernel_size) // stride ) + 1
in_channels = layer_params[0] # update in_channels
shape_log.append((h,w))
print((h,w))
# record the output channels of the current layer
channels_at_layer[idx] = in_channels
self.layers.append(layer)