API#

Using the package#

To use ChronoProp in your own code, install it with

pip install "chronoprop @ git+https://github.com/Poirazi-Lab/chronoprop"

It needs Python 3.10 or newer, PyTorch, NumPy (1.x or 2.x), SciPy, h5py, scikit-learn and matplotlib, and torchvision for the image datasets. Build each network directly on the device it will run on (device='cuda' or 'cpu'); moving a built network with .to() is not supported.

cp.jit compiles a network with TorchScript, as the paper did. Recent PyTorch versions (such as 2.14) can no longer compile the surrogate gradient of the BPTT baseline, which every neuron model contains, and cp.jit then returns the networks uncompiled, which gives the same results up to rounding (see Run locally). We plan to port the code to torch.compile.

A network of the paper, trained as the paper trained it (here the recurrent network of Fig. 3 at Δt = 0.1 ms, a few hours on a GPU):

import chronoprop as cp
from chronoprop import configs

train_set, val_set, test_set = cp.data.load_shd('data/SHD', dt_us=1000)   # downloads SHD once
cp.set_seed(1234)
net, info = configs.build_fig3_network('rec', 'chronoprop', 'fine', 'cuda')
net = cp.jit(net)
res = cp.train.train(net, train_set, test_set, val_data=val_set, batch_size=128,
                     epochs=400, lr=info['lr'], device='cuda',
                     window_steps=info['window_steps'], recurrent=True)
acc, epoch = cp.train.test_at_best_val(res)

The tutorials build networks from their parts, and the scripts of Run locally show every figure’s training.

Module

What it holds

neurons, proxy, fi

the neuron models, the ChronoProp proxy and the measured FI curves it uses

networks

the networks of every figure, each trained by ChronoProp or by BPTT

data

SHD, addSHD, MNIST and Fashion-MNIST with the paper’s splits

train, configs

the training loop, the paper’s settings and a builder per figure

pretrained

the trained networks of Fig. 6, Fig. 5’s best SHD network among them

defects

the simulated hardware defects of Fig. 6

cost

the time, memory and operations of a training step (Fig. 2c–f)

utils

seeding, TorchScript compilation, matched hidden sizes

Neurons, proxy and FI curves#

neurons#

Neuron models used in the paper.

Every neuron is a torch.nn.Module whose forward advances the state by one time step of length dt (exponential-Euler discretisation) and returns (spike, new_state). Parameters are stored as buffers on the device given at construction, so build a neuron (and any network) directly on the device you will run it on; moving it later with .to() is not supported.

All three neurons are current based: an incoming spike adds a jump to a synaptic current that decays with tau_syn, and that current drives the membrane.

  • LIF: the leaky integrate-and-fire neuron of Figs 1-3, 5 and 6.

  • AdaptiveLIF: adds a spike-triggered adaptation current (Fig 4).

  • TwoCompartmentLIF: a soma coupled to a passive dendrite (Supp. Fig. 7).

The same classes serve ChronoProp (hard threshold, simulated without gradients) and the BPTT baseline (use_surrogate=True: the threshold is replaced in the backward pass by the derivative of an arctangent, ATanSurrogate).

Research-code names: LIF = CUBAPointLeaky, AdaptiveLIF = CUBAPointAdaptiveLeaky (the paper’s ChronoProp runs used its refractory twin with a refractory period of 0, which is numerically identical), TwoCompartmentLIF = CUBAPassiveDendriticLeaky.

class chronoprop.neurons.ATanSurrogate(*args, **kwargs)[source]#

Heaviside step forward, arctangent-derivative surrogate backward.

Used only by the BPTT baseline. alpha sets the steepness of the surrogate: d spike / d x = (alpha / 2) / (1 + (pi / 2 * alpha * x)^2).

class chronoprop.neurons.LIF(threshold, reset, tau_mem, tau_syn, R, dt, device, mem_noise_sigma=0.0)[source]#

Current-based leaky integrate-and-fire neuron.

One step:

i_syn <- alpha_syn * i_syn + x                    (x: weighted input spikes)
v     <- alpha_mem * v + R (1 - alpha_mem) (i_syn + I_ext)
spike  = v > threshold;  v <- reset where spike

with alpha = exp(-dt / tau). tau_mem and R may be floats or per-neuron tensors (Fig 6, time-constant mismatch). mem_noise_sigma adds Gaussian noise to v every step during training (Fig 6, membrane noise); it is 0 everywhere else.

Parameters:
  • threshold (float)

  • reset (float)

  • tau_syn (float)

  • dt (float)

  • device (device)

initialize_state(batch_size, num_neurons)[source]#

Return the zero state (v, i_syn) of shape [batch_size, num_neurons].

Parameters:
  • batch_size (int)

  • num_neurons (int)

Return type:

tuple[Tensor, Tensor]

class chronoprop.neurons.AdaptiveLIF(threshold, reset, tau_mem, tau_syn, R, tau_w, subthreshold_adaptation, spike_triggered_adaptation, dt, device)[source]#

Current-based LIF neuron with an adaptation current w (Fig 4).

The adaptation current opposes the drive and decays with tau_w. Every spike increments it by spike_triggered_adaptation (b); a subthreshold coupling subthreshold_adaptation (a) is supported and is 0 in the paper.

Parameters:
  • threshold (float)

  • reset (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

  • tau_w (float)

  • subthreshold_adaptation (float)

  • spike_triggered_adaptation (float)

  • dt (float)

  • device (device)

initialize_state(batch_size, num_neurons)[source]#

Return the zero state (v, i_syn, w).

Parameters:
  • batch_size (int)

  • num_neurons (int)

Return type:

tuple[Tensor, Tensor, Tensor]

class chronoprop.neurons.TwoCompartmentLIF(threshold_soma, reset_soma, tau_mem, tau_syn, R, scale_dend, coupling, dt, device)[source]#

Two-compartment current-based LIF: a spiking soma coupled to a passive dendrite.

Soma and dendrite each receive their own synaptic input (X_soma, X_dend). The dendrite is a leaky integrator coupled to the soma through coupling; its input is scaled down by scale_dend. Only the soma has a threshold and a reset (Supp. Fig. 7).

Parameters:
  • threshold_soma (float)

  • reset_soma (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

  • scale_dend (float)

  • coupling (float)

  • dt (float)

  • device (device)

initialize_state(batch_size, num_neurons)[source]#

Return the zero state (v_soma, v_dend, i_syn_soma, i_syn_dend).

Parameters:
  • batch_size (int)

  • num_neurons (int)

Return type:

tuple[Tensor, Tensor, Tensor, Tensor]

proxy#

The ChronoProp proxy: spike counts forward, a fitted FI curve backward.

In the forward pass a proxy layer passes the spike counts measured in the simulation through unchanged. In the backward pass it treats them as the output of the neuron’s fitted FI curve, a rectified line gain * (drive - threshold). The gradient with respect to the drive is therefore gain where the drive lies above the fitted threshold and 0 elsewhere. The spike counts themselves never receive a gradient.

  • SpikesToRate: 1-D FI curve (point neurons).

  • SpikesToRateAdaptive: 2-D FI plane of adaptive neurons. The threshold moves right by alpha * w (the adaptation level in the window).

  • SpikesToRateDendrite: 2-D FI plane of two-compartment neurons, with one gain per compartment.

Research-code names: SpikesToRatePoint, SpikesToRateAdaptive, SpikesToRateDendPassive.

class chronoprop.proxy.SpikesToRate(gain=1.0, threshold=0.0)[source]#

Proxy for point neurons: forward returns counts; backward is a ReLU of slope gain with threshold threshold (floats or per-neuron tensors).

class chronoprop.proxy.SpikesToRateAdaptive(gain=1.0, thr0=0.0, alpha=0.0)[source]#

Proxy for adaptive neurons, fitted to max(0, gain * (I - thr0 - alpha * w)).

w_window is the mean adaptation level of each neuron in the time window, taken from the simulation without a gradient; it only moves the threshold.

class chronoprop.proxy.SpikesToRateDendrite(gain_soma, gain_dend, threshold_soma)[source]#

Proxy for two-compartment neurons, fitted to max(0, gain_dend * I_dend + gain_soma * (I_soma - threshold_soma)).

fi#

Measuring a neuron’s FI curve once and turning it into a ChronoProp proxy.

ChronoProp treats the neuron as a black box. Before training, it injects constant currents I into an isolated neuron for one time window, counts the spikes, and fits a rectified line count = gain * (I - threshold) (fit_relu()). The paper fits over 201 currents from 0 to 1, on a window of window_steps simulation steps (10 ms). The neuron is compiled with TorchScript for the measurement, as in the paper: on a GPU, compiled and uncompiled code can round differently, and one count on a rounding edge changes a fit.

During training the proxy does not read a constant current. It reads the window’s summed synaptic input, which reaches the membrane through the synaptic low-pass filter. drive_scale() gives the factor between the two axes, and rescale_fit() moves the fit onto the axis the proxy reads (the paper’s “A1” correction).

chronoprop.fi.measure_fi_curve(neuron, num_steps, max_current=1.0, num_currents=201, device=None)[source]#

Inject constant currents into neuron for num_steps steps; count spikes.

Returns (currents, counts), both 1-D tensors of length num_currents. Every current is simulated in parallel from the resting state, without input spikes; the current enters after the synapse, as external_current.

Parameters:
  • num_steps (int)

  • max_current (float)

  • num_currents (int)

chronoprop.fi.fit_relu(currents, counts)[source]#

Least-squares fit of counts = max(0, gain * (I - threshold)).

Returns a dict with fitted_gain, fitted_threshold, r_squared and relative_mae. The fit starts from gain 1 and the lowest current that made the neuron fire (scipy curve_fit, Levenberg-Marquardt).

Return type:

dict

chronoprop.fi.drive_scale(window_steps, dt, tau_syn)[source]#

Factor between the FI axis and the drive the proxy reads, K (1 - exp(-dt/tau_syn)).

The FI probe adds a current I after the synapse at every step, delivering K * I over a window of K steps. In training, the proxy reads the summed weighted input S of the window, which reaches the membrane through the synapse and delivers S / (1 - exp(-dt/tau_syn)). Equating the two gives I = S / drive_scale.

Parameters:
  • window_steps (int)

  • dt (float)

  • tau_syn (float)

Return type:

float

chronoprop.fi.rescale_fit(fit, scale)[source]#

Express a fit_relu() result on the proxy’s axis: (gain / scale, threshold * scale).

Only the threshold changes which neurons receive a gradient; the gain is a uniform rescaling of the gradient.

Parameters:
  • fit (dict)

  • scale (float)

Return type:

tuple

chronoprop.fi.window_steps(window, dt)[source]#

Number of simulation steps in a time window, computed as in the paper’s code.

Parameters:
  • window (float)

  • dt (float)

Return type:

int

chronoprop.fi.proxy_from_neuron(neuron, window, dt, tau_syn, max_current=1.0, num_currents=201)[source]#

Measure, fit and rescale in one call; returns (gain, threshold, info).

info holds the raw fit, the scale factor and the applied values, as the paper records them for every run.

Parameters:
  • window (float)

  • dt (float)

  • tau_syn (float)

  • max_current (float)

  • num_currents (int)

chronoprop.fi.proxy_for_population(tau_mem, R, window, dt, threshold=1.0, reset=0.0, tau_syn=0.002, max_current=1.0, num_currents=201, device=None)[source]#

One FI fit per neuron of a population whose neurons may differ in tau_mem and R, moved onto the proxy’s axis; returns (gains, thresholds, r_squared).

tau_mem is a tensor [N]; R a float or a tensor [N]. All neurons are simulated in one pass, as in the paper; neurons with identical parameters get identical fits, so each distinct curve is fitted once. gains and thresholds are float32 tensors [N]; r_squared a list of N floats.

Parameters:
  • tau_mem (Tensor)

  • window (float)

  • dt (float)

  • threshold (float)

  • reset (float)

  • tau_syn (float)

  • max_current (float)

  • num_currents (int)

chronoprop.fi.measure_fi_plane(neuron, num_steps, max_current=1.0, w_max=5.0, num_currents=201, num_w=101, device=None)[source]#

Spike counts of an adaptive neuron over a grid of currents I and adaptation levels w.

Each cell injects a constant current I for num_steps steps while the adaptation current is held at w (reset to w before every step), so the window’s mean adaptation equals w: the surface is what the proxy reads at (drive, mean adaptation). Holding w also makes the surface independent of the neuron’s spike-triggered adaptation. All cells run in parallel.

Returns (currents, w_levels, counts) with counts of shape [num_currents, num_w].

Parameters:
  • num_steps (int)

  • max_current (float)

  • w_max (float)

  • num_currents (int)

  • num_w (int)

chronoprop.fi.fit_relu_adaptive(currents, w_levels, counts)[source]#

Least-squares fit of counts = max(0, gain * (I - thr0 - alpha * w)) to an FI plane.

Adaptation acts as a threshold shift on the input axis; for the paper’s neuron the fit finds alpha close to 1/R. Returns a dict with gain, thr0, alpha, r_squared and relative_mae (scipy curve_fit, bounded, starting from gain 10, the lowest current that fires at w = 0 and alpha 0.2).

Return type:

dict

chronoprop.fi.proxy_from_adaptive_neuron(neuron, window, dt, tau_syn, max_current=1.0, num_currents=201, w_max=5.0, num_w=101)[source]#

Measure the FI plane, fit it and move it onto the proxy’s axis, in one call.

Returns (gain, thr0, alpha, info). thr0 and alpha are both thresholds on the input axis, so both are multiplied by drive_scale(); the gain is divided by it. info holds the raw fit, the scale and the applied values, as the paper records them for every run, plus the measured plane.

Parameters:
  • window (float)

  • dt (float)

  • tau_syn (float)

  • max_current (float)

  • num_currents (int)

  • w_max (float)

  • num_w (int)

chronoprop.fi.measure_fi_plane_dendrite(neuron, num_steps, max_current=1.0, num_currents=101, device=None)[source]#

Spike counts of a two-compartment neuron over a grid of somatic and dendritic currents.

Each cell injects a constant current I_soma into the soma and I_dend into the dendrite (both after the synapse, as the network’s input arrives), starting from rest, and counts the somatic spikes over num_steps steps. All cells run in parallel.

Returns (currents_soma, currents_dend, counts) with counts of shape [num_currents, num_currents] (soma along the rows).

Parameters:
  • num_steps (int)

  • max_current (float)

  • num_currents (int)

chronoprop.fi.fit_relu_dendrite(currents_soma, currents_dend, counts)[source]#

Least-squares fit of counts = max(0, gain_dend * I_dend + gain_soma * (I_soma - threshold_soma)).

The dendrite adds to the somatic drive with its own gain, so dendritic input lowers the somatic current needed to fire. Returns a dict with gain_soma, gain_dend, threshold_soma, r_squared and relative_mae (scipy curve_fit, bounded, starting from gains 10 and the lowest somatic current that fires without dendritic input).

Return type:

dict

chronoprop.fi.proxy_from_dendritic_neuron(neuron, window, dt, tau_syn, max_current=1.0, num_currents=101)[source]#

Measure the soma x dendrite FI plane, fit it and move it onto the proxy’s axis.

Returns (gain_soma, gain_dend, threshold_soma, info). Both compartments receive their input through the same synaptic filter, so both gains are divided by drive_scale() and the threshold is multiplied by it. info holds the raw fit, the scale and the applied values, as the paper records them for every run, plus the measured plane.

Parameters:
  • window (float)

  • dt (float)

  • tau_syn (float)

  • max_current (float)

  • num_currents (int)

Networks#

networks.static#

Networks for static images (Fig. 2): ChronoProp as a drop-in replacement for BPTT.

An image is shown for num_input_ticks input ticks of input_dt (the paper: 50 ticks of 1 ms, a 50 ms window). At every tick each pixel fires a Bernoulli spike with probability pixel * input_rate_hz * input_dt (200 Hz for a white pixel). Each tick lasts substeps_per_input simulation steps (1, 2 or 10 at Δt = 1, 0.5 or 0.1 ms), and the input spike arrives on the first of them, so the input spike train does not depend on Δt; only the simulation’s resolution does. One hidden layer of LIF neurons feeds a non-spiking readout whose membrane potential, averaged over all steps, is the logit.

ChronoProp uses a single time window spanning the whole image. It simulates the hidden layer without gradients, counts the input and hidden spikes, and builds the proxy from them: input counts times the input weights, through SpikesToRate, times the readout weights; this drive is held on the readout for all steps.

BPTT simulates the same network step by step with the surrogate spike function; the hidden spikes reach the readout through its synapse, the standard wiring.

Research-code names: CUBAStaticRatepropNetNS and CUBAStaticSurrogateNetNS (readout_via_synapse=True), the networks of Fig. 2 and Supplementary Figs. 1-3.

class chronoprop.networks.static.ChronoPropStatic(num_inputs, num_hidden, num_outputs, num_input_ticks, substeps_per_input, proxy_gain, proxy_threshold, dt, device, input_rate_hz=200.0, input_dt=0.001, threshold=1.0, reset=0.0, tau_mem=0.01, tau_syn=0.002, R=5.0)[source]#

One-hidden-layer network for images, trained by ChronoProp (one window per image).

proxy_gain and proxy_threshold are the FI fit over the whole window, on the proxy’s axis (chronoprop.fi.proxy_from_neuron() with the window = the image’s presentation time).

Parameters:
  • num_inputs (Final[int])

  • num_hidden (Final[int])

  • num_outputs (Final[int])

  • num_input_ticks (Final[int])

  • substeps_per_input (Final[int])

  • proxy_gain (float)

  • proxy_threshold (float)

  • dt (float)

  • device (device)

  • input_rate_hz (float)

  • input_dt (float)

  • threshold (float)

  • reset (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

class chronoprop.networks.static.BPTTStatic(num_inputs, num_hidden, num_outputs, num_input_ticks, substeps_per_input, dt, device, surrogate_alpha=8.0, input_rate_hz=200.0, input_dt=0.001, threshold=1.0, reset=0.0, tau_mem=0.01, tau_syn=0.002, R=5.0)[source]#

The same network trained by BPTT with a surrogate gradient (steepness 8 in Fig. 2).

Parameters:
  • num_inputs (Final[int])

  • num_hidden (Final[int])

  • num_outputs (Final[int])

  • num_input_ticks (Final[int])

  • substeps_per_input (Final[int])

  • dt (float)

  • device (device)

  • surrogate_alpha (Final[float])

  • input_rate_hz (float)

  • input_dt (float)

  • threshold (float)

  • reset (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

chronoprop.networks.static.hidden_spike_counts(net, images)[source]#

Spikes fired by each hidden neuron on each image, [images, hidden].

Runs the hidden layer of a Fig. 2 network (either method) on fresh input spikes, without gradients. Draws from the global random number generator.

Parameters:

images (Tensor)

Return type:

Tensor

networks.temporal#

Networks for event streams such as SHD (Figs 3 and 4 use these).

Every network has one hidden layer of LIF neurons (feedforward or recurrent) and a non-spiking readout: an LIF neuron whose threshold is never reached, so its membrane potential integrates the drive. The logit of each class is the readout’s membrane potential averaged over all simulation steps.

ChronoProp (temporal ChronoProp, tCP) cuts the input into time windows of window_steps steps. For each window it

  1. simulates the hidden layer without gradients, carrying every state (membrane, synaptic current and, in recurrent networks, the last spikes) across window boundaries, so the dynamics never notice the windows;

  2. builds the proxy: the window’s input spike counts times the input weights (plus the window’s hidden spike counts times the recurrent weights), passed through SpikesToRate;

  3. drives the readout with the proxy for the window’s steps, starting from a readout state detached from the previous window, so no gradient crosses a window boundary.

BPTT simulates the same network step by step with the surrogate spike function and backpropagates through the whole sequence.

Inputs are spike frames of shape [batch, steps, 1, channels] (or [batch, steps, channels]). ChronoProp ignores trailing steps that do not fill a whole window; chronoprop.data.PadToWindow pads batches to whole windows.

Research-code names: CUBATemporalRatepropNet, CUBARecurrentTemporalRatepropNet, CUBATemporalSurrogateNet, CUBARecurrentTemporalSurrogateNet, with the paper’s settings fixed (non-spiking readout, one step per input frame, recurrent spikes carried across windows).

class chronoprop.networks.temporal.ChronoPropFeedforward(num_inputs, num_hidden, num_outputs, window_steps, proxy_gain, proxy_threshold, dt, device, threshold=1.0, reset=0.0, tau_mem=0.01, tau_syn=0.002, R=5.0)[source]#

Feedforward network trained by ChronoProp (one gradient per time window).

Parameters:
  • num_inputs (Final[int])

  • num_hidden (Final[int])

  • num_outputs (Final[int])

  • window_steps (Final[int])

  • proxy_gain (float)

  • proxy_threshold (float)

  • dt (float)

  • device (device)

  • threshold (float)

  • reset (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

class chronoprop.networks.temporal.ChronoPropRecurrent(num_inputs, num_hidden, num_outputs, window_steps, proxy_gain, proxy_threshold, dt, device, recurrent_prob=1.0, threshold=1.0, reset=0.0, tau_mem=0.01, tau_syn=0.002, R=5.0)[source]#

Recurrent network trained by ChronoProp.

recurrent_prob is the fraction of recurrent connections kept (1 = all-to-all). The proxy of a window uses the window’s hidden spike counts as recurrent input.

Parameters:
  • num_inputs (Final[int])

  • num_hidden (Final[int])

  • num_outputs (Final[int])

  • window_steps (Final[int])

  • proxy_gain (float)

  • proxy_threshold (float)

  • dt (float)

  • device (device)

  • recurrent_prob (float)

  • threshold (float)

  • reset (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

apply_recurrent_mask()[source]#

Keep pruned recurrent weights at zero; call after every optimizer step.

Return type:

None

class chronoprop.networks.temporal.BPTTFeedforward(num_inputs, num_hidden, num_outputs, dt, device, surrogate_alpha=2.0, threshold=1.0, reset=0.0, tau_mem=0.01, tau_syn=0.002, R=5.0)[source]#

The same feedforward network trained by BPTT with a surrogate gradient.

Parameters:
  • num_inputs (Final[int])

  • num_hidden (Final[int])

  • num_outputs (Final[int])

  • dt (float)

  • device (device)

  • surrogate_alpha (Final[float])

  • threshold (float)

  • reset (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

class chronoprop.networks.temporal.BPTTRecurrent(num_inputs, num_hidden, num_outputs, dt, device, recurrent_prob=1.0, surrogate_alpha=2.0, threshold=1.0, reset=0.0, tau_mem=0.01, tau_syn=0.002, R=5.0)[source]#

The same recurrent network trained by BPTT with a surrogate gradient.

Parameters:
  • num_inputs (Final[int])

  • num_hidden (Final[int])

  • num_outputs (Final[int])

  • dt (float)

  • device (device)

  • recurrent_prob (float)

  • surrogate_alpha (Final[float])

  • threshold (float)

  • reset (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

apply_recurrent_mask()[source]#

Keep pruned recurrent weights at zero; call after every optimizer step.

Return type:

None

networks.adaptive#

Networks of adaptive neurons for event streams (Fig 4).

The Fig 3 networks (chronoprop.networks.temporal) with one change: the hidden neurons are AdaptiveLIF, whose adaptation current w grows with every spike and decays with tau_w, so a neuron’s response to the same input depends on its recent firing.

ChronoProp needs one extra number per neuron and window for this: the window’s mean adaptation w, read from the simulation like the spike counts. The proxy (SpikesToRateAdaptive) is fitted to the neuron’s FI plane, count = max(0, gain * (I - thr0 - alpha * w)), so adaptation moves the threshold above which a neuron receives a gradient. Everything else (windows, carried states, the non-spiking readout) is as in Fig 3.

BPTT simulates the same network step by step; its surrogate gradient also flows through the adaptation current.

Research-code names: CUBAAdaptive2DTemporalRatepropNet, CUBAAdaptive2DRecurrentTemporalRatepropNet, CUBAAdaptiveTemporalSurrogateNet, CUBAAdaptiveRecurrentTemporalSurrogateNet, with the paper’s settings fixed (no refractory period, one step per input frame, recurrent spikes carried across windows).

class chronoprop.networks.adaptive.ChronoPropAdaptiveFeedforward(num_inputs, num_hidden, num_outputs, window_steps, proxy_gain, proxy_thr0, proxy_alpha, dt, device, tau_w=0.15, spike_triggered_adaptation=2.0, subthreshold_adaptation=0.0, threshold=1.0, reset=0.0, tau_mem=0.01, tau_syn=0.002, R=5.0)[source]#

Feedforward network of adaptive neurons trained by ChronoProp.

proxy_gain, proxy_thr0 and proxy_alpha are the FI-plane fit on the proxy’s axis (chronoprop.fi.proxy_from_adaptive_neuron()).

Parameters:
  • num_inputs (Final[int])

  • num_hidden (Final[int])

  • num_outputs (Final[int])

  • window_steps (Final[int])

  • proxy_gain (float)

  • proxy_thr0 (float)

  • proxy_alpha (float)

  • dt (float)

  • device (device)

  • tau_w (float)

  • spike_triggered_adaptation (float)

  • subthreshold_adaptation (float)

  • threshold (float)

  • reset (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

class chronoprop.networks.adaptive.ChronoPropAdaptiveRecurrent(num_inputs, num_hidden, num_outputs, window_steps, proxy_gain, proxy_thr0, proxy_alpha, dt, device, recurrent_prob=1.0, tau_w=0.15, spike_triggered_adaptation=2.0, subthreshold_adaptation=0.0, threshold=1.0, reset=0.0, tau_mem=0.01, tau_syn=0.002, R=5.0)[source]#

Recurrent network of adaptive neurons trained by ChronoProp.

Parameters:
  • num_inputs (Final[int])

  • num_hidden (Final[int])

  • num_outputs (Final[int])

  • window_steps (Final[int])

  • proxy_gain (float)

  • proxy_thr0 (float)

  • proxy_alpha (float)

  • dt (float)

  • device (device)

  • recurrent_prob (float)

  • tau_w (float)

  • spike_triggered_adaptation (float)

  • subthreshold_adaptation (float)

  • threshold (float)

  • reset (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

apply_recurrent_mask()[source]#

Keep pruned recurrent weights at zero; call after every optimizer step.

Return type:

None

class chronoprop.networks.adaptive.BPTTAdaptiveFeedforward(num_inputs, num_hidden, num_outputs, dt, device, surrogate_alpha=2.0, tau_w=0.15, spike_triggered_adaptation=2.0, subthreshold_adaptation=0.0, threshold=1.0, reset=0.0, tau_mem=0.01, tau_syn=0.002, R=5.0)[source]#

The same feedforward network of adaptive neurons trained by BPTT.

Parameters:
  • num_inputs (Final[int])

  • num_hidden (Final[int])

  • num_outputs (Final[int])

  • dt (float)

  • device (device)

  • surrogate_alpha (Final[float])

  • tau_w (float)

  • spike_triggered_adaptation (float)

  • subthreshold_adaptation (float)

  • threshold (float)

  • reset (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

class chronoprop.networks.adaptive.BPTTAdaptiveRecurrent(num_inputs, num_hidden, num_outputs, dt, device, recurrent_prob=1.0, surrogate_alpha=2.0, tau_w=0.15, spike_triggered_adaptation=2.0, subthreshold_adaptation=0.0, threshold=1.0, reset=0.0, tau_mem=0.01, tau_syn=0.002, R=5.0)[source]#

The same recurrent network of adaptive neurons trained by BPTT.

Parameters:
  • num_inputs (Final[int])

  • num_hidden (Final[int])

  • num_outputs (Final[int])

  • dt (float)

  • device (device)

  • recurrent_prob (float)

  • surrogate_alpha (Final[float])

  • tau_w (float)

  • spike_triggered_adaptation (float)

  • subthreshold_adaptation (float)

  • threshold (float)

  • reset (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

apply_recurrent_mask()[source]#

Keep pruned recurrent weights at zero; call after every optimizer step.

Return type:

None

networks.dendritic#

Networks of two-compartment neurons for addSHD (Supplementary Fig. 7).

The Fig 3 networks with one change: each hidden neuron is a TwoCompartmentLIF, a spiking soma coupled to a passive dendrite, and each compartment has its own input weights. On addSHD the soma receives an English SHD digit and the dendrite a German one (chronoprop.data.AddSHD); the network reports their sum.

Inputs are spike frames of shape [batch, steps, 2, channels]: channel 0 of the third axis drives the somata, channel 1 the dendrites.

ChronoProp needs no extra state for this neuron. The proxy (SpikesToRateDendrite) is fitted to the neuron’s soma x dendrite FI plane, count = max(0, g_d * I_dend + g_s * (I_soma - theta)), and reads the window’s two drives (input counts times each compartment’s weights). Recurrent networks send the hidden spikes back to the somata. Everything else (windows, carried states, the non-spiking readout) is as in Fig 3.

BPTT simulates the same network step by step with the surrogate spike function.

Research-code names: CUBAPassiveDendriticTemporalRatepropNetA2 and CUBAPassiveDendriticTemporalSurrogateNet with rec_target='none' (feedforward) or 'soma' (recurrent), the non-spiking readout and one step per input frame. The research classes also allocate a soma-to-dendrite recurrent matrix that the paper never used; these networks leave it out but draw the same random numbers for it, so a seed gives the paper’s initial weights.

class chronoprop.networks.dendritic.ChronoPropDendriteFeedforward(num_inputs, num_hidden, num_outputs, window_steps, proxy_gain_soma, proxy_gain_dend, proxy_threshold, dt, device, threshold=1.0, reset=0.0, tau_mem=0.01, tau_syn=0.002, R=5.0, scale_dend=1.0, coupling=1.0)[source]#

Feedforward network of two-compartment neurons trained by ChronoProp.

proxy_gain_soma, proxy_gain_dend and proxy_threshold are the FI-plane fit on the proxy’s axis (chronoprop.fi.proxy_from_dendritic_neuron()).

Parameters:
  • num_inputs (Final[int])

  • num_hidden (Final[int])

  • num_outputs (Final[int])

  • window_steps (Final[int])

  • proxy_gain_soma (float)

  • proxy_gain_dend (float)

  • proxy_threshold (float)

  • dt (float)

  • device (device)

  • threshold (float)

  • reset (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

  • scale_dend (float)

  • coupling (float)

class chronoprop.networks.dendritic.ChronoPropDendriteRecurrent(num_inputs, num_hidden, num_outputs, window_steps, proxy_gain_soma, proxy_gain_dend, proxy_threshold, dt, device, threshold=1.0, reset=0.0, tau_mem=0.01, tau_syn=0.002, R=5.0, scale_dend=1.0, coupling=1.0)[source]#

Recurrent network of two-compartment neurons trained by ChronoProp.

The hidden spikes return to the somata through all-to-all recurrent weights without self-connections; the proxy of a window adds the window’s hidden spike counts times these weights to the somatic drive.

Parameters:
  • num_inputs (Final[int])

  • num_hidden (Final[int])

  • num_outputs (Final[int])

  • window_steps (Final[int])

  • proxy_gain_soma (float)

  • proxy_gain_dend (float)

  • proxy_threshold (float)

  • dt (float)

  • device (device)

  • threshold (float)

  • reset (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

  • scale_dend (float)

  • coupling (float)

class chronoprop.networks.dendritic.BPTTDendriteFeedforward(num_inputs, num_hidden, num_outputs, dt, device, surrogate_alpha=2.0, threshold=1.0, reset=0.0, tau_mem=0.01, tau_syn=0.002, R=5.0, scale_dend=1.0, coupling=1.0)[source]#

The same feedforward network trained by BPTT with a surrogate gradient.

Parameters:
  • num_inputs (Final[int])

  • num_hidden (Final[int])

  • num_outputs (Final[int])

  • dt (float)

  • device (device)

  • surrogate_alpha (Final[float])

  • threshold (float)

  • reset (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

  • scale_dend (float)

  • coupling (float)

class chronoprop.networks.dendritic.BPTTDendriteRecurrent(num_inputs, num_hidden, num_outputs, dt, device, surrogate_alpha=2.0, threshold=1.0, reset=0.0, tau_mem=0.01, tau_syn=0.002, R=5.0, scale_dend=1.0, coupling=1.0)[source]#

The same recurrent network trained by BPTT with a surrogate gradient.

Parameters:
  • num_inputs (Final[int])

  • num_hidden (Final[int])

  • num_outputs (Final[int])

  • dt (float)

  • device (device)

  • surrogate_alpha (Final[float])

  • threshold (float)

  • reset (float)

  • tau_mem (float)

  • tau_syn (float)

  • R (float)

  • scale_dend (float)

  • coupling (float)

networks.techniques#

The network of Figs 5 and 6, trained by ChronoProp or by BPTT.

One recurrent hidden layer of LIF neurons with a non-spiking readout, as in Fig 3, plus the three techniques of Fig 5:

  • receptive fields: hidden neuron i sees a window of rf_window neighbouring input channels (after pooling), the windows spread evenly over the channels; the masked input weights stay zero and receive no gradient;

  • sparse recurrence: a fraction recurrent_prob of the recurrent synapses exists, fixed at construction;

  • dropout: during training each hidden neuron is silenced for a whole recording with probability dropout_p (one draw per neuron and recording, held for every step, without rescaling, so the FI fit stays valid).

Input pooling and channel jitter act on the data (chronoprop.data), the cosine schedule in chronoprop.train.train().

The hidden neurons may differ: tau_mem_hidden and R_hidden are per-neuron tensors, and the proxy gets one FI fit per neuron. In the paper they differ only under the time-constant mismatch of Fig 6; everywhere else they are identical.

Research-code names: CUBAHeterogeneousRecurrentTemporalRatepropNet and its surrogate-gradient twin CUBAHeterogeneousRecurrentTemporalSurrogateNet, with the paper’s settings fixed (non-spiking readout, one step per input frame, recurrent spikes carried across windows). Parameter and buffer names are those of the research code, so the released networks load unchanged (see chronoprop.pretrained.load_state_dict()).

class chronoprop.networks.techniques.ChronoPropTechniques(num_inputs, num_hidden, num_outputs, window_steps, tau_mem_hidden, R_hidden, proxy_gain, proxy_threshold, dt, device, recurrent_prob=0.25, rf_window=40, rf_connections=40, dropout_p=0.025, input_pool_size=5, threshold=1.0, reset=0.0, tau_syn=0.002, tau_mem_out=0.01, R_out=5.0, mem_noise_sigma=0.0, mem_noise_sigma_out=0.0)[source]#

The network of Figs 5 and 6 trained by ChronoProp.

Parameters:
  • num_inputs (Final[int]) – input channels the network sees (after pooling; 140 on SHD).

  • num_hidden (Final[int]) – layer sizes (Fig 5’s best SHD network: 512, 20).

  • num_outputs (Final[int]) – layer sizes (Fig 5’s best SHD network: 512, 20).

  • window_steps (int) – steps per ChronoProp time window (100 at dt = 0.1 ms).

  • tau_mem_hidden (Tensor) – per-neuron membrane time constants, tensor [num_hidden].

  • R_hidden – membrane resistance, a float or a tensor [num_hidden].

  • proxy_gain (Tensor) – per-neuron FI fit on the proxy’s axis, tensors [num_hidden].

  • proxy_threshold (Tensor) – per-neuron FI fit on the proxy’s axis, tensors [num_hidden].

  • dt (Final[float]) – simulation step in seconds.

  • recurrent_prob (float) – fraction of recurrent synapses that exist.

  • rf_window (int) – receptive-field width and synapses per window (0, 0 = every neuron sees every channel).

  • rf_connections (int) – receptive-field width and synapses per window (0, 0 = every neuron sees every channel).

  • dropout_p (Final[float]) – probability that a hidden neuron is silenced for a training recording.

  • input_pool_size (int) – channels summed per input (only rescales the initial input weights to the pooled input’s variance).

  • tau_mem_out – readout neuron (floats, or per-class tensors under the time-constant mismatch of Fig 6).

  • R_out – readout neuron (floats, or per-class tensors under the time-constant mismatch of Fig 6).

  • mem_noise_sigma – membrane noise per step (Fig 6).

  • mem_noise_sigma_out – membrane noise per step (Fig 6).

  • device (device)

  • threshold (float)

  • reset (float)

  • tau_syn (float)

apply_recurrent_mask()[source]#

Keep the absent recurrent and input synapses at zero; call after every optimizer step.

Return type:

None

dropout_mask(B)[source]#

[B, num_hidden]: 0 for the neurons silenced in each of B recordings (training only; all ones in evaluation).

Parameters:

B (int)

Return type:

Tensor

class chronoprop.networks.techniques.BPTTTechniques(*args, surrogate_alpha=2.0, **kwargs)[source]#

The same network trained by BPTT, Fig 6’s control.

Built by the same constructor, so a seed gives the same weights and masks as ChronoPropTechniques. The hidden layer is simulated with the surrogate spike function and differentiated through the whole recording; every hidden spike enters the readout synapse at the step it fires. The proxy’s FI fit is stored and never used.

Parameters:

surrogate_alpha (Final[float])

Datasets#

data#

Datasets and batching.

class chronoprop.data.SHD(root='data/SHD', train=True, dt_us=1000, download=True, pool=1)[source]#

One SHD split as spike frames; items are (frames [T, 1, 700 // pool] int16 tensor, label).

The spike times are read once into memory (about 0.3 GB for the training split); frames are built on access. pool sums neighbouring channels (pool_channels(); 1 = off).

Parameters:
  • train (bool)

  • dt_us (int)

  • download (bool)

  • pool (int)

class chronoprop.data.PadToWindow(window_steps=1, batch_first=True)[source]#

Collate function: pad a batch of sequences with zeros to a multiple of window_steps.

Sequences in a batch are first padded to the longest one. For ChronoProp the batch is then padded further to a whole number of time windows, so no step is left out; for BPTT use window_steps=1. Research-code name: PadTensors.

Parameters:
  • window_steps (int)

  • batch_first (bool)

class chronoprop.data.ChannelJitter(dataset, sigma=4.0)[source]#

Training augmentation of Figs 5 and 6: shift each recording along the channel axis by round(N(0, sigma)) channels, filling the vacated edge with zeros.

A new shift is drawn every time a recording is loaded, so every epoch sees new ones. Items come out as float32. Research-code name: AugmentedDataset with only ch_jitter_sigma set (the paper’s other augmentations are off).

Parameters:

sigma (float)

chronoprop.data.load_shd(root='data/SHD', dt_us=1000, val_fraction=0.15, seed=42, download=True, pool=1)[source]#

Return (train, val, test) datasets with the paper’s split (6,932 / 1,224 / 2,264).

pool=5 gives the 140 pooled channels of Figs 5 and 6.

Parameters:
  • dt_us (int)

  • val_fraction (float)

  • seed (int)

  • download (bool)

  • pool (int)

chronoprop.data.pool_channels(frames, pool)[source]#

Sum neighbouring channels in groups of pool: [T, 1, 700] -> [T, 1, 700 // pool].

The network of Figs 5 and 6 sees SHD’s 700 channels pooled to 140 (pool=5).

Parameters:
  • frames (ndarray)

  • pool (int)

Return type:

ndarray

chronoprop.data.spikes_to_frames(times_s, units, dt_us)[source]#

Bin one sample’s spikes into frames, identical to tonic 1.6 ToFrame.

times_s are the float16 spike times in seconds as stored in the h5 file, units the channel of each spike. Returns int16 counts [frames, 1, 700].

Parameters:
  • times_s (ndarray)

  • units (ndarray)

  • dt_us (int)

Return type:

ndarray

chronoprop.data.paper_split()[source]#

The paper’s exact split of the SHD training set: (train_indices, val_indices).

Shipped with the package (computed with scikit-learn 1.7.1; versions 1.7-1.9 give the same indices), so a future scikit-learn cannot change it.

data.images#

MNIST and Fashion-MNIST as the paper used them (Fig. 2).

Images are scaled to [0, 1] and kept as one tensor in memory. The network turns each pixel into a spike train itself (Bernoulli spikes at a rate proportional to the pixel value), so the dataset holds plain images. The paper holds out a label-stratified 20 % of the training set for validation (seed 42); the split ships with the package, so it cannot change with a scikit-learn version.

chronoprop.data.images.image_split(dataset='mnist')[source]#

The paper’s split of the training set: (train_indices, val_indices) as lists.

Parameters:

dataset (str)

chronoprop.data.images.load_images(dataset='mnist', root='data', download=True)[source]#

Return (train, val, test) for 'mnist' or 'fmnist' with the paper’s split (48,000 / 12,000 / 10,000 images); items are (image [1, 28, 28] in [0, 1], label).

Parameters:
  • dataset (str)

  • download (bool)

data.addshd#

addSHD (Supplementary Fig. 7): two spoken digits at once, one per compartment.

Each item pairs an English SHD digit (classes 0-9) with a German one (10-19). The English recording drives the somata, the German one the dendrites, and the label is the sum of the two digits (0-18, 19 classes). The two recordings are padded to a common length and stacked, so an item is (frames [T, 2, 700] float32, label) with the English stream in channel 0 and the German stream in channel 1.

Pairs: every English recording gets one German partner, drawn as one permutation of the German pool per epoch.

  • Training draws a new permutation every epoch (AddSHD.set_epoch(), which chronoprop.train.train() calls before each epoch), seeded by the run’s seed.

  • Validation and test keep one fixed permutation (seed 0), so every run, method and learning rate is scored on the same pairs.

Split: the paper splits each language’s training recordings separately (label-stratified 15 % validation, seed 42); validation pairs come from the two validation pools. Test pairs come from the SHD test file. Research-code name: AddSHDPairs (task8 dend_ext.py).

class chronoprop.data.addshd.AddSHD(english, german, seed)[source]#

English recordings paired with German partners; label = sum of the two digits.

Parameters:

seed (int)

set_epoch(epoch)[source]#

Draw the German partners of epoch (one permutation of the German pool).

Parameters:

epoch (int)

Return type:

None

pair(i)[source]#

(english frames, german frames, label) of item i, unpadded.

chronoprop.data.addshd.addshd_split()[source]#

The paper’s split of the SHD training file for addSHD, as lists of indices: (english_train, english_val, german_train, german_val).

chronoprop.data.addshd.load_addshd(root='data/SHD', dt_us=1000, seed=1234, download=True)[source]#

Return (train, val, test) addSHD datasets with the paper’s split and pairing.

seed seeds the training pairs (the paper uses the run’s seed); validation and test pairs are fixed. Sizes: 3,409 / 602 / 1,079 pairs.

Parameters:
  • dt_us (int)

  • seed (int)

  • download (bool)

Training and the paper’s settings#

train#

Training and evaluation, as in the paper.

Each epoch trains on shuffled batches, then evaluates the validation set and the test set. The paper reports the test accuracy at the epoch of best validation accuracy (test_at_best_val()); it never selects anything on the test set.

The loop keeps the paper’s order of operations, so a run with the same seed draws the same random numbers (weight initialisation, shuffling). Two additions are off by default and do not change a run: resume_path saves the full training state every epoch so an interrupted run continues where it stopped, and checkpoint_path keeps the weights of the best-validation epoch.

chronoprop.train.evaluate(model, loader, device, loss_fn=None)[source]#

Mean loss and accuracy (%) of model over loader, without gradients.

Parameters:
  • model (Module)

  • loader (DataLoader)

  • device (device)

  • loss_fn (Module | None)

Return type:

tuple

chronoprop.train.test_at_best_val(results)[source]#

(test accuracy, epoch index) at the epoch of best validation accuracy.

Parameters:

results (dict)

Return type:

tuple

chronoprop.train.train(model, train_data, test_data, *, batch_size, epochs, lr, device, window_steps=1, val_data=None, recurrent=False, optimizer_name='Adam', grad_clip=None, weight_decay=0.0, lr_schedule='constant', warmup_epochs=10, lr_min=1e-06, num_workers=0, pin_memory=False, checkpoint_path=None, resume_path=None, print_progress=True, defects=None, stop_after_epoch=None)[source]#

Train model and return per-epoch losses and accuracies.

window_steps pads every batch to whole time windows (ChronoProp); use 1 for BPTT. recurrent=True re-applies the recurrent mask after each optimizer step. stop_after_epoch ends training early while keeping the schedule of epochs (a short look at the first epochs of a long run). defects (optional, Fig 6) is a chronoprop.defects.Defects describing the hardware the network is trained and evaluated on.

Returns a dict with lists train_loss, train_acc, val_loss, val_acc (if val_data), test_loss, test_acc and the wall-clock seconds per epoch epoch_seconds.

Parameters:
  • model (Module)

  • batch_size (int)

  • epochs (int)

  • lr (float)

  • window_steps (int)

  • recurrent (bool)

  • optimizer_name (str)

  • grad_clip (float | None)

  • weight_decay (float)

  • lr_schedule (str)

  • warmup_epochs (int)

  • lr_min (float)

  • num_workers (int)

  • pin_memory (bool)

  • checkpoint_path (str | None)

  • resume_path (str | None)

  • print_progress (bool)

  • stop_after_epoch (int | None)

Return type:

dict

configs#

The paper’s settings, and builders that reproduce its networks.

Everything here is a default of the paper’s final runs. The learning rate of every condition is the one the paper selected on validation accuracy (the highest seed-mean of each run’s peak validation accuracy over the learning rates it tried); the selected values and the paper’s results ship in chronoprop/reference/*.json, derived from the raw runs (paper/data).

chronoprop.configs.reference(figure='fig3')[source]#

The paper’s results for one figure (selected learning rates, per-seed results, mean curves).

Parameters:

figure (str)

Return type:

dict

chronoprop.configs.fig3_cell(arch, timestep, method, dataset='shd')[source]#

The paper’s record of one Fig 3 condition, e.g. fig3_cell('rec', 'fine', 'chronoprop').

Parameters:
  • arch (str)

  • timestep (str)

  • method (str)

  • dataset (str)

Return type:

dict

chronoprop.configs.build_fig3_network(arch, method, timestep, device, dataset='shd')[source]#

Build a Fig 3 network exactly as the paper did.

For ChronoProp, the FI curve of the hidden neuron is measured over one window, fitted and moved onto the proxy’s axis before the network is created. Seed the random number generator (chronoprop.set_seed) right before calling this to reproduce the paper’s initial weights for that seed.

Returns (network, info); info holds the hidden size, the selected learning rate, the window length in steps and, for ChronoProp, the FI fit.

Parameters:
  • arch (str)

  • method (str)

  • timestep (str)

  • dataset (str)

chronoprop.configs.fig2_cell(dataset, timestep, method)[source]#

The paper’s record of one Fig 2 condition, e.g. fig2_cell('mnist', '0.1', 'chronoprop') (timestep in ms: '1.0', '0.5' or '0.1').

Parameters:
  • dataset (str)

  • timestep (str)

  • method (str)

Return type:

dict

chronoprop.configs.build_fig2_network(method, timestep, device, dataset='mnist')[source]#

Build a Fig 2 network (MNIST or Fashion-MNIST) exactly as the paper did.

For ChronoProp, the FI curve is measured over the whole 50 ms presentation (the single window), fitted and moved onto the proxy’s axis before the network is created. Seed the random number generator (chronoprop.set_seed) right before calling this to reproduce the paper’s initial weights for that seed.

Returns (network, info); info holds the simulation steps per image, the selected learning rate and, for ChronoProp, the FI fit.

Parameters:
  • method (str)

  • timestep (str)

  • dataset (str)

chronoprop.configs.build_fig2_cost_network(method, steps, device)[source]#

A Fig 2 network (MNIST) simulated with steps steps per image, as in Fig 2c-f.

Each 1 ms input tick lasts steps / 50 simulation steps, so steps must be a multiple of 50. Returns (network, info) as build_fig2_network() does; info['lr'] is the learning rate the paper selected for that step count (None off the paper’s grid).

Parameters:
  • method (str)

  • steps (int)

chronoprop.configs.fig4_cell(arch, timestep, method)[source]#

The paper’s record of one Fig 4 (SHD) condition, e.g. fig4_cell('rec', 'fine', 'chronoprop').

Parameters:
  • arch (str)

  • timestep (str)

  • method (str)

Return type:

dict

chronoprop.configs.build_fig4_network(arch, method, timestep, device)[source]#

Build a Fig 4 network (SHD, adaptive neurons) exactly as the paper did.

For ChronoProp, the FI plane of the adaptive neuron (current x adaptation level) is measured over one window, fitted with max(0, gain * (I - thr0 - alpha * w)) and moved onto the proxy’s axis before the network is created. Seed the random number generator (chronoprop.set_seed) right before calling this to reproduce the paper’s initial weights for that seed.

Returns (network, info); info holds the hidden size, the selected learning rate, the window length in steps and, for ChronoProp, the FI-plane fit.

Parameters:
  • arch (str)

  • method (str)

  • timestep (str)

chronoprop.configs.fig4b_cell(arch, timestep, method)[source]#

The paper’s record of one Supplementary Fig. 7 condition (addSHD), e.g. fig4b_cell('rec', 'fine', 'chronoprop').

Parameters:
  • arch (str)

  • timestep (str)

  • method (str)

Return type:

dict

chronoprop.configs.build_fig4b_network(arch, method, timestep, device)[source]#

Build a Supplementary Fig. 7 network (addSHD, two-compartment neurons) as the paper did.

For ChronoProp, the soma x dendrite FI plane is measured over one window, fitted with max(0, g_d * I_dend + g_s * (I_soma - theta)) and moved onto the proxy’s axis before the network is created. Seed the random number generator (chronoprop.set_seed) right before calling this to reproduce the paper’s initial weights for that seed.

Returns (network, info); info holds the hidden size, the selected learning rate, the window length in steps and, for ChronoProp, the FI-plane fit.

Parameters:
  • arch (str)

  • method (str)

  • timestep (str)

chronoprop.configs.cosine_floor(lr)[source]#

The floor of the cosine schedule of Figs 5 and 6: lr / 10 to four significant digits, as the paper’s runs set it (3e-5 for 3e-4, where 3e-4 / 10 gives 2.9999999999999997e-05).

Parameters:

lr (float)

Return type:

float

chronoprop.configs.build_techniques_network(arm, device, num_hidden=None, recurrent_prob=None, defects=None, chip_seed=None)[source]#

Build the network of Figs 5 and 6 (with the three techniques) exactly as the paper did.

arm is 'chronoprop', 'bptt' or 'bptt_star' (Fig 6’s three networks). num_hidden and recurrent_prob override the arm’s defaults (Fig 5’s grid). Seed the random number generator (chronoprop.set_seed) right before calling this to reproduce the paper’s initial network for that seed. Every arm measures the FI curve, as the paper’s code did, so the random number stream is the same; BPTT never uses the fit.

defects (a chronoprop.defects.Defects, Fig 6) builds the network for training with a defect: membrane noise in every neuron, or a chip with tau mismatch, seeded by chip_seed (the paper uses the training seed), whose neurons each get their own FI fit. The FI fit always comes from the neuron without membrane noise, measured once before training.

Returns (network, info); info holds the timestep, window length, learning rates and the FI fit.

Parameters:
  • arm (str)

  • num_hidden (int)

  • recurrent_prob (float)

  • chip_seed (int)

Released networks#

pretrained#

The trained networks released with the paper.

fetch() downloads them once (from Zenodo) into a local folder; load_network(arm, seed) rebuilds one and loads its weights. The files are the paper’s own checkpoints, byte for byte: a dict with state_dict (the network at its epoch of best validation accuracy), best_val_epoch and best_val_acc. A manifest.json lists every file with its checksum and the accuracies the paper recorded for it.

The folder defaults to ~/.cache/chronoprop; set the environment variable CHRONOPROP_DATA_DIR to use another one (or a copy you already have).

chronoprop.pretrained.fetch(name='shd_networks')[source]#

Return the folder of a released archive, downloading it on first use.

Parameters:

name (str)

Return type:

Path

chronoprop.pretrained.manifest(name='shd_networks')[source]#

The archive’s manifest: per arm and seed, the file, its SHA-256 and the paper’s record.

Parameters:

name (str)

Return type:

dict

chronoprop.pretrained.load_state_dict(model, state_dict)[source]#

Load a research or package state dict into model (strict), in place.

Parameters:
  • model (Module)

  • state_dict (dict)

Return type:

Module

chronoprop.pretrained.load_checkpoint(path, model, device='cpu')[source]#

Load a released checkpoint file into model; returns the file’s metadata (best_val_epoch, best_val_acc).

Parameters:

model (Module)

Return type:

dict

chronoprop.pretrained.load_network(arm, seed, device='cpu', model=None, defect=None)[source]#

A released network, ready to evaluate: (model, record).

arm is 'chronoprop', 'bptt' or 'bptt_star'; seed one of the paper’s ten. Without defect, the defect-free network (archive shd_networks); with defect ('membrane_noise', 'weight_noise', 'weight_bits' or 'tau_mismatch'), the network trained with that defect (archive shd_hil_networks), returned with its chronoprop.defects.Defects as record['defects']: evaluate it inside record['defects'].evaluation(model, device).

record holds what the paper measured for this network (test_acc at the epoch of best validation accuracy, val_acc, best_val_epoch). Pass model (built by chronoprop.configs.build_techniques_network()) to reuse one defect-free network object for several seeds; its FI fit is measured only once that way.

Parameters:
  • arm (str)

  • seed (int)

  • defect (str)

Hardware defects#

defects#

Simulated hardware defects (Fig 6).

Four defects of analog neuromorphic chips, each applied on its own:

  • membrane noise: Gaussian noise added to every membrane potential at every step, declared as its steady-state standard deviation in units of the firing threshold (sigma_Vinf / theta) and converted to a per-step value by membrane_noise_step_sigma();

  • weight noise: every synapse is programmed with an error, declared as a fraction of the full-scale weight (0.10 = 10% of full scale); one draw is a chip, fixed for a whole evaluation pass;

  • weight quantization: every synapse stored on a symmetric grid of 2**bits - 1 levels;

  • tau mismatch: every neuron’s membrane time constant varies across the chip. The spread arises in the leak conductance, so tau and the membrane resistance R scale together by the same factor (log-normal, median 1, the declared coefficient of variation); the chip is frozen for the network’s lifetime.

Weight noise and quantization map each layer’s weights onto the device with the range that minimizes the expected weight error (noise_full_scale(), quantization_full_scale()). Synapses that do not exist (outside the receptive fields, absent recurrent connections) are not devices: they take no error and never set a range. Every on-chip neuron takes every defect, the readout included.

Hardware-in-the-loop (HIL) training applies the defect during training (Defects passed to chronoprop.train.train()); post-training perturbation (PTP) applies it to a network trained without it, only at test.

Research-code names: MemNoiseContext, WeightNoiseContext and WeightQuantContext with the 'mse' mapping, mem_noise_step_sigma, mse_full_scale, mse_quant_scale, sample_leak_factors.

chronoprop.defects.membrane_noise_step_sigma(sigma_vinf, tau_mem, dt)[source]#

Per-step noise that gives a steady-state membrane jitter sigma_vinf.

The noisy membrane is an Ornstein-Uhlenbeck process: a per-step increment of standard deviation s and decay alpha = exp(-dt / tau) give a stationary standard deviation s / sqrt(1 - alpha**2). tau_mem may be a tensor.

Parameters:

dt (float)

class chronoprop.defects.MembraneNoise(model, sigma)[source]#

Context manager: every on-chip membrane (hidden and readout) receives Gaussian noise of per-step standard deviation sigma during the wrapped forward passes, in evaluation too. sigma <= 0 does nothing.

Parameters:
  • model (Module)

  • sigma (float)

chronoprop.defects.noise_full_scale(existing, device_error)[source]#

The full-scale weight F minimizing the expected weight error:

E(F) = sum_i (|w_i| - F)_+^2  +  n (device_error * F)^2

i.e. the clipping error of the synapses above F plus the device error of all n. Convex in F; solved exactly after one sort. device_error = 0 returns max |w| (nothing is clipped).

Parameters:
  • existing (Tensor)

  • device_error (float)

Return type:

float

class chronoprop.defects.WeightNoise(model, device_error, range_error=None)[source]#

Context manager: the weights programmed onto a noisy chip for the wrapped forward passes, the trained (master) weights restored on exit.

Each array is clipped to its full scale (noise_full_scale() at range_error, default device_error) and every existing synapse gets Gaussian error of device_error x full scale. One draw per with block: an evaluation pass sees one chip. In training, the gradient computed on the noisy weights updates the masters. A network trained under weight noise is deployed with the range it trained with: pass its training level as range_error.

Parameters:
  • model (Module)

  • device_error (float)

  • range_error (float)

chronoprop.defects.quantization_full_scale(existing, bits, n_grid=200, n_refine=50)[source]#

The full-scale weight minimizing the squared error of storing the synapses on a symmetric bits-bit grid (Nagel et al. 2021), found by a grid search and a finer search around its best point, in float64.

Parameters:
  • existing (Tensor)

  • bits (int)

  • n_grid (int)

  • n_refine (int)

Return type:

float

class chronoprop.defects.WeightQuantization(model, bits)[source]#

Context manager: every weight array stored on a symmetric bits-bit grid (2**bits - 1 levels) for the wrapped forward passes, the masters restored on exit. Deterministic. In training, the gradient reaches the masters straight-through. bits <= 0 does nothing.

Parameters:
  • model (Module)

  • bits (int)

chronoprop.defects.tau_mismatch_chip(num_hidden, num_outputs, cv, seed, tau_mem=0.01, R=5.0)[source]#

One chip with tau mismatch cv: per-neuron (tau, R) of the hidden layer and of the readout, {'tau_hidden', 'R_hidden', 'tau_out', 'R_out'}. The paper seeds a network’s chip with its training seed.

Parameters:
  • num_hidden (int)

  • num_outputs (int)

  • cv (float)

  • seed (int)

  • tau_mem (float)

  • R (float)

chronoprop.defects.tau_mismatch(model, cv, seed, dt, tau_mem=0.01, R=5.0)[source]#

Context manager: the network deployed on a fresh chip with tau mismatch cv (seeded by seed), the original neurons restored on exit. For PTP: nothing is refitted, since the FI fit enters only the backward pass.

Parameters:
  • model (Module)

  • cv (float)

  • seed (int)

  • dt (float)

  • tau_mem (float)

  • R (float)

class chronoprop.defects.Defects(membrane_noise=0.0, weight_noise=0.0, weight_bits=0, tau_mismatch=0.0)[source]#

The defect a network is trained with (HIL) and evaluated at.

membrane_noise (sigma_Vinf / theta), weight_noise (fraction of full scale), weight_bits (0 = full precision) and tau_mismatch (CV of tau). Pass to chronoprop.configs.build_techniques_network() (membrane noise and tau mismatch are part of the network) and to chronoprop.train.train() (weight noise and quantization act on every training batch, and validation and test run at the defect, with fresh noise every pass).

Parameters:
  • membrane_noise (float)

  • weight_noise (float)

  • weight_bits (int)

  • tau_mismatch (float)

training(model)[source]#

Context for one training batch: quantization first, then device error (a chip is programmed to a grid level, then the device errs).

evaluation(model, device)[source]#

Context for one evaluation pass at the defect. Its noise is drawn from the GPU generator, whose state is restored afterwards, so evaluating at the defect changes which epoch is selected, never the training.

Training cost#

cost#

What one training step of a Fig. 2 network costs: time, memory and operations.

Time and memory are measured on the device. Operations are counted as effective floating-point operations (EFLOPs) by the rules of Narduzzi, Zenke, Liu & Dunbar (2025, Neuromorph. Comput. Eng. 5 034011): an operation on a zero operand is free, so a network that fires less does less work. Counts are exact and per image. The networks are replayed operation by operation, forward and backward, on the masks of the tensors they actually multiply and add.

Operators, on non-zero masks M = [A != 0]:

  • matrix product, per output element: max(0, 2K - 1), where K counts the positions where both factors are non-zero;

  • element-wise product: M_A AND M_B; a product by a non-zero constant costs one per non-zero element;

  • addition: M_A OR M_B;

  • an activation (the spike threshold, the surrogate derivative, the proxy’s gate): one per non-zero argument; the reset after a spike is free;

  • softmax: one per class.

The paper counts inference only. The backward pass is counted with the same operators on the operations autograd executes: a weight used at many steps receives one gradient per step, and their running sum is charged (the first is stored, each later one added). Spike counters and the readout’s voltage sum are running sums too. A running sum is charged on the non-zero entries of what is added (sum_rule='inplace', the paper’s default). Conventions holds the alternatives the paper reports as a sensitivity analysis.

class chronoprop.cost.Conventions(sum_rule='inplace', binary_add=False, charge_accumulators=True, surrogate_elementary=False)[source]#

Where the paper of Narduzzi et al. does not fix the count. The defaults are Fig. 2’s.

  • sum_rule: 'inplace' charges a running sum on the addend’s non-zeros; 'or' applies the addition operator at the size of the running total.

  • binary_add: a product with a binary spike vector costs max(0, K - 1) additions instead of max(0, 2K - 1), and a spike-by-gradient outer product is free.

  • charge_accumulators: count spike counters and the readout’s voltage sum.

  • surrogate_elementary: charge the surrogate derivative’s three elementary operations instead of one activation.

Parameters:
  • sum_rule (str)

  • binary_add (bool)

  • charge_accumulators (bool)

  • surrogate_elementary (bool)

chronoprop.cost.select(terms, conv=Conventions(sum_rule='inplace', binary_add=False, charge_accumulators=True, surrogate_elementary=False))[source]#

The terms charged under conv.

Parameters:
Return type:

dict

chronoprop.cost.totals(terms, conv=Conventions(sum_rule='inplace', binary_add=False, charge_accumulators=True, surrogate_elementary=False))[source]#

Forward and backward EFLOPs per image under conv.

Parameters:
chronoprop.cost.draw_input_spikes(net, images, generator=None)[source]#

Every input frame of a batch at once, [ticks, batch, pixels].

chronoprop.cost.count_operations(net, images, labels, spikes=None)[source]#

Replay one training step of a Fig. 2 network on a batch, forward and backward.

net is a ChronoPropStatic or BPTTStatic (eager, not TorchScript). spikes are the input frames (draw_input_spikes()); give two networks the same frames to count both on the same input. Without them the frames are drawn from the global generator in the network’s own order, so the replay returns exactly the network’s output under the same seed. Returns (terms, stats, grads, logits): terms maps each ledger term to its EFLOPs per image (a float64 tensor [batch]; totals() sums them), stats holds the input and hidden spikes per image, grads the weight gradients (hidden, readout) of the mean cross-entropy, which equal autograd’s, and logits the network’s output.

chronoprop.cost.count_dataset(net, images, labels, batch_size=1024, seed=0)[source]#

Per-image EFLOPs and spikes over a dataset, as Fig. 2 counts them: the input frames of the batch starting at image i are drawn from a generator seeded with seed * 100003 + i, so every network counted with the same seed and batch size sees the same spikes. Returns (terms, stats) as numpy arrays [images].

chronoprop.cost.time_training_steps(net, images, labels, batch_size=256)[source]#

Forward and backward of every full batch, weights frozen (no optimizer step).

On a GPU, CUDA events time the forward (network and loss), the backward and both, and the peak memory allocated across each step is recorded. On a CPU the times come from time.perf_counter and no memory is recorded. Returns per-batch arrays fwd_ms, bwd_ms, fwd_bwd_ms and peak_mb.

Helpers#

The three helpers are also available directly as cp.set_seed, cp.jit and cp.matched_hidden_size.

utils#

Small helpers.

chronoprop.utils.set_seed(seed)[source]#

Seed Python, numpy and torch. The paper’s scripts seeded torch only (torch.manual_seed), which is what matters for weight init and shuffling.

Parameters:

seed (int)

Return type:

None

chronoprop.utils.matched_hidden_size(num_inputs, num_hidden_ff, num_outputs, recurrent_prob)[source]#

Hidden size of a recurrent network with the parameter count of a feedforward one.

Solves p H^2 + (I + O) H = (I + O) H_ff for H (the paper’s Figs 3, 4 and Supp. Fig. 7: 256 feedforward units match 200 all-to-all recurrent units on SHD).

Parameters:
  • num_inputs (int)

  • num_hidden_ff (int)

  • num_outputs (int)

  • recurrent_prob (float)

Return type:

int

chronoprop.utils.jit(module)[source]#

Compile a network with TorchScript, as the paper did, for faster simulation loops.

The paper’s networks were compiled with TorchScript. PyTorch has since deprecated TorchScript, and recent versions (such as 2.14) can no longer compile the surrogate gradient of the BPTT baseline (ATanSurrogate). Every neuron model contains it, so no network compiles there, ChronoProp’s included; the module is then returned uncompiled, with one notice per session. Uncompiled, a network computes the same on a CPU; on a GPU it can round differently and run slower, so only a compiled run repeats the paper’s.

Parameters:

module (Module)

Return type:

Module