Tutorial 2
Efficient image classification#
In its simplest form, ChronoProp uses one time window for the whole input. Here the input is an image, shown to a spiking network for 50 ms as trains of random spikes. ChronoProp then computes one gradient per image from the hidden neurons’ spike counts, whereas BPTT computes one per simulation step. We train both methods on the same network at two timesteps, compare their accuracy with the paper’s, and measure what each costs, as in the paper’s Fig. 2. To run it on Colab’s GPU, please select Runtime → Change runtime type → T4 GPU.
a: Three of the 50 frames of one image, in which each pixel fires random spikes with a probability proportional to its intensity.
b: Test accuracy of ChronoProp (CP) and BPTT at three timesteps on MNIST and Fashion-MNIST. Markers are the 10 seeds, lines their mean.
# 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
cuda = torch.cuda.is_available()
device = torch.device('cuda' if cuda else 'cpu')
print(device)
cuda
Settings#
We use the paper’s network, input encoding and learning rates, but train for 10 of its 120 epochs and at two of its three timesteps. A finer timestep follows the neuron’s dynamics more closely, nearer the continuous time of analog hardware, but needs more steps per image, 50 at 1 ms and 500 at 0.1 ms. The number of steps is what drives BPTT’s cost (see Training cost below).
DATASET = 'mnist' # or 'fmnist' (Fashion-MNIST)
TIMESTEPS = ['1.0', '0.1'] # in ms, any of '1.0', '0.5', '0.1'
EPOCHS = 10 # the paper trains for 120
SEED = 42 # the first of the paper's 10 seeds
Images as spike trains#
The image is shown for 50 input ticks of 1 ms. At every tick, pixel \(j\) (intensity \(x_j\) between 0 and 1) fires a spike with probability
so a white pixel fires 10 spikes per image on average. Each tick lasts one simulation step at Δt = 1
ms and ten steps at 0.1 ms, with the spike on the first of them. The input is therefore the same at
every timestep, and only the resolution of the simulation changes. Below,
cp.data.load_images
loads the dataset with the paper’s validation split, and we draw the spikes of one test image.
train, val, test = cp.data.load_images(DATASET, 'data')
print(f'{len(train)} training, {len(val)} validation, {len(test)} test images')
image, label = test[0]
rate, tick = 200.0, 1e-3
probability = (image.view(-1) * rate * tick).clamp(0, 1)
torch.manual_seed(0)
spikes = torch.bernoulli(probability.expand(50, -1)) # [ticks, pixels]
times, pixels = spikes.nonzero(as_tuple=True)
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(11, 2.6), width_ratios=[1, 1, 2.2])
ax1.imshow(image[0], cmap='gray')
ax1.set_title(f'image (label {label})')
ax1.axis('off')
ax2.imshow(spikes.sum(0).view(28, 28), cmap='gray')
ax2.set_title('spikes per pixel, 50 ms')
ax2.axis('off')
ax3.plot(times, pixels, '|', ms=2, color='k')
ax3.set_title(f'{int(spikes.sum())} input spikes')
ax3.set_xlabel('time (ms)')
ax3.set_ylabel('pixel')
plt.tight_layout()
48000 training, 12000 validation, 10000 test images
Network setup#
The network has 784 inputs, 128 hidden LIF neurons and a non-spiking readout whose membrane potential, averaged over all steps, gives the logits. With one window spanning the image, ChronoProp’s training step is that of Tutorial 1, applied to the whole image at once. The hidden layer is simulated without gradients, and each neuron’s spike count \(N_i\) stands in for its output. Its current \(I_i\) is the input spike counts \(X_j\) times the weights, and the gradient reaches each weight through the slope of the fitted FI curve,
where \(f'(I)\) equals the slope \(g\) above the threshold \(\theta_0\) and 0 below. Both come from the
neuron’s FI curve, measured once over the 50 ms window and rescaled by \(\kappa\)
(Tutorial 1’s note on the proxy’s scale). Below,
cp.fi.proxy_from_neuron
measures, fits and rescales the curve in one call at both timesteps.
ChronoProp’s backward pass therefore has one step, whatever the number of simulation steps, while BPTT’s has one per simulation step, 50 at 1 ms and 500 at 0.1 ms.
for ts in TIMESTEPS:
dt = cp.configs.FIG2_TIMESTEPS[ts]
neuron = cp.neurons.LIF(dt=dt, device='cpu', **cp.configs.NEURON)
gain, threshold, fit = cp.fi.proxy_from_neuron(neuron, window=0.05, dt=dt,
tau_syn=cp.configs.NEURON['tau_syn'])
print(f"Δt = {ts} ms, {fit['window_steps']} steps, R² = {fit['r_squared']:.3f}, "
f"proxy slope {gain:.3f}, threshold {threshold:.3f}")
Δt = 1.0 ms, 50 steps, R² = 0.974, proxy slope 1.052, threshold 2.167
Δt = 0.1 ms, 500 steps, R² = 0.997, proxy slope 1.045, threshold 3.587
Training#
cp.configs.build_fig2_network
builds the network as in the paper, with the learning rate selected on validation for each method
and timestep, and
cp.train.train trains
it. The training loop also records the seconds per epoch and, on a GPU, the peak memory, which
the Training cost section compares.
BPTT’s network
BPTT trains the same network. Its hidden spikes reach the readout through the readout’s synapse, the standard wiring, and its surrogate gradient is that of an arctangent with steepness 8.
results, nets = {}, {}
for ts in TIMESTEPS:
for method in ['chronoprop', 'bptt']:
cp.set_seed(SEED)
net, info = cp.configs.build_fig2_network(method, ts, device, DATASET)
print(f"--- {method}, Δt = {ts} ms, learning rate {info['lr']:g}")
if cuda:
net = cp.jit(net) # compiled, as in the paper
results[ts, method] = cp.train.train(
net, train, test, val_data=val, batch_size=256, epochs=EPOCHS, lr=info['lr'],
device=device, num_workers=2, pin_memory=cuda)
nets[ts, method] = net
--- chronoprop, Δt = 1.0 ms, learning rate 0.0003
Epoch 1/10 | train loss 0.5652 | val acc 91.77% | test acc 92.32% | 9.1 s
Epoch 2/10 | train loss 0.2225 | val acc 94.10% | test acc 94.37% | 9.4 s
Epoch 3/10 | train loss 0.1637 | val acc 95.08% | test acc 95.36% | 8.8 s
Epoch 4/10 | train loss 0.1303 | val acc 95.96% | test acc 95.76% | 8.9 s
Epoch 5/10 | train loss 0.1123 | val acc 96.03% | test acc 96.15% | 9.4 s
Epoch 6/10 | train loss 0.0955 | val acc 96.08% | test acc 96.02% | 8.4 s
Epoch 7/10 | train loss 0.0842 | val acc 96.40% | test acc 96.25% | 9.1 s
Epoch 8/10 | train loss 0.0744 | val acc 96.45% | test acc 96.72% | 9.5 s
Epoch 9/10 | train loss 0.0676 | val acc 96.61% | test acc 96.65% | 8.5 s
Epoch 10/10 | train loss 0.0584 | val acc 96.84% | test acc 97.03% | 9.2 s
--- bptt, Δt = 1.0 ms, learning rate 0.003
Epoch 1/10 | train loss 0.3752 | val acc 93.14% | test acc 93.16% | 14.1 s
Epoch 2/10 | train loss 0.1772 | val acc 95.37% | test acc 95.47% | 14.2 s
Epoch 3/10 | train loss 0.1294 | val acc 96.05% | test acc 96.35% | 14.2 s
Epoch 4/10 | train loss 0.1030 | val acc 96.38% | test acc 96.69% | 13.9 s
Epoch 5/10 | train loss 0.0841 | val acc 96.43% | test acc 96.39% | 13.9 s
Epoch 6/10 | train loss 0.0767 | val acc 96.93% | test acc 96.94% | 14.4 s
Epoch 7/10 | train loss 0.0673 | val acc 96.65% | test acc 96.88% | 14.5 s
Epoch 8/10 | train loss 0.0560 | val acc 97.18% | test acc 97.18% | 14.7 s
Epoch 9/10 | train loss 0.0546 | val acc 96.60% | test acc 96.61% | 14.4 s
Epoch 10/10 | train loss 0.0495 | val acc 97.03% | test acc 97.01% | 15.0 s
--- chronoprop, Δt = 0.1 ms, learning rate 0.0003
Epoch 1/10 | train loss 0.6308 | val acc 91.91% | test acc 91.83% | 65.5 s
Epoch 2/10 | train loss 0.2355 | val acc 94.16% | test acc 94.07% | 66.6 s
Epoch 3/10 | train loss 0.1744 | val acc 94.99% | test acc 95.45% | 68.3 s
Epoch 4/10 | train loss 0.1423 | val acc 95.63% | test acc 95.86% | 66.1 s
Epoch 5/10 | train loss 0.1218 | val acc 95.90% | test acc 95.99% | 66.7 s
Epoch 6/10 | train loss 0.1048 | val acc 96.23% | test acc 96.32% | 66.1 s
Epoch 7/10 | train loss 0.0909 | val acc 96.22% | test acc 96.34% | 64.8 s
Epoch 8/10 | train loss 0.0815 | val acc 96.50% | test acc 96.84% | 67.1 s
Epoch 9/10 | train loss 0.0726 | val acc 96.38% | test acc 96.65% | 65.9 s
Epoch 10/10 | train loss 0.0652 | val acc 96.72% | test acc 96.71% | 66.4 s
--- bptt, Δt = 0.1 ms, learning rate 0.003
Epoch 1/10 | train loss 0.4011 | val acc 92.88% | test acc 92.80% | 126.7 s
Epoch 2/10 | train loss 0.1911 | val acc 95.29% | test acc 95.34% | 127.5 s
Epoch 3/10 | train loss 0.1359 | val acc 96.05% | test acc 96.21% | 127.9 s
Epoch 4/10 | train loss 0.1089 | val acc 96.05% | test acc 96.41% | 129.5 s
Epoch 5/10 | train loss 0.0929 | val acc 96.24% | test acc 96.29% | 129.0 s
Epoch 6/10 | train loss 0.0837 | val acc 96.61% | test acc 96.84% | 125.1 s
Epoch 7/10 | train loss 0.0727 | val acc 96.21% | test acc 96.82% | 125.7 s
Epoch 8/10 | train loss 0.0656 | val acc 97.07% | test acc 96.97% | 125.6 s
Epoch 9/10 | train loss 0.0625 | val acc 96.48% | test acc 96.76% | 125.2 s
Epoch 10/10 | train loss 0.0558 | val acc 97.05% | test acc 97.11% | 124.1 s
Comparison with the paper#
The figure compares the test accuracy reached here, at the epoch of best validation accuracy
(cp.train.test_at_best_val),
with the paper’s mean ± s.d. over 10 seeds after 120 epochs. Light bars are the networks trained here
and dark bars the paper’s.
short = {'chronoprop': 'CP', 'bptt': 'BPTT'}
dark = {'chronoprop': '#384860', 'bptt': '#E1963C'}
light = {'chronoprop': '#d7dadf', 'bptt': '#f5dcbd'}
x = np.arange(len(TIMESTEPS))
fig, ax = plt.subplots(figsize=(6, 3))
for i, method in enumerate(['chronoprop', 'bptt']):
here = [cp.train.test_at_best_val(results[ts, method])[0] for ts in TIMESTEPS]
ax.bar(x + [-0.33, -0.15][i], here, 0.18, color=light[method], label=f'{short[method]} here')
for i, method in enumerate(['chronoprop', 'bptt']):
paper = [cp.configs.fig2_cell(DATASET, ts, method) for ts in TIMESTEPS]
means = [p['mean'] for p in paper]
sds = [p['sd'] for p in paper]
ax.bar(x + [0.15, 0.33][i], means, 0.18, yerr=sds, color=dark[method],
label=f'{short[method]} paper')
ax.set_xticks(x, [f'Δt = {ts} ms' for ts in TIMESTEPS])
ax.set_ylim(90 if DATASET == 'mnist' else 80, 100)
ax.set_ylabel('test accuracy (%)')
ax.spines[['top', 'right']].set_visible(False)
ax.legend(ncol=4, frameon=False, loc='lower center', bbox_to_anchor=(0.5, 1))
plt.tight_layout()
Training cost#
Here, we recorded each network’s seconds per training epoch and peak GPU memory. Below, we also
count the hidden layer’s firing rate after training, on 1,000 test images, with
cp.networks.hidden_spike_counts.
Timings
The paper’s ratios, 2.98 times the time and 21.7 times the memory, were measured at 2,000 steps per image, and here we use 50 and 500. BPTT keeps and differentiates every step, so its cost grows with the number of steps, while ChronoProp’s backward pass has one step per time window. The ratios here are therefore smaller. These epoch times also include evaluating the validation and test sets and loading the data, which shrinks the time ratio further, since the paper timed the training step alone.
names = {'chronoprop': 'ChronoProp', 'bptt': 'BPTT'}
images = torch.stack([test[i][0] for i in range(1000)])
print(f"{'':24}{'s per epoch':>12}{'peak MB':>12}{'firing Hz':>12}")
for ts in TIMESTEPS:
cost = {}
for method in ['chronoprop', 'bptt']:
r = results[ts, method]
counts = torch.cat([cp.networks.hidden_spike_counts(nets[ts, method], batch)
for batch in images.split(250)])
seconds = np.mean(r['epoch_seconds'])
memory = r.get('peak_memory_mb', np.nan)
rate = counts.mean().item() / 0.05 # spikes per second
cost[method] = np.array([seconds, memory, rate])
label = f'{names[method]}, Δt = {ts} ms'
print(f'{label:24}{seconds:12.1f}{memory:12.1f}{rate:12.1f}')
ratio = cost['bptt'] / cost['chronoprop']
row = f"{'BPTT / ChronoProp':24}{ratio[0]:11.1f}x{ratio[1]:11.1f}x{ratio[2]:11.1f}x"
print(f'\033[1m{row}\033[0m') # ANSI codes for bold text
s per epoch peak MB firing Hz
ChronoProp, Δt = 1.0 ms 9.0 24.1 29.4
BPTT, Δt = 1.0 ms 14.3 97.1 198.8
BPTT / ChronoProp 1.6x 4.0x 6.8x
ChronoProp, Δt = 0.1 ms 66.4 28.8 25.1
BPTT, Δt = 0.1 ms 126.6 254.2 237.8
BPTT / ChronoProp 1.9x 8.8x 9.5x
Summary#
In 10 epochs with one seed, ChronoProp and BPTT reached nearly the same test accuracy on MNIST, 97.03% and 97.18% at Δt = 1 ms and 96.71% and 96.97% at 0.1 ms, close to the 97.6 to 97.8% the paper reached for both after 120 epochs. BPTT needed 1.6 to 1.9 times the time per epoch and 4.0 to 8.8 times the memory of ChronoProp, and its hidden neurons fired 6.8 to 9.5 times as often. Even in this simplified setting, these numbers approach the paper’s, where BPTT needed 2.98 times the time and 21.7 times the memory at 2,000 steps per image and fired 6 to 10 times as often.
What’s next#
Tutorial 3. Learning from temporal data: Learn how to extend ChronoProp to temporal datasets such as spoken digits.