Tutorial 1

A gradient per time window#

Open In Colab under a minute on Colab’s CPU

ChronoProp learns only from each neuron’s spike count \(N\) in a time window, and takes the derivative \(\partial N/\partial I\) from the slope of the neuron’s fitted FI curve. The membrane potential is simulated at every step but never differentiated. In this tutorial we build each piece by hand in PyTorch, to show how ChronoProp works without the package. The chronoprop package contains all of it, and more, and we point to the matching part at each step. The other tutorials use the package directly.

Fig. 1 of the paper: ChronoProp versus BPTT

Left: In ChronoProp, the forward pass simulates the neuron without gradients and reports its spike count \(N\). The backward pass reaches the weights through the fitted FI curve, whose derivative is a step.
Right: BPTT differentiates every spike \(S_t\) through a surrogate \(\sigma(U)\) of the threshold function and sums the chain over all simulation steps \(t\).

import matplotlib.pyplot as plt
import numpy as np
import torch
from scipy.optimize import curve_fit

The LIF neuron#

We use the paper’s neuron, a current-based leaky integrate-and-fire (LIF) neuron. The synaptic current \(I\) low-pass filters the weighted input spikes \(X_j\), the membrane potential \(U\) low-pass filters the current, and the neuron fires a spike \(S\) when \(U\) crosses the threshold \(\vartheta\), after which \(U\) resets. In discrete time, with timestep \(\Delta t\),

\[\begin{split}\begin{aligned} I[t] &= \alpha_\text{syn}\, I[t-1] + \textstyle\sum_j W_j X_j[t] \\ U[t] &= \alpha_\text{mem}\, U[t-1] + R\,(1-\alpha_\text{mem})\, I[t] \\ S[t] &= \Theta\big(U[t] - \vartheta\big), \qquad U[t] \leftarrow U_\text{reset} \ \text{ if } S[t] = 1 \end{aligned}\end{split}\]

with decay factors \(\alpha = e^{-\Delta t/\tau}\), time constants \(\tau_\text{mem} = 10\) ms and \(\tau_\text{syn} = 2\) ms, membrane resistance \(R = 5\), \(\vartheta = 1\), \(U_\text{reset} = 0\) and the Heaviside step function \(\Theta\). We simulate at the paper’s fine timestep, \(\Delta t = 0.1\) ms.

Below we write one step of these equations in PyTorch, with I_syn for the synaptic current \(I\), and inject four constant currents into the neuron. The current enters after the synapse, so it adds to \(I[t]\) in the second line. In the package, this neuron is cp.LIF.

dt = 1e-4  # 0.1 ms
tau_mem, tau_syn, R, threshold, reset = 10e-3, 2e-3, 5.0, 1.0, 0.0
alpha_mem = torch.exp(torch.tensor(-dt / tau_mem))
alpha_syn = torch.exp(torch.tensor(-dt / tau_syn))

def lif_step(X, U, I_syn, I_ext=0.0):
    I_syn = alpha_syn * I_syn + X
    U = alpha_mem * U + R * (1 - alpha_mem) * (I_syn + I_ext)
    S = (U > threshold).float()
    U = U * (1 - S) + reset * S
    return S, U, I_syn

currents = torch.tensor([0.15, 0.3, 0.45, 0.6])
U, I_syn = torch.zeros(4), torch.zeros(4)
trace, spikes = [], []
for t in range(300):  # 30 ms
    S, U, I_syn = lif_step(torch.zeros(4), U, I_syn, currents)
    trace.append(U)
    spikes.append(S)
trace, spikes = torch.stack(trace), torch.stack(spikes)

time_ms = torch.arange(300) * dt * 1e3
fig, axes = plt.subplots(2, 2, figsize=(9, 5.5), sharex=True, sharey=True)
for k, ax in enumerate(axes.flat):
    ax.plot(time_ms, trace[:, k])
    ax.vlines(time_ms[spikes[:, k] > 0], 1.0, 1.3, color='k')
    ax.axhline(1.0, ls=':', color='gray')
    n_spikes = int(spikes[:, k].sum())
    ax.set_title(f'I = {currents[k]:.2f}, {n_spikes} spikes')
for ax in axes[1]:
    ax.set_xlabel('time (ms)')
for ax in axes[:, 0]:
    ax.set_ylabel('membrane potential U')
plt.tight_layout()
../_images/7a92fe5c11c937cae2450d4a466b5a46f0edc5be29358097fe50b5b30558a703.png

The weakest current never reaches the threshold, and stronger currents fire more often. ChronoProp’s gradient uses neither the membrane potential nor the individual spikes, only how many spikes fall in a time window, which is what we measure next.

Measuring and fitting the FI curve#

Before training, ChronoProp measures how the spike count \(N\) in one time window depends on a constant input current \(I\), the neuron’s FI curve. The window is 10 ms, as in the paper’s networks trained on audio, or 100 steps at \(\Delta t = 0.1\) ms. We drive 201 neurons from rest, one per current between 0 and 1, and count their spikes. Once the neuron starts to fire, the count rises nearly in proportion to \(I\), so we fit it with a rectified line, \(f(I) = g\,\max(0,\, I - \theta_0)\), with gain \(g\) and threshold current \(\theta_0\). In the package, cp.fi.measure_fi_curve measures the curve and cp.fi.fit_relu fits it.

window_steps = 100  # 10 ms
currents = torch.linspace(0, 1, 201)
U, I_syn = torch.zeros(201), torch.zeros(201)
N = torch.zeros(201)
for t in range(window_steps):
    S, U, I_syn = lif_step(torch.zeros(201), U, I_syn, currents)
    N += S

def f(I, g, theta0):
    return np.maximum(0, g * (I - theta0))

I_np, N_np = currents.numpy(), N.numpy()
first_spiking = I_np[N_np > 0][0]
# start from gain 1 and the first current that fires
params, _ = curve_fit(f, I_np, N_np, p0=[1, first_spiking])
g, theta0 = params
ss_res = np.sum((N_np - f(I_np, g, theta0)) ** 2)
ss_tot = np.sum((N_np - N_np.mean()) ** 2)
r_squared = 1 - ss_res / ss_tot

fig, ax = plt.subplots(figsize=(6, 3.8))
ax.plot(I_np, N_np, '.', ms=4, label='measured')
ax.plot(I_np, f(I_np, g, theta0), label='fitted ReLU')
ax.text(0.97, 0.05, f'R² = {r_squared:.4f}\ngain = {g:.4f}\nthreshold current = {theta0:.4f}',
        transform=ax.transAxes, ha='right', va='bottom')
ax.set_xlabel('input current I')
ax.set_ylabel('spike count N')
ax.legend(loc='upper left')
plt.tight_layout()
../_images/30e7008589b5b6ffb55461457e971eb553b6ef3b7dfcb7018cf808cc5a8c588a.png

The fit matches the paper’s at this timestep (\(R^2\) = 0.9655). ChronoProp calls this fitted curve the neuron’s proxy. The simulated neuron is deterministic, so one measurement per timestep and window length suffices, made once before training. The two numbers \(g\) and \(\theta_0\) are all ChronoProp needs to know about the neuron.

The backward pass#

Training needs the derivative of each neuron’s spike count with respect to its input current, \(\partial N/\partial I\), and the count has no useful one. It rises in whole steps, so its slope is zero between the steps and undefined at them. ChronoProp takes the derivative from the fitted ReLU instead, which is why we fitted it. Its slope \(f'(I)\) is the gain \(g\) above \(\theta_0\) and 0 below (Fig. 1, left insets), and it is the middle factor in the gradient of the loss \(\mathcal{L}\) with respect to each weight \(W\),

\[\frac{\partial \mathcal{L}}{\partial W} = \frac{\partial \mathcal{L}}{\partial N}\cdot \frac{\partial N}{\partial I}\cdot\frac{\partial I}{\partial W}.\]

The first factor comes from the layers after the neuron, and the last is the input spike count \(X\).

Autograd cannot compute this factor itself, because the counts come from a simulation run without gradients. We therefore define the layer with torch.autograd.Function, which takes the forward and backward passes separately. The forward pass returns the measured counts \(N\), and the backward pass multiplies the incoming gradient by \(f'(I)\) at the current saved in the forward pass. In the package, this layer is cp.proxy.SpikesToRate.

class SpikesToRate(torch.autograd.Function):

    @staticmethod
    def forward(ctx, I, N, gain, threshold):
        ctx.save_for_backward(I)
        ctx.gain, ctx.threshold = gain, threshold
        return N

    @staticmethod
    def backward(ctx, grad_N):
        I = ctx.saved_tensors[0]
        grad_I = grad_N * (I > ctx.threshold).float() * ctx.gain
        # one gradient per input of forward: only I receives one
        return grad_I, None, None, None

We pass the 201 currents and their counts through it. Summing the output gives each neuron an incoming gradient of 1, so I.grad shows \(\partial N/\partial I\).

I = currents.clone().requires_grad_()
out = SpikesToRate.apply(I, N, g, theta0)
out.sum().backward()

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 2.8))
ax1.plot(I_np, N_np, '.', ms=3, label='measured')
ax1.plot(I_np, f(I_np, g, theta0), label='fitted f(I)')
ax1.set_title('fitted proxy')
ax1.set_xlabel('input current I')
ax1.set_ylabel('spike count N')
ax1.legend()
ax2.plot(I_np, I.grad)
ax2.set_title('proxy derivative')
ax2.set_xlabel('input current I')
ax2.set_ylabel('gradient dN/dI')
plt.tight_layout()
../_images/838bfdd73af83742d8fe0d92c4e32701247fce675fee409214980cf86725240c.png

The two panels are the left insets of Fig. 1. Neurons below \(\theta_0\) receive no gradient, and all others the same slope \(g\), however many spikes they fire.

From one neuron to a network#

ChronoProp applies this layer to every hidden neuron in every time window. The forward pass simulates the whole network step by step without gradients, carrying every state across window boundaries, and records each hidden neuron’s spike count in each window. The backward pass treats each hidden layer as an ordinary layer with SpikesToRate as its activation, whose input is the window’s input spike counts times the weights, read on the proxy’s scale (see the note below). The output neurons start each window from their state at the end of the previous one, taken as a constant, so no gradient crosses a window boundary and the gradient is a sum of one term per window.

The proxy’s scale

During training, the proxy does not read a constant current. It reads the window’s summed input, the input spike counts times the weights, and a spike reaches the membrane through the synapse’s low-pass filter, so it delivers less than a current held for the whole window. The two scales differ by the factor \(\kappa = n\,(1 - e^{-\Delta t/\tau_\text{syn}})\), with \(n\) the number of steps in the window, so the proxy divides the gain by \(\kappa\) and multiplies the threshold by \(\kappa\). In this tutorial, \(\kappa\) = 4.877, so the proxy’s gain is 1.0794 and its threshold 1.1227. In the package, cp.fi.rescale_fit does this, and cp.fi.proxy_from_neuron measures, fits and rescales in one call.

Summary#

ChronoProp needs two things from a neuron, its spike count in each time window and the slope of its FI curve. Each time window adds its own term to the gradient, and no gradient crosses a window boundary. Every ChronoProp network in the package is built around SpikesToRate.

What’s next#