-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathnode.py
1502 lines (1266 loc) · 58.4 KB
/
node.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
# encoding: utf-8
# Author : Floyed<[email protected]>
# Datetime : 2022/4/10 18:46
# User : Floyed
# Product : PyCharm
# Project : braincog
# File : node.py
# explain : 神经元节点类型
import abc
import math
from abc import ABC
import numpy as np
import random
import torch
from torch import nn
from torch.nn import Parameter
import torch.nn.functional as F
from einops import rearrange, repeat
from braincog.base.connection.layer import CustomLinear
from braincog.base.strategy.surrogate import *
class BaseNode(nn.Module, abc.ABC):
"""
神经元模型的基类
:param threshold: 神经元发放脉冲需要达到的阈值
:param v_reset: 静息电位
:param dt: 时间步长
:param step: 仿真步
:param requires_thres_grad: 是否需要计算对于threshold的梯度, 默认为 ``False``
:param sigmoid_thres: 是否使用sigmoid约束threshold的范围搭到 [0, 1], 默认为 ``False``
:param requires_fp: 是否需要在推理过程中保存feature map, 需要消耗额外的内存和时间, 默认为 ``False``
:param layer_by_layer: 是否以一次性计算所有step的输出, 在网络模型较大的情况下, 一般会缩短单次推理的时间, 默认为 ``False``
:param n_groups: 在不同的时间步, 是否使用不同的权重, 默认为 ``1``, 即不分组
:param mem_detach: 是否将上一时刻的膜电位在计算图中截断
:param args: 其他的参数
:param kwargs: 其他的参数
"""
def __init__(self,
threshold=.5,
v_reset=0.,
dt=1.,
step=8,
requires_thres_grad=False,
sigmoid_thres=False,
requires_fp=False,
layer_by_layer=False,
n_groups=1,
*args,
**kwargs):
super(BaseNode, self).__init__()
self.threshold = Parameter(torch.tensor(threshold), requires_grad=requires_thres_grad)
self.sigmoid_thres = sigmoid_thres
self.mem = 0.
self.spike = 0.
self.dt = dt
self.feature_map = []
self.mem_collect = []
self.requires_fp = requires_fp
self.v_reset = v_reset
self.step = step
self.layer_by_layer = layer_by_layer
self.groups = n_groups
self.mem_detach = kwargs['mem_detach'] if 'mem_detach' in kwargs else False
self.requires_mem = kwargs['requires_mem'] if 'requires_mem' in kwargs else False
@abc.abstractmethod
def calc_spike(self):
"""
通过当前的mem计算是否发放脉冲,并reset
:return: None
"""
pass
def integral(self, inputs):
"""
计算由当前inputs对于膜电势的累积
:param inputs: 当前突触输入电流
:type inputs: torch.tensor
:return: None
"""
pass
def get_thres(self):
return self.threshold if not self.sigmoid_thres else self.threshold.sigmoid()
def rearrange2node(self, inputs):
if self.groups != 1:
if len(inputs.shape) == 4:
outputs = rearrange(inputs, 'b (c t) w h -> t b c w h', t=self.step)
elif len(inputs.shape) == 2:
outputs = rearrange(inputs, 'b (c t) -> t b c', t=self.step)
else:
raise NotImplementedError
elif self.layer_by_layer:
if len(inputs.shape) == 4:
outputs = rearrange(inputs, '(t b) c w h -> t b c w h', t=self.step)
elif len(inputs.shape) == 3:
outputs = rearrange(inputs, '(t b) n c -> t b n c', t=self.step)
elif len(inputs.shape) == 2:
outputs = rearrange(inputs, '(t b) c -> t b c', t=self.step)
else:
raise NotImplementedError
else:
outputs = inputs
return outputs
def rearrange2op(self, inputs):
if self.groups != 1:
if len(inputs.shape) == 5:
outputs = rearrange(inputs, 't b c w h -> b (c t) w h')
elif len(inputs.shape) == 3:
outputs = rearrange(inputs, ' t b c -> b (c t)')
else:
raise NotImplementedError
elif self.layer_by_layer:
if len(inputs.shape) == 5:
outputs = rearrange(inputs, 't b c w h -> (t b) c w h')
elif len(inputs.shape) == 4:
outputs = rearrange(inputs, ' t b n c -> (t b) n c')
elif len(inputs.shape) == 3:
outputs = rearrange(inputs, ' t b c -> (t b) c')
else:
raise NotImplementedError
else:
outputs = inputs
return outputs
def forward(self, inputs):
"""
torch.nn.Module 默认调用的函数,用于计算膜电位的输入和脉冲的输出
在```self.requires_fp is True``` 的情况下,可以使得```self.feature_map```用于记录trace
:param inputs: 当前输入的膜电位
:return: 输出的脉冲
"""
if hasattr(self, 'parallel') and self.parallel is True:
inputs = self.rearrange2node(inputs)
if self.mem_detach and hasattr(self.mem, 'detach'):
self.mem = self.mem.detach()
self.spike = self.spike.detach()
self.integral(inputs)
self.calc_spike()
if self.requires_fp is True:
self.feature_map.append(self.spike)
if self.requires_mem is True:
self.mem_collect.append(self.mem)
return self.rearrange2op(self.spike)
elif self.layer_by_layer or self.groups != 1:
inputs = self.rearrange2node(inputs)
outputs = []
for i in range(self.step):
if self.mem_detach and hasattr(self.mem, 'detach'):
self.mem = self.mem.detach()
self.spike = self.spike.detach()
self.integral(inputs[i])
self.calc_spike()
if self.requires_fp is True:
self.feature_map.append(self.spike)
if self.requires_mem is True:
self.mem_collect.append(self.mem)
outputs.append(self.spike)
outputs = torch.stack(outputs)
outputs = self.rearrange2op(outputs)
return outputs
else:
if self.mem_detach and hasattr(self.mem, 'detach'):
self.mem = self.mem.detach()
self.spike = self.spike.detach()
self.integral(inputs)
self.calc_spike()
if self.requires_fp is True:
self.feature_map.append(self.spike)
if self.requires_mem is True:
self.mem_collect.append(self.mem)
return self.spike
def n_reset(self):
"""
神经元重置,用于模型接受两个不相关输入之间,重置神经元所有的状态
:return: None
"""
self.mem = self.v_reset
self.spike = 0.
self.feature_map = []
self.mem_collect = []
def get_n_attr(self, attr):
if hasattr(self, attr):
return getattr(self, attr)
else:
return None
def set_n_warm_up(self, flag):
"""
一些训练策略会在初始的一些epoch,将神经元视作ANN的激活函数训练,此为设置是否使用该方法训练
:param flag: True:神经元变为激活函数, False:不变
:return: None
"""
self.warm_up = flag
def set_n_threshold(self, thresh):
"""
动态设置神经元的阈值
:param thresh: 阈值
:return:
"""
self.threshold = Parameter(torch.tensor(thresh, dtype=torch.float), requires_grad=False)
def set_n_tau(self, tau):
"""
动态设置神经元的衰减系数,用于带Leaky的神经元
:param tau: 衰减系数
:return:
"""
if hasattr(self, 'tau'):
self.tau = Parameter(torch.tensor(tau, dtype=torch.float), requires_grad=False)
else:
raise NotImplementedError
#============================================================================
# node的基类
class BaseMCNode(nn.Module, abc.ABC):
"""
多房室神经元模型的基类
:param threshold: 神经元发放脉冲需要达到的阈值
:param v_reset: 静息电位
:param comps: 神经元不同房室, 例如["apical", "basal", "soma"]
"""
def __init__(self,
threshold=1.0,
v_reset=0.,
comps=[]):
super().__init__()
self.threshold = Parameter(torch.tensor(threshold), requires_grad=False)
# self.decay = Parameter(torch.tensor(decay), requires_grad=False)
self.v_reset = v_reset
assert len(comps) != 0
self.mems = dict()
for c in comps:
self.mems[c] = None
self.spike = None
self.warm_up = False
@abc.abstractmethod
def calc_spike(self):
pass
@abc.abstractmethod
def integral(self, inputs):
pass
def forward(self, inputs: dict):
'''
Params:
inputs dict: Inputs for every compartments of neuron
'''
if self.warm_up:
return inputs
else:
self.integral(**inputs)
self.calc_spike()
return self.spike
def n_reset(self):
for c in self.mems.keys():
self.mems[c] = self.v_reset
self.spike = 0.0
def get_n_fire_rate(self):
if self.spike is None:
return 0.
return float((self.spike.detach() >= self.threshold).sum()) / float(np.product(self.spike.shape))
def set_n_warm_up(self, flag):
self.warm_up = flag
def set_n_threshold(self, thresh):
self.threshold = Parameter(torch.tensor(thresh, dtype=torch.float), requires_grad=False)
class ThreeCompNode(BaseMCNode):
"""
三房室神经元模型
:param threshold: 神经元发放脉冲需要达到的阈值
:param v_reset: 静息电位
:param tau: 胞体膜电位时间常数, 用于控制胞体膜电位衰减
:param tau_basal: 基底树突膜电位时间常数, 用于控制基地树突胞体膜电位衰减
:param tau_apical: 远端树突膜电位时间常数, 用于控制远端树突胞体膜电位衰减
:param comps: 神经元不同房室, 例如["apical", "basal", "soma"]
:param act_fun: 脉冲梯度代理函数
"""
def __init__(self,
threshold=1.0,
tau=2.0,
tau_basal=2.0,
tau_apical=2.0,
v_reset=0.0,
comps=['basal', 'apical', 'soma'],
act_fun=AtanGrad):
g_B = 0.6
g_L = 0.05
super().__init__(threshold, v_reset, comps)
self.tau = tau
self.tau_basal = tau_basal
self.tau_apical = tau_apical
self.act_fun = act_fun(alpha=tau, requires_grad=False)
def integral(self, basal_inputs, apical_inputs):
'''
Params:
inputs torch.Tensor: Inputs for basal dendrite
'''
self.mems['basal'] = (self.mems['basal'] + basal_inputs) / self.tau_basal
self.mems['apical'] = (self.mems['apical'] + apical_inputs) / self.tau_apical
self.mems['soma'] = self.mems['soma'] + (self.mems['apical'] + self.mems['basal'] - self.mems['soma']) / self.tau
def calc_spike(self):
self.spike = self.act_fun(self.mems['soma'] - self.threshold)
self.mems['soma'] = self.mems['soma'] * (1. - self.spike.detach())
self.mems['basal'] = self.mems['basal'] * (1. - self.spike.detach())
self.mems['apical'] = self.mems['apical'] * (1. - self.spike.detach())
#============================================================================
# 用于静态测试 使用ANN的情况 不累积电位
class ReLUNode(BaseNode):
"""
用于相同连接的ANN的测试
"""
def __init__(self,
*args,
**kwargs):
super().__init__(requires_fp=False, *args, **kwargs)
self.act_fun = nn.ReLU()
def forward(self, x):
"""
参考```BaseNode```
:param x:
:return:
"""
self.spike = self.act_fun(x)
if self.requires_fp is True:
self.feature_map.append(self.spike)
if self.requires_mem is True:
self.mem_collect.append(self.mem)
return self.spike
def calc_spike(self):
pass
class BiasReLUNode(BaseNode):
"""
用于相同连接的ANN的测试, 会在每个时刻注入恒定电流, 使得神经元更容易激发
"""
def __init__(self,
*args,
**kwargs):
super().__init__(*args, **kwargs)
self.act_fun = nn.ReLU()
def forward(self, x):
self.spike = self.act_fun(x + 0.1)
if self.requires_fp is True:
self.feature_map += self.spike
return self.spike
def calc_spike(self):
pass
# ============================================================================
# 用于SNN的node
class IFNode(BaseNode):
"""
Integrate and Fire Neuron
:param threshold: 神经元发放脉冲需要达到的阈值
:param v_reset: 静息电位
:param dt: 时间步长
:param step: 仿真步
:param act_fun: 使用surrogate gradient 对梯度进行近似, 默认为 ``surrogate.AtanGrad``
:param requires_thres_grad: 是否需要计算对于threshold的梯度, 默认为 ``False``
:param sigmoid_thres: 是否使用sigmoid约束threshold的范围搭到 [0, 1], 默认为 ``False``
:param requires_fp: 是否需要在推理过程中保存feature map, 需要消耗额外的内存和时间, 默认为 ``False``
:param layer_by_layer: 是否以一次性计算所有step的输出, 在网络模型较大的情况下, 一般会缩短单次推理的时间, 默认为 ``False``
:param n_groups: 在不同的时间步, 是否使用不同的权重, 默认为 ``1``, 即不分组
:param args: 其他的参数
:param kwargs: 其他的参数
"""
def __init__(self, threshold=.5, act_fun=AtanGrad, *args, **kwargs):
"""
:param threshold:
:param act_fun:
:param args:
:param kwargs:
"""
super().__init__(threshold, *args, **kwargs)
if isinstance(act_fun, str):
act_fun = eval(act_fun)
self.act_fun = act_fun(alpha=2., requires_grad=False)
def integral(self, inputs):
self.mem = self.mem + inputs * self.dt
def calc_spike(self):
self.spike = self.act_fun(self.mem - self.get_thres())
self.mem = self.mem * (1 - self.spike.detach())
class LIFNode(BaseNode):
"""
Leaky Integrate and Fire
:param threshold: 神经元发放脉冲需要达到的阈值
:param v_reset: 静息电位
:param dt: 时间步长
:param step: 仿真步
:param tau: 膜电位时间常数, 用于控制膜电位衰减
:param act_fun: 使用surrogate gradient 对梯度进行近似, 默认为 ``surrogate.AtanGrad``
:param requires_thres_grad: 是否需要计算对于threshold的梯度, 默认为 ``False``
:param sigmoid_thres: 是否使用sigmoid约束threshold的范围搭到 [0, 1], 默认为 ``False``
:param requires_fp: 是否需要在推理过程中保存feature map, 需要消耗额外的内存和时间, 默认为 ``False``
:param layer_by_layer: 是否以一次性计算所有step的输出, 在网络模型较大的情况下, 一般会缩短单次推理的时间, 默认为 ``False``
:param n_groups: 在不同的时间步, 是否使用不同的权重, 默认为 ``1``, 即不分组
:param args: 其他的参数
:param kwargs: 其他的参数
"""
def __init__(self, threshold=0.5, tau=2., act_fun=QGateGrad, *args, **kwargs):
super().__init__(threshold, *args, **kwargs)
self.tau = tau
if isinstance(act_fun, str):
act_fun = eval(act_fun)
self.act_fun = act_fun(alpha=2., requires_grad=False)
# self.threshold = threshold
# print(threshold)
# print(tau)
def integral(self, inputs):
self.mem = self.mem + (inputs - self.mem) / self.tau
def calc_spike(self):
self.spike = self.act_fun(self.mem - self.threshold)
self.mem = self.mem * (1 - self.spike.detach())
class BurstLIFNode(LIFNode):
def __init__(self, threshold=.5, tau=2., act_fun=RoundGrad, *args, **kwargs):
super().__init__(threshold=threshold, tau=tau, act_fun=act_fun, *args, **kwargs)
self.burst_factor = 1.5
def calc_spike(self):
LIFNode.calc_spike(self)
self.spike = torch.where(self.spike > 1., self.burst_factor * self.spike, self.spike)
class BackEINode(BaseNode):
"""
BackEINode with self feedback connection and excitatory and inhibitory neurons
Reference:https://www.sciencedirect.com/science/article/pii/S0893608022002520
:param threshold: 神经元发放脉冲需要达到的阈值
:param if_back whether to use self feedback
:param if_ei whether to use excitotory and inhibitory neurons
:param args: 其他的参数
:param kwargs: 其他的参数
"""
def __init__(self, threshold=0.5, decay=0.2, act_fun=BackEIGateGrad, th_fun=EIGrad, channel=40, if_back=True,
if_ei=True, cfg_backei=2, *args, **kwargs):
super().__init__(threshold, *args, **kwargs)
self.decay = decay
if isinstance(act_fun, str):
act_fun = eval(act_fun)
if isinstance(th_fun, str):
th_fun = eval(th_fun)
self.act_fun = act_fun()
self.th_fun = th_fun()
self.channel = channel
self.if_back = if_back
if self.if_back:
self.back = nn.Conv2d(channel, channel, kernel_size=2 * cfg_backei+1, stride=1, padding=cfg_backei)
self.if_ei = if_ei
if self.if_ei:
self.ei = nn.Conv2d(channel, channel, kernel_size=2 * cfg_backei+1, stride=1, padding=cfg_backei)
def integral(self, inputs):
if self.mem is None:
self.mem = torch.zeros_like(inputs)
self.spike = torch.zeros_like(inputs)
self.mem = self.decay * self.mem
if self.if_back:
self.mem += F.sigmoid(self.back(self.spike)) * inputs
else:
self.mem += inputs
def calc_spike(self):
if self.if_ei:
ei_gate = self.th_fun(self.ei(self.mem))
self.spike = self.act_fun(self.mem-self.threshold)
self.mem = self.mem * (1 - self.spike)
self.spike = ei_gate * self.spike
else:
self.spike = self.act_fun(self.mem-self.threshold)
self.mem = self.mem * (1 - self.spike)
def n_reset(self):
self.mem = None
self.spike = None
self.feature_map = []
self.mem_collect = []
class NoiseLIFNode(LIFNode):
"""
Noisy Leaky Integrate and Fire
在神经元中注入噪声, 默认的噪声分布为 ``Beta(log(2), log(6))``
:param threshold: 神经元发放脉冲需要达到的阈值
:param v_reset: 静息电位
:param dt: 时间步长
:param step: 仿真步
:param tau: 膜电位时间常数, 用于控制膜电位衰减
:param act_fun: 使用surrogate gradient 对梯度进行近似, 默认为 ``surrogate.AtanGrad``
:param requires_thres_grad: 是否需要计算对于threshold的梯度, 默认为 ``False``
:param sigmoid_thres: 是否使用sigmoid约束threshold的范围搭到 [0, 1], 默认为 ``False``
:param requires_fp: 是否需要在推理过程中保存feature map, 需要消耗额外的内存和时间, 默认为 ``False``
:param layer_by_layer: 是否以一次性计算所有step的输出, 在网络模型较大的情况下, 一般会缩短单次推理的时间, 默认为 ``False``
:param n_groups: 在不同的时间步, 是否使用不同的权重, 默认为 ``1``, 即不分组
:param log_alpha: 控制 beta 分布的参数 ``a``
:param log_beta: 控制 beta 分布的参数 ``b``
:param args: 其他的参数
:param kwargs: 其他的参数
"""
def __init__(self,
threshold=1,
tau=2.,
act_fun=GateGrad,
log_alpha=np.log(2),
log_beta=np.log(6),
*args,
**kwargs):
super().__init__(threshold=threshold, tau=tau, act_fun=act_fun, *args, **kwargs)
self.log_alpha = Parameter(torch.as_tensor(log_alpha), requires_grad=True)
self.log_beta = Parameter(torch.as_tensor(log_beta), requires_grad=True)
# self.fc = nn.Sequential(
# nn.Linear(1, 5),
# nn.ReLU(),
# nn.Linear(5, 5),
# nn.ReLU(),
# nn.Linear(5, 2)
# )
def integral(self, inputs): # b, c, w, h / b, c
# self.mu, self.log_var = self.fc(inputs.mean().unsqueeze(0)).split(1)
alpha, beta = torch.exp(self.log_alpha), torch.exp(self.log_beta)
mu = alpha / (alpha + beta)
var = ((alpha + 1) * alpha) / ((alpha + beta + 1) * (alpha + beta))
noise = torch.distributions.beta.Beta(alpha, beta).sample(inputs.shape) * self.get_thres()
noise = noise * var / var.detach() + mu - mu.detach()
self.mem = self.mem + ((inputs - self.mem) / self.tau + noise) * self.dt
class BiasLIFNode(BaseNode):
"""
带有恒定电流输入Bias的LIF神经元,用于带有抑制性/反馈链接的网络的测试
Noisy Leaky Integrate and Fire
在神经元中注入噪声, 默认的噪声分布为 ``Beta(log(2), log(6))``
:param threshold: 神经元发放脉冲需要达到的阈值
:param v_reset: 静息电位
:param dt: 时间步长
:param step: 仿真步
:param tau: 膜电位时间常数, 用于控制膜电位衰减
:param act_fun: 使用surrogate gradient 对梯度进行近似, 默认为 ``surrogate.AtanGrad``
:param requires_thres_grad: 是否需要计算对于threshold的梯度, 默认为 ``False``
:param sigmoid_thres: 是否使用sigmoid约束threshold的范围搭到 [0, 1], 默认为 ``False``
:param requires_fp: 是否需要在推理过程中保存feature map, 需要消耗额外的内存和时间, 默认为 ``False``
:param layer_by_layer: 是否以一次性计算所有step的输出, 在网络模型较大的情况下, 一般会缩短单次推理的时间, 默认为 ``False``
:param n_groups: 在不同的时间步, 是否使用不同的权重, 默认为 ``1``, 即不分组
:param args: 其他的参数
:param kwargs: 其他的参数
"""
def __init__(self, threshold=1., tau=2., act_fun=AtanGrad, *args, **kwargs):
super().__init__(threshold, *args, **kwargs)
self.tau = tau
if isinstance(act_fun, str):
act_fun = eval(act_fun)
self.act_fun = act_fun(alpha=2., requires_grad=False)
def integral(self, inputs):
self.mem = self.mem + ((inputs - self.mem) / self.tau) * self.dt + 0.1
def calc_spike(self):
self.spike = self.act_fun(self.mem - self.get_thres())
self.mem = self.mem * (1 - self.spike.detach())
class LIFSTDPNode(BaseNode):
"""
用于执行STDP运算时使用的节点 decay的方式是膜电位乘以decay并直接加上输入电流
"""
def __init__(self, threshold=1., tau=2., act_fun=AtanGrad, *args, **kwargs):
super().__init__(threshold, *args, **kwargs)
self.tau = tau
if isinstance(act_fun, str):
act_fun = eval(act_fun)
self.act_fun = act_fun(alpha=2., requires_grad=False)
def integral(self, inputs):
self.mem = self.mem * self.tau + inputs
def calc_spike(self):
self.spike = self.act_fun(self.mem - self.threshold)
# print(( self.threshold).max())
self.mem = self.mem * (1 - self.spike.detach())
def requires_activation(self):
return False
class PLIFNode(BaseNode):
"""
Parametric LIF, 其中的 ```tau``` 会被backward过程影响
Reference:https://arxiv.org/abs/2007.05785
:param threshold: 神经元发放脉冲需要达到的阈值
:param v_reset: 静息电位
:param dt: 时间步长
:param step: 仿真步
:param tau: 膜电位时间常数, 用于控制膜电位衰减
:param act_fun: 使用surrogate gradient 对梯度进行近似, 默认为 ``surrogate.AtanGrad``
:param requires_thres_grad: 是否需要计算对于threshold的梯度, 默认为 ``False``
:param sigmoid_thres: 是否使用sigmoid约束threshold的范围搭到 [0, 1], 默认为 ``False``
:param requires_fp: 是否需要在推理过程中保存feature map, 需要消耗额外的内存和时间, 默认为 ``False``
:param layer_by_layer: 是否以一次性计算所有step的输出, 在网络模型较大的情况下, 一般会缩短单次推理的时间, 默认为 ``False``
:param n_groups: 在不同的时间步, 是否使用不同的权重, 默认为 ``1``, 即不分组
:param args: 其他的参数
:param kwargs: 其他的参数
"""
def __init__(self, threshold=1., tau=2., act_fun=AtanGrad, *args, **kwargs):
super().__init__(threshold, *args, **kwargs)
init_w = -math.log(tau - 1.)
if isinstance(act_fun, str):
act_fun = eval(act_fun)
self.act_fun = act_fun(alpha=2., requires_grad=True)
self.w = nn.Parameter(torch.as_tensor(init_w))
def integral(self, inputs):
self.mem = self.mem + ((inputs - self.mem) * self.w.sigmoid()) * self.dt
def calc_spike(self):
self.spike = self.act_fun(self.mem - self.get_thres())
self.mem = self.mem * (1 - self.spike.detach())
class PSU(BaseNode):
def __init__(self, threshold=1., tau=2., act_fun=AtanGrad, *args, **kwargs):
super().__init__(threshold, *args, **kwargs)
init_w = -math.log(tau - 1.)
if isinstance(act_fun, str):
act_fun = eval(act_fun)
self.parallel = True
self.act_fun = act_fun(alpha=2., requires_grad=True)
T = self.step
m1, m2 = generate_matrix(T, tau)
self.register_buffer('m1', m1)
self.register_buffer('m2', m2)
self.m2 *= self.threshold
def integral(self, inputs):
d1 = self.m1 @ inputs.flatten(1)
self.mem = (d1 + self.m2 @ d1.sigmoid()).view(inputs.shape)
def calc_spike(self):
self.spike = self.act_fun(self.mem - self.threshold)
class IPSU(BaseNode):
def masked_weight(self):
return self.fc.weight * self.mask0
def __init__(self, threshold=1., tau=2., act_fun=AtanGrad, *args, **kwargs):
super().__init__(threshold, *args, **kwargs)
init_w = -math.log(tau - 1.)
if isinstance(act_fun, str):
act_fun = eval(act_fun)
self.parallel = True
self.act_fun = act_fun(alpha=2., requires_grad=True)
T = self.step
matrix, matrix2 = generate_matrix(T, tau)
self.register_buffer('m1', matrix)
self.register_buffer('m2', matrix2)
# self.m2 *= self.threshold
self.fc = nn.Linear(T, T)
nn.init.constant_(self.fc.bias, 0.)
nn.init.kaiming_normal_(self.fc.weight, mode='fan_out', nonlinearity='relu')
mask0 = torch.tril(torch.ones([T, T]))
self.register_buffer('mask0', mask0)
def integral(self, inputs):
d1 = torch.addmm(self.fc.bias.unsqueeze(1), self.masked_weight(), inputs.flatten((1)))
self.mem = (d1 + self.m2 @ inputs.flatten(1)).view(inputs.shape)
def calc_spike(self):
self.spike = self.act_fun(self.mem - self.threshold)
class RPSU(BaseNode):
def masked_weight(self):
return self.fc.weight * self.mask0
def __init__(self, threshold=1., tau=2., act_fun=AtanGrad, *args, **kwargs):
super().__init__(threshold, *args, **kwargs)
init_w = -math.log(tau - 1.)
if isinstance(act_fun, str):
act_fun = eval(act_fun)
self.parallel = True
self.act_fun = act_fun(alpha=2., requires_grad=True)
T = self.step
matrix, matrix2 = generate_matrix(T, tau)
self.register_buffer('m1', matrix)
self.register_buffer('m2', matrix2)
# self.m2 *= self.threshold
self.fc = nn.Linear(T, T)
nn.init.constant_(self.fc.bias, 0.)
nn.init.kaiming_normal_(self.fc.weight, mode='fan_out', nonlinearity='relu')
mask0 = torch.tril(torch.ones([T, T]))
self.register_buffer('mask0', mask0)
def integral(self, inputs):
d1 = self.m1 @ inputs.flatten(1)
d2 = torch.addmm(self.fc.bias.unsqueeze(1), self.masked_weight(), inputs.flatten((1)))
self.mem = (d1 + self.m2 @ d2.sigmoid()).view(inputs.shape)
def calc_spike(self):
self.spike = self.act_fun(self.mem - self.threshold)
class SPSN(BaseNode):
def __init__(self, threshold=1., tau=2., act_fun=AtanGrad, *args, **kwargs):
super().__init__(threshold, *args, **kwargs)
init_w = -math.log(tau - 1.)
if isinstance(act_fun, str):
act_fun = eval(act_fun)
self.parallel = True
self.act_fun = act_fun(alpha=2., requires_grad=True)
m1, m2 = generate_matrix(self.step, tau)
self.register_buffer('m1', m1)
def integral(self, inputs):
self.mem = (self.m1 @ inputs.flatten(1)).sigmoid().view(inputs.shape)
def calc_spike(self):
self.spike = torch.bernoulli(self.mem)
class NoisePLIFNode(PLIFNode):
"""
Noisy Parametric Leaky Integrate and Fire
:param threshold: 神经元发放脉冲需要达到的阈值
:param v_reset: 静息电位
:param dt: 时间步长
:param step: 仿真步
:param tau: 膜电位时间常数, 用于控制膜电位衰减
:param act_fun: 使用surrogate gradient 对梯度进行近似, 默认为 ``surrogate.AtanGrad``
:param requires_thres_grad: 是否需要计算对于threshold的梯度, 默认为 ``False``
:param sigmoid_thres: 是否使用sigmoid约束threshold的范围搭到 [0, 1], 默认为 ``False``
:param requires_fp: 是否需要在推理过程中保存feature map, 需要消耗额外的内存和时间, 默认为 ``False``
:param layer_by_layer: 是否以一次性计算所有step的输出, 在网络模型较大的情况下, 一般会缩短单次推理的时间, 默认为 ``False``
:param n_groups: 在不同的时间步, 是否使用不同的权重, 默认为 ``1``, 即不分组
:param args: 其他的参数
:param kwargs: 其他的参数
"""
def __init__(self,
threshold=1,
tau=2.,
act_fun=GateGrad,
*args,
**kwargs):
super().__init__(threshold=threshold, tau=tau, act_fun=act_fun, *args, **kwargs)
log_alpha = kwargs['log_alpha'] if 'log_alpha' in kwargs else np.log(2)
log_beta = kwargs['log_beta'] if 'log_beta' in kwargs else np.log(6)
self.log_alpha = Parameter(torch.as_tensor(log_alpha), requires_grad=True)
self.log_beta = Parameter(torch.as_tensor(log_beta), requires_grad=True)
# self.fc = nn.Sequential(
# nn.Linear(1, 5),
# nn.ReLU(),
# nn.Linear(5, 5),
# nn.ReLU(),
# nn.Linear(5, 2)
# )
def integral(self, inputs): # b, c, w, h / b, c
# self.mu, self.log_var = self.fc(inputs.mean().unsqueeze(0)).split(1)
alpha, beta = torch.exp(self.log_alpha), torch.exp(self.log_beta)
mu = alpha / (alpha + beta)
var = ((alpha + 1) * alpha) / ((alpha + beta + 1) * (alpha + beta))
noise = torch.distributions.beta.Beta(alpha, beta).sample(inputs.shape) * self.get_thres()
noise = noise * var / var.detach() + mu - mu.detach()
self.mem = self.mem + ((inputs - self.mem) * self.w.sigmoid() + noise) * self.dt
class BiasPLIFNode(BaseNode):
"""
Parametric LIF with bias
:param threshold: 神经元发放脉冲需要达到的阈值
:param v_reset: 静息电位
:param dt: 时间步长
:param step: 仿真步
:param tau: 膜电位时间常数, 用于控制膜电位衰减
:param act_fun: 使用surrogate gradient 对梯度进行近似, 默认为 ``surrogate.AtanGrad``
:param requires_thres_grad: 是否需要计算对于threshold的梯度, 默认为 ``False``
:param sigmoid_thres: 是否使用sigmoid约束threshold的范围搭到 [0, 1], 默认为 ``False``
:param requires_fp: 是否需要在推理过程中保存feature map, 需要消耗额外的内存和时间, 默认为 ``False``
:param layer_by_layer: 是否以一次性计算所有step的输出, 在网络模型较大的情况下, 一般会缩短单次推理的时间, 默认为 ``False``
:param n_groups: 在不同的时间步, 是否使用不同的权重, 默认为 ``1``, 即不分组
:param args: 其他的参数
:param kwargs: 其他的参数
"""
def __init__(self, threshold=1., tau=2., act_fun=AtanGrad, *args, **kwargs):
super().__init__(threshold, *args, **kwargs)
init_w = -math.log(tau - 1.)
if isinstance(act_fun, str):
act_fun = eval(act_fun)
self.act_fun = act_fun(alpha=2., requires_grad=True)
self.w = nn.Parameter(torch.as_tensor(init_w))
def integral(self, inputs):
self.mem = self.mem + ((inputs - self.mem) * self.w.sigmoid() + 0.1) * self.dt
def calc_spike(self):
self.spike = self.act_fun(self.mem - self.get_thres())
self.mem = self.mem * (1 - self.spike.detach())
class DoubleSidePLIFNode(LIFNode):
"""
能够输入正负脉冲的 PLIF
:param threshold: 神经元发放脉冲需要达到的阈值
:param v_reset: 静息电位
:param dt: 时间步长
:param step: 仿真步
:param tau: 膜电位时间常数, 用于控制膜电位衰减
:param act_fun: 使用surrogate gradient 对梯度进行近似, 默认为 ``surrogate.AtanGrad``
:param requires_thres_grad: 是否需要计算对于threshold的梯度, 默认为 ``False``
:param sigmoid_thres: 是否使用sigmoid约束threshold的范围搭到 [0, 1], 默认为 ``False``
:param requires_fp: 是否需要在推理过程中保存feature map, 需要消耗额外的内存和时间, 默认为 ``False``
:param layer_by_layer: 是否以一次性计算所有step的输出, 在网络模型较大的情况下, 一般会缩短单次推理的时间, 默认为 ``False``
:param n_groups: 在不同的时间步, 是否使用不同的权重, 默认为 ``1``, 即不分组
:param args: 其他的参数
:param kwargs: 其他的参数
"""
def __init__(self,
threshold=.5,
tau=2.,
act_fun=AtanGrad,
*args,
**kwargs):
super().__init__(threshold, tau, act_fun, *args, **kwargs)
if isinstance(act_fun, str):
act_fun = eval(act_fun)
self.act_fun = act_fun(alpha=2., requires_grad=True)
def calc_spike(self):
self.spike = self.act_fun(self.mem - self.get_thres()) - self.act_fun(self.get_thres - self.mem)
self.mem = self.mem * (1. - torch.abs(self.spike.detach()))
class IzhNode(BaseNode):
"""
Izhikevich 脉冲神经元
:param threshold: 神经元发放脉冲需要达到的阈值
:param v_reset: 静息电位
:param dt: 时间步长
:param step: 仿真步
:param tau: 膜电位时间常数, 用于控制膜电位衰减
:param act_fun: 使用surrogate gradient 对梯度进行近似, 默认为 ``surrogate.AtanGrad``
:param args: 其他的参数
:param kwargs: 其他的参数
"""
def __init__(self, threshold=1., tau=2., act_fun=AtanGrad, *args, **kwargs):
super().__init__(threshold, *args, **kwargs)
self.tau = tau
if isinstance(act_fun, str):
act_fun = eval(act_fun)
self.act_fun = act_fun(alpha=2., requires_grad=False)
self.a = kwargs['a'] if 'a' in kwargs else 0.02
self.b = kwargs['b'] if 'b' in kwargs else 0.2
self.c = kwargs['c'] if 'c' in kwargs else -55.
self.d = kwargs['d'] if 'd' in kwargs else -2.
'''
v' = 0.04v^2 + 5v + 140 -u + I
u' = a(bv-u)
下面是将Izh离散化的写法
if v>= thresh:
v = c
u = u + d
'''
# 初始化膜电势 以及 对应的U
self.mem = 0.
self.u = 0.
self.dt = kwargs['dt'] if 'dt' in kwargs else 1.
def integral(self, inputs):
self.mem = self.mem + self.dt * (0.04 * self.mem * self.mem + 5 * self.mem - self.u + 140 + inputs)
self.u = self.u + self.dt * (self.a * self.b * self.mem - self.a * self.u)
def calc_spike(self):
self.spike = self.act_fun(self.mem - self.get_thres()) # 大于阈值释放脉冲
self.mem = self.mem * (1 - self.spike.detach()) + self.spike.detach() * self.c
self.u = self.u + self.spike.detach() * self.d
def n_reset(self):
self.mem = 0.
self.u = 0.
self.spike = 0.
class IzhNodeMU(BaseNode):
"""
Izhikevich 脉冲神经元多参数版
:param threshold: 神经元发放脉冲需要达到的阈值
:param v_reset: 静息电位
:param dt: 时间步长
:param step: 仿真步
:param tau: 膜电位时间常数, 用于控制膜电位衰减
:param act_fun: 使用surrogate gradient 对梯度进行近似, 默认为 ``surrogate.AtanGrad``
:param args: 其他的参数
:param kwargs: 其他的参数
"""
def __init__(self, threshold=1., tau=2., act_fun=AtanGrad, *args, **kwargs):
super().__init__(threshold, *args, **kwargs)
self.tau = tau
if isinstance(act_fun, str):
act_fun = eval(act_fun)
self.act_fun = act_fun(alpha=2., requires_grad=False)
self.a = kwargs['a'] if 'a' in kwargs else 0.02
self.b = kwargs['b'] if 'b' in kwargs else 0.2
self.c = kwargs['c'] if 'c' in kwargs else -55.
self.d = kwargs['d'] if 'd' in kwargs else -2.
self.mem = kwargs['mem'] if 'mem' in kwargs else 0.
self.u = kwargs['u'] if 'u' in kwargs else 0.
self.dt = kwargs['dt'] if 'dt' in kwargs else 1.
def integral(self, inputs):
self.mem = self.mem + self.dt * (0.04 * self.mem * self.mem + 5 * self.mem - self.u + 140 + inputs)
self.u = self.u + self.dt * (self.a * self.b * self.mem - self.a * self.u)
def calc_spike(self):
self.spike = self.act_fun(self.mem - self.threshold)
self.mem = self.mem * (1 - self.spike.detach()) + self.spike.detach() * self.c
self.u = self.u + self.spike.detach() * self.d
def n_reset(self):