tracetorch 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: tracetorch
3
+ Version: 0.1.0
4
+ Summary: An extension to PyTorch: SNN layers that function on traces.
5
+ Author-email: Yegor Men <yegor.mn@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Yegor-men/tracetorch
8
+ Project-URL: Repository, https://github.com/Yegor-men/tracetorch
9
+ Project-URL: Issues, https://github.com/Yegor-men/tracetorch/issues
10
+ Project-URL: Documentation, https://yegor-men.github.io/tracetorch/
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Requires-Python: >=3.8
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: torch
18
+ Requires-Dist: numpy
19
+ Requires-Dist: matplotlib
20
+ Dynamic: license-file
21
+
22
+ ![traceTorch Banner](media/tracetorch_banner.png)
23
+
24
+ [![License](https://img.shields.io/badge/License-Apache%202.0-purple.svg)](https://www.apache.org/licenses/LICENSE-2.0)
25
+
26
+ ``traceTorch`` is a PyTorch-based library built on the principles of spiking neural networks, replacing the PyTorch
27
+ default backpropagation through time with lightweight, per-layer input traces, enabling biologically inspired, constant
28
+ time and memory consumption learning on arbitrarily long or even streaming sequences.
29
+
30
+ ## Documentation
31
+
32
+ It is highly recommended that you read the [documentation](https://yegor-men.github.io/tracetorch/) first. It contains:
33
+
34
+ 1. **Introduction**: An introduction to traceTorch, how and why it works, it's founding principles. It's thoroughly
35
+ recommended that you read through the entire introduction and gain an intuitive understanding before proceeding.
36
+ 2. **Tutorials**: Various tutorials to create your own traceTorch models. The resultant code can be found in
37
+ `tutorials/`.
38
+ 3. **Documentation**: The actual documentation to all the modules included in `traceTorch`. It includes detailed
39
+ explanations, examples and math to gain a full understanding.
40
+
41
+ ## Roadmap
42
+
43
+ - Create the poisson click test example
44
+ - Implement the trace alternative to REINFORCE
45
+ - Make traceTorch into a PyPI library
46
+ - Finish writing the documentation
47
+ - Clean up the tutorial code
48
+ - Implement abstract graph based models, not just sequential
49
+
50
+ ## Installation
51
+
52
+ ⚠️ WARNING, traceTorch is _not yet_ a library. For now, you'll just have to clone this repository and use the
53
+ `tracetorch/` folder within.
54
+
55
+ ```
56
+ git clone https://github.com/Yegor-men/tracetorch
57
+ cd tracetorch/
58
+ pip install -r requirements.txt
59
+ ```
60
+
61
+ Then, within a python file where from where the repository root folder is visible, simply do:
62
+
63
+ ```
64
+ from tracetorch import tracetorch
65
+ ```
66
+
67
+ ## Usage examples
68
+
69
+ `tutorials/` contains all the tutorial files, ready to run and playtest. The tutorials themselves can be
70
+ found [here](https://yegor-men.github.io/tracetorch/tutorials/index.html).
71
+
72
+ To ensure that you have all the necessary packages for the tutorials installed, please execute the following command:
73
+
74
+ ```
75
+ cd tutorials/
76
+ pip install -r requirements.txt
77
+ ```
78
+
79
+ ## Authors
80
+
81
+ - [@Yegor-men](https://github.com/Yegor-men)
82
+
83
+ ## Acknowledgements
84
+
85
+ I built traceTorch from the ground up, trying to reverse engineer biological neurons with a sprinkle of intelligent
86
+ design, but I would also like to recognize the following projects and people who helped shape my thinking:
87
+
88
+ - [snntorch](https://github.com/jeshraghian/snntorch) for introducing me to SNN networks in the first place, and their
89
+ principles of function. Ironically, its dependency on constructing the full autograd graph is what largely inspired me
90
+ to make traceTorch.
91
+ - [Artem Kirsanov](https://www.youtube.com/@ArtemKirsanov) for introducing me to computational neuroscience, presenting
92
+ interesting concepts in an easy-to-understand manner. My earliest tests, when I naively wanted to implement 1:1
93
+ biological neurons, largely revolved around his work.
94
+ - [e-prop (eligibility propagation)](https://www.biorxiv.org/content/biorxiv/early/2020/04/16/738385.full.pdf) inspired
95
+ the whole "trace" concept, the idea of keeping a decaying value. Earlier, before traceTorch, I wanted to use e-prop
96
+ for online learning instead. Admittedly unsuccessful in my attempts, and a little put off by the relative difficulty,
97
+ I instead wanted to make something simpler.
98
+
99
+ ## Contributing
100
+
101
+ Contributions are always welcome. Feel free to submit pull requests or report issues, I will occasionally check in on
102
+ it.
103
+
104
+ You can also reach out to me via either email or Twitter:
105
+
106
+ - yegor.mn@gmail.com
107
+ - [Twitter](https://x.com/Yegor_Men)
@@ -0,0 +1,86 @@
1
+ ![traceTorch Banner](media/tracetorch_banner.png)
2
+
3
+ [![License](https://img.shields.io/badge/License-Apache%202.0-purple.svg)](https://www.apache.org/licenses/LICENSE-2.0)
4
+
5
+ ``traceTorch`` is a PyTorch-based library built on the principles of spiking neural networks, replacing the PyTorch
6
+ default backpropagation through time with lightweight, per-layer input traces, enabling biologically inspired, constant
7
+ time and memory consumption learning on arbitrarily long or even streaming sequences.
8
+
9
+ ## Documentation
10
+
11
+ It is highly recommended that you read the [documentation](https://yegor-men.github.io/tracetorch/) first. It contains:
12
+
13
+ 1. **Introduction**: An introduction to traceTorch, how and why it works, it's founding principles. It's thoroughly
14
+ recommended that you read through the entire introduction and gain an intuitive understanding before proceeding.
15
+ 2. **Tutorials**: Various tutorials to create your own traceTorch models. The resultant code can be found in
16
+ `tutorials/`.
17
+ 3. **Documentation**: The actual documentation to all the modules included in `traceTorch`. It includes detailed
18
+ explanations, examples and math to gain a full understanding.
19
+
20
+ ## Roadmap
21
+
22
+ - Create the poisson click test example
23
+ - Implement the trace alternative to REINFORCE
24
+ - Make traceTorch into a PyPI library
25
+ - Finish writing the documentation
26
+ - Clean up the tutorial code
27
+ - Implement abstract graph based models, not just sequential
28
+
29
+ ## Installation
30
+
31
+ ⚠️ WARNING, traceTorch is _not yet_ a library. For now, you'll just have to clone this repository and use the
32
+ `tracetorch/` folder within.
33
+
34
+ ```
35
+ git clone https://github.com/Yegor-men/tracetorch
36
+ cd tracetorch/
37
+ pip install -r requirements.txt
38
+ ```
39
+
40
+ Then, within a python file where from where the repository root folder is visible, simply do:
41
+
42
+ ```
43
+ from tracetorch import tracetorch
44
+ ```
45
+
46
+ ## Usage examples
47
+
48
+ `tutorials/` contains all the tutorial files, ready to run and playtest. The tutorials themselves can be
49
+ found [here](https://yegor-men.github.io/tracetorch/tutorials/index.html).
50
+
51
+ To ensure that you have all the necessary packages for the tutorials installed, please execute the following command:
52
+
53
+ ```
54
+ cd tutorials/
55
+ pip install -r requirements.txt
56
+ ```
57
+
58
+ ## Authors
59
+
60
+ - [@Yegor-men](https://github.com/Yegor-men)
61
+
62
+ ## Acknowledgements
63
+
64
+ I built traceTorch from the ground up, trying to reverse engineer biological neurons with a sprinkle of intelligent
65
+ design, but I would also like to recognize the following projects and people who helped shape my thinking:
66
+
67
+ - [snntorch](https://github.com/jeshraghian/snntorch) for introducing me to SNN networks in the first place, and their
68
+ principles of function. Ironically, its dependency on constructing the full autograd graph is what largely inspired me
69
+ to make traceTorch.
70
+ - [Artem Kirsanov](https://www.youtube.com/@ArtemKirsanov) for introducing me to computational neuroscience, presenting
71
+ interesting concepts in an easy-to-understand manner. My earliest tests, when I naively wanted to implement 1:1
72
+ biological neurons, largely revolved around his work.
73
+ - [e-prop (eligibility propagation)](https://www.biorxiv.org/content/biorxiv/early/2020/04/16/738385.full.pdf) inspired
74
+ the whole "trace" concept, the idea of keeping a decaying value. Earlier, before traceTorch, I wanted to use e-prop
75
+ for online learning instead. Admittedly unsuccessful in my attempts, and a little put off by the relative difficulty,
76
+ I instead wanted to make something simpler.
77
+
78
+ ## Contributing
79
+
80
+ Contributions are always welcome. Feel free to submit pull requests or report issues, I will occasionally check in on
81
+ it.
82
+
83
+ You can also reach out to me via either email or Twitter:
84
+
85
+ - yegor.mn@gmail.com
86
+ - [Twitter](https://x.com/Yegor_Men)
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0.3", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tracetorch"
7
+ version = "0.1.0"
8
+ authors = [{ name = "Yegor Men", email = "yegor.mn@gmail.com" }]
9
+ description = "An extension to PyTorch: SNN layers that function on traces."
10
+ readme = "README.md"
11
+ requires-python = ">=3.8"
12
+ license = "Apache-2.0"
13
+ dependencies = ["torch", "numpy", "matplotlib"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Operating System :: OS Independent",
17
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/Yegor-men/tracetorch"
22
+ Repository = "https://github.com/Yegor-men/tracetorch"
23
+ Issues = "https://github.com/Yegor-men/tracetorch/issues"
24
+ Documentation = "https://yegor-men.github.io/tracetorch/"
25
+
26
+ [tool.setuptools.packages.find]
27
+ where = ["."]
28
+ include = ["tracetorch*"]
29
+ exclude = ["media*", "tutorials*, docs*, tests*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ from . import functional, nn, loss, plot
@@ -0,0 +1,3 @@
1
+ from ._sigmoid_inverse import sigmoid_inverse
2
+ from ._softplus_inverse import softplus_inverse
3
+ from ._sample_softmax import sample_softmax
@@ -0,0 +1,10 @@
1
+ import torch
2
+
3
+
4
+ def sample_softmax(probability_dist, return_one_hot: bool = True):
5
+ index = torch.multinomial(probability_dist, num_samples=1)
6
+ if not return_one_hot:
7
+ return index
8
+ out_spikes = torch.zeros_like(probability_dist)
9
+ out_spikes[index] = 1
10
+ return out_spikes
@@ -0,0 +1,9 @@
1
+ import torch
2
+
3
+ def sigmoid_inverse(tensor: torch.Tensor) -> torch.Tensor:
4
+ """
5
+ Calculates the necessary tensor such that passing it through sigmoid yields this tensor
6
+ :param tensor:
7
+ :return:
8
+ """
9
+ return torch.log(tensor / (1 - tensor))
@@ -0,0 +1,9 @@
1
+ import torch
2
+
3
+ def softplus_inverse(tensor: torch.Tensor) -> torch.Tensor:
4
+ """
5
+ Calculates the necessary tensor such that passing it through softplus yields this tensor
6
+ :param tensor:
7
+ :return:
8
+ """
9
+ return torch.log(torch.e ** tensor - 1)
@@ -0,0 +1 @@
1
+ from ._mse import mse
@@ -0,0 +1,25 @@
1
+ import torch
2
+
3
+
4
+ def mse(
5
+ received: torch.Tensor,
6
+ expected: torch.Tensor,
7
+ reduction: str = "mean"
8
+ ) -> tuple[torch.Tensor, torch.Tensor]:
9
+ """
10
+ calculates the mse loss
11
+ :param received:
12
+ :param expected:
13
+ :param reduction:
14
+ :return:
15
+ """
16
+ received = received.detach().clone().requires_grad_(True)
17
+ expected = expected.detach().to(received)
18
+
19
+ loss_fn = torch.nn.MSELoss(reduction=reduction)
20
+ loss = loss_fn.forward(received, expected)
21
+ loss.backward()
22
+
23
+ ls = received.grad.detach()
24
+
25
+ return loss.detach(), ls
@@ -0,0 +1,4 @@
1
+ from ._sequential import Sequential
2
+
3
+ from ._lif import LIF
4
+ from ._lis import LIS
@@ -0,0 +1,83 @@
1
+ import torch
2
+
3
+ from .. import functional
4
+
5
+
6
+ class LIF:
7
+ """
8
+ Leaky integrate and fire neuron layer
9
+ """
10
+
11
+ def __init__(
12
+ self,
13
+ num_in: int,
14
+ num_out: int,
15
+ weight_scaling: float = 0.1,
16
+ mem_decay: float = 0.9,
17
+ in_trace_decay: float = 0.9,
18
+ threshold: float = 1,
19
+ device: str = "cpu",
20
+ lr: float = 1e-3,
21
+ learn_weight: bool = True,
22
+ learn_mem_decay: bool = True,
23
+ learn_in_trace_decay: bool = True,
24
+ learn_threshold: bool = True
25
+ ):
26
+ self.device = device
27
+ self.lr = lr
28
+
29
+ self.weight = (torch.randn(num_out, num_in) * weight_scaling).to(self.device)
30
+ self.mem_decay = (functional.sigmoid_inverse(torch.ones(num_out) * mem_decay)).to(self.device)
31
+ self.in_trace_decay = (functional.sigmoid_inverse(torch.ones(num_in) * in_trace_decay)).to(self.device)
32
+ self.threshold = (functional.softplus_inverse(torch.ones(num_out) * threshold)).to(self.device)
33
+
34
+ self.weight.requires_grad_(learn_weight)
35
+ self.mem_decay.requires_grad_(learn_mem_decay)
36
+ self.in_trace_decay.requires_grad_(learn_in_trace_decay)
37
+ self.threshold.requires_grad_(learn_threshold)
38
+
39
+ self.optimizer = torch.optim.AdamW(
40
+ [p for p in (self.weight, self.mem_decay, self.in_trace_decay, self.threshold) if p.requires_grad],
41
+ lr=self.lr
42
+ )
43
+
44
+ self.mem = torch.zeros(num_out).to(self.device)
45
+ self.in_trace = torch.zeros(num_in).to(self.device)
46
+
47
+ def forward(self, in_spikes: torch.Tensor) -> torch.Tensor:
48
+ with torch.no_grad():
49
+ in_spikes = in_spikes.to(self.device)
50
+ in_trace_decay = torch.nn.functional.sigmoid(self.in_trace_decay)
51
+ self.in_trace = self.in_trace * in_trace_decay + in_spikes
52
+ syn_current = torch.einsum("i, oi -> o", in_spikes, self.weight)
53
+ mem_decay = torch.nn.functional.sigmoid(self.mem_decay)
54
+ self.mem = self.mem * mem_decay + syn_current
55
+ threshold = torch.nn.functional.softplus(self.threshold)
56
+ out_spikes = (self.mem >= threshold).float()
57
+ self.mem -= threshold * out_spikes
58
+ return out_spikes
59
+
60
+ def backward(self, learning_signal: torch.Tensor) -> torch.Tensor:
61
+ in_trace_decay = torch.nn.functional.sigmoid(self.in_trace_decay)
62
+ average_input = self.in_trace * (1 - in_trace_decay)
63
+ avg_in = average_input.detach().requires_grad_(True)
64
+
65
+ i = torch.einsum("i, oi -> o", avg_in, self.weight)
66
+ d = torch.nn.functional.sigmoid(self.mem_decay)
67
+ t = torch.nn.functional.softplus(self.threshold)
68
+
69
+ excess = (2 * i - i * d) / 2 - t * (1 - d)
70
+ f = torch.nn.functional.sigmoid(5 * excess)
71
+
72
+ f.backward(learning_signal)
73
+ passed_ls = avg_in.grad
74
+ average_input.backward(passed_ls)
75
+
76
+ self.optimizer.step()
77
+ self.optimizer.zero_grad(set_to_none=True)
78
+ return passed_ls
79
+
80
+ def zero_states(self):
81
+ with torch.no_grad():
82
+ self.in_trace.zero_()
83
+ self.mem.zero_()
@@ -0,0 +1,77 @@
1
+ import torch
2
+ from math import log as ln
3
+
4
+ from .. import functional
5
+
6
+
7
+ class LIS:
8
+ """
9
+ Leaky integrate and softmax layer
10
+ """
11
+ def __init__(
12
+ self,
13
+ num_in: int,
14
+ num_out: int,
15
+ weight_scaling: float = 0.1,
16
+ mem_decay: float = 0.9,
17
+ in_trace_decay: float = 0.9,
18
+ device: str = "cpu",
19
+ lr: float = 1e-3,
20
+ learn_weight: bool = True,
21
+ learn_mem_decay: bool = True,
22
+ learn_in_trace_decay: bool = True,
23
+ ):
24
+ self.device = device
25
+ self.lr = lr
26
+
27
+ self.weight = (torch.randn(num_out, num_in) * weight_scaling).to(self.device)
28
+ self.mem_decay = (functional.sigmoid_inverse(torch.ones(num_out) * mem_decay)).to(self.device)
29
+ self.in_trace_decay = (functional.sigmoid_inverse(torch.ones(num_in) * in_trace_decay)).to(self.device)
30
+
31
+ self.weight.requires_grad_(learn_weight)
32
+ self.mem_decay.requires_grad_(learn_mem_decay)
33
+ self.in_trace_decay.requires_grad_(learn_in_trace_decay)
34
+
35
+ self.optimizer = torch.optim.AdamW(
36
+ [p for p in (self.weight, self.mem_decay, self.in_trace_decay) if p.requires_grad],
37
+ lr=self.lr
38
+ )
39
+
40
+ self.mem = torch.zeros(num_out).to(self.device)
41
+ self.in_trace = torch.zeros(num_in).to(self.device)
42
+
43
+ def forward(self, in_spikes: torch.Tensor) -> torch.Tensor:
44
+ with torch.no_grad():
45
+ in_spikes = in_spikes.to(self.device)
46
+ in_trace_decay = torch.nn.functional.sigmoid(self.in_trace_decay)
47
+ self.in_trace = self.in_trace * in_trace_decay + in_spikes
48
+ syn_current = torch.einsum("i, oi -> o", in_spikes, self.weight)
49
+ mem_decay = torch.nn.functional.sigmoid(self.mem_decay)
50
+ self.mem = self.mem * mem_decay + syn_current
51
+
52
+ probability_dist = torch.nn.functional.softmax(self.mem, dim=-1)
53
+ return probability_dist
54
+
55
+ def backward(self, learning_signal: torch.Tensor) -> torch.Tensor:
56
+ in_trace_decay = torch.nn.functional.sigmoid(self.in_trace_decay)
57
+ average_input = self.in_trace * (1 - in_trace_decay)
58
+ avg_in = average_input.detach().requires_grad_(True)
59
+
60
+ i = torch.einsum("i, oi -> o", avg_in, self.weight)
61
+ d = torch.nn.functional.sigmoid(self.mem_decay)
62
+
63
+ stabilized_mem_level = i / (1 - d + 1e-6)
64
+ f = torch.nn.functional.softmax(stabilized_mem_level, dim=-1)
65
+
66
+ f.backward(learning_signal)
67
+ passed_ls = avg_in.grad
68
+ average_input.backward(passed_ls)
69
+
70
+ self.optimizer.step()
71
+ self.optimizer.zero_grad(set_to_none=True)
72
+ return passed_ls
73
+
74
+ def zero_states(self):
75
+ with torch.no_grad():
76
+ self.in_trace.zero_()
77
+ self.mem.zero_()
@@ -0,0 +1,22 @@
1
+ import torch
2
+
3
+
4
+ class Sequential:
5
+ """
6
+ binds layers into a sequential modde
7
+ """
8
+ def __init__(self, *layers):
9
+ self.layers = list(layers)
10
+
11
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
12
+ for index, layer in enumerate(self.layers):
13
+ x = layer.forward(x)
14
+ return x
15
+
16
+ def backward(self, ls: torch.Tensor) -> None:
17
+ for index, layer in enumerate(reversed(self.layers)):
18
+ ls = layer.backward(ls)
19
+
20
+ def zero_states(self):
21
+ for layer in self.layers:
22
+ layer.zero_states()
@@ -0,0 +1,5 @@
1
+ from ._spike_train import spike_train
2
+ from ._line_graph import line_graph
3
+ from ._measurement_manager import MeasurementManager
4
+ from ._render_image import render_image
5
+ from ._distributions import distributions
@@ -0,0 +1,213 @@
1
+ from typing import List, Dict, Any, Optional, Tuple
2
+ import torch
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+
6
+
7
+ def _safe_to_numpy(t: torch.Tensor) -> np.ndarray:
8
+ t = t.detach().cpu().ravel()
9
+ a = t.numpy()
10
+ # remove nans and infs
11
+ a = a[np.isfinite(a)]
12
+ return a
13
+
14
+
15
+ def _silverman_bandwidth(x: np.ndarray) -> float:
16
+ n = x.size
17
+ if n < 2:
18
+ return 1.0
19
+ s = np.std(x, ddof=1)
20
+ # Silverman's rule of thumb for Gaussian kernel
21
+ bw = 1.06 * s * n ** (-1 / 5)
22
+ # guard against zero bandwidth
23
+ if bw <= 0 or not np.isfinite(bw):
24
+ bw = np.ptp(x) / 10.0 if np.ptp(x) > 0 else 1.0
25
+ return bw
26
+
27
+
28
+ def _gaussian_kde_eval(samples: np.ndarray,
29
+ grid: np.ndarray,
30
+ bw: Optional[float] = None,
31
+ max_samples: int = 20000) -> np.ndarray:
32
+ """
33
+ Vectorized Gaussian KDE evaluation at points in `grid`.
34
+ - samples: 1D numpy array of data
35
+ - grid: 1D numpy array of evaluation points
36
+ - bw: bandwidth (if None uses Silverman)
37
+ - max_samples: if samples too large, random subsample for speed
38
+ Returns density values aligned with grid (integrates approximately to 1).
39
+ """
40
+ if samples.size == 0:
41
+ return np.zeros_like(grid, dtype=float)
42
+ x = samples
43
+ n = x.size
44
+ if n > max_samples:
45
+ rng = np.random.default_rng(0)
46
+ x = rng.choice(x, size=max_samples, replace=False)
47
+ n = x.size
48
+ if bw is None:
49
+ bw = _silverman_bandwidth(x)
50
+ # compute kernel densities: sum of Gaussians
51
+ # density = (1/(n*bw)) * sum_j phi((grid - x_j)/bw)
52
+ # vectorized with broadcasting (grid[:,None] - x[None,:])
53
+ diffs = (grid[:, None] - x[None, :]) / bw
54
+ # gaussian kernel
55
+ K = np.exp(-0.5 * diffs * diffs) / np.sqrt(2 * np.pi)
56
+ dens = K.sum(axis=1) / (n * bw)
57
+ # normalize numerical integration to 1 (improves comparability across grids)
58
+ area = np.trapz(dens, grid)
59
+ if area > 0:
60
+ dens = dens / area
61
+ return dens
62
+
63
+
64
+ def distributions(layers: List[torch.Tensor],
65
+ title: str,
66
+ *,
67
+ n_grid: int = 1024,
68
+ n_percentiles: int = 100,
69
+ bandwidths: Optional[List[Optional[float]]] = None,
70
+ show_percentile_lines: bool = False,
71
+ compute_metrics: bool = True,
72
+ max_kde_samples: int = 20000
73
+ ) -> Dict[str, Any]:
74
+ """
75
+ Estimate and plot continuous distributions for each layer (torch.Tensor) in `layers`.
76
+ Parameters
77
+ ----------
78
+ title : str
79
+ Title for the single overlay plot.
80
+ layers : list[torch.Tensor]
81
+ Each item is a tensor containing continuous values for that layer (will be flattened).
82
+ n_grid : int
83
+ Number of x points for KDE evaluation.
84
+ n_percentiles : int
85
+ Number of percentile buckets (e.g. 100 -> percentiles at 0,1,...,100).
86
+ bandwidths : list or None
87
+ Optional list of bandwidths per layer; None to use Silverman's rule.
88
+ show_percentile_lines : bool
89
+ If True, plots vertical lines for a few percentiles (can clutter plot).
90
+ compute_metrics : bool
91
+ If True attempts to compute pairwise similarity metrics and returns them.
92
+ max_kde_samples : int
93
+ Maximum number of samples per layer used to compute KDE (subsample if larger).
94
+ Returns
95
+ -------
96
+ dict with keys:
97
+ - 'grid': evaluation grid (numpy array)
98
+ - 'kdes': list of density arrays (same order as layers)
99
+ - 'percentiles': list of percentile arrays per layer
100
+ - 'stats': list of dicts {n, mean, std, min, max}
101
+ - 'metrics': dict of pairwise metrics (if compute_metrics)
102
+ :param title:
103
+ :param layers:
104
+ :param n_grid:
105
+ :param n_percentiles:
106
+ :param bandwidths:
107
+ :param show_percentile_lines:
108
+ :param compute_metrics:
109
+ :param max_kde_samples:
110
+ :return:
111
+ """
112
+ # prepare data arrays
113
+ arrs = [_safe_to_numpy(t) for t in layers]
114
+ stats = []
115
+ # compute global x-range for consistent plotting
116
+ finite_arrs = [a for a in arrs if a.size > 0]
117
+ if len(finite_arrs) == 0:
118
+ raise ValueError("No finite values found in any input tensor.")
119
+ global_min = min(a.min() for a in finite_arrs)
120
+ global_max = max(a.max() for a in finite_arrs)
121
+ # expand a bit for display
122
+ pad = 0.01 * (global_max - global_min) if global_max > global_min else 1.0
123
+ x_min = global_min - pad
124
+ x_max = global_max + pad
125
+ grid = np.linspace(x_min, x_max, n_grid, dtype=float)
126
+
127
+ if bandwidths is None:
128
+ bandwidths = [None] * len(arrs)
129
+ elif len(bandwidths) != len(arrs):
130
+ raise ValueError("If provided, bandwidths must have same length as layers")
131
+
132
+ kdes = []
133
+ percentiles = []
134
+ for i, (a, bw) in enumerate(zip(arrs, bandwidths)):
135
+ if a.size == 0:
136
+ kdes.append(np.zeros_like(grid))
137
+ percentiles.append(np.full(n_percentiles + 1, np.nan))
138
+ stats.append({'n': 0, 'mean': np.nan, 'std': np.nan, 'min': np.nan, 'max': np.nan})
139
+ continue
140
+ dens = _gaussian_kde_eval(a, grid, bw=bw, max_samples=max_kde_samples)
141
+ kdes.append(dens)
142
+ pct_values = np.percentile(a, np.linspace(0, 100, n_percentiles + 1))
143
+ percentiles.append(pct_values)
144
+ stats.append({'n': int(a.size), 'mean': float(a.mean()), 'std': float(a.std(ddof=1)),
145
+ 'min': float(a.min()), 'max': float(a.max())})
146
+
147
+ # plotting
148
+ fig, ax = plt.subplots(figsize=(10, 6))
149
+ ax.set_title(title)
150
+ ax.set_xlabel("value")
151
+ ax.set_ylabel("density (KDE)")
152
+ lines = []
153
+ labels = []
154
+ for i, dens in enumerate(kdes):
155
+ # label contains index and base stats
156
+ s = stats[i]
157
+ label = f"layer {i} (n={s['n']}, μ={s['mean']:.3g}, σ={s['std']:.3g})"
158
+ l, = ax.plot(grid, dens, label=label)
159
+ lines.append(l)
160
+ labels.append(label)
161
+ if show_percentile_lines and np.isfinite(percentiles[i]).all():
162
+ # show a few percentiles lightly (10th, 50th, 90th)
163
+ for p in (10, 50, 90):
164
+ v = np.percentile(arrs[i], p)
165
+ ax.axvline(v, linestyle='--', linewidth=0.6, alpha=0.6)
166
+
167
+ ax.legend(loc='best', fontsize='small')
168
+ ax.grid(True, linestyle=':', alpha=0.4)
169
+ plt.tight_layout()
170
+ plt.show()
171
+
172
+ result: Dict[str, Any] = {
173
+ 'grid': grid,
174
+ 'kdes': kdes,
175
+ 'percentiles': percentiles,
176
+ 'stats': stats,
177
+ 'fig_ax': (fig, ax) # note: matplotlib objects included for programmatic use
178
+ }
179
+
180
+ # compute pairwise similarity metrics
181
+ if compute_metrics:
182
+ # try to use scipy for Wasserstein and KS if available; otherwise fall back to grid L1
183
+ pairwise_wasserstein = None
184
+ pairwise_l1 = np.zeros((len(arrs), len(arrs)), dtype=float)
185
+ try:
186
+ from scipy.stats import wasserstein_distance
187
+ use_wasserstein = True
188
+ pairwise_wasserstein = np.zeros((len(arrs), len(arrs)), dtype=float)
189
+ except Exception:
190
+ use_wasserstein = False
191
+ pairwise_wasserstein = None
192
+
193
+ # L1 between normalized KDEs on the grid: integral |f - g|
194
+ for i in range(len(arrs)):
195
+ for j in range(len(arrs)):
196
+ f = kdes[i]
197
+ g = kdes[j]
198
+ pairwise_l1[i, j] = np.trapz(np.abs(f - g), grid)
199
+ if use_wasserstein:
200
+ # if one of the arrays empty, put nan
201
+ a = arrs[i]
202
+ b = arrs[j]
203
+ if a.size == 0 or b.size == 0:
204
+ pairwise_wasserstein[i, j] = np.nan
205
+ else:
206
+ pairwise_wasserstein[i, j] = wasserstein_distance(a, b)
207
+
208
+ metrics = {'l1_kde': pairwise_l1}
209
+ if use_wasserstein:
210
+ metrics['wasserstein'] = pairwise_wasserstein
211
+ result['metrics'] = metrics
212
+
213
+ return result
@@ -0,0 +1,42 @@
1
+ import torch
2
+ import matplotlib.pyplot as plt
3
+
4
+
5
+ def line_graph(list_of_values, title: str, label=None) -> None:
6
+ """
7
+ Uses a list of values (allows tensors) to make a line graph
8
+ :param list_of_values:
9
+ :param title:
10
+ :param label:
11
+ :return:
12
+ """
13
+ # Check if it's a list of tensors
14
+ if isinstance(list_of_values[0], torch.Tensor):
15
+ T = len(list_of_values)
16
+ N = list_of_values[0].numel()
17
+
18
+ # stack into shape (T, …)
19
+ data = torch.stack(list_of_values, dim=0) # if scalars, shape == (T,)
20
+ if data.dim() == 1:
21
+ data = data.unsqueeze(1) # now shape == (T,1)
22
+
23
+ data = data.cpu().numpy()
24
+ x = range(T)
25
+
26
+ for neuron_idx in range(N):
27
+ if label is not None:
28
+ plt.plot(x, data[:, neuron_idx], label=f'{label[neuron_idx]}')
29
+ else:
30
+ plt.plot(x, data[:, neuron_idx], label=f'Neuron {neuron_idx}')
31
+
32
+ plt.title(title)
33
+ if N > 1:
34
+ plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
35
+ else:
36
+ # Assume list of floats (or ints)
37
+ x = range(len(list_of_values))
38
+ plt.plot(x, list_of_values)
39
+ plt.title(title)
40
+
41
+ plt.tight_layout()
42
+ plt.show()
@@ -0,0 +1,31 @@
1
+ import torch
2
+ from .. import plot
3
+
4
+
5
+ class MeasurementManager:
6
+ """
7
+ Manages measurements over time like loss or accuracy
8
+ """
9
+ def __init__(
10
+ self,
11
+ title: str,
12
+ decay: torch.Tensor = torch.tensor([0., 0.9, 0.99, 0.999])
13
+ ):
14
+ self.title = title
15
+ self.trace = torch.zeros_like(decay)
16
+ self.decay = decay
17
+ self.measurement = []
18
+
19
+ def append(self, value):
20
+ with torch.no_grad():
21
+ if isinstance(value, torch.Tensor):
22
+ value = value.item()
23
+ self.trace *= self.decay
24
+ self.trace += value * torch.ones_like(self.trace)
25
+ avg_input = self.trace * (1 - self.decay)
26
+ self.measurement.append(avg_input)
27
+
28
+ def plot(self, title: str = None):
29
+ plot_title = title if title is not None else self.title
30
+ rounded_list = [round(x, 4) for x in self.decay.tolist()]
31
+ plot.line_graph(self.measurement, title=plot_title, label=rounded_list)
@@ -0,0 +1,109 @@
1
+ import torch
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ from matplotlib import cm
5
+ from matplotlib.colors import Normalize
6
+
7
+
8
+ def render_image(tensor, figsize=(4, 4), title=None, vmin=None, vmax=None):
9
+ """
10
+ Plot a tensor image.
11
+
12
+ - tensor: torch.Tensor in either HW (H,W) or CHW (C,H,W) format.
13
+ C may be 1 (grayscale) or 3 (RGB).
14
+ - figsize: matplotlib figure size tuple
15
+ - title: optional title string
16
+ - vmin/vmax: if provided, these define the original data range (used for the colorbar).
17
+ If None, the function uses tensor.min() / tensor.max().
18
+ Behavior change for grayscale: the image is rescaled to [0,1] for display (max contrast),
19
+ but the colorbar shows the original numeric range (vmin..vmax).
20
+ :param tensor:
21
+ :param figsize:
22
+ :param title:
23
+ :param vmin:
24
+ :param vmax:
25
+ :return:
26
+ """
27
+ if not torch.is_tensor(tensor):
28
+ tensor = torch.as_tensor(tensor)
29
+
30
+ t = tensor.detach()
31
+ if t.device.type != "cpu":
32
+ t = t.cpu()
33
+
34
+ # helper to determine original vmin/vmax (either from args or data)
35
+ def _orig_range(arr, vmin_arg, vmax_arg):
36
+ data_min = float(np.nanmin(arr))
37
+ data_max = float(np.nanmax(arr))
38
+ orig_vmin = data_min if vmin_arg is None else float(vmin_arg)
39
+ orig_vmax = data_max if vmax_arg is None else float(vmax_arg)
40
+ return orig_vmin, orig_vmax
41
+
42
+ if t.dim() == 2:
43
+ # HW grayscale
44
+ img = t.numpy().astype(np.float32)
45
+
46
+ orig_vmin, orig_vmax = _orig_range(img, vmin, vmax)
47
+
48
+ # avoid divide-by-zero for constant images
49
+ if orig_vmax > orig_vmin:
50
+ img_scaled = (img - orig_vmin) / (orig_vmax - orig_vmin)
51
+ # numerical safety
52
+ img_scaled = np.clip(img_scaled, 0.0, 1.0)
53
+ else:
54
+ # constant image -> show mid-gray but colorbar will show the constant value
55
+ img_scaled = np.full_like(img, 0.5, dtype=np.float32)
56
+
57
+ fig, ax = plt.subplots(figsize=figsize)
58
+ im = ax.imshow(img_scaled, cmap="gray", vmin=0.0, vmax=1.0, interpolation="nearest")
59
+ ax.axis("off")
60
+ if title:
61
+ ax.set_title(title)
62
+
63
+ # colorbar referencing original scale
64
+ mappable = cm.ScalarMappable(norm=Normalize(vmin=orig_vmin, vmax=orig_vmax), cmap="gray")
65
+ mappable.set_array([]) # required for colorbar
66
+ plt.colorbar(mappable, ax=ax, fraction=0.046, pad=0.04)
67
+ plt.show()
68
+ return
69
+
70
+ if t.dim() == 3:
71
+ c, h, w = t.shape
72
+ if c == 1:
73
+ img = t.squeeze(0).numpy().astype(np.float32)
74
+
75
+ orig_vmin, orig_vmax = _orig_range(img, vmin, vmax)
76
+
77
+ if orig_vmax > orig_vmin:
78
+ img_scaled = (img - orig_vmin) / (orig_vmax - orig_vmin)
79
+ img_scaled = np.clip(img_scaled, 0.0, 1.0)
80
+ else:
81
+ img_scaled = np.full_like(img, 0.5, dtype=np.float32)
82
+
83
+ fig, ax = plt.subplots(figsize=figsize)
84
+ im = ax.imshow(img_scaled, cmap="gray", vmin=0.0, vmax=1.0, interpolation="nearest")
85
+ ax.axis("off")
86
+ if title:
87
+ ax.set_title(title)
88
+
89
+ mappable = cm.ScalarMappable(norm=Normalize(vmin=orig_vmin, vmax=orig_vmax), cmap="gray")
90
+ mappable.set_array([])
91
+ plt.colorbar(mappable, ax=ax, fraction=0.046, pad=0.04)
92
+ plt.show()
93
+ return
94
+
95
+ elif c == 3:
96
+ # CHW -> HWC for matplotlib (leave RGB untouched)
97
+ img = t.permute(1, 2, 0).numpy()
98
+ img = np.clip(img, 0.0, 1.0) # assume RGB in 0..1; you can change handling if needed
99
+ fig, ax = plt.subplots(figsize=figsize)
100
+ ax.imshow(img, interpolation="nearest")
101
+ ax.axis("off")
102
+ if title:
103
+ ax.set_title(title)
104
+ plt.show()
105
+ return
106
+ else:
107
+ raise ValueError(f"Unsupported channel dimension: C={c}. Expected C==1 or C==3 for CHW.")
108
+
109
+ raise ValueError(f"Unsupported tensor shape {tuple(t.shape)}. Expected HW or CHW.")
@@ -0,0 +1,75 @@
1
+ import torch
2
+ import matplotlib.pyplot as plt
3
+ import numpy as np
4
+
5
+
6
+ def spike_train(
7
+ list_of_tensors,
8
+ spacing: float = 1.0,
9
+ linelength: float = 0.8,
10
+ linewidth: float = 0.5,
11
+ title: str = "Spike Train Raster",
12
+ use_imshow: bool = True,
13
+ ):
14
+ """
15
+ Plot a spike train raster for a list of 1D tensors.
16
+
17
+ If use_imshow is True, uses imshow with grayscale to reflect values
18
+ (0=white, 1=black). Otherwise falls back to eventplot, plotting spikes
19
+ (only non-zero) in black.
20
+
21
+ Args:
22
+ list_of_tensors: list of 1D torch.Tensors of equal length T.
23
+ spacing: vertical spacing between rows.
24
+ linelength: length of eventplot lines (ignored for imshow).
25
+ linewidth: width of eventplot lines (ignored for imshow).
26
+ title: figure title.
27
+ use_imshow: whether to plot using imshow and grayscale mapping.
28
+ :param list_of_tensors:
29
+ :param spacing:
30
+ :param linelength:
31
+ :param linewidth:
32
+ :param title:
33
+ :param use_imshow:
34
+ :return:
35
+ """
36
+ # Stack into 2D array: shape (num_neurons, T)
37
+ # list_of_tensors assumed length T each
38
+ data = torch.stack(list_of_tensors).cpu().numpy() # shape (T, N)
39
+ data = data.T # shape (N, T)
40
+
41
+ plt.figure(figsize=(8, 4))
42
+ if use_imshow:
43
+ # Display as image with grayscale: 1=black, 0=white
44
+ plt.imshow(
45
+ data,
46
+ aspect='auto',
47
+ cmap='gray_r',
48
+ origin='lower',
49
+ interpolation='nearest'
50
+ )
51
+ plt.colorbar(label='Spike value')
52
+ else:
53
+ N, T = data.shape
54
+ # for each neuron i, list of spike times where value != 0
55
+ spike_times = [
56
+ [t for t in range(T) if data[i, t] != 0]
57
+ for i in range(N)
58
+ ]
59
+ # y offsets
60
+ offsets = np.arange(N) * spacing
61
+ plt.eventplot(
62
+ spike_times,
63
+ orientation='horizontal',
64
+ lineoffsets=offsets,
65
+ linelengths=linelength,
66
+ linewidths=linewidth,
67
+ colors='k'
68
+ )
69
+ plt.ylim(-spacing, offsets[-1] + spacing)
70
+
71
+ plt.xlabel("Time step")
72
+ plt.ylabel("Neuron index")
73
+ plt.title(title)
74
+ plt.tight_layout()
75
+ plt.show()
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: tracetorch
3
+ Version: 0.1.0
4
+ Summary: An extension to PyTorch: SNN layers that function on traces.
5
+ Author-email: Yegor Men <yegor.mn@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Yegor-men/tracetorch
8
+ Project-URL: Repository, https://github.com/Yegor-men/tracetorch
9
+ Project-URL: Issues, https://github.com/Yegor-men/tracetorch/issues
10
+ Project-URL: Documentation, https://yegor-men.github.io/tracetorch/
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Requires-Python: >=3.8
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: torch
18
+ Requires-Dist: numpy
19
+ Requires-Dist: matplotlib
20
+ Dynamic: license-file
21
+
22
+ ![traceTorch Banner](media/tracetorch_banner.png)
23
+
24
+ [![License](https://img.shields.io/badge/License-Apache%202.0-purple.svg)](https://www.apache.org/licenses/LICENSE-2.0)
25
+
26
+ ``traceTorch`` is a PyTorch-based library built on the principles of spiking neural networks, replacing the PyTorch
27
+ default backpropagation through time with lightweight, per-layer input traces, enabling biologically inspired, constant
28
+ time and memory consumption learning on arbitrarily long or even streaming sequences.
29
+
30
+ ## Documentation
31
+
32
+ It is highly recommended that you read the [documentation](https://yegor-men.github.io/tracetorch/) first. It contains:
33
+
34
+ 1. **Introduction**: An introduction to traceTorch, how and why it works, it's founding principles. It's thoroughly
35
+ recommended that you read through the entire introduction and gain an intuitive understanding before proceeding.
36
+ 2. **Tutorials**: Various tutorials to create your own traceTorch models. The resultant code can be found in
37
+ `tutorials/`.
38
+ 3. **Documentation**: The actual documentation to all the modules included in `traceTorch`. It includes detailed
39
+ explanations, examples and math to gain a full understanding.
40
+
41
+ ## Roadmap
42
+
43
+ - Create the poisson click test example
44
+ - Implement the trace alternative to REINFORCE
45
+ - Make traceTorch into a PyPI library
46
+ - Finish writing the documentation
47
+ - Clean up the tutorial code
48
+ - Implement abstract graph based models, not just sequential
49
+
50
+ ## Installation
51
+
52
+ ⚠️ WARNING, traceTorch is _not yet_ a library. For now, you'll just have to clone this repository and use the
53
+ `tracetorch/` folder within.
54
+
55
+ ```
56
+ git clone https://github.com/Yegor-men/tracetorch
57
+ cd tracetorch/
58
+ pip install -r requirements.txt
59
+ ```
60
+
61
+ Then, within a python file where from where the repository root folder is visible, simply do:
62
+
63
+ ```
64
+ from tracetorch import tracetorch
65
+ ```
66
+
67
+ ## Usage examples
68
+
69
+ `tutorials/` contains all the tutorial files, ready to run and playtest. The tutorials themselves can be
70
+ found [here](https://yegor-men.github.io/tracetorch/tutorials/index.html).
71
+
72
+ To ensure that you have all the necessary packages for the tutorials installed, please execute the following command:
73
+
74
+ ```
75
+ cd tutorials/
76
+ pip install -r requirements.txt
77
+ ```
78
+
79
+ ## Authors
80
+
81
+ - [@Yegor-men](https://github.com/Yegor-men)
82
+
83
+ ## Acknowledgements
84
+
85
+ I built traceTorch from the ground up, trying to reverse engineer biological neurons with a sprinkle of intelligent
86
+ design, but I would also like to recognize the following projects and people who helped shape my thinking:
87
+
88
+ - [snntorch](https://github.com/jeshraghian/snntorch) for introducing me to SNN networks in the first place, and their
89
+ principles of function. Ironically, its dependency on constructing the full autograd graph is what largely inspired me
90
+ to make traceTorch.
91
+ - [Artem Kirsanov](https://www.youtube.com/@ArtemKirsanov) for introducing me to computational neuroscience, presenting
92
+ interesting concepts in an easy-to-understand manner. My earliest tests, when I naively wanted to implement 1:1
93
+ biological neurons, largely revolved around his work.
94
+ - [e-prop (eligibility propagation)](https://www.biorxiv.org/content/biorxiv/early/2020/04/16/738385.full.pdf) inspired
95
+ the whole "trace" concept, the idea of keeping a decaying value. Earlier, before traceTorch, I wanted to use e-prop
96
+ for online learning instead. Admittedly unsuccessful in my attempts, and a little put off by the relative difficulty,
97
+ I instead wanted to make something simpler.
98
+
99
+ ## Contributing
100
+
101
+ Contributions are always welcome. Feel free to submit pull requests or report issues, I will occasionally check in on
102
+ it.
103
+
104
+ You can also reach out to me via either email or Twitter:
105
+
106
+ - yegor.mn@gmail.com
107
+ - [Twitter](https://x.com/Yegor_Men)
@@ -0,0 +1,25 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ tracetorch/__init__.py
5
+ tracetorch.egg-info/PKG-INFO
6
+ tracetorch.egg-info/SOURCES.txt
7
+ tracetorch.egg-info/dependency_links.txt
8
+ tracetorch.egg-info/requires.txt
9
+ tracetorch.egg-info/top_level.txt
10
+ tracetorch/functional/__init__.py
11
+ tracetorch/functional/_sample_softmax.py
12
+ tracetorch/functional/_sigmoid_inverse.py
13
+ tracetorch/functional/_softplus_inverse.py
14
+ tracetorch/loss/__init__.py
15
+ tracetorch/loss/_mse.py
16
+ tracetorch/nn/__init__.py
17
+ tracetorch/nn/_lif.py
18
+ tracetorch/nn/_lis.py
19
+ tracetorch/nn/_sequential.py
20
+ tracetorch/plot/__init__.py
21
+ tracetorch/plot/_distributions.py
22
+ tracetorch/plot/_line_graph.py
23
+ tracetorch/plot/_measurement_manager.py
24
+ tracetorch/plot/_render_image.py
25
+ tracetorch/plot/_spike_train.py
@@ -0,0 +1,3 @@
1
+ torch
2
+ numpy
3
+ matplotlib
@@ -0,0 +1 @@
1
+ tracetorch