API reference

Main

nengo_loihi.Simulator(network[, dt, seed, …])

Nengo Loihi simulator for Loihi hardware and emulator.

nengo_loihi.add_params(network)

Add nengo_loihi config option to network.

nengo_loihi.BlockShape(shape, …)

Specifies how an ensemble should be split across Loihi neuron cores.

nengo_loihi.set_defaults()

Modify Nengo’s default parameters for better performance with Loihi.

class nengo_loihi.Simulator(network, dt=0.001, seed=None, model=None, precompute=None, target=None, progress_bar=None, remove_passthrough=True, hardware_options=None)[source]

Nengo Loihi simulator for Loihi hardware and emulator.

The simulator takes a nengo.Network and builds internal data structures to run the model defined by that network on Loihi emulator or hardware. Run the simulator with the Simulator.run method, and access probed data through the data attribute.

Building and running the simulation allocates resources. To properly free these resources, call the Simulator.close method. Alternatively, Simulator.close will automatically be called if you use with syntax:

with nengo_loihi.Simulator(my_network) as sim:
    sim.run(0.1)
print(sim.data[my_probe])

Note that the data attribute is still accessible even when a simulator has been closed. Running the simulator, however, will raise an error.

Parameters
networkNetwork

A network object to be built and then simulated. If None, then the model parameter must be provided instead.

dtfloat, optional (Default: 0.001)

The length of a simulator timestep, in seconds.

seedint, optional (Default: None)

A seed for all stochastic operators used in this simulator. Will be set to network.seed + 1 if not given.

modelModel, optional (Default: None)

A Model that contains build artifacts to be simulated. Usually the simulator will build this model for you; however, if you want to build the network manually, or you want to inject build artifacts in the model before building the network, then you can pass in a Model instance.

precomputebool, optional (Default: None)

Whether model inputs should be precomputed to speed up simulation. When precompute is False, the simulator will be run one step at a time in order to use model outputs as inputs in other parts of the model. By default, the simulator will choose True if it works for your model, and False otherwise.

targetstr, optional (Default: None)

Whether the simulator should target the emulator ('sim') or Loihi hardware ('loihi'). If None, target will default to 'loihi' if NxSDK is installed, and the emulator if it is not.

hardware_optionsdict, optional (Default: {})

Dictionary of additional configuration for the hardware. See hardware.HardwareInterface for possible parameters.

Attributes
closedbool

Whether the simulator has been closed. Once closed, it cannot be reopened.

dataProbeDict

The dictionary mapping from Nengo objects to the data associated with those objects. In particular, each nengo.Probe maps to the data probed while running the simulation.

modelModel

The Model containing the data structures necessary for simulating the network.

precomputebool

Whether model inputs should be precomputed to speed up simulation. When precompute is False, the simulator will be run one step at a time in order to use model outputs as inputs in other parts of the model.

property dt

(float) The step time of the simulator.

property n_steps

(int) The current time step of the simulator.

property time

(float) The current time of the simulator.

close(self)[source]

Closes the simulator.

Any call to Simulator.run, Simulator.run_steps, Simulator.step, and Simulator.reset on a closed simulator raises a SimulatorClosed exception.

reset(self, seed=None)[source]

Reset the simulator state.

Parameters
seedint, optional

A seed for all stochastic operators used in the simulator. This will change the random sequences generated for noise or inputs (e.g. from processes), but not the built objects (e.g. ensembles, connections).

run(self, time_in_seconds)[source]

Simulate for the given length of time.

If the given length of time is not a multiple of dt, it will be rounded to the nearest dt. For example, if dt is 0.001 and run is called with time_in_seconds=0.0006, the simulator will advance one timestep, resulting in the actual simulator time being 0.001.

The given length of time must be positive. The simulator cannot be run backwards.

Parameters
time_in_secondsfloat

Amount of time to run the simulation for. Must be positive.

run_steps(self, steps)[source]

Simulate for the given number of dt steps.

Parameters
stepsint

Number of steps to run the simulation for.

step(self)[source]

Advance the simulator by 1 step (dt seconds).

trange(self, sample_every=None, dt=None)[source]

Create a vector of times matching probed data.

Note that the range does not start at 0 as one might expect, but at the first timestep (i.e., dt).

Parameters
sample_everyfloat, optional (Default: None)

The sampling period of the probe to create a range for. If None, a time value for every dt will be produced.

nengo_loihi.add_params(network)[source]

Add nengo_loihi config option to network.

The following options will be added:

nengo.Ensemble
  • on_chip: Whether the ensemble should be simulated on a Loihi chip. Marking specific ensembles for simulation off of a Loihi chip can help with debugging.

  • block_shape: Specifies how this ensemble should be split across Loihi neuron cores. See BlockShape for more details.

nengo.Connection
  • pop_type: The axon format when using population spikes, which are only used for convolutional connections. Must be an int between 16 and 32. By default, we use pop_type 32.

Examples

>>> with nengo.Network() as model:
...     ens = nengo.Ensemble(10, dimensions=1)
...     # By default, ens will be placed on a Loihi chip
...     nengo_loihi.add_params(model)
...     model.config[ens].on_chip = False
...     # Now it will be simulated with Nengo
class nengo_loihi.BlockShape(shape, ensemble_shape_or_transform)[source]

Specifies how an ensemble should be split across Loihi neuron cores.

Each neuron core can have, at most, 1024 compartments. Ensembles with more than 1024 neurons are automatically split such that they will be distributed evenly across as few cores as possible.

This class allows you to split a smaller ensemble onto multiple cores. It also allows you to control the splitting process for any ensemble, which is particularly useful when that ensemble participates in a convolutional connection.

Parameters
shapetuple of int

The conceptual shape of the compartments on each core after splitting. This tuple must have the same number of elements as ensemble_shape.

ensemble_shape_or_transformtuple of int or nengo.Convolution

The conceptual shape of the neurons in the ensemble. If a nengo.Convolution instance is passed, the conceptual shape is inferred automatically.

Examples

Split an ensemble across two Loihi blocks.

with nengo.Network() as net:
    nengo_loihi.add_params(net)
    ens = nengo.Ensemble(10, 1)
    net.config[ens].block_shape = nengo_loihi.BlockShape((5,), (10,))
print(net.config[ens].block_shape.n_splits)
2

Interpret an ensemble as a two dimensional layer and split into four blocks.

with nengo.Network() as net:
    nengo_loihi.add_params(net)
    ens = nengo.Ensemble(16, 1)
    net.config[ens].block_shape = nengo_loihi.BlockShape((2, 2), (4, 4))
print(net.config[ens].block_shape.n_splits)
4
Attributes
shapetuple of int

The conceptual shape of the compartments on each core after splitting.

ensemble_shapetuple of int

The conceptual shape of the neurons in the ensemble.

nengo_loihi.set_defaults()[source]

Modify Nengo’s default parameters for better performance with Loihi.

The following defaults will be modified:

nengo.Ensemble
  • max_rates: Set to Uniform(low=100, high=120)

  • intercepts: Set to Uniform(low=-0.5, high=0.5)

Neurons

nengo_loihi.neurons.LoihiLIF([tau_rc, …])

Simulate LIF neurons as done by Loihi.

nengo_loihi.neurons.LoihiSpikingRectifiedLinear([…])

Simulate spiking rectified linear neurons as done by Loihi.

nengo_loihi.neurons.NeuronOutputNoise

Noise added to the output of a rate neuron.

nengo_loihi.neurons.LowpassRCNoise(tau_s)

Noise model combining Lowpass synapse and neuron membrane filters.

nengo_loihi.neurons.AlphaRCNoise(tau_s)

Noise model combining Alpha synapse and neuron membrane filters.

class nengo_loihi.neurons.LoihiLIF(tau_rc=0.02, tau_ref=0.002, min_voltage=0, amplitude=1, nengo_dl_noise=None)[source]

Simulate LIF neurons as done by Loihi.

On Loihi, the inter-spike interval has to be an integer. This causes aliasing the firing rates where a wide variety of inputs can produce the same output firing rate. This class reproduces this effect, as well as the discretization of some of the neuron parameters. It can be used in e.g. nengo or nengo_dl to reproduce these unique Loihi effects.

Parameters
nengo_dl_noiseNeuronOutputNoise

Noise added to the rate-neuron output when training with this neuron type in nengo_dl.

rates(self, x, gain, bias, dt=0.001)[source]

Always use LIFRate to determine rates.

step_math(self, dt, J, spiked, voltage, refractory_time)[source]

Implement the LIFRate nonlinearity.

class nengo_loihi.neurons.LoihiSpikingRectifiedLinear(amplitude=1)[source]

Simulate spiking rectified linear neurons as done by Loihi.

On Loihi, the inter-spike interval has to be an integer. This causes aliasing in the firing rates such that a wide variety of inputs produce the same output firing rate. This class reproduces this effect. It can be used in e.g. nengo or nengo_dl to reproduce these unique Loihi effects.

rates(self, x, gain, bias, dt=0.001)[source]

Use RectifiedLinear to determine rates.

step_math(self, dt, J, spiked, voltage)[source]

Implement the integrate and fire nonlinearity.

class nengo_loihi.neurons.NeuronOutputNoise[source]

Noise added to the output of a rate neuron.

Often used when training deep networks with rate neurons for final implementation in spiking neurons to simulate the variability caused by spiking.

class nengo_loihi.neurons.LowpassRCNoise(tau_s)[source]

Noise model combining Lowpass synapse and neuron membrane filters.

Samples “noise” (i.e. variability) from a regular spike train filtered by the following transfer function, where \(\tau_{rc}\) is the membrane time constant and \(\tau_s\) is the synapse time constant:

\[H(s) = [(\tau_s s + 1) (\tau_{rc} s + 1)]^{-1}\]

See [1] for background and derivations.

References

1

E. Hunsberger (2018) “Spiking Deep Neural Networks: Engineered and Biological Approaches to Object Recognition.” PhD thesis. pp. 106–113. (http://compneuro.uwaterloo.ca/publications/hunsberger2018.html)

Attributes
tau_sfloat

Time constant for Lowpass synaptic filter.

class nengo_loihi.neurons.AlphaRCNoise(tau_s)[source]

Noise model combining Alpha synapse and neuron membrane filters.

Samples “noise” (i.e. variability) from a regular spike train filtered by the following transfer function, where \(\tau_{rc}\) is the membrane time constant and \(\tau_s\) is the synapse time constant:

\[H(s) = [(\tau_s s + 1)^2 (\tau_{rc} s + 1)]^{-1}\]

See [1] for background and derivations.

References

1

E. Hunsberger (2018) “Spiking Deep Neural Networks: Engineered and Biological Approaches to Object Recognition.” PhD thesis. pp. 106–113. (http://compneuro.uwaterloo.ca/publications/hunsberger2018.html)

Attributes
tau_sfloat

Time constant for Alpha synaptic filter.

Decode neurons

Decode neurons facilitate NEF-style connections on the chip. The type of decode neurons used by a model can be set on builder.Model.

nengo_loihi.decode_neurons.DecodeNeurons([dt])

Defines parameters for a group of decode neurons.

nengo_loihi.decode_neurons.OnOffDecodeNeurons([…])

One or more pairs of on/off neurons per dimension.

nengo_loihi.decode_neurons.NoisyDecodeNeurons(…)

Uses multiple on/off neuron pairs per dimension, plus noise.

nengo_loihi.decode_neurons.Preset5DecodeNeurons([…])

Uses five heterogeneous on/off pairs with pre-set values per dimension.

nengo_loihi.decode_neurons.Preset10DecodeNeurons([…])

Uses ten heterogeneous on/off pairs with pre-set values per dimension.

class nengo_loihi.decode_neurons.DecodeNeurons(dt=0.001)[source]

Defines parameters for a group of decode neurons.

DecodeNeurons are used on the chip to facilitate NEF-style connections, where activities from a neural ensemble are first transformed into a decoded value (which is stored in the activities and synapses of the spiking decode neurons), before being passed on to another ensemble (via that ensemble’s encoders).

Parameters
dtfloat

Time step used by the simulator.

get_block(self, weights, block_label=None, syn_label=None)[source]

Get a LoihiBlock for implementing neurons on the chip.

Parameters
weights(n, d) ndarray

Weights that project the n inputs to the d dimensions represented by these neurons. Typically, the inputs will be neurons belonging to an Ensemble, and these weights will be decoders.

block_labelstring (Default: None)

Optional label for the LoihiBlock.

syn_labelstring (Default: None)

Optional label for the Synapse.

Returns
blockLoihiBlock

The neurons on the chip.

synSynapse

The synapses connecting into the chip neurons.

get_ensemble(self, dim, add_to_container=True)[source]

Get a Nengo Ensemble for implementing neurons on the host.

Parameters
dimint

Number of dimensions to be represented by these neurons.

add_to_containerbool, optional (Default: True)

Whether to add the ensemble to the currently active network.

Returns
ensEnsemble

An Ensemble for implementing these neurons in a Nengo network.

get_post_encoders(self, encoders)[source]

Encoders for post population that these neurons connect in to.

Parameters
encoders(n, d) ndarray

Regular scaled encoders for the ensemble, which map the ensemble’s d input dimensions to its n neurons.

Returns
decode_neuron_encoders(?, n) ndarray

Encoders for mapping these neurons to the post-ensemble’s neurons. The number of rows depends on how get_post_inds is being used (i.e. there could be one row per neuron in this block, or there could be fewer rows with get_post_inds mapping multiple neurons to each row).

get_post_inds(self, inds, d)[source]

Indices for mapping neurons to post-encoder dimensions.

Parameters
indslist of ints

Indices for mapping decode neuron dimensions to post-ensemble dimensions. Usually, this will be determined by a slice on the post ensemble in a connection (which maps the output of the transform/function to select dimensions on the post ensemble).

dint

Number of dimensions in the post-ensemble.

class nengo_loihi.decode_neurons.OnOffDecodeNeurons(pairs_per_dim=1, dt=0.001, rate=None, is_input=False)[source]

One or more pairs of on/off neurons per dimension.

In this class itself, all the pairs in a dimension are identical. It can still be advantageous to have more than one pair per dimension, though, since this can allow all neurons to have lower firing rates and thus act more linearly (due to period aliasing at high firing rates). Subclasses may use pairs that are not identical (by adding noise or heterogeneity).

Parameters
pairs_per_dimint

Number of repeated neurons per dimension. Currently, all DecodeNeuron classes use separate on/off neuron pairs for each dimension. This is the number of such pairs per dimension.

dtfloat

Time step used by the simulator.

ratefloat (Default: None)

Max firing rate of each neuron. By default, this is chosen so that the sum of all repeated neuron rates is 1. / dt, and thus as a group the neurons average one spike per timestep.

is_inputbool (Default: False)

Whether these decode neurons are being used to provide input.

get_block(self, weights, block_label=None, syn_label=None)[source]

Get a LoihiBlock for implementing neurons on the chip.

Parameters
weights(n, d) ndarray

Weights that project the n inputs to the d dimensions represented by these neurons. Typically, the inputs will be neurons belonging to an Ensemble, and these weights will be decoders.

block_labelstring (Default: None)

Optional label for the LoihiBlock.

syn_labelstring (Default: None)

Optional label for the Synapse.

Returns
blockLoihiBlock

The neurons on the chip.

synSynapse

The synapses connecting into the chip neurons.

get_ensemble(self, dim, add_to_container=True)[source]

Get a Nengo Ensemble for implementing neurons on the host.

Parameters
dimint

Number of dimensions to be represented by these neurons.

add_to_containerbool, optional (Default: True)

Whether to add the ensemble to the currently active network.

Returns
ensEnsemble

An Ensemble for implementing these neurons in a Nengo network.

get_post_encoders(self, encoders)[source]

Encoders for post population that these neurons connect in to.

Parameters
encoders(n, d) ndarray

Regular scaled encoders for the ensemble, which map the ensemble’s d input dimensions to its n neurons.

Returns
decode_neuron_encoders(?, n) ndarray

Encoders for mapping these neurons to the post-ensemble’s neurons. The number of rows depends on how get_post_inds is being used (i.e. there could be one row per neuron in this block, or there could be fewer rows with get_post_inds mapping multiple neurons to each row).

get_post_inds(self, inds, d)[source]

Indices for mapping neurons to post-encoder dimensions.

Parameters
indslist of ints

Indices for mapping decode neuron dimensions to post-ensemble dimensions. Usually, this will be determined by a slice on the post ensemble in a connection (which maps the output of the transform/function to select dimensions on the post ensemble).

dint

Number of dimensions in the post-ensemble.

class nengo_loihi.decode_neurons.NoisyDecodeNeurons(pairs_per_dim, dt=0.001, rate=None, noise_exp=- 2.0)[source]

Uses multiple on/off neuron pairs per dimension, plus noise.

The noise allows each on-off neuron pair to do something different. The population average is a better representation of the encoded value than can be achieved with a single on/off neuron pair (if the magnitude of the noise is correctly calibrated).

Parameters
pairs_per_dimint

Number of repeated neurons per dimension. Currently, all DecodeNeuron classes use separate on/off neuron pairs for each dimension. This is the number of such pairs per dimension.

dtfloat

Time step used by the simulator.

ratefloat (Default: None)

Max firing rate of each neuron. By default, this is chosen so that the sum of all repeated neuron rates is 1. / dt, and thus as a group the neurons average one spike per timestep.

noise_expfloat, optional (Default: -2.)

Base-10 exponent for noise added to neuron voltages.

get_block(self, weights, block_label=None, syn_label=None)[source]

Get a LoihiBlock for implementing neurons on the chip.

Parameters
weights(n, d) ndarray

Weights that project the n inputs to the d dimensions represented by these neurons. Typically, the inputs will be neurons belonging to an Ensemble, and these weights will be decoders.

block_labelstring (Default: None)

Optional label for the LoihiBlock.

syn_labelstring (Default: None)

Optional label for the Synapse.

Returns
blockLoihiBlock

The neurons on the chip.

synSynapse

The synapses connecting into the chip neurons.

class nengo_loihi.decode_neurons.Preset5DecodeNeurons(dt=0.001, rate=None)[source]

Uses five heterogeneous on/off pairs with pre-set values per dimension.

The script for configuring these values can be found at:

nengo-loihi-sandbox/utils/interneuron_unidecoder_design.py

class nengo_loihi.decode_neurons.Preset10DecodeNeurons(dt=0.001, rate=None)[source]

Uses ten heterogeneous on/off pairs with pre-set values per dimension.

The script for configuring these values can be found at:

nengo-loihi-sandbox/utils/interneuron_unidecoder_design.py

Builder

The builder turns a Nengo network into a builder.Model appropriate for running on Loihi. This model is mainly composed of LoihiBlock objects, which map parts of the network to Loihi compartments, axons, and synapses. The model also contains LoihiInput objects to provide input, and LoihiProbe objects to collect output.

nengo_loihi.builder.Model([dt, label, builder])

The data structure for the emulator/hardware simulator.

nengo_loihi.builder.Builder

Fills in the Loihi Model object based on the Nengo Network.

nengo_loihi.block.LoihiBlock(n_neurons[, label])

Class holding Loihi objects that can be placed on the chip.

nengo_loihi.block.Compartment(n_compartments)

Stores information for configuring Loihi compartments.

nengo_loihi.block.Axon(n_axons[, label])

A group of axons targeting a specific Synapse object.

nengo_loihi.block.Synapse(n_axons[, label])

A group of Loihi synapses that share some properties.

nengo_loihi.inputs.LoihiInput([label])

nengo_loihi.inputs.SpikeInput(n_neurons[, label])

nengo_loihi.probe.LoihiProbe([target, key, …])

Record data from one or more LoihiBlock target states.

class nengo_loihi.builder.Model(dt=0.001, label=None, builder=None)[source]

The data structure for the emulator/hardware simulator.

Defines methods for adding inputs, blocks and probes. Also handles build functions, and information associated with building the Nengo model.

Some of the Model attributes can be modified before the build process to change how certain build functions work. Those attributes are listed first in the attributes section below. To change them, create an instance of Model and pass it in to Simulator along with your network:

model = nengo_loihi.builder.Model(dt=0.001)
model.pes_error_scale = 50.

with nengo_loihi.Simulator(network, model=model) as sim:
    sim.run(1.0)
Parameters
dtfloat, optional (Default: 0.001)

The length of a simulator timestep, in seconds.

labelstr, optional (Default: None)

A name or description to differentiate models.

builderBuilder, optional (Default: None)

A Builder instance to keep track of build functions. If None, the default builder will be used.

Attributes
Build parameters
decode_neuronsDecodeNeurons

Type of neurons used to facilitate decoded (NEF-style) connections.

decode_taufloat

Time constant of lowpass synaptic filter used with decode neurons.

intercept_limitfloat

Limit for clipping intercepts, to avoid neurons with high gains.

node_neuronsDecodeNeurons

Type of neurons used to convert real-valued node outputs to spikes for the chip.

pes_error_scalefloat

Scaling for PES errors, before rounding and clipping to -127..127.

pes_wgt_expint

Learning weight exponent (base 2) for PES learning connections. This controls the maximum weight magnitude (where a larger exponent means larger potential weights, but lower weight resolution).

vth_nonspikingfloat

Voltage threshold for non-spiking neurons (i.e. voltage decoders).

Internal attributes
blocksdict

Mapping from Loihi blocks to a unique integer for that block.

block_shapesdict

Mapping from Loihi blocks to BlockShape instances.

builderBuilder

The build functions used by this model.

dtfloat

The length of a simulator timestep, in seconds.

chip2host_paramsdict

Mapping from Nengo objects to any additional parameters associated with those objects for use during the build process.

inputslist of LoihiInput

List of inputs to this model.

labelstr or None

A name or description to differentiate models.

objsdict

Dictionary mapping from Nengo objects to Nengo Loihi objects.

paramsdict

Mapping from objects to namedtuples containing parameters generated in the build process.

probeslist

List of probes on this model.

seededdict

All objects are assigned a seed, whether the user defined the seed or it was automatically generated. ‘seeded’ keeps track of whether the seed is user-defined. We consider the seed to be user-defined if it was set directly on the object, or if a seed was set on the network in which the object resides, or if a seed was set on any ancestor network of the network in which the object resides.

seedsdict

Mapping from objects to the integer seed assigned to that object.

host_model(self, obj)[source]

Returns the Model corresponding to where obj should be built.

class nengo_loihi.builder.Builder[source]

Fills in the Loihi Model object based on the Nengo Network.

We cannot use the Nengo builder as is because we make normal Nengo networks for host-to-chip and chip-to-host communication. To keep Nengo and Nengo Loihi builders separate, we make a blank subclass, which effectively copies the class.

class nengo_loihi.block.LoihiBlock(n_neurons, label=None)[source]

Class holding Loihi objects that can be placed on the chip.

This class can be thought of as a block of the Loihi board, and is how Nengo Loihi keeps track of how Loihi Neuron cores will be configured. Generally, the job of the build process is to convert Nengo objects (ensembles, connections, and nodes) to LoihiBlocks, which will then be used by the EmulatorInterface or HardwareInterface.

Initially, parameters in a LoihiBlock are floating point values. The discretize_block function converts them to integer values inplace for use on Loihi.

Attributes
axonslist of Axon

Axon objects outputting from the compartments in the block.

compartmentCompartment

Compartment object representing all compartments in the block.

n_neuronsint

The number of neurons in the block.

named_synapsesdict {str: Synape}

Mapping from a name to a Synapse object.

labelstring

A label for the block (for debugging purposes).

synapseslist of Synapse

Synapse objects projecting to compartments in the block.

class nengo_loihi.block.Compartment(n_compartments, label=None)[source]

Stores information for configuring Loihi compartments.

The information stored here will be associated with some block, and all compartments will share certain information. While compartments are usually thought of neurons, we use compartments to implement Nengo ensembles, nodes, and connection through special decode neurons.

Before discretize_compartment has been called, most attributes in this class are floating-point values. Calling discretize_compartment converts them to integer values inplace for use on Loihi.

Attributes
bias(n,) ndarray

Compartment biases.

enable_noise(n,) ndarray

Whether to enable noise for each compartment.

decay_u(n,) ndarray

Input (synapse) decay constant for each compartment.

decay_v(n,) ndarray

Voltage decay constant for each compartment.

labelstring

A label for the block (for debugging purposes).

n_compartmentsint

The number of compartments in the block.

noise_at_membrane{0, 1}

Inject noise into current (0) or voltage (1).

noise_expfloat or int

Exponent for noise generation. Floating point values are base 10 in units of current or voltage. Integer values are in base 2.

noise_offsetfloat or int

Offset for noise generation.

refract_delay(n,) ndarray

Compartment refractory delays, in time steps.

scale_ubool

Scale input (U) by decay_u so that the integral of U is the same before and after filtering.

scale_vbool

Scale voltage (V) by decay_v so that the integral of V is the same before and after filtering.

tau_sfloat or None

Time constant used to set decay_u. None if decay_u has not been set.

vmaxfloat or int (range [2**9 - 1, 2**23 - 1])

Maximum voltage for all compartments, in the same units as vth.

vminfloat or int (range [-2**23 + 1, 0])

Minimum voltage for all compartments, in the same units as vth.

vth(n,) ndarray

Compartment voltage thresholds.

configure_default_filter(self, tau_s, dt=0.001)[source]

Set the default Lowpass synaptic input filter for compartments.

Parameters
tau_sfloat

nengo.Lowpass synapse time constant for filtering.

dtfloat

Simulator time step.

configure_filter(self, tau_s, dt=0.001)[source]

Set Lowpass synaptic input filter for compartments.

Parameters
tau_sfloat

nengo.Lowpass synapse time constant for filtering.

dtfloat

Simulator time step.

configure_lif(self, tau_rc=0.02, tau_ref=0.001, vth=1, dt=0.001, min_voltage=0)[source]

Configure these compartments as individual LIF neurons.

Parameters
tau_rcfloat

Membrane time constant (in seconds) of the neurons.

tau_reffloat

Refractory period (in seconds) of the neurons.

vthfloat

Voltage firing threshold of the neurons.

dtfloat

Simulator time step length (in seconds).

min_voltagefloat

The minimum voltage for the neurons.

configure_nonspiking(self, tau_ref=0.0, vth=1, dt=0.001)[source]

Configure these compartments as individual non-spiking neurons.

Parameters
tau_reffloat

Refractory period (in seconds) of the neurons.

vthfloat

Voltage firing threshold of the neurons.

dtfloat

Simulator time step length (in seconds).

configure_relu(self, tau_ref=0.0, vth=1, dt=0.001)[source]

Configure these compartments as individual Rectified Linear neurons.

These are also known as non-leaky integrate-and-fire neurons. The voltage is the integral of the input current.

Parameters
tau_reffloat

Refractory period (in seconds) of the neurons.

vthfloat

Voltage firing threshold of the neurons.

dtfloat

Simulator time step length (in seconds).

class nengo_loihi.block.Axon(n_axons, label=None)[source]

A group of axons targeting a specific Synapse object.

Attributes
compartment_atomslist of length block.n_neurons

Atom (weight index) associated with each block compartment.

compartment_maplist of length block.n_neurons

Index of the axon in target targeted by each block compartment.

n_axonsint

The number of outgoing axons.

targetSynapse

Target synapses for these axons.

class Spike(axon_idx, atom=0)[source]

A spike targeting a particular axon within a Synapse object.

The Synapse target is implicit, given by the Axon object that creates this Spike.

Parameters
axon_idxint

The index of the axon within the targeted Synapse object.

atomint, optional (Default: 0)

An index into the target Synapse weights. This allows spikes targeting a particular axon to use different weights.

property slots_per_axon

The number of axon_cfg slots occupied by each axon.

axon_slots(self)[source]

The total number of axon_cfg slots used by all axons.

set_compartment_axon_map(self, target_axons, atoms=None)[source]

Set mapping from compartments to axons in target.

Parameters
target_axonsarray_like (n_compartments,)

Indices indicating which target axon each compartment maps to. If < 0, the corresponding compartment will not be used with these axons.

atomsarray_like (n_compartments,)

Atoms to use for each compartment. Use only if pop_type != 0.

class nengo_loihi.block.Synapse(n_axons, label=None)[source]

A group of Loihi synapses that share some properties.

Attributes
axon_compartment_baseslist or None

List providing base (compartment offset) for each input axon.

axon_to_weight_mapdict or None

Map from input axon index to weight index, to allow weights to be re-used by axons. If None, the weight index for an input axon is the axon index.

indices(population, axon, compartment) ndarray

The synapse indices.

learningbool

Whether synaptic tracing and learning is enabled for these synapses.

learning_ratefloat

The learning rate.

learning_wgt_expint

The weight exponent used on this connection if learning is enabled.

n_axonsint

Number of input axons to this group of synapses.

pop_typeint (0, 16, 32)

Whether these synapses are discrete (0), pop16, or pop32. This determines the type of axons these synapses can connect to.

synapse_cfgSynapseConfig

The synapse format object for these synapses.

tracing_magfloat

Magnitude by which the learning trace is increased for each spike.

tracing_tauint

Decay time constant for the learning trace, in timesteps (not seconds).

weights(n_axons,) list of (n_populations, n_compartments) ndarray

The synapse weights. Organized as a list of arrays so each axon can have a different number of target compartments.

atom_bits(self)[source]

Number of bits needed to represent the atom for incoming spikes.

atom_bits_extra(self)[source]

Number of extra bits needed for the atom for incoming pop16 spikes.

axon_bits(self)[source]

Number of bits available to represent the target axon on incoming spikes.

axon_compartment_base(self, axon_idx)[source]

Offset for compartment indices for a particular axon.

A return value of None indicates the axon is unused.

axon_populations(self, axon_idx)[source]

Number of populations (atom values) for a particular axon.

axon_weight_idx(self, axon_idx)[source]

Index of weights in weight array for a particular axon.

axon_weights_indices(self, axon_idx, atom=0)[source]

The weights and indices for a particular axon (and atom, if applicable).

bits(self)[source]

The total number of bits used by all weights in this Synapse.

format(self, \*\*kwargs)[source]

Modify the SynapseConfig format of this Synapse.

idx_bits(self)[source]

The number of index bits required for each weight entry.

idxs_per_synapse(self)[source]

The number of axon indices (slots) required for each incoming axon.

max_abs_weight(self)[source]

The maximum absolute value of all the weights in this Synapse.

max_ind(self)[source]

The maximum compartment index in weight memory.

Does not include axon_compartment_base.

set_weights(self, weights)[source]

Set dense or sparse weights on this Synapse.

set_learning(self, learning_rate=1.0, tracing_tau=2, tracing_mag=1.0, wgt_exp=4)[source]

Set the learning parameters for this Synapse.

set_population_weights(self, weights, indices, axon_to_weight_map, compartment_bases, pop_type=None)[source]

Set population weights on this Synapse.

class nengo_loihi.inputs.LoihiInput(label=None)[source]
class nengo_loihi.inputs.SpikeInput(n_neurons, label=None)[source]
class nengo_loihi.probe.LoihiProbe(target=None, key=None, slice=None, weights=None, synapse=None, reindexing=None)[source]

Record data from one or more LoihiBlock target states.

To get the final output of the probe:

  1. The LoihiBlock state given by key will be collected from each target.

  2. The slices will be applied to the outputs.

  3. The weights will be applied to the sliced outputs.

  4. If the weights change the output shape then weighted outputs are summed. If no weights or scalar weights, the weighted outputs are concatenated.

  5. Reindexing is applied to order the outputs correctly (in the case of multiple targets with no transformitive weights).

  6. Outputs are filtered using synapse.

The difference between summing and concatenating based on transformitive weights is to facilitate splitting blocks: Splitting a block with weights splits the weight matrix across the inputs but not across outputs, thus it is natural to sum outputs. Splitting a block with scalar weights results in new blocks with scalar weights, thus to get the same size of output as before the individual outputs are concatenated.

Parameters
targetLoihiBlock or list of LoihiBlock

The block to record values from. Use slice to record from a subset of compartments.

keystring (‘current’, ‘voltage’, ‘spiked’)

The compartment attribute to probe.

slicelist of <slice or list>

Select a subset of the compartments in each block to record from.

synapsenengo.synapses.Synapse

A synapse to use for filtering the probe.

weightsnp.ndarray

A linear transformation to apply to the outputs.

reindexingnp.ndarray

A list of indices used to reorder the outputs.

weight_outputs(self, outputs)[source]

Apply weights and reindexing to the target outputs.

We assume that probe slices have already been applied, since these are typically performed when collecting the target outputs

Parameters
outputslist of lists or arrays (n_blocks, n_timesteps (optional), n_outputs)

Outputs of the target blocks. The timesteps dimension is optional, and defaults to 1 if not provided. n_outputs can be different across blocks.

Returns
result(n_timesteps, n_outputs)

Discretization

nengo_loihi.builder.discretize.discretize_model(model)[source]

Discretize a Model in-place.

Turns a floating-point Model into a discrete (integer) model appropriate for Loihi.

Parameters
modelModel

The model to discretize.

nengo_loihi.builder.discretize.discretize_block(block)[source]

Discretize a LoihiBlock in-place.

Turns a floating-point LoihiBlock into a discrete (integer) block appropriate for Loihi.

Parameters
blockLoihiBlock

The block to discretize.

nengo_loihi.builder.discretize.discretize_compartment(comp, w_max)[source]

Discretize a Compartment in-place.

Turns a floating-point Compartment into a discrete (integer) block appropriate for Loihi.

Parameters
compCompartment

The compartment to discretize.

w_maxfloat

The largest connection weight in the LoihiBlock containing comp. Used to set several scaling factors.

nengo_loihi.builder.discretize.discretize_synapse(synapse, w_max, w_scale, w_exp)[source]

Discretize a Synapse in-place.

Turns a floating-point Synapse into a discrete (integer) block appropriate for Loihi.

Parameters
synapseSynapse

The synapse to discretize.

w_maxfloat

The largest connection weight in the LoihiBlock containing synapse. Used to scale weights appropriately.

w_scalefloat

Connection weight scaling factor. Usually computed by discretize_compartment.

w_expfloat

Exponent on the connection weight scaling factor. Usually computed by discretize_compartment.

nengo_loihi.builder.discretize.discretize_weights(synapse_cfg, w, dtype=<class 'numpy.int32'>, lossy_shift=True, check_result=True)[source]

Takes weights and returns their quantized values with weight_exp.

The actual weight to be put on the chip is this returned value divided by the scale attribute.

Parameters
wfloat ndarray

Weights to be discretized, in the range -255 to 255.

dtypenp.dtype, optional (Default: np.int32)

Data type for discretized weights.

lossy_shiftbool, optional (Default: True)

Whether to mimic the two-part weight shift that currently happens on the chip, which can lose information for small weight_exp.

check_resultsbool, optional (Default: True)

Whether to check that the discretized weights fall in the valid range for weights on the chip (-256 to 255).

nengo_loihi.builder.discretize.discretize_probe(probe, i, v_scale)[source]

Validation

nengo_loihi.builder.validate.validate_model(model)[source]
nengo_loihi.builder.validate.validate_block(block)[source]
nengo_loihi.builder.validate.validate_compartment(comp)[source]
nengo_loihi.builder.validate.validate_axon(axon)[source]
nengo_loihi.builder.validate.validate_synapse(synapse)[source]
nengo_loihi.builder.validate.validate_synapse_cfg(synapse_cfg)[source]
nengo_loihi.builder.validate.validate_probe(probe)[source]

Emulator

nengo_loihi.emulator.EmulatorInterface(model)

Software emulator for Loihi chip behaviour.

nengo_loihi.emulator.interface.BlockInfo(blocks)

Provide information about all the LoihiBlocks in the model.

nengo_loihi.emulator.interface.IterableState(…)

Base class for aspects of the emulator state.

nengo_loihi.emulator.interface.CompartmentState(…)

State representing the Compartments of all blocks.

nengo_loihi.emulator.interface.NoiseState(…)

State representing the noise parameters for all compartments.

nengo_loihi.emulator.interface.SynapseState(…)

State representing all synapses.

nengo_loihi.emulator.interface.AxonState(…)

State representing all (output) Axons.

nengo_loihi.emulator.interface.ProbeState(…)

State representing all probes.

class nengo_loihi.emulator.EmulatorInterface(model, seed=None)[source]

Software emulator for Loihi chip behaviour.

Parameters
modelModel

Model specification that will be simulated.

seedint, optional (Default: None)

A seed for all stochastic operations done in this simulator.

run_steps(self, steps)[source]

Simulate for the given number of dt steps.

Parameters
stepsint

Number of steps to run the simulation for.

step(self)[source]

Advance the simulation by 1 step (dt seconds).

class nengo_loihi.emulator.interface.BlockInfo(blocks)[source]

Provide information about all the LoihiBlocks in the model.

Attributes
dtypedtype

Datatype of the blocks. Either np.float32 if the blocks are not discretized or np.int32 if they are. All blocks are the same.

blockslist of LoihiBlock

List of all the blocks in the model.

n_compartmentsint

Total number of compartments across all blocks.

slicesdict of {LoihiBlock: slice}

Maps each block to a slice for that block’s compartments with respect to all compartments. Used to slice into any array storing data across all compartments.

class nengo_loihi.emulator.interface.IterableState(block_info, block_key, strict=True)[source]

Base class for aspects of the emulator state.

This class takes the name of a LoihiBlock attribute as the block_key and maps these objects to their parent blocks and slices.

Attributes
dtypedtype

Datatype of the state elements (given by the BlockInfo datatype).

block_mapdict of {item: block}

Maps an item (determined by block_key) to the block it belongs to.

n_compartmentsint

The total number of neuron compartments (given by BlockInfo).

slicesdict of {item: slice}

Maps an item to the block_info.slice for the block it belongs to.

strictbool (Default: True)

Whether “undesired” chip effects (ex. overflow) raise errors (True) or whether they only raise warnings (False).

class nengo_loihi.emulator.interface.CompartmentState(block_info, strict=True)[source]

State representing the Compartments of all blocks.

class nengo_loihi.emulator.interface.NoiseState(block_info)[source]

State representing the noise parameters for all compartments.

class nengo_loihi.emulator.interface.SynapseState(block_info, pes_error_scale=1.0, strict=True)[source]

State representing all synapses.

Attributes
pes_error_scalefloat

Scaling for the errors of PES learning rules.

pes_errors{Synapse: ndarray(n_neurons / 2)}

Maps synapse to PES learning rule errors for those synapses.

spikes_in{Synapse: list}

Maps synapse to a queue of input spikes targeting those synapses.

traces{Synapse: ndarray(Synapse.n_axons)}

Maps synapse to trace values for each of their axons.

trace_spikes{Synapse: set}

Maps synapse to a queue of input spikes waiting to be added to those synapse traces.

class nengo_loihi.emulator.interface.AxonState(block_info)[source]

State representing all (output) Axons.

class nengo_loihi.emulator.interface.ProbeState(block_info, probes, dt)[source]

State representing all probes.

Attributes
dtfloat

Time constant of the Emulator.

filters{nengo_loihi.Probe: function}

Maps Probes to the filtering function for that probe.

filter_pos{nengo_loihi.Probe: int}

Maps Probes to the position of their filter in the data.

block_probes{nengo_loihi.Probe: slice}

Maps Probes to the BlockInfo slice for the block they are probing.

input_probes{nengo_loihi.Probe: SpikeInput}

Maps Probes to the SpikeInput that they are probing.

send(self, probe, already_sent, receiver)[source]

Send probed data to the receiver node.

Returns
stepsint

The number of steps sent to the receiver.

Hardware

nengo_loihi.hardware.HardwareInterface(model)

Place a Model onto a Loihi board and run it.

class nengo_loihi.hardware.HardwareInterface(model, use_snips=True, seed=None, snip_max_spikes_per_step=50, n_chips=2, allocator=None)[source]

Place a Model onto a Loihi board and run it.

Parameters
modelModel

Model specification that will be placed on the Loihi board.

use_snipsboolean, optional (Default: True)

Whether to use snips (e.g., for precompute=False).

seedint, optional (Default: None)

A seed for stochastic operations.

snip_max_spikes_per_stepint

The maximum number of spikes that can be sent to each chip in one timestep if .use_snips is True.

n_chipsint, optional (Default: 2)

The number of chips on the board.

allocatorAllocator, optional (Default: Greedy())

Callable object that allocates the board’s devices to given models. Defaults to one block and one input per core on a single chip.

connect(self)[source]

Connects to the board.