foreshore 0.0.1.dev0__tar.gz → 0.0.2__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.
Files changed (52) hide show
  1. foreshore-0.0.2/LICENSE +202 -0
  2. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/PKG-INFO +3 -1
  3. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/README.md +30 -24
  4. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore/__init__.py +1 -2
  5. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore/data_preparation/prepare_evaluation_data.py +2 -4
  6. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore/debugging/afe_chirp_experiment.py +9 -4
  7. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore/deployment/xyloSim_test.py +1 -1
  8. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore/deployment/xylo_deployment.py +17 -11
  9. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore/deployment/xylo_experiment.py +3 -2
  10. foreshore-0.0.2/foreshore/train/__init__.py +3 -0
  11. {foreshore-0.0.1.dev0/foreshore/training_testing → foreshore-0.0.2/foreshore/train}/data_module.py +17 -1
  12. {foreshore-0.0.1.dev0/foreshore/training_testing → foreshore-0.0.2/foreshore/train}/loss.py +0 -121
  13. foreshore-0.0.2/foreshore/train/metrics/__init__.py +4 -0
  14. {foreshore-0.0.1.dev0/foreshore/training_testing → foreshore-0.0.2/foreshore/train}/metrics/binary_metrics.py +1 -1
  15. {foreshore-0.0.1.dev0/foreshore/training_testing → foreshore-0.0.2/foreshore/train}/metrics/multiclass_metrics.py +2 -2
  16. {foreshore-0.0.1.dev0/foreshore/training_testing → foreshore-0.0.2/foreshore/train}/metrics/non_scalar_metrics.py +1 -1
  17. {foreshore-0.0.1.dev0/foreshore/training_testing → foreshore-0.0.2/foreshore/train}/metrics/stat_scores.py +1 -1
  18. {foreshore-0.0.1.dev0/foreshore/training_testing → foreshore-0.0.2/foreshore/train}/predictions/binary.py +6 -5
  19. {foreshore-0.0.1.dev0/foreshore/training_testing → foreshore-0.0.2/foreshore/train}/training_module.py +149 -248
  20. foreshore-0.0.2/foreshore/train/transforms/__init__.py +2 -0
  21. {foreshore-0.0.1.dev0/foreshore/training_testing → foreshore-0.0.2/foreshore/train}/transforms/basic_transforms.py +18 -6
  22. foreshore-0.0.2/foreshore/utils/__init__.py +0 -0
  23. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore/utils/xylohdk_utils.py +4 -2
  24. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore.egg-info/PKG-INFO +3 -1
  25. foreshore-0.0.2/foreshore.egg-info/SOURCES.txt +44 -0
  26. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/setup.py +2 -1
  27. foreshore-0.0.2/tests/test_afesim.py +63 -0
  28. {foreshore-0.0.1.dev0/foreshore → foreshore-0.0.2}/tests/test_basic_transforms.py +3 -3
  29. {foreshore-0.0.1.dev0/foreshore → foreshore-0.0.2}/tests/test_binary_predicitons.py +15 -15
  30. {foreshore-0.0.1.dev0/foreshore → foreshore-0.0.2}/tests/test_loss.py +1 -94
  31. {foreshore-0.0.1.dev0/foreshore → foreshore-0.0.2}/tests/test_multiclass_predictions.py +1 -1
  32. foreshore-0.0.1.dev0/foreshore/docs/templates/dataset/your_dataset.py +0 -256
  33. foreshore-0.0.1.dev0/foreshore/docs/templates/train_snn.py +0 -161
  34. foreshore-0.0.1.dev0/foreshore/docs/tutorial_rare_sound/data_module_rare_sound.py +0 -138
  35. foreshore-0.0.1.dev0/foreshore/docs/tutorial_rare_sound/train_snn_rare_sound.py +0 -119
  36. foreshore-0.0.1.dev0/foreshore/tests/test_afesim.py +0 -71
  37. foreshore-0.0.1.dev0/foreshore.egg-info/SOURCES.txt +0 -43
  38. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore/debugging/AFESamna_AFESim_chirp_test.py +0 -0
  39. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore/debugging/chirp_gen.py +0 -0
  40. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore/deployment/xyloMonitor_test.py +0 -0
  41. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore/deployment/xyloSamna_test.py +0 -0
  42. {foreshore-0.0.1.dev0/foreshore/training_testing → foreshore-0.0.2/foreshore/train}/predictions/__init__.py +0 -0
  43. {foreshore-0.0.1.dev0/foreshore/training_testing → foreshore-0.0.2/foreshore/train}/predictions/multiclass.py +0 -0
  44. {foreshore-0.0.1.dev0/foreshore/training_testing → foreshore-0.0.2/foreshore/train}/transforms/to_spike_transform.py +0 -0
  45. {foreshore-0.0.1.dev0/foreshore/training_testing → foreshore-0.0.2/foreshore/train}/weights_checkpoint.py +0 -0
  46. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore/utils/audio_test_utils.py +0 -0
  47. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore/utils/cache_utils.py +0 -0
  48. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore/utils/model_validation_utils.py +0 -0
  49. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore.egg-info/dependency_links.txt +0 -0
  50. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore.egg-info/requires.txt +0 -0
  51. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/foreshore.egg-info/top_level.txt +0 -0
  52. {foreshore-0.0.1.dev0 → foreshore-0.0.2}/setup.cfg +0 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -1,11 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: foreshore
3
- Version: 0.0.1.dev0
3
+ Version: 0.0.2
4
4
  Summary: Python package for training a network with Rockpool.
5
5
  Home-page: https://gitlab.com/synsense/thunder-experiments/rockpool_training_pipeline
6
6
  Author: Karla Burelo and Vanessa Leite
7
7
  Author-email: support@synsense.ai
8
8
  License: Apache-2.0
9
+ License-File: LICENSE
9
10
  Requires-Dist: rockpool
10
11
  Requires-Dist: torch
11
12
  Requires-Dist: pytorch_lightning>=2.6.6
@@ -17,5 +18,6 @@ Dynamic: author
17
18
  Dynamic: author-email
18
19
  Dynamic: home-page
19
20
  Dynamic: license
21
+ Dynamic: license-file
20
22
  Dynamic: requires-dist
21
23
  Dynamic: summary
@@ -1,39 +1,45 @@
1
1
  # Rockpool training pipeline
2
2
  This repository provides a training pipeline example for Rockpool.
3
- The main branch contains templates for dataset, datamodule as well as general deployment and debugging example code.
4
- We provide three branches with example code.
3
+ The `train` folder contains the scripts needed to perform a training loop.
4
+ We provide metrics, predictions, transforms, and loss functions that we have previosly used to train models for our Xylo boards.
5
+ The TrainingRockpoolModule is a LightningModule based module that handles the training pipeline with some particular additions that are necessary for training a model for Xylo.
5
6
 
6
- - rare-sound
7
- - neurobench
8
- - baby-cry
7
+ We provide a working example in docs/tutorial_rare_sound. The train_rare_sound.ipynb tutorial runs a training loop of 2 epochs using the MIVIAAudioEvents data. Other parameters for the training are specified in the train_rare_sound.yaml file.
9
8
 
10
- The rare-sound and neurobench branches are fully worked examples that the user should be able to reproduce after downloading the corresponding data.
11
- Additionally, we provide a baby-cry branch. While the data for this case is not publicly available, these are other good examples of how the Dataset and DataModule change for each dataset.
12
- Moreover, since baby-cry is a binary classification problem, we use different metrics that might be useful for the user to explore.
13
-
14
- We mainly focus on the rare-sound branch as we have also provided a trained checkpoint and figures of the results at the deployment stage.
9
+ We recommend going through these tutorial first to understand how you can modify the scripts and run a training loop for your dataset using Foreshore.
15
10
 
16
11
  ## Python version and repository dependencies
17
- Python 3.10.8
18
- Create a new environment using the `requirements.txt ` file
12
+ We recommend stay up-to-date with the latest python versions supported in Rockpool.
13
+ The latest python version at the moment is Python 3.13.
14
+ Make sure to follow the steps to install `Rockpool` (https://rockpool.ai/basics/installation.html)
15
+ Additionally, `Foreshore` uses `torch` and `pytorch_lightning`.
16
+ We recommend to do a CUDA installation for `torch`. This installation requires to find the version that fits your GPU. Refer to this page https://pytorch.org/get-started/previous-versions/ to find the correct version for you.
17
+ Once you have installed `Rockpool` and `torch`, you can continue with the installation of the packages in the `requirements.txt ` file
18
+
19
+ ## Installation
20
+ The simplest way to install Foreshore is from PyPI:
21
+ ```
22
+ pip install foreshore
23
+ ```
19
24
 
20
25
  ## Dataset
21
26
  The first step is to work on the dataset. We provide a general template so the user familiarizes with how we prepare a dataset for our training pipeline.
22
- The DataModule handles the load and preparation of the data together with the Dataset. Once again, in the main branch the Datamodule is a template that should be modified according to the dataset and use-case. However, we expect most of the changes to be done on the Dataset, while the structure of the DataModule will stay very similar to that of the template.
23
- See rare-sound, neurobench and baby-cry examples of Dataset and Datamodule for more concrete examples. Keep in mind, however, that the dataset might require extra functions depending on the formatting of the original dataset and will therefore vary across datasets and applications.
27
+ The DataModule handles the load and preparation of the data together with the Dataset. The DataModule template should be modified according to the dataset and use-case. However, we expect most of the changes to be done on the Dataset, while the structure of the DataModule will stay very similar to that of the template.
28
+ See the `data_module_template` and `dataset_template` tutorials to understand the general idea of this scripts. Keep in mind that the dataset might require extra functions depending on the formatting of the original dataset and will therefore vary across datasets and applications.
29
+ See also `data_module_rare_sound` and `dataset_rare_sound` for a concrete example.
24
30
 
25
31
  ## TrainingRockpoolModule and Datamodule
26
- We provide a TrainingRockpoolModule and a ThresholdSweep module. The TrainingRockpoolModule is the basis for handling the training steps.
27
- However we have extended this module to have a threshold sweep.
28
- In this child class, the training, validation and test steps include an extra computation after passing the data through the model.
29
- While we compute our model's loss using the vmem, we evaluate the model in spike mode. This decision allows us to have a better control on the mapping of the model in the xylo board.
30
-
32
+ We provide a TrainingRockpoolModule module, which handles the training, validation, and test steps.
33
+ Even though the loss is calculated based on the membrane potential (Vmem) of the readout neurons, the model needs to be evaluated in spike mode in order to match the final evaluation in the Xylo HW. Therefore, by default the module performs a threshold sweep. This sweep consist of thresholding the Vmem and calculate the metrics for each of the thresholds specified in monitored_thresholds.
34
+ For the validation step, the best performing thresholds are saved along with the model checkpoint.
31
35
 
32
36
  ## Training a model
33
37
  In order to train a model, the user must provide a config yaml file specifying the parameters for training.
34
- We have included templates for this yaml file in the `config` folder. Additionally we provide templates with examples for configurations used for XyloA2, XyloA3, as well as for binary and multiclass classification.
38
+ We have included templates for this yaml file in the `docs/config` folder.
39
+ Additionally we provide a tutorial `yaml_file_template` where we explain in more detail what is specified in this file.
40
+ We also providde examples for configurations used for XyloA2, XyloA3, as well as for binary and multiclass classification.
35
41
 
36
- The information in this yaml file contains, but it is not limited to:
42
+ The information in the yaml file contains:
37
43
  - Parameters of the dataset
38
44
  - SNN model and init parameters
39
45
  - Prediction method
@@ -42,7 +48,7 @@ The information in this yaml file contains, but it is not limited to:
42
48
  Once the user has updated their Dataset as well as their DataModule, they can run a training experiment:
43
49
  - open a terminal
44
50
  - go to the parent folder of this repository
45
- - run `python training_testing/train_snn.py fit --config config/train.yaml`
51
+ - run `python train/train_snn.py fit --config config/train.yaml`
46
52
 
47
53
  Where `train.yaml` should include the user's specifications for the training.
48
54
 
@@ -52,8 +58,8 @@ In the example `train.yaml` file, this path is already set as an example
52
58
 
53
59
  ## Model validation and deployment using XyloSim, XyloSamna, and XyloMonitor:
54
60
  After training a model, we recommend to move to the deployment stage.
55
- In the rare-sound branch, we provide a trained model as well as the validation dataset to validate the model.
56
- The trained model is under `./experiments/trained_checkpoints/{experiment_id}/`
61
+ In the tutorial_rare_sound folder we provide a trained model.
62
+ The trained model is under `docs/tutorial_rare_sound/experiments/trained_checkpoints/{experiment_id}/`
57
63
  In this folder the user can find the `trained_model_dict.json` containing all the trained parameters (weights, time constants, etc) and the `config.yaml` which contains all the information used to train this model. For example, in this file the user can find the initialization of the SynNet model.
58
64
 
59
65
  ### Model deployment in XyloSim and XyloSamna
@@ -1,6 +1,5 @@
1
1
  from .data_preparation import *
2
2
  from .debugging import *
3
3
  from .deployment import *
4
- from .experiments import *
5
- from .training_testing import *
4
+ from .train import *
6
5
  from .utils import *
@@ -3,6 +3,7 @@ import yaml
3
3
  import json
4
4
  import numpy as np
5
5
 
6
+
6
7
  def prepare_evaluation_data(txt_file, partition, model_path, data_module_cls):
7
8
  """
8
9
  During training we save the cache data path for the AFESim data for each partition.
@@ -76,7 +77,7 @@ def prepare_evaluation_data(txt_file, partition, model_path, data_module_cls):
76
77
  raise Exception("Data loader is empty, please check your parameters")
77
78
 
78
79
 
79
- def prepare_audio_paths(txt_file, partition):
80
+ def prepare_audio_paths(json_config, partition):
80
81
  """
81
82
  During training we save the cache data path for the AFESim data
82
83
  But also the config_data that points to the original audio paths in each partition.
@@ -88,10 +89,7 @@ def prepare_audio_paths(txt_file, partition):
88
89
  txt_file (str): Path to the text file that was saved during training. This text file includes the paths for AFEsim data and original audio paths
89
90
  partition(str): Indicates the partition data to be used to evaluate the model. Options are: 'train', 'val', or 'test'
90
91
  """
91
- with open(txt_file, "r") as f:
92
- data = dict(line.strip().split("=", 1) for line in f)
93
92
 
94
- json_config = data["config_data"]
95
93
  with open(json_config) as f:
96
94
  config = json.load(f)
97
95
  partition_audio_paths = config[partition]
@@ -2,7 +2,7 @@ import os
2
2
  import numpy as np
3
3
  from scipy.io import wavfile
4
4
  import matplotlib.pyplot as plt
5
- from chirp_gen import ChirpGen
5
+ from foreshore.debugging.chirp_gen import ChirpGen
6
6
  from foreshore.utils.xylohdk_utils import find_xylo
7
7
  from foreshore.utils.audio_test_utils import get_wave_object
8
8
 
@@ -66,6 +66,7 @@ class AFE_chirp_experiment:
66
66
  duration_input_signal=2,
67
67
  add_silence_period=False,
68
68
  experiment_tag=None,
69
+ output_path=None,
69
70
  ):
70
71
  """
71
72
  Instantiates AFE_chirp_experiment
@@ -76,6 +77,7 @@ class AFE_chirp_experiment:
76
77
  experiment_tag (str): extra tag name to add to the experiment results filename to identify a specific experiment. For example, let's say the user
77
78
  would like to run two experiments with the same parameters but changing the distance between speaker and xylo board. Then the user can add
78
79
  a "_distance_5cm" and "_distance_10cm" to the results filename and compare them later. Default to None
80
+ output_path (str): path where the afe results will be saved
79
81
 
80
82
  """
81
83
 
@@ -85,7 +87,7 @@ class AFE_chirp_experiment:
85
87
  self.fmin = CHIRP_PARAMETERS["fmin"]
86
88
  self.fmax = CHIRP_PARAMETERS["fmax"]
87
89
  self.num_bits_Q = CHIRP_PARAMETERS["num_bits_Q"]
88
-
90
+ self.output_path = output_path
89
91
  self.prepare_folders()
90
92
  self.generate_chirp_file_name_tag(experiment_tag=experiment_tag)
91
93
  # Load or generate chirp data
@@ -101,8 +103,11 @@ class AFE_chirp_experiment:
101
103
  - results of the test
102
104
  - figures
103
105
  """
104
- folders = ["afe_test_resutls", f"chirp_test"]
105
- test_results_path = debug_path
106
+ folders = ["afe_test_results", f"chirp_test"]
107
+ if self.output_path is None:
108
+ test_results_path = os.getcwd()
109
+ else:
110
+ test_results_path = self.output_path
106
111
  for name in folders:
107
112
  test_results_path = os.path.join(test_results_path, name)
108
113
  if not os.path.exists(test_results_path):
@@ -26,7 +26,7 @@ In this tutorial you can also run the experiment with a previously trained model
26
26
  """
27
27
 
28
28
  # ------------------------------------------- TEST PARAMS ------------------------------------------- #
29
- device_type = "XyloA3" # XyloA2 or XyloA3
29
+ device_type = "XyloA3" # XyloA2 or XyloA3
30
30
  record_power = False
31
31
  record_states = False
32
32
  output_mode = "Vmem"
@@ -3,10 +3,10 @@ import time
3
3
  import samna
4
4
  import numpy as np
5
5
  import pytorch_lightning as pl
6
- from utils.xylohdk_utils import find_xylo
7
- from deployment.xylo_experiment import XyloExperiment
8
- from utils.audio_test_utils import get_wave_object
9
- from data_preparation.prepare_evaluation_data import (
6
+ from foreshore.utils.xylohdk_utils import find_xylo
7
+ from foreshore.deployment.xylo_experiment import XyloExperiment
8
+ from foreshore.utils.audio_test_utils import get_wave_object
9
+ from foreshore.data_preparation.prepare_evaluation_data import (
10
10
  prepare_evaluation_data,
11
11
  prepare_audio_paths,
12
12
  )
@@ -481,7 +481,7 @@ class XyloMonitorExperiment(XyloExperiment):
481
481
  dn_active=divisive_norm,
482
482
  )
483
483
 
484
- def load_input_data(self, input_path=None):
484
+ def load_input_data(self, input_path=None, data_json_config=None):
485
485
  """
486
486
  By default, we provide the trained model together with a config.json file for XyloMonitor.
487
487
  This json file includes the paths to the audios that will be used for the experiment
@@ -499,12 +499,18 @@ class XyloMonitorExperiment(XyloExperiment):
499
499
  input_path (str, optional): specific path to a config.json file created by the user. Defaults to None.
500
500
  """
501
501
  if input_path is None:
502
- # Find data.txt file
503
- data_txt_file = os.path.join(self.model_path, "data.txt")
504
-
505
- input_path = prepare_audio_paths(
506
- txt_file=data_txt_file, partition=self.partition
507
- )
502
+ if data_json_config is not None:
503
+ json_config = data_json_config
504
+ else:
505
+ # Find data.txt file
506
+ data_txt_file = os.path.join(self.model_path, "data.txt")
507
+ with open(data_txt_file, "r") as f:
508
+ data = dict(line.strip().split("=", 1) for line in f)
509
+ json_config = data["config_data"]
510
+
511
+ input_path = prepare_audio_paths(
512
+ json_config=json_config, partition=self.partition
513
+ )
508
514
  self.labels = []
509
515
  self.input_data = input_path
510
516
  for i, data in enumerate(self.input_data):
@@ -5,12 +5,13 @@ import matplotlib.pyplot as plt
5
5
  import matplotlib.gridspec as gridspec
6
6
  from torchmetrics import ConfusionMatrix as confmat_torch
7
7
  from rockpool.transform import quantize_methods as q
8
- from utils.model_validation_utils import (
8
+ from foreshore.utils.model_validation_utils import (
9
9
  confmat_elements,
10
10
  load_ckpt_into_backbone,
11
11
  predict_most_active_neuron,
12
12
  )
13
13
 
14
+
14
15
  class XyloExperiment:
15
16
  """
16
17
  XyloExperiment contains all the shared functions to run a xylo experiment using one of the following modes:
@@ -77,7 +78,7 @@ class XyloExperiment:
77
78
  # XyloExperiment will save the results on the library's 'experiments' folder
78
79
  results_save_path = self.model_path.split("experiments")[0]
79
80
  else:
80
- results_save_path = repo_path
81
+ results_save_path = os.getcwd()
81
82
  folder_names = [
82
83
  "experiments/",
83
84
  "validated_results/",
@@ -0,0 +1,3 @@
1
+ from .metrics import *
2
+ from .predictions import *
3
+ from .transforms import *
@@ -7,9 +7,25 @@ from torchvision.transforms import Compose
7
7
  from typing import Callable, Iterable, Optional
8
8
  from torch.utils.data import DataLoader, WeightedRandomSampler
9
9
 
10
- # from your_dataset_repo.dataset import DATA_PATH, YourDataSet
10
+ """
11
+ This script includes the general ForeshoreDataModule that you can use for training your model.
12
+ This module is based on LightningDataModule and includes extra useful functions to train a model for Xylo.
13
+ In the tutorial DataModule (/docs/tutorial_rare_sound/data_module_template.ipynb), we explain how to use the
14
+ ForeshoreDataModule to build your own. In particular, we explain how to adapt the `_get_dataset()` function to your use-case.
15
+ Note that the DataModule calls an existing Dataset that you will also need to create.
16
+ Remember to import your dataset at the beginning of your DataModule
17
+
18
+ ```
19
+ from your_dataset_repo.dataset import DATA_PATH, YourDataSet
20
+
21
+ ```
22
+
23
+ See also the train_rare_sound tutorial (/docs/tutorial_rare_sound/train_rare_sound.ipynb) to see how the DataModule fits in the training pipeline.
24
+ """
25
+
11
26
  from foreshore.utils.cache_utils import create_config_str
12
27
 
28
+
13
29
  class ForeshoreDataModule(pl.LightningDataModule):
14
30
  """
15
31
  Load and preprocess the data for a given dataset `DataSet`.
@@ -616,124 +616,3 @@ class MultilabelBinaryPeakLoss(BaseLoss):
616
616
  loss += self.weight_nontarget_noise * loss_nontarget_noise
617
617
 
618
618
  return loss
619
-
620
-
621
- class BinaryLatencyControlPeakLoss(BaseLoss):
622
- """
623
- Binary peak loss with explicit control over the reaction time window.
624
-
625
- This loss function is designed for binary classification where the timing of
626
- neural response matters. It encourages target neurons to be silent before a
627
- specified reaction window, active within the window, and optionally active
628
- (but at reduced level) after the window. Non-target neurons should remain
629
- silent throughout.
630
-
631
- Parameters:
632
- max_interval (int): Number of consecutive time steps to average around the
633
- peak within the reaction window.
634
- weight_nontarget (float): Weighting factor for the non-target loss component.
635
- reaction_window (List[int]): Two-element list [start, end] specifying the
636
- time window where target neurons should exhibit peak activity.
637
-
638
- Attributes:
639
- max_interval (int): Averaging window size around peak within reaction window.
640
- weight_nontarget (float): Weight for non-target loss.
641
- reaction_window (List[int]): Time window for target activation.
642
- crit (nn.MSELoss): Mean squared error criterion.
643
- """
644
-
645
- def __init__(
646
- self, max_interval: int, weight_nontarget: float, reaction_window: list
647
- ):
648
- super().__init__()
649
- if (
650
- isinstance(max_interval, bool)
651
- or not isinstance(max_interval, Integral)
652
- or max_interval <= 0
653
- ):
654
- raise ValueError("max_interval must be a positive integer.")
655
- self.max_interval = max_interval
656
- self.weight_nontarget = weight_nontarget
657
- self.crit = nn.MSELoss()
658
- self.reaction_window = (
659
- reaction_window # The range where we want to force the neuron to spike
660
- )
661
-
662
- # @staticmethod
663
- def calculate_loss(self, data, output, preds, target, model, **kwargs):
664
- """
665
- Loss computation:
666
- - Pre-reaction window (target samples): MSE between vmem and 0
667
- - Reaction window (target samples): MSE between averaged peak vmem and 1.5
668
- - Post-reaction window (target samples, if present): MSE between vmem and 0.5
669
- - Non-target samples: MSE between vmem and 0 across all time steps
670
- - Total loss = loss_target + loss_out_reaction_window + weight_nontarget * loss_nontarget
671
- """
672
- _validate_reaction_window(self.reaction_window, output.size(1))
673
- vmem = output
674
- max_interval = self.max_interval
675
- weight_nontarget = self.weight_nontarget
676
-
677
- loss_target = 0
678
- loss_nontarget = 0
679
- loss_out_reaction_window = 0
680
-
681
- nr_time_steps = vmem.size()[1]
682
- nr_time_steps_reaction_window = (
683
- self.reaction_window[1] - self.reaction_window[0]
684
- )
685
-
686
- if (target == 1).any():
687
- vmem_pre_reaction_window = vmem[target == 1, : self.reaction_window[0], 0]
688
- vmem_reaction_window = vmem[
689
- target == 1, self.reaction_window[0] : self.reaction_window[1], 0
690
- ]
691
-
692
- if nr_time_steps > self.reaction_window[1]:
693
- vmem_post_reaction_window = vmem[
694
- target == 1, self.reaction_window[1] :, 0
695
- ]
696
-
697
- max_indices_start = vmem_reaction_window.max(1)[1]
698
- max_indices = torch.clone(max_indices_start)
699
-
700
- batch_indices_on = torch.arange(vmem_reaction_window.size()[0]).long()
701
- vmem_on_max = (
702
- vmem_reaction_window[batch_indices_on, max_indices] / max_interval
703
- )
704
- for i in range(1, max_interval):
705
- max_indices = torch.clip(
706
- max_indices + 1, max=nr_time_steps_reaction_window
707
- )
708
- # when we reach the end of the array we jump back to the first max_index
709
- max_indices[max_indices == nr_time_steps_reaction_window] = (
710
- max_indices_start[max_indices == nr_time_steps_reaction_window]
711
- )
712
- vmem_on_max += (
713
- vmem_reaction_window[batch_indices_on, max_indices] / max_interval
714
- )
715
-
716
- # readout neuron should be active in reaction window
717
- loss_target = self.crit(vmem_on_max, torch.ones_like(vmem_on_max) * 1.5)
718
- loss_out_reaction_window = vmem.new_zeros(())
719
- if self.reaction_window[0] > 0:
720
- loss_out_reaction_window = self.crit(
721
- vmem_pre_reaction_window, torch.zeros_like(vmem_pre_reaction_window)
722
- )
723
-
724
- if nr_time_steps > self.reaction_window[1]:
725
- loss_out_reaction_window += self.crit(
726
- vmem_post_reaction_window,
727
- torch.ones_like(vmem_post_reaction_window) * 0.5,
728
- )
729
-
730
- if (target != 1).any():
731
- # readout neuron should be silent
732
- vmem_off = vmem[target == 0, :, 0]
733
- loss_nontarget = self.crit(vmem_off, torch.zeros_like(vmem_off))
734
-
735
- # add losses
736
- loss = loss_target + loss_out_reaction_window
737
- loss += weight_nontarget * loss_nontarget
738
-
739
- return loss
@@ -0,0 +1,4 @@
1
+ from .binary_metrics import *
2
+ from .multiclass_metrics import *
3
+ from .non_scalar_metrics import *
4
+ from .stat_scores import *
@@ -2,7 +2,7 @@ import torch
2
2
  from torch import Tensor, FloatTensor
3
3
  from typing import Optional
4
4
  from torchmetrics.utilities.compute import _safe_divide
5
- from metrics.stat_scores import __torch2ts_scalar
5
+ from .stat_scores import __torch2ts_scalar
6
6
  from torchmetrics.classification.stat_scores import BinaryStatScores
7
7
 
8
8