Tutorial 3

Learning from temporal data#

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

Sounds carry much of their information in the timing of their features. A single spike count per neuron, as in Tutorial 2, records how many spikes a neuron fired, but not when. Temporal ChronoProp keeps this timing by counting spikes in short, successive time windows. Each window gives its own gradient, and the gradients add up to one weight update. Time is divided only for learning, and the network runs through the whole recording without interruption.

We train the same network with temporal ChronoProp and with BPTT on the Spiking Heidelberg Digits (SHD), spoken digits encoded as spikes on 700 channels, and compare the two with the paper’s Fig. 3. The default is the condition in which the two methods differ most, a recurrent network at the fine timestep of 0.1 ms. The settings below switch to a feedforward network or to the coarse timestep of 1 ms. To run it on Colab’s GPU, please select Runtime → Change runtime type → T4 GPU.

Fig. 3a,b of the paper: static and temporal ChronoProp, and input windows

a: Static ChronoProp computes one gradient per sample from one spike count per neuron, whereas temporal ChronoProp divides the recording into time windows and computes one per window.
b: One SHD recording (700 input channels) and its windows of duration \(K = 10\) ms. The network runs through the whole recording without interruption, and only the gradient is divided.

# 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#

The paper trains each condition for 400 epochs with 10 seeds. Here we train one seed for 10 epochs, because all 400 would take too long on Colab, especially with BPTT. Ten epochs are enough to see the difference open up, and everything else (network size, time window, learning rates) is as in the paper.

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

Data#

load_shd downloads SHD (about 170 MB) and splits it as in the paper, into 6,932 training and 1,224 validation recordings from the same speakers, and 2,264 test recordings, most of them from two speakers never heard in training. Each recording becomes a sequence of spike-count frames, one per simulation step, holding 1 ms of audio at the fine timestep and 10 ms at the coarse one.

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')

frames, label = train[0]
steps, channels = frames[:, 0, :].nonzero(as_tuple=True)
fig, ax = plt.subplots(figsize=(8, 2.6))
ax.plot(steps, channels, '|', ms=2, color='k')
ax.set_xlabel('simulation step')
ax.set_ylabel('input channel')
ax.set_title(f'one recording, digit class {label}: {frames.shape[0]} steps')
plt.tight_layout()
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
../_images/b1a12565b7254e675129657cf227ff620c6bd3b64a23094d8a41e9d047dbd7f2.png

Training#

build_fig3_network builds a network as in the paper. Both methods train the same architecture, one hidden layer of LIF neurons (200 recurrent or 256 feedforward units, so that both have about 184,000 weights) and a non-spiking readout. For ChronoProp it first measures the neuron’s FI curve over one 10 ms window, as in Tutorial 1. Each method uses the learning rate the paper selected for it on validation accuracy.

Seeding right before building repeats the paper’s procedure for this seed, so both methods start from the same initial weights and see the same batches in the same order. ChronoProp pads each batch to whole windows, while BPTT processes every step.

results = {}
for method in ['chronoprop', 'bptt']:
    cp.set_seed(SEED)
    net, info = cp.configs.build_fig3_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 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.0005
    100 steps per window, FI fit R² = 0.965
Epoch 1/10 | train loss 2.7073 | val acc 32.03% | test acc 32.24% | 87.4 s
Epoch 2/10 | train loss 1.8773 | val acc 45.34% | test acc 45.76% | 86.9 s
Epoch 3/10 | train loss 1.3801 | val acc 56.13% | test acc 49.07% | 86.6 s
Epoch 4/10 | train loss 1.0662 | val acc 67.73% | test acc 60.16% | 87.1 s
Epoch 5/10 | train loss 0.8315 | val acc 72.88% | test acc 62.23% | 86.2 s
Epoch 6/10 | train loss 0.6980 | val acc 79.74% | test acc 67.31% | 86.7 s
Epoch 7/10 | train loss 0.5657 | val acc 82.76% | test acc 67.98% | 86.5 s
Epoch 8/10 | train loss 0.4559 | val acc 85.29% | test acc 70.49% | 86.5 s
Epoch 9/10 | train loss 0.3986 | val acc 81.45% | test acc 69.30% | 86.4 s
Epoch 10/10 | train loss 0.3462 | val acc 86.85% | test acc 70.94% | 86.9 s
--- bptt: hidden 200, 184,000 weights, learning rate 0.001
Epoch 1/10 | train loss 2.9858 | val acc 7.27% | test acc 7.69% | 130.1 s
Epoch 2/10 | train loss 2.8247 | val acc 12.01% | test acc 20.27% | 129.1 s
Epoch 3/10 | train loss 2.6607 | val acc 15.28% | test acc 21.42% | 128.3 s
Epoch 4/10 | train loss 2.5764 | val acc 17.89% | test acc 20.14% | 130.8 s
Epoch 5/10 | train loss 2.5168 | val acc 22.14% | test acc 26.06% | 131.6 s
Epoch 6/10 | train loss 2.4720 | val acc 25.00% | test acc 30.04% | 131.1 s
Epoch 7/10 | train loss 2.4297 | val acc 22.63% | test acc 26.59% | 132.4 s
Epoch 8/10 | train loss 2.3830 | val acc 31.37% | test acc 34.58% | 133.0 s
Epoch 9/10 | train loss 2.3515 | val acc 28.51% | test acc 33.48% | 131.1 s
Epoch 10/10 | train loss 2.3201 | val acc 30.80% | test acc 34.01% | 131.3 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. Light bars are the networks trained here and dark bars the paper’s. Test accuracy is lower than validation accuracy because most test recordings come from speakers the network never heard in training.

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.fig3_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/5f0f5361e7a976c4d6781a5be4979ff8faab7b329bfcc7edee74cda401d5080a.png

The gap between the methods comes from the chains along which they compute the gradient. BPTT follows the network’s state \(h_t\) (membrane potentials, synaptic currents and, in a recurrent network, the spikes fed back) step by step, so a loss at step \(t\) reaches an earlier step \(s\) through one factor per step:

\[\frac{\partial h_t}{\partial h_s} = \prod_{u=s+1}^{t} \frac{\partial h_u}{\partial h_{u-1}}\]

Across one 10 ms window that is 10 factors at \(\Delta t = 1\) ms and 100 at 0.1 ms, and in a recurrent network each factor passes through the recurrent loop. ChronoProp’s gradient is a sum over windows \(k\) of chains that each stay inside their window (Tutorial 1),

\[\frac{\partial \mathcal{L}}{\partial W} = \sum_k \frac{\partial \mathcal{L}}{\partial N_k}\, f'(I_k)\, \frac{\partial I_k}{\partial W}\]

so its chain has the same length at any timestep. In the recurrent network at the fine timestep, BPTT multiplies one derivative per 0.1 ms step around the loop, and it learns slowly or not at all. At the coarse timestep or in the feedforward network, BPTT’s chain is shorter or has no loop, and BPTT does as well as or better than ChronoProp, as in the paper. 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   86.7 s per epoch, peak GPU memory 778 MB
BPTT        130.9 s per epoch, peak GPU memory 1136 MB

ChronoProp’s gains in time and memory appear more modest here (34% less total epoch time and 32% less peak memory than BPTT on Colab’s T4 GPU) than in Tutorial 2. These numbers are totals for a whole epoch, not the cost of the gradient alone. Both methods simulate every step of every recording in the forward pass, load and batch the data, and evaluate the validation and test sets, and these parts take about the same time for both. Loading the data on Colab’s two CPU cores can also hold the GPU back. The peak memory includes the input batch, thousands of steps on 700 channels per recording, which is the same for both methods. The difference between the two gradients alone is larger than these totals show.

Summary#

In a recurrent network at the fine timestep, temporal ChronoProp reached 70.94% test accuracy on SHD in 10 epochs and BPTT 34.58%, the same order as the paper’s 80.07% and 63.60% after 400 epochs. BPTT’s gradient passes through one factor per 0.1 ms step around the recurrent loop, while ChronoProp’s stays inside each time window, so its length does not depend on the timestep. On Colab’s T4 GPU, ChronoProp also needed 34% 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#