Tutorial 4a

Adaptive neurons#

Open In Colab about 45 min on Colab’s T4 GPU

ChronoProp also extends to more complex neurons, by changing how the FI curve is measured and fitted. Adaptive neurons need such an extension, because their spike count in a time window depends on more than that window’s input. Each spike strengthens a slow adaptation current that lasts over many windows, so each window begins at a different level of adaptation, and one FI curve cannot describe the neuron in every window.

We therefore fit each neuron’s count as a function of two variables, its input current and its adaptation current averaged over the window, which gives an FI plane. We first show the effect of adaptation, then measure and fit the FI plane, and train the networks of Tutorial 3 again with adaptive neurons, as in the paper’s Fig. 4. To run it on Colab’s GPU, please select Runtime → Change runtime type → T4 GPU.

# install ChronoProp (skipped when it is already installed)
try:
    import chronoprop as cp
except ImportError:
    %pip install -q "chronoprop @ git+https://github.com/Poirazi-Lab/chronoprop"
    import chronoprop as cp

import matplotlib.pyplot as plt
import numpy as np
import torch
from torch.utils.data import Subset

cuda = torch.cuda.is_available()
device = torch.device('cuda' if cuda else 'cpu')
print(device)
cuda

Settings#

As in Tutorial 3, we keep the paper’s network sizes, time window and learning rates, train for 10 of its 400 epochs, and choose the architecture and timestep below.

ARCH = 'rec'         # 'rec' (recurrent) or 'ff' (feedforward)
TIMESTEP = 'fine'    # 'fine' (0.1 ms) or 'coarse' (1 ms)
EPOCHS = 10          # the paper trains for 400
SEED = 1234          # the first of the paper's 10 seeds
DATA_DIR = 'data/SHD'
SUBSET = 0           # keep only the first SUBSET recordings per split; 0 keeps all

The adaptive neuron#

The adaptive neuron is the LIF neuron of Tutorials 1 and 3 with one more state, an adaptation current \(w\) that is subtracted from the membrane’s input:

\[\begin{split}\begin{aligned} U[t] &= \alpha_\text{mem}\, U[t-1] + (1-\alpha_\text{mem})\,\big(R\, I[t] - w[t-1]\big) \\ w[t] &= \beta\, w[t-1] + b\, S[t], \qquad \beta = e^{-\Delta t/\tau_w} \end{aligned}\end{split}\]

The synaptic current \(I\), the spike \(S\) and the reset are those of Tutorial 1. Each spike adds \(b = 2\) to \(w\), and \(w\) decays with \(\tau_w = 150\) ms, or 15 time windows. To see the effect, we drive the adaptive neuron and a plain LIF neuron with the same constant current for 100 ms and count their spikes in each 10 ms window.

dt = cp.configs.TIMESTEPS[TIMESTEP]['dt']
window_steps = cp.fi.window_steps(cp.configs.WINDOW, dt)  # steps per 10 ms window
print(f'adaptation: {cp.configs.ADAPTATION}')

plain = cp.neurons.LIF(dt=dt, device='cpu', **cp.configs.NEURON)
adaptive = cp.neurons.AdaptiveLIF(dt=dt, device='cpu', **cp.configs.ADAPTATION,
                                  **cp.configs.NEURON)

current = torch.tensor([1.0])
no_input = torch.zeros(1)
n_windows = 10
state_plain = plain.initialize_state(1, 1)
state_adaptive = adaptive.initialize_state(1, 1)
counts_plain = np.zeros(n_windows, int)
counts_adaptive = np.zeros(n_windows, int)
w_trace = []
with torch.no_grad():
    for t in range(n_windows * window_steps):
        spike, state_plain = plain(no_input, state_plain, external_current=current)
        counts_plain[t // window_steps] += int(spike)
        spike, state_adaptive = adaptive(no_input, state_adaptive, external_current=current)
        counts_adaptive[t // window_steps] += int(spike)
        w_trace.append(state_adaptive[2].item())  # the adaptation current w

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 2.8))
time_ms = np.arange(len(w_trace)) * dt * 1e3
ax1.plot(time_ms, w_trace, color='tab:purple')
for k in range(1, n_windows):
    ax1.axvline(k * 10, color='0.85', lw=0.8, zorder=0)  # window boundaries
ax1.set_xlabel('time (ms)')
ax1.set_ylabel('adaptation current w')
ax1.set_title('the adaptive neuron')

windows = np.arange(1, n_windows + 1)
ax2.bar(windows - 0.2, counts_plain, 0.4, color='0.6', label='plain LIF')
ax2.bar(windows + 0.2, counts_adaptive, 0.4, color='tab:purple', label='adaptive')
ax2.set_xticks(windows)
ax2.set_xlabel('time window')
ax2.set_ylabel('spikes')
ax2.set_ylim(0, 1.45 * max(counts_plain.max(), counts_adaptive.max()))  # room for the legend
ax2.legend(loc='upper right', ncol=2)
ax2.set_title('spike count per window, same constant current')
plt.tight_layout()
adaptation: {'tau_w': 0.15, 'spike_triggered_adaptation': 2.0, 'subthreshold_adaptation': 0.0}
../_images/affc4542ff0a5366f504d515405c4edeac40005315671a804e069ba59937ced4.png

The plain neuron fires the same few spikes in every window. The adaptive neuron fires in the first window and then mostly falls silent, because its spikes raised \(w\), which carries over into the following windows. The input current alone no longer tells how many spikes a window will hold. The count also depends on the adaptation the window starts with.

Measuring the FI plane#

ChronoProp therefore measures the count against two variables, the input current \(I\) and the adaptation current averaged over the window, \(\bar w\). measure_fi_plane injects every combination of 201 currents and 101 adaptation levels for one window, holding \(w\) fixed at its level, and counts the spikes. A rectified linear function whose threshold shifts with the adaptation current fits the counts:

\[N = \max\big(0,\; g\,(I - \theta_0 - c\,\bar w)\big)\]

with gain \(g\), threshold \(\theta_0\) without adaptation, and threshold shift \(c\) per unit of \(\bar w\) (gain, thr0 and alpha in the code).

probe = cp.neurons.AdaptiveLIF(dt=dt, device='cpu', tau_w=cp.configs.ADAPTATION['tau_w'],
                               subthreshold_adaptation=0.0, spike_triggered_adaptation=0.0,
                               **cp.configs.NEURON)
I, w_levels, N = cp.fi.measure_fi_plane(probe, num_steps=window_steps, **cp.configs.FI_PLANE)
fit = cp.fi.fit_relu_adaptive(I, w_levels, N)
g, theta0, c = fit['gain'], fit['thr0'], fit['alpha']
print(f"g = {g:.3f}, theta_0 = {theta0:.3f}, c = {c:.3f}, R² = {fit['r_squared']:.3f}")

I_grid, w_grid = np.meshgrid(I.numpy(), w_levels.numpy(), indexing='ij')
fitted = np.maximum(0, g * (I_grid - theta0 - c * w_grid))
onset = theta0 + c * w_levels.numpy()  # where the fit leaves 0
I_max, w_max = I[-1].item(), w_levels[-1].item()

fig, axes = plt.subplots(1, 2, figsize=(11, 3.4), sharey=True)
for ax, Z, title in zip(axes, [N.numpy(), fitted], ['measured', 'fitted']):
    im = ax.imshow(Z.T, origin='lower', aspect='auto', extent=[0, I_max, 0, w_max],
                   cmap='viridis', vmin=0, vmax=N.max().item())
    ax.plot(onset, w_levels.numpy(), 'w--', lw=1)
    ax.set_xlim(0, I_max)
    ax.set_xlabel('input current I')
    ax.set_title(title)
axes[0].set_ylabel('adaptation current w̄')
fig.colorbar(im, ax=axes, label='spikes per window')
g = 5.268, theta_0 = 0.230, c = 0.200, R² = 0.963
<matplotlib.colorbar.Colorbar at 0x7fba47993cb0>
../_images/144d61d6662a4c3af6e139eeed68072816f55bf29f286dd5e7617602ef784c88.png

The dashed line is the fitted onset of firing, \(I = \theta_0 + c\,\bar w\). A stronger adaptation current needs a stronger input before the neuron fires. Above the onset, the count rises with the input at the same slope at every adaptation level, as in the plain neuron. The fit finds \(c\) close to 0.2, which is \(1/R\), as the neuron’s equation predicts. The membrane receives \(R\,I - w = R\,(I - w/R)\), so one unit of \(w\) cancels \(1/R\) units of \(I\).

The backward pass#

In training, each hidden neuron reports its spike count and its mean adaptation current in every window, both read from the simulation without a gradient. The proxy (SpikesToRateAdaptive) passes the count forward unchanged. In the backward pass, it multiplies the gradient by the fitted slope, \(g\) where the neuron’s drive lies above its shifted threshold \(\theta_0 + c\,\bar w\) and 0 below. Two neurons with the same drive but different adaptation therefore get different gradients:

gain, thr0, alpha, _ = cp.fi.proxy_from_adaptive_neuron(probe, window=cp.configs.WINDOW, dt=dt,
                                                        tau_syn=cp.configs.NEURON['tau_syn'])
proxy = cp.proxy.SpikesToRateAdaptive(gain=gain, thr0=thr0, alpha=alpha)

drive = torch.tensor([2.0, 2.0], requires_grad=True)  # same summed input in the window
w_bar = torch.tensor([0.5, 2.0])                      # mean adaptation in the window
counts = torch.tensor([3.0, 0.0])                     # counts from the simulation
proxy(drive, counts, w_bar).sum().backward()
for k in range(2):
    threshold = thr0 + alpha * w_bar[k]
    print(f'w̄ = {w_bar[k]:.1f}: shifted threshold {threshold:.2f}, gradient {drive.grad[k]:.3f}')
w̄ = 0.5: shifted threshold 1.61, gradient 1.080
w̄ = 2.0: shifted threshold 3.07, gradient 0.000

The proxy reads the window’s summed input rather than a constant current, so proxy_from_adaptive_neuron moves the fit onto that axis, as in Tutorial 1. It divides \(g\) by the factor between the two axes and multiplies both thresholds, \(\theta_0\) and \(c\), by it.

Data#

SHD, split as in Tutorial 3.

dt_us = cp.configs.TIMESTEPS[TIMESTEP]['dt_us']
train, val, test = cp.data.load_shd(DATA_DIR, dt_us=dt_us)
if SUBSET:
    train, val, test = (Subset(d, range(min(SUBSET, len(d)))) for d in (train, val, test))
print(f'{len(train)} training, {len(val)} validation, {len(test)} test recordings')
Downloading https://zenkelab.org/datasets/shd_train.h5.zip ...
Downloading https://zenkelab.org/datasets/shd_test.h5.zip ...
6932 training, 1224 validation, 2264 test recordings

Training#

build_fig4_network builds the networks of Tutorial 3 with adaptive hidden neurons, as in the paper, with the same sizes, readout and seeds, and the learning rate the paper selected on validation for each method in this condition. For ChronoProp, it measures and fits the FI plane above before creating the network. BPTT needs no fit, because its surrogate gradient flows through the spikes and, step by step, through the adaptation current.

results = {}
for method in ['chronoprop', 'bptt']:
    cp.set_seed(SEED)
    net, info = cp.configs.build_fig4_network(ARCH, method, TIMESTEP, device)
    n_weights = sum(p.numel() for p in net.parameters())
    print(f"--- {method}: hidden {info['hidden']}, {n_weights:,} weights, "
          f"learning rate {info['lr']:g}")
    if method == 'chronoprop':
        print(f"    {info['window_steps']} steps per window, "
              f"FI plane fit R² = {info['fi']['r_squared']:.3f}")
        window = info['window_steps']
    else:
        window = 1  # BPTT has no time windows
    if cuda:
        net = cp.jit(net)  # compiled, as in the paper
    results[method] = cp.train.train(
        net, train, test, val_data=val, batch_size=128, epochs=EPOCHS, lr=info['lr'],
        device=device, window_steps=window, recurrent=ARCH == 'rec',
        num_workers=2, pin_memory=cuda)
--- chronoprop: hidden 200, 184,000 weights, learning rate 0.0015
    100 steps per window, FI plane fit R² = 0.963
Epoch 1/10 | train loss 2.2977 | val acc 54.00% | test acc 55.87% | 98.7 s
Epoch 2/10 | train loss 1.1935 | val acc 70.02% | test acc 71.16% | 99.7 s
Epoch 3/10 | train loss 0.7386 | val acc 80.80% | test acc 76.46% | 99.2 s
Epoch 4/10 | train loss 0.5232 | val acc 83.50% | test acc 79.68% | 100.7 s
Epoch 5/10 | train loss 0.4345 | val acc 81.78% | test acc 76.86% | 100.6 s
Epoch 6/10 | train loss 0.3775 | val acc 88.40% | test acc 81.45% | 99.9 s
Epoch 7/10 | train loss 0.3258 | val acc 88.32% | test acc 80.70% | 100.3 s
Epoch 8/10 | train loss 0.2705 | val acc 89.54% | test acc 82.73% | 100.9 s
Epoch 9/10 | train loss 0.2414 | val acc 87.91% | test acc 83.30% | 100.3 s
Epoch 10/10 | train loss 0.2091 | val acc 88.81% | test acc 80.39% | 100.7 s
--- bptt: hidden 200, 184,000 weights, learning rate 0.0003
Epoch 1/10 | train loss 2.9881 | val acc 5.15% | test acc 5.70% | 159.3 s
Epoch 2/10 | train loss 2.9747 | val acc 8.74% | test acc 7.07% | 157.0 s
Epoch 3/10 | train loss 2.9605 | val acc 11.85% | test acc 11.75% | 158.3 s
Epoch 4/10 | train loss 2.9435 | val acc 11.60% | test acc 11.13% | 158.4 s
Epoch 5/10 | train loss 2.9279 | val acc 14.46% | test acc 16.52% | 160.1 s
Epoch 6/10 | train loss 2.9090 | val acc 14.13% | test acc 17.45% | 156.1 s
Epoch 7/10 | train loss 2.8926 | val acc 14.30% | test acc 13.12% | 153.8 s
Epoch 8/10 | train loss 2.8778 | val acc 17.48% | test acc 20.54% | 154.4 s
Epoch 9/10 | train loss 2.8616 | val acc 17.16% | test acc 22.13% | 155.1 s
Epoch 10/10 | train loss 2.8449 | val acc 13.32% | test acc 18.46% | 155.7 s

Comparison with the paper#

The figure compares the test accuracy reached here, at the epoch of best validation accuracy, with the paper’s mean ± s.d. over 10 seeds after 400 epochs with adaptive neurons. Light bars are the networks trained here and dark bars the paper’s.

names = {'chronoprop': 'ChronoProp', 'bptt': 'BPTT'}
dark = {'chronoprop': '#384860', 'bptt': '#E1963C'}
light = {'chronoprop': '#d7dadf', 'bptt': '#f5dcbd'}

fig, ax = plt.subplots(figsize=(4, 3))
for i, method in enumerate(['chronoprop', 'bptt']):
    here, _ = cp.train.test_at_best_val(results[method])
    ax.bar([-0.33, -0.15][i], here, 0.18, color=light[method], label=f'{names[method]} here')
for i, method in enumerate(['chronoprop', 'bptt']):
    paper = cp.configs.fig4_cell(ARCH, TIMESTEP, method)
    ax.bar([0.15, 0.33][i], paper['mean'], 0.18, yerr=paper['sd'], color=dark[method],
           label=f'{names[method]} paper')
condition = {'rec': 'recurrent', 'ff': 'feedforward'}[ARCH]
ax.set_xticks([0], [f'{condition}, {TIMESTEP} timestep'])
ax.set_ylim(0, 100)
ax.set_ylabel('test accuracy (%)')
ax.spines[['top', 'right']].set_visible(False)
ax.legend(ncol=2, frameon=False, loc='lower center', bbox_to_anchor=(0.5, 1))
plt.tight_layout()
../_images/a4d4d270e1f167c9d91fe46a23a7bd841cade4be35b34a478845ee1c7d14177b.png

In the paper, adaptive neurons raise ChronoProp’s accuracy on SHD in every condition. The comparison between the methods keeps the pattern of Tutorial 3. In recurrent networks at the fine timestep, ChronoProp reaches 84.03% against BPTT’s 64.38% (80.07% and 63.60% without adaptation), and wherever BPTT’s chain is short or has no recurrent loop, BPTT matches or exceeds ChronoProp. Set ARCH or TIMESTEP above to see it.

Training cost#

Seconds per epoch and peak GPU memory of each method in this run.

for method in ['chronoprop', 'bptt']:
    r = results[method]
    line = f"{names[method]:10} {np.mean(r['epoch_seconds']):6.1f} s per epoch"
    if 'peak_memory_mb' in r:
        line += f", peak GPU memory {r['peak_memory_mb']:.0f} MB"
    print(line)
ChronoProp  100.1 s per epoch, peak GPU memory 778 MB
BPTT        156.8 s per epoch, peak GPU memory 1137 MB

As in Tutorial 3, ChronoProp needed less time and memory than BPTT (36% less total epoch time and 32% less peak memory on Colab’s T4 GPU). These are totals for a whole epoch, which include simulating every step in the forward pass, loading the data and evaluating the network, so the difference between the two gradients alone is larger.

Summary#

With adaptive neurons in a recurrent network at the fine timestep, temporal ChronoProp reached 82.73% test accuracy on SHD in 10 epochs, close to the paper’s 84.03% after 400 epochs. BPTT reached 20.54%, rising slowly as in the paper’s first epochs, on its way to the paper’s 64.38%. ChronoProp described the adaptive neuron by an FI plane, measured once over the input current and the adaptation current, and its proxy shifts each neuron’s threshold by the adaptation the neuron carries in every window. On Colab’s T4 GPU, ChronoProp also needed 36% less total epoch time and 32% less peak memory, measured over whole epochs that include loading the data and evaluating the network.

What’s next#