devices.dynapse.DynapseSamnaο
- class devices.dynapse.DynapseSamna(*args, **kwargs)[source]ο
Bases:
Module
DynapseSamna bridges the gap between the chip and the computer. Provides a simulation-like interface for users, but executes all the operations on the hardware under the hood. Use
devices.dynapse.find_dynapse_boards
to find the HDK. Usedevices.dynapse.config_from_specification
to obtain a configuration object.# Connect se2_devices = find_dynapse_boards() se2 = DynapseSamna(se2_devices[0], **config) out, state, rec = se2(raster, record=True)
See also
- Parameters:
shape (Tuple[int]) β Two dimensions
(Nin, Nout)
, which defines a input and output conections of Dynap-SE2 neurons.device (DeviceInfo) β the Dynan-SE2 the device object to open and configure
config (Dynapse2Configuration) β a Dynan-SE2
samna
configuration objectinput_channel_map (Dict[int, List[Dynapse2Destination]]) β the mapping between input timeseries channels and the destinations
dt (float, optional) β the simulation timestep resolution, defaults to 1e-3
dt_fpga (float, optional) β the FPGA timestep resolution, defaults to 1e-6
control_tag (int, optional) β a tag used in special occacions such as current time reading. Do not capture events with this tag and control_hop, defaults to 2047
control_hop (int, optional) β a chip position (-7 means x_hop=-7, y_hop=-7) which does not really exist, works in cooperation with control_tag. Do not capture events coming from this hop and control tag, defauts to -7.
Attributes overview
Class name of
self
the configuration object stored on the Dynap-SE2 board
The full name of this module (class plus module name)
the HDK model object that can be used to configure the device
The name of this module, or an empty string if
None
The shape of this module
(DEPRECATED) The output size of this module
The input size of this module
The output size of this module
If
True
, this module receives spiking input.If
True
, this module sends spiking output.the simulation timestep resolution
the FPGA timestep resolution
a tag used in special occacions such as current time reading.
a chip position (-7 means x_hop=-7, y_hop=-7) which does not really exist, works in cooperation with control_tag.
the mapping between input timeseries channels and the destinations
a configured samna Dynan-SE2 interface node
Dynapse2Interface
the samna configuration object deployed to the chip
a dummy object to discharge all the capacitors on chip
Methods overview
__init__
(device,Β config,Β input_channel_map)__init__ initializes
DynapseSamna
module.apply_config writes the configuration object to the device
as_graph
()Convert this module to a computational graph
attributes_named
(name)Search for attributes of this or submodules by time
current_timestamp
([timeout,Β poll_step])current_timestamp bounces a dummy event from FPGA to get the exact FPGA time at that moment.
discharge_capacitors applies the leaky configuration object to the hardware model in order to discharge all the capacitors
disconnect breaks the connection between CPU and the device
evolve
(input_data[,Β read_timeout,Β offset,Β ...])evolve simulates the network on Dynap-SE2 HDK in real-time The function first converts raster plot to a sequence of AER packages and dispatches to the device.
modules
()Return a dictionary of all sub-modules of this module
parameters
([family])Return a nested dictionary of module and submodule Parameters
Reset all parameters in this module
Reset the state of this module
set_attributes
(new_attributes)Set the attributes and sub-module attributes from a dictionary
simulation_parameters
([family])Return a nested dictionary of module and submodule SimulationParameters
state
([family])Return a nested dictionary of module and submodule States
timed
([output_num,Β dt,Β add_events])Convert this module to a
TimedModule
- __aer_to_raster(buffer: List[NormalGridEvent], stop_time: float, start_time: float = 0) Tuple[ndarray, Dict[int, Dynapse2Destination]] ο
__aer_to_raster converts a list of Dynap-SE2 AER packages to a discrete raster record The events does not meet the start and stop time criteria are descarded
- Parameters:
buffer (List[NormalGridEvent]) β the event buffer, a list of Dynap-SE2 AER packages
stop_time (float) β the stop time cut-off for the events.
start_time β the start time cut-off for the events, defaults to 0
- Returns:
ts, cmap raster_out: the raster record referenced on the event buffer cmap: the mapping between raster channels and the destinations
- Return type:
Tuple[np.ndarray, Dict[int, Dynapse2Destination]]
- __configure_dynapse2_fpga(device: DeviceInfo, bitfile: str | None = None) Dynapse2Interface ο
configure_dynapse2_fpga configures the FPGA on board and builds a connection node between CPU and the device. It allows one to configure the device, read or write AER events to bus, and monitor the activity of device neurons
- Parameters:
device (DeviceInfo) β the device object to open and configure
bitfile (Optional[str], optional) β the bitfile path if known, defaults to None
- Raises:
IOError β Failed to configure Opal Kelly
- Returns:
an open and configured Dynan-SE2 interface node
- Return type:
Dynapse2Interface
- __control_event(event_time: float = 0.0) NormalGridEvent ο
__control_event generates a dummy event to be bounced back from the FPGA This event helps to read the current FPGA time or understand the simulation is done
- Parameters:
event_time (float) β the time that the event happened in seconds
- Returns:
a virtual samna AER package for control
- Return type:
NormalGridEvent
- __control_sequence(event_time: float = 0.0, num_events: int = 3) List[NormalGridEvent] ο
__control_sequence creates a sequence of control events. In general, one control event is not enough because it can easily get lost.
- Parameters:
num_events (int, optional) β number of event to append to the list, defaults to 3
- Returns:
a sequence of control events
- Return type:
List[NormalGridEvent]
- __default_channel_map(num_channels: int) Dict[int, Dynapse2Destination] ο
__default_channel_map creates a dummy channel map which helps to bounce the AER events back from the FPGA
- Parameters:
num_channels (int) β number of input channels
- Returns:
a channel map which assigns the neuron ids as tags, and use the control hop to bounce the neurons
- Return type:
Dict[int, Dynapse2Destination]
- __event_generator(event_time: float, core: List[bool] = [True, True, True, True], x_hop: int = -7, y_hop: int = -7, tag: uint64 = 2047) NormalGridEvent ο
__event_generator can be used to generate dummy events
- Parameters:
event_time (float) β the time that the event happened in seconds
core (List[bool], optional) β the core mask used while sending the events, defaults to [True, True, True, True] [1,1,1,1] means all 4 cores are on the target [0,0,1,0] means the event will arrive at core 2 only
x_hop (int, optional) β number of chip hops on x axis, defaults -7
y_hop (int, optional) β number of chip hops on y axis, defaults to -7
tag (np.uint, optional) β globally multiplexed locally unique event tag which is used to identify the connection between two neurons, defaults to 2047
- Returns:
a virtual samna AER package for DynapSE2
- Return type:
NormalGridEvent
- __extract_channel_map(buffer: List[NormalGridEvent]) Dict[int, Dynapse2Destination] ο
extract_channel_map obtains a channel map from a list of dummy AER packages (samna alias)
- Parameters:
buffer (List[NormalGridEvent]) β the list of AER packages
- Returns:
the mapping between timeseries channels and the destinations
- Return type:
Dict[int, Dynapse2Destination]
- __get_leaky_config() Dynapse2Configuration ο
get_leaky_config returns a configuration object to discharge all the capacitors on chip
- __if_control_event(event: NormalGridEvent) bool ο
__if_control_event returns true if the event is a control event which is bounced back from FPGA
- Parameters:
event (NormalGridEvent) β any Dynap-SE2 AER package to check
- Returns:
true if the package is a control event bounced back from FPGA
- Return type:
bool
- __init__(device: DeviceInfo, config: Dynapse2Configuration, input_channel_map: Dict[int, List[Dynapse2Destination]], dt: float = 0.001, dt_fpga: float = 1e-06, control_tag: int = 2047, control_hop: int = -7, *args, **kwargs) None [source]ο
__init__ initializes
DynapseSamna
module. Parameters are explained in the class docstring.
- __poll_events(duration: float, poll_step: float = 0.001) Tuple[List[NormalGridEvent], bool, float] ο
__poll_events records the deviceβs output and stores in an event buffer
- Parameters:
duration (float) β the maximum duration that the events will be captured
poll_step (float, optional) β the pollling step, 1 ms means the CPU fetches events from FPGA in every 1 ms, defaults to 1e-3
- Returns:
output_events, done, t_done :output_events: the event buffer, a list of Dynap-SE2 AER packages captured :done: a bloolean flag indicating if all the events read or not :t_done: the time in seconds that the reading is done.
- Return type:
Tuple[List[NormalGridEvent], bool, float]
- __raster_to_aer(raster: ndarray, start_time: float = 0.0) List[NormalGridEvent] ο
__raster_to_aer converts a discrete raster record to a list of AER packages. It uses a channel map to map the channels to destinations, and by default it returns a list of samna objects.
- Parameters:
raster (np.ndarray) β the discrete timeseries to be converted into list of Dynap-SE2 AER packages
start_time (float) β the start time of the record in seconds, defaults to 0.0
- Raises:
ValueError β Raster should be 2 dimensional!
ValueError β Channel map does not map the channels of the timeseries provided!
- Returns:
a list of Dynap-SE2 AER packages
- Return type:
List[NormalGridEvent]
- _abc_impl = <_abc._abc_data object>ο
- _auto_batch(data: ndarray, states: Tuple = (), target_shapes: Tuple | None = None) Tuple[ndarray, Tuple[ndarray]] ο
Automatically replicate states over batches and verify input dimensions
Examples
>>> data, (state0, state1, state2) = self._auto_batch(data, (self.state0, self.state1, self.state2))
This will verify that
data
has the correct final dimension (i.e.self.size_in
).If
data
has only two dimensions(T, Nin)
, then it will be augmented to(1, T, Nin)
. The individual states will be replicated out from shape(a, b, c, ...)
to(n_batches, a, b, c, ...)
and returned.If
data
has only a single dimension(T,)
, it will be expanded to(1, T, self.size_in)
.state0
,state1
,state2
will be replicated out along the batch dimension.>>> data, (state0,) = self._auto_batch(data, (self.state0,), ((10, -1, self.size_in),))
Attempt to replicate
state0
to a specified size(10, -1, self.size_in)
.- Parameters:
data (np.ndarray) β Input data tensor. Either
(batches, T, Nin)
or(T, Nin)
states (Tuple) β Tuple of state variables. Each will be replicated out over batches by prepending a batch dimension
target_shapes (Tuple) β A tuple of target size tuples, each corresponding to each state argument. The individual states will be replicated out to match the corresponding target sizes. If not provided (the default), then states will be only replicated along batches.
- Returns:
(np.ndarray, Tuple[np.ndarray]) data, states
- _force_set_attributesο
(bool) If
True
, do not sanity-check attributes when setting.
- _get_attribute_family(type_name: str, family: Tuple | List | str | None = None) dict ο
Search for attributes of this module and submodules that match a given family
This method can be used to conveniently get all weights for a network; or all time constants; or any other family of parameters. Parameter families are defined simply by a string:
"weights"
for weights;"taus"
for time constants, etc. These strings are arbitrary, but if you follow the conventions then future developers will thank you (that includes you in six monthβs time).- Parameters:
type_name (str) β The class of parameters to search for. Must be one of
["Parameter", "SimulationParameter", "State"]
or another future subclass ofParameterBase
family (Union[str, Tuple[str]]) β A string or list or tuple of strings, that define one or more attribute families to search for
- Returns:
A nested dictionary of attributes that match the provided
type_name
andfamily
- Return type:
dict
- _get_attribute_registry() Tuple[Dict, Dict] ο
Return or initialise the attribute registry for this module
- Returns:
registered_attributes, registered_modules
- Return type:
(tuple)
- _has_registered_attribute(name: str) bool ο
Check if the module has a registered attribute
- Parameters:
name (str) β The name of the attribute to check
- Returns:
True
if the attributename
is in the attribute registry,False
otherwise.- Return type:
bool
- _in_Module_initο
(bool) If exists and
True
, indicates that the module is in the__init__
chain.
- _name: str | Noneο
Name of this module, if assigned
- _register_attribute(name: str, val: ParameterBase)ο
Record an attribute in the attribute registry
- Parameters:
name (str) β The name of the attribute to register
val (ParameterBase) β The
ParameterBase
subclass object to register. e.g.Parameter
,SimulationParameter
orState
.
- _register_module(name: str, mod: ModuleBase)ο
Register a sub-module in the module registry
- Parameters:
name (str) β The name of the module to register
mod (ModuleBase) β The
ModuleBase
object to register
- _reset_attribute(name: str) ModuleBase ο
Reset an attribute to its initialisation value
- Parameters:
name (str) β The name of the attribute to reset
- Returns:
For compatibility with the functional API
- Return type:
self (
Module
)
- _shapeο
The shape of this module
- _spiking_input: boolο
Whether this module receives spiking input
- _spiking_output: boolο
Whether this module produces spiking output
- _submodulenames: List[str]ο
Registry of sub-module names
- _wrap_recorded_state(recorded_dict: dict, t_start: float) Dict[str, TimeSeries] ο
Convert a recorded dictionary to a
TimeSeries
representationThis method is optional, and is provided to make the
timed()
conversion to aTimedModule
work better. You should override this method in your customModule
, to wrap each element of your recorded state dictionary as aTimeSeries
- Parameters:
state_dict (dict) β A recorded state dictionary as returned by
evolve()
t_start (float) β The initial time of the recorded state, to use as the starting point of the time series
- Returns:
The mapped recorded state dictionary, wrapped as
TimeSeries
objects- Return type:
Dict[str, TimeSeries]
- app_configο
the samna configuration object deployed to the chip
- as_graph() GraphModuleBase ο
Convert this module to a computational graph
- Returns:
The computational graph corresponding to this module
- Return type:
- Raises:
NotImplementedError β If
as_graph()
is not implemented for this subclass
- attributes_named(name: Tuple[str] | List[str] | str) dict ο
Search for attributes of this or submodules by time
- Parameters:
name (Union[str, Tuple[str]) β The name of the attribute to search for
- Returns:
A nested dictionary of attributes that match
name
- Return type:
dict
- board: Dynapse2Interfaceο
a configured samna Dynan-SE2 interface node
Dynapse2Interface
- property class_name: strο
Class name of
self
- Type:
str
- property config: Dynapse2Configurationο
the configuration object stored on the Dynap-SE2 board
- control_hopο
a chip position (-7 means x_hop=-7, y_hop=-7) which does not really exist, works in cooperation with control_tag. Do not capture events coming from this hop and control tag
- control_tagο
a tag used in special occacions such as current time reading. Do not capture events with this tag and control_hop
- current_timestamp(timeout: float = 20.0, poll_step: float = 0.001) float [source]ο
current_timestamp bounces a dummy event from FPGA to get the exact FPGA time at that moment.
- Parameters:
timeout (float, optional) β the maximum timeout limit in seconds, defaults to 20.0
poll_step (float, optional) β the pollling step, 1 ms means the CPU fetches events from FPGA in every 1 ms, defaults to 1e-3
- Raises:
TimeoutError β FPGA could not respond in {timeout} seconds!
- Returns:
the current FPGA time in seconds
- Return type:
float
- discharge_capacitors() None [source]ο
discharge_capacitors applies the leaky configuration object to the hardware model in order to discharge all the capacitors
- dtο
the simulation timestep resolution
- dt_fpgaο
the FPGA timestep resolution
- evolve(input_data: ndarray, read_timeout: float = 60.0, offset: float = 0.1, poll_step: float = 0.001, record: bool = False) Tuple[ndarray, Dict, Dict] [source]ο
evolve simulates the network on Dynap-SE2 HDK in real-time The function first converts raster plot to a sequence of AER packages and dispatches to the device. Then reads the output buffers
- Parameters:
input_data (np.ndarray) β A raster
(T, Nin)
specifying for each bin the number of input events sent to the corresponding input channel on Dynap-SE2, at the corresponding time point.read_timeout (float, optional) β the maximum time to wait until reading finishes, defaults to 60.0
offset (float, optional) β user defined start time offset in seconds, defaults to 100e-3
poll_step (float, optional) β the pollling step, 1 ms means the CPU fetches events from FPGA in every 1 ms, defaults to 1e-3
record (bool, optional) β record the states in each timestep of evolution or not, defaults to False
- Returns:
spikes_ts, states, record_dict :spikes_ts: is an array with shape
(T, Nrec)
containing the output data(spike raster) produced by the module. :states: is a dictionary containing the updated module state following evolution. :record_dict: is a dictionary containing the recorded state variables during the evolution at each time step, if therecord
argument isTrue
else empty dictionary {}- Return type:
Tuple[np.ndarray, Dict, Dict]
- property full_name: strο
The full name of this module (class plus module name)
- Type:
str
- input_channel_mapο
the mapping between input timeseries channels and the destinations
- leaky_configο
a dummy object to discharge all the capacitors on chip
- property model: Dynapse2Modelο
the HDK model object that can be used to configure the device
- modules() Dict ο
Return a dictionary of all sub-modules of this module
- Returns:
A dictionary containing all sub-modules. Each item will be named with the sub-module name.
- Return type:
dict
- property name: strο
The name of this module, or an empty string if
None
- Type:
str
- parameters(family: Tuple | List | str | None = None) Dict ο
Return a nested dictionary of module and submodule Parameters
Use this method to inspect the Parameters from this and all submodules. The optional argument
family
allows you to search for Parameters in a particular family β for example"weights"
for all weights of this module and nested submodules.Although the
family
argument is an arbitrary string, reasonable choises are"weights"
,"taus"
for time constants,"biases"
for biasesβ¦Examples
Obtain a dictionary of all Parameters for this module (including submodules):
>>> mod.parameters() dict{ ... }
Obtain a dictionary of Parameters from a particular family:
>>> mod.parameters("weights") dict{ ... }
- Parameters:
family (str) β The family of Parameters to search for. Default:
None
; return all parameters.- Returns:
A nested dictionary of Parameters of this module and all submodules
- Return type:
dict
- reset_parameters()ο
Reset all parameters in this module
- Returns:
The updated module is returned for compatibility with the functional API
- Return type:
- reset_state() ModuleBase ο
Reset the state of this module
- Returns:
The updated module is returned for compatibility with the functional API
- Return type:
- set_attributes(new_attributes: dict) ModuleBase ο
Set the attributes and sub-module attributes from a dictionary
This method can be used with the dictionary returned from module evolution to set the new state of the module. It can also be used to set multiple parameters of a module and submodules.
Examples
Use the functional API to evolve, obtain new states, and set those states:
>>> _, new_state, _ = mod(input) >>> mod = mod.set_attributes(new_state)
Obtain a parameter dictionary, modify it, then set the parameters back:
>>> params = mod.parameters() >>> params['w_input'] *= 0. >>> mod.set_attributes(params)
- Parameters:
new_attributes (dict) β A nested dictionary containing parameters of this module and sub-modules.
- property shape: tupleο
The shape of this module
- Type:
tuple
- simulation_parameters(family: Tuple | List | str | None = None) Dict ο
Return a nested dictionary of module and submodule SimulationParameters
Use this method to inspect the SimulationParameters from this and all submodules. The optional argument
family
allows you to search for SimulationParameters in a particular family.Examples
Obtain a dictionary of all SimulationParameters for this module (including submodules):
>>> mod.simulation_parameters() dict{ ... }
- Parameters:
family (str) β The family of SimulationParameters to search for. Default:
None
; return all SimulationParameter attributes.- Returns:
A nested dictionary of SimulationParameters of this module and all submodules
- Return type:
dict
- property size: intο
(DEPRECATED) The output size of this module
- Type:
int
- property size_in: intο
The input size of this module
- Type:
int
- property size_out: intο
The output size of this module
- Type:
int
- property spiking_input: boolο
If
True
, this module receives spiking input. IfFalse
, this module expects continuous input.- Type:
bool
- property spiking_outputο
If
True
, this module sends spiking output. IfFalse
, this module sends continuous output.- Type:
bool
- state(family: Tuple | List | str | None = None) Dict ο
Return a nested dictionary of module and submodule States
Use this method to inspect the States from this and all submodules. The optional argument
family
allows you to search for States in a particular family.Examples
Obtain a dictionary of all States for this module (including submodules):
>>> mod.state() dict{ ... }
- Parameters:
family (str) β The family of States to search for. Default:
None
; return all State attributes.- Returns:
A nested dictionary of States of this module and all submodules
- Return type:
dict
- timed(output_num: int = 0, dt: float | None = None, add_events: bool = False)ο
Convert this module to a
TimedModule
- Parameters:
output_num (int) β Specify which output of the module to take, if the module returns multiple output series. Default:
0
, take the first (or only) output.dt (float) β Used to provide a time-step for this module, if the module does not already have one. If
self
already defines a time-step, thenself.dt
will be used. Default:None
add_events (bool) β Iff
True
, theTimedModule
will add events occurring on a single timestep on input and output. Default:False
, donβt add time steps.
Returns:
TimedModule
: A timed module that wraps this module