Tutorial 5
Near-SOTA performance with LIF networks#
Up to Fig. 4, both methods trained networks of one fixed width with Adam and nothing else, so that the comparisons concerned the learning rules alone. ChronoProp’s best network of Fig. 3 reached 96.99% on the SHD validation set but 80.07% on the test set, whose speakers are mostly new, so generalization, not learning, limited it. Fig. 5 adds three simple, hardware-compatible techniques (receptive fields, dropout and channel jitter) and varies the width and the recurrent connection density of the hidden layer. Its best network on SHD has 512 plain LIF neurons and a quarter of the possible recurrent connections, and reaches 92.81 ± 0.91% with 96,256 parameters, training only its weights.
We build that network, look at each technique, and test the ten networks the paper trained, which are released with it.
# 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 DataLoader
cuda = torch.cuda.is_available()
device = torch.device('cuda' if cuda else 'cpu')
print(device)
cpu
Settings#
Everything below is the paper’s setting. Training is optional. The paper trained each network for 400 epochs, 1.7 hours per network on its cluster GPUs, so this tutorial tests the released networks instead.
SEED = 5183 # the network built and trained below; the first of the paper's 10 seeds
TRAIN_EPOCHS = 0 # optional: train it for this many epochs of the paper's 400 (0 = skip)
DATA_DIR = 'data/SHD'
Data#
SHD encodes each spoken digit as spikes on 700 channels, ordered along the frequency axis of a cochlea model. The network sees them summed in groups of five neighbouring channels, 140 inputs, at the fine timestep of 0.1 ms with one input frame per millisecond of audio.
train, val, test = cp.data.load_shd(DATA_DIR, dt_us=1000, pool=5)
raw = cp.data.SHD(DATA_DIR, train=False, dt_us=1000)
print(f'{len(train)} training, {len(val)} validation, {len(test)} test recordings')
recorded = raw[0][0][:, 0, :] # [frames, 700 channels]
pooled = test[0][0][:, 0, :] # [frames, 140 channels]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 3))
ax1.imshow(recorded.T > 0, aspect='auto', origin='lower', cmap='Greys', interpolation='none')
ax1.set_title('as recorded: 700 channels')
ax1.set_ylabel('channel')
im = ax2.imshow(pooled.T, aspect='auto', origin='lower', cmap='Greys', interpolation='none')
ax2.set_title('as the network sees it: 140 channels')
fig.colorbar(im, ax=ax2, label='spikes per frame')
for ax in (ax1, ax2):
ax.set_xlabel('frame (1 ms)')
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
Network architecture#
build_techniques_network builds the network as in the paper, with 140 inputs, one recurrent hidden
layer of 512 LIF neurons and a non-spiking readout for the 20 digits. All hidden neurons are
identical, so one FI curve, measured once over a 10 ms time window as in Tutorial 1, serves every
neuron.
cp.set_seed(SEED)
net, info = cp.configs.build_techniques_network('chronoprop', device)
inputs = int(net.rf_mask.sum())
recurrent = int(net.rec_mask.sum())
readout = net.weights_out.weight.numel()
n_params = 40 * 512 + 512 * 512 // 4 + 512 * 20
print(f'input synapses {inputs:7,d} (40 channels for each of the 512 neurons)')
print(f'recurrent synapses {recurrent:7,d} (a random quarter of 512 x 512)')
print(f'readout synapses {readout:7,d}')
print(f'the paper counts 40 x 512 + 0.25 x 512² + 512 x 20 = {n_params:,} parameters')
print(f"proxy of every hidden neuron: gain {info['proxy_gain'][0]:.4f}, "
f"threshold {info['proxy_threshold'][0]:.4f}, FI fit R² = {info['fi_r_squared'][0]:.3f}")
input synapses 20,480 (40 channels for each of the 512 neurons)
recurrent synapses 65,179 (a random quarter of 512 x 512)
readout synapses 10,240
the paper counts 40 x 512 + 0.25 x 512² + 512 x 20 = 96,256 parameters
proxy of every hidden neuron: gain 1.0794, threshold 1.1227, FI fit R² = 0.965
Technique 1: receptive fields#
Each hidden neuron receives a contiguous window of 40 of the 140 input channels, the windows spaced evenly across the range, much as auditory neurons respond to a narrow band of frequencies. The other input synapses do not exist. They stay at zero and receive no gradient. Neuron \(i = 0, \dots, N-1\) keeps the input weights \(W_{ij}\) with
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 3), width_ratios=[2, 1])
ax1.imshow(net.rf_mask.cpu().T, aspect='auto', origin='lower', cmap='Blues', interpolation='none')
ax1.set_xlabel('hidden neuron')
ax1.set_ylabel('input channel')
ax1.set_title('input synapses that exist')
neuron = 256
weights = net.weights_hidden.weight[neuron].detach().cpu()
ax2.bar(range(140), weights, 1.0, color='tab:blue')
ax2.set_xlabel('input channel')
ax2.set_title(f'initial input weights of neuron {neuron}')
plt.tight_layout()
Technique 2: dropout#
In every training recording, each hidden neuron is silenced with probability 0.025 for the whole recording. Its spikes are set to zero and reach neither the readout nor the recurrent connections,
with one \(m_i\) per neuron and recording. The kept spikes are not rescaled, so the FI curve still describes every neuron. In evaluation all neurons take part.
net.train()
silenced = 1 - net.dropout_mask(2000).cpu() # [recordings, neurons], 1 = silenced
print(f'training: {silenced.sum(1).mean():.1f} of 512 neurons silenced per recording on average')
net.eval()
print(f'evaluation: {(1 - net.dropout_mask(2000)).sum().item():.0f} silenced')
fig, ax = plt.subplots(figsize=(10, 1.8))
ax.imshow(silenced[:20], aspect='auto', cmap='Reds', interpolation='none')
ax.set_xlabel('hidden neuron')
ax.set_ylabel('recording')
ax.set_title('silenced neurons in 20 training recordings')
plt.tight_layout()
training: 12.8 of 512 neurons silenced per recording on average
evaluation: 0 silenced
Technique 3: channel jitter#
Each time a training recording is loaded, it is shifted along the channel axis by a random number of channels, drawn from a normal distribution with a standard deviation of 4 and rounded:
Channels shifted past the edge are lost and the vacated ones stay silent. The network thus meets every recording at slightly different positions on the frequency axis.
def spikes_per_channel(dataset):
frames, _ = dataset[0]
return frames[:, 0, :].sum(0)
jittered = cp.data.ChannelJitter(train, sigma=4.0)
torch.manual_seed(0)
fig, ax = plt.subplots(figsize=(8, 2.8))
ax.plot(spikes_per_channel(train), 'k', lw=2, label='as recorded')
for k in range(3):
ax.plot(spikes_per_channel(jittered), lw=1, label=f'draw {k + 1}')
ax.set_xlabel('input channel')
ax.set_ylabel('spikes in the recording')
ax.legend()
plt.tight_layout()
Training settings#
Adam with a learning rate of 3·10⁻⁴, batches of 128 recordings, 400 epochs. The learning rate rises over the first 10 epochs and then follows a cosine down to a tenth of its peak. As in every figure, the test accuracy reported is the one at the epoch of best validation accuracy.
weight = torch.zeros(1, requires_grad=True) # a stand-in for the network's weights
optimizer = torch.optim.Adam([weight], lr=info['lr'])
schedule = cp.train.lr_scheduler(optimizer, 'cosine_warmup', epochs=400, warmup_epochs=10,
lr_min=info['lr_min'])
lrs = []
for _ in range(400):
lrs.append(optimizer.param_groups[0]['lr'])
optimizer.step()
schedule.step()
fig, ax = plt.subplots(figsize=(6, 2.4))
ax.plot(np.arange(1, 401), lrs)
ax.set_xlabel('epoch')
ax.set_ylabel('learning rate')
plt.tight_layout()
Pretrained networks#
The paper trained this network with its ten seeds and kept each at its epoch of best validation
accuracy. cp.pretrained downloads them once and loads each into the network built above, which is
then tested on the 2,264 test recordings.
loader = DataLoader(test, batch_size=128, collate_fn=cp.data.PadToWindow(info['window_steps']))
accs = []
for seed in cp.configs.TECHNIQUES['seeds']:
net, record = cp.pretrained.load_network('chronoprop', seed, device, model=net)
_, acc = cp.train.evaluate(net, loader, device)
accs.append(acc)
print(f"seed {seed}: {acc:.2f}% "
f"(paper {record['test_acc']:.2f}%, epoch {record['best_val_epoch'] + 1})")
rerun = np.array(accs)
fig5 = cp.configs.reference('fig5')
paper = fig5['cells']['shd/512/0.25']
print(f"\nre-evaluated: {rerun.mean():.2f} ± {rerun.std(ddof=1):.2f}% "
f"paper: {paper['mean']:.2f} ± {paper['sd']:.2f}%")
seed 5183: 92.31% (paper 92.31%, epoch 299)
seed 2741: 93.29% (paper 93.29%, epoch 400)
seed 7396: 93.77% (paper 93.82%, epoch 384)
seed 3058: 91.78% (paper 91.78%, epoch 294)
seed 9624: 93.64% (paper 93.60%, epoch 363)
seed 7193: 93.02% (paper 93.02%, epoch 286)
seed 8826: 92.18% (paper 92.18%, epoch 287)
seed 1532: 93.73% (paper 93.73%, epoch 277)
seed 4097: 91.12% (paper 91.12%, epoch 288)
seed 6258: 93.29% (paper 93.29%, epoch 400)
re-evaluated: 92.81 ± 0.91% paper: 92.81 ± 0.91%
The two should match. The paper ran on GPUs. On another processor, a recurrent network simulated for about 1,000 steps can occasionally shift one spike through a rounding difference near a neuron’s threshold, and a network may then classify one of the 2,264 recordings differently (0.04 points).
Comparison with the paper#
Fig. 5a trained three widths at five recurrent connection densities, ten seeds each. Within the ranges tested, recurrence matters far more than width, and the best network is the one tested above. The orange diamonds are published SNNs validated, like these, on data held out from the training set. They were trained with BPTT and have more layers, richer neuron dynamics or learned neuron parameters.
shades = {128: '#9ecae1', 256: '#4292c6', 512: '#08519c'}
offsets = {'BHRF': (6, -14)} # keep the label off the point it sits next to
fig, ax = plt.subplots(figsize=(6.5, 4))
for N, color in shades.items():
cells = [fig5['cells'][f'shd/{N}/{density}'] for density in (0.0, 0.25, 0.5, 0.75, 1.0)]
params = [c['params'] for c in cells]
means = [c['mean'] for c in cells]
sds = [c['sd'] for c in cells]
ax.errorbar(params, means, yerr=sds, color=color, marker='o', ms=4, capsize=2,
label=f'N = {N}')
for c in cells: # label each point with its recurrent density
ax.annotate(f"{c['recurrent_prob']:g}", (c['params'], c['mean']), fontsize=7,
xytext=(4, -9), textcoords='offset points')
for p in fig5['published']['points']:
ax.errorbar(p['params'], p['acc'], yerr=p['sd'], color='tab:orange', marker='D', ms=5,
capsize=2)
ax.annotate(p['name'], (p['params'], p['acc']), fontsize=7,
xytext=offsets.get(p['name'], (5, 4)), textcoords='offset points')
ax.scatter([n_params], [rerun.mean()], s=150, facecolors='none', edgecolors='k', zorder=5,
label='re-evaluated here')
ax.set_xscale('log')
ax.set_xlim(5e3, 2e6)
ax.set_ylim(70, 96)
ax.set_xlabel('trainable parameters')
ax.set_ylabel('test accuracy (%)')
ax.legend(loc='lower right')
plt.tight_layout()
Training from scratch (optional)#
Set TRAIN_EPOCHS above to train the network from scratch, with the training data pooled and
jittered and the paper’s 400-epoch schedule, stopping after TRAIN_EPOCHS epochs. The plot compares
the validation accuracy of this run with the mean of the paper’s ten runs. The learning rate is
still warming up during the first 10 epochs, so accuracy rises slowly at first.
if TRAIN_EPOCHS > 0:
cp.set_seed(SEED)
net, info = cp.configs.build_techniques_network('chronoprop', device)
if cuda:
net = cp.jit(net) # compiled, as in the paper
res = cp.train.train(
net, cp.data.ChannelJitter(train, 4.0), test, val_data=val, batch_size=128, epochs=400,
lr=info['lr'], device=device, window_steps=info['window_steps'], recurrent=True,
lr_schedule='cosine_warmup', warmup_epochs=10, lr_min=info['lr_min'],
num_workers=2, pin_memory=cuda, stop_after_epoch=TRAIN_EPOCHS)
here = res['val_acc']
epoch = np.arange(1, len(here) + 1)
mean = np.array(paper['val_acc_mean'][:len(here)])
sd = np.array(paper['val_acc_sd'][:len(here)])
fig, ax = plt.subplots(figsize=(6, 3))
ax.fill_between(epoch, mean - sd, mean + sd, color='tab:blue', alpha=0.2,
label='paper, mean ± s.d.')
ax.plot(epoch, here, 'o-', color='tab:blue', label='this run')
ax.set_xlabel('epoch')
ax.set_ylabel('validation accuracy (%)')
ax.legend()
plt.tight_layout()
else:
print('Training skipped (TRAIN_EPOCHS = 0).')
Training skipped (TRAIN_EPOCHS = 0).
What’s next#
Tutorial 6. Robustness to hardware defects: Test ChronoProp’s robustness to common hardware defects and limitations.