API
1. SNN Simulator¶
This is the main module that orchestrates the simulation process of SNN. It handles the creation of input images, netlist generation, parameter substitution, and execution of the simulation, along with the collection of results.
This module
- Accepts user-specificatied parameter combinations for different SNN designs.
- Loads the generated input images, flattens them, and uses frequency coding proportional to pixel intensity
- Generates files and process-specific directory for each SNN simulation named with the date, process ID, and parameter details
- Creates the netlist for each simulation using the net_generator module.
- Substitutes parameters into the OCEAN script template and launches the SPICE simulation using the subst_run module.
- Collects and saves the waveforms results of the selected signals.
- Executes the simulations of different SNN designs in parallel.
main()
¶
Main function to run all simulations using multiprocessing.
Steps
- Distribute parameter combinations across multiple processes.
- Run simulations in parallel.
- Measure and print the total simulation time.
Source code in src/snn_simulator.py
run_simulation(params)
¶
Runs a single SNN simulation with the given parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params |
dict
|
A dictionary containing global and local simulation parameters. |
required |
Steps
- Load and flatten input image.
- Calculate the number of spikes for each input neuron based on pixel intensity.
- Generate and prepare directories and files for the simulation.
- Create the netlist for the simulation.
- Substitute parameters into the OCEAN script and run the simulation.
- Clean up temporary files.
Source code in src/snn_simulator.py
2. Network Generation¶
Spice simulation with Spectre simulator requires a netlist file that includes the description of all the components of the circuit, and describes how these componenents are wired. The framework allows flexible geneartion of the netlist according to the desired network to be simulated. Only some network parameters should be given, for the corresponding netlist to be automatically generated. The follwoing module net_generator.py which contains diffrent classes is responsible of generating the netlist.
Circuit componenents are mangaged by the follwing classes : Synapse, Synapse_subskt, Input_neuron, Output_neuron, each contains a generate_netlist_bloc method that sets a string template bloc specific to that componenent and which should be added to the netlist file.
The class Netlist concatinates the instances of the componenets in a list, and generates a string bloc of a single componenent ready to be inserted in the final netlist.
The class NetworkGenerator is the main class that assembles all the components by iterating the appending method of Netlist class. and trigers the netlist generation method of Netlist.
Finally Separotor is a class to add a separation between a group of similar componenets for a bette rformatting.
Input_neuron
¶
A class to specify a netlist bloc that describes an input neuron of the SNN, a method takes a template, adds information of the current neuron (neuron index, number of spikes associated to that input neuron, the duration of a single input spike, and the duration of presenting an input example to the netowrk). That sting bloc will then be included in the final netlist.
Attributes:
| Name | Type | Description |
|---|---|---|
input_index |
[int]
|
The index of this input neuron. |
n_spikes |
[int]
|
The number of spikes this neuron will generate. |
Methods¶
generate_netlist_bloc(): Generates a string bloc specefic to that input neuron in the final netlist file.
Source code in src/net_generator.py
Netlist
¶
A class which assemles the instances of all the components, it then generates the netlist file add_component is a method that appends the instances of the componenets in one list called components. generate_netlist_file is a method that generates the diffrent parts of the netlist by using the generate_netlist_bloc() which is commun to all the components classes.
Attributes:
| Name | Type | Description |
|---|---|---|
file_path |
[str]
|
The path to the file where the netlist will be written. |
components |
[list]
|
The list of components instances (synapses, neurons, etc.). |
Methods¶
add_component(component): appends the instance of each omponenent to the components list. generate_netlist_file(): Writes the netlist to a file.
Source code in src/net_generator.py
NetworkGenerator
¶
The main class that generates all the netlist file, it is based on the Netlist class, It iterates over all the components by group of similar ones, it appends instances of each component to the components list, while adding separation formatting between groups of similar components.
Attributes:
| Name | Type | Description |
|---|---|---|
file_path |
[str]
|
The path to the file where the netlist will be written. |
num_input |
[int]
|
The number of input neurons in the network. |
num_output |
[int]
|
The number of output neurons in the network. |
num_cells |
[int]
|
The number of MTJ cells in each synapse. |
netlist |
[Netlist]
|
The netlist object that will be written to a file. |
n_spik_vec |
[list of int]
|
A list containing the number of spikes for each input neuron. |
Methods¶
generate_netlist_file(): similar to the generate_netlist_file of the Netlist class, but instead of generating a single component, it operates globally, ie: it generates the whole netlist by iterating through the method of Netlist class.
Source code in src/net_generator.py
Output_neuron
¶
A class to specify a netlist bloc of an output neuron of the SNN, a method takes a template, adds information of the current neuron (neuron index, membrane threshold). That sting bloc will then be included in the final netlist.
Attributes:
| Name | Type | Description |
|---|---|---|
output_index |
[int]
|
The index of this output neuron. |
Methods¶
generate_netlist_bloc(): Generates a string bloc specefic to that output neuron in the final netlist file.
Source code in src/net_generator.py
Separator
¶
A class to seperate between componenets in the netlist for a better formatting.
Methods¶
generate_netlist_bloc(): Generates a separation as a string.
Source code in src/net_generator.py
Synapse
¶
A class to specify a netlist bloc that describes an MTJ-based synapse of the SNN, generate_netlist_bloc is a method that returns as string which represents a template bloc of the synapse to be included in the netlist later. It personalizes the synapse at the current iteration by adding its specific informatio (connected neurons, number of MTJs per synapse, initialized states, seeds,... ). The synapse template calls the compound_synapse subcircuit which should be included once in the head of the netlist.
Attributes:
| Name | Type | Description |
|---|---|---|
input_index |
[int]
|
The index of the input neuron connected to this synapse. |
output_index |
[int]
|
The index of the output neuron connected to this synapse. |
paps |
[list of int]
|
The list of initial states of free layers for each MTJ in the synapse. (0 parallel, 1 anti-parallel). |
seeds |
[list of int]
|
The list of seed values used for stochasticity for each MTJ in the synapse. |
Methods¶
generate_netlist_bloc(): Generates a string bloc specefic to that synapse in the final netlist file.
Source code in src/net_generator.py
Synapse_subskt
¶
A class to specify a netlist bloc of the synapse subcircuit named compound_synapse, which will be called by all the synapses. It is composed of multiple MTJs (the number is given as attribute), and it makes call of the cellPMAMTJ subcircuit which is predefined in the initial netlist file. generate_netlist_bloc is a method that returns the subcircuit template to be included in the netlist. It takes an initial template, adds parameters to it : either to set stochasticity, variability, temperature and its variation or not, and sets as parameters the initial state of the MTJ, and the seed.
Attributes:
| Name | Type | Description |
|---|---|---|
num_cells |
[int]
|
The number of MTJ cells in each synapse. |
Methods¶
generate_netlist_bloc(): Generates a string bloc specefic to the compound_synapse subcircuit in the final netlist file.
Source code in src/net_generator.py
3. Substitution Run¶
This module provides utility functions for substituting values into templates and executing shell commands. It is designed to facilitate the automation of script generation and execution processes. The substitution method used here is inspired by the approach in the monaco project by @servinagrero: https://github.com/servinagrero/monaco/tree/develop
Functions:
| Name | Description |
|---|---|
substitute_templ |
Reads a template from a file, substitutes values from |
exec_cmd |
Executes a given shell command, optionally displaying the output. |
Example Usage:
substitute_templ('input_template.txt', 'output_file.txt', {'key1': 'value1'}, {'key2': 'value2'})
exec_cmd('ls -la', verbose=True)
exec_cmd(command, *, verbose=False)
¶
Execute a given shell command using subprocess.run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command |
str
|
Shell command to execute. |
required |
verbose |
bool
|
Whether to display the output of the command. |
False
|
Source code in src/subst_run.py
substitute_templ(template_file, output_file, *substitution_dicts)
¶
Substitute values into a template read from a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template_file |
str
|
Path to the input file containing the template. |
required |
output_file |
str
|
Path to the output file to write the substituted content. |
required |
*substitution_dicts |
Dict[str, str]
|
Dictionaries containing values to substitute into the template. |
()
|
Source code in src/subst_run.py
4. Plot Euclidean Distance¶
This module calculates and plots the Euclidean distance between the final weights of trained SNNs and the input images. The module provides functions to compute the distances for individual letters as well as average distances across multiple letters.
Functions:
| Name | Description |
|---|---|
eucl_dist |
Calculate and plot Euclidean distances for a specific letter. |
avg_eucl_dist |
Calculate and plot average Euclidean distances across multiple letters. |
calculate_dist |
Helper function to calculate Euclidean distances for a given letter. |
plot_distances |
Helper function to plot the Euclidean distances. |
Example Usage:
avg_eucl_dist(trained_letters_dict)
¶
Calculate and plot average Euclidean distances across multiple letters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trained_letters_dict |
dict
|
Dictionary containing base directories for trained letters. |
required |
Source code in src/plot_eucl_dist.py
calculate_dist(base_dir, letter_image)
¶
Helper function to calculate Euclidean distances for a given letter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_dir |
str
|
Base directory containing the trained folders. |
required |
letter_image |
ndarray
|
The image of the specific letter. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dictionary containing Euclidean distances for each combination of num_cells and VR_std. |
Source code in src/plot_eucl_dist.py
eucl_dist(trained_letters_dict, specific_letter)
¶
Calculate and plot Euclidean distances for a specific letter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trained_letters_dict |
dict
|
Dictionary containing base directories for trained letters. |
required |
specific_letter |
str
|
The letter to calculate distances for. |
required |
Source code in src/plot_eucl_dist.py
plot_distances(euclidean_distances, title)
¶
Helper function to plot the Euclidean distances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
euclidean_distances |
dict
|
Dictionary containing Euclidean distances to plot. |
required |
title |
str
|
Title of the plot. |
required |
Source code in src/plot_eucl_dist.py
5. Plot Weight Membrane¶
This script processes and plots simulation results for an SNN. It loads data from a specified results file, plots the weights history, the output neuron membrane potential, and compares initial and final weights.
Functions:
| Name | Description |
|---|---|
parse_arguments |
Parse command-line arguments. |
load_data |
from results.txt, organized as : time | synapse1 | synapse2 | ... | membrane_out_neuron. |
plot_weights_history |
Plot the weights history. |
plot_membrane_potential |
Plot the output neuron membrane potential. |
plot_weights_comparison |
Plot initial and final weights comparison. |
main |
Main function to orchestrate loading data and plotting results. |
Example Usage:
load_data(folder_name)
¶
Load data from the results file.
Source code in src/plot_weig_membr.py
main()
¶
Main function to orchestrate loading data and plotting results.
Source code in src/plot_weig_membr.py
parse_arguments()
¶
Parse command-line arguments.
plot_membrane_potential(data)
¶
Plot the output neuron membrane potential.
Source code in src/plot_weig_membr.py
plot_weights_comparison(init_weights_img, final_weights_img)
¶
Plot initial and final weights comparison.
Source code in src/plot_weig_membr.py
plot_weights_history(data)
¶
Plot the weights history.
6. Generate Letters¶
This script generates binary images of letters, saves them in both .npy and .pkl formats, and stores them in a specified directory. Each letter is represented by specific pixel positions in a 5x5 image grid. Images are saved individually as .npy arrays, and collectively as .pkl dict. all images are generated at once.
create_letter_image(letter, positions)
¶
Create and save an image of a specified letter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
letter |
str
|
The letter to create an image for. |
required |
positions |
list of tuples
|
The pixel positions of the letter in the image. |
required |
Source code in src/input_images/gen_letters.py
7. View Images¶
This script loads and displays an image stored in a .npy file. It uses matplotlib to visualize the image and print its size and shape.
load_and_display_image(input_path)
¶
Load an image from a .npy file and display it using matplotlib.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path |
str
|
Path to the .npy file containing the image. |
required |
Source code in src/input_images/see_img.py
8. Extract from MNIST¶
This script extracts specific images from the MNIST dataset and saves them as .npy files. The script loads MNIST images from the idx3-ubyte format and saves selected images in a specified directory.
Functions:
| Name | Description |
|---|---|
load_idx3_ubyte |
Loads MNIST images from a given idx3-ubyte file. |
load_idx3_ubyte(idx3_ubyte_file)
¶
Load MNIST data from the given file path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx3_ubyte_file |
str
|
Path to the idx3-ubyte file containing MNIST images. |
required |
Returns:
| Type | Description |
|---|---|
|
np.ndarray: Array of shape (num_images, rows, cols) containing the MNIST images. |