Tutorial 6
Robustness to hardware defects#
Every network so far ran in an ideal simulation. On a chip, membrane potentials are noisy, weights are programmed imprecisely and stored in few bits, and membrane time constants vary from neuron to neuron (τ mismatch). The paper’s Fig. 6 tests each of these defects on its own, on the best network of Fig. 5, in two settings.
hardware-in-the-loop (HIL) training, where the network trains with the defect present and is tested with it;
post-training perturbation (PTP), where the network trains without defects and meets them only at test.
ChronoProp suits a chip in the loop, because its gradient needs only one spike count per neuron and time window, and an FI curve measured once before training. The paper compares it with BPTT on the same network, and with BPTT*, the same network without recurrent connections at Δt = 1 ms, where BPTT is most stable (Tutorial 3). The three reach different accuracies without defects (92.81%, 77.16% and 83.40%), so each is scored by its retained accuracy, the share of its own defect-free accuracy that it keeps under a defect.
We look at each defect, test the paper’s released networks with it in both settings, and compare the results with Fig. 6.
# 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)
cuda
Settings#
We test each defect at one level, the one the paper’s text quotes. Membrane noise has a steady-state
standard deviation of 3 firing thresholds, weight noise is 10% of the full-scale weight, weights
have 2 bits, and τ varies with a coefficient of variation of 30%. We use 3 of the paper’s 10 networks
per method and 3 chips per network. Fewer SEEDS or CHIPS make the tutorial faster.
SEEDS = [5183, 2741, 7396] # the first 3 of the paper's 10 seeds (cp.configs.TECHNIQUES['seeds'])
CHIPS = 3 # chips per network; the paper uses 20 (5 for membrane noise)
DATA_DIR = 'data/SHD'
levels = cp.pretrained.manifest('shd_hil_networks')['levels']
names = {'chronoprop': 'ChronoProp', 'bptt': 'BPTT', 'bptt_star': 'BPTT*'}
defect_names = {'membrane_noise': 'membrane noise', 'weight_noise': 'weight noise',
'weight_bits': 'quantization', 'tau_mismatch': 'τ mismatch'}
print(levels)
# ChronoProp and BPTT run at Δt = 0.1 ms (100 steps per window), BPTT* at 1 ms (10 steps)
loaders = {}
for timestep in ('fine', 'coarse'):
dt_us = cp.configs.TIMESTEPS[timestep]['dt_us']
window_steps = cp.fi.window_steps(cp.configs.WINDOW, cp.configs.TIMESTEPS[timestep]['dt'])
test = cp.data.SHD(DATA_DIR, train=False, dt_us=dt_us, pool=5)
loaders[timestep] = DataLoader(test, batch_size=128,
collate_fn=cp.data.PadToWindow(window_steps))
def accuracy(net, method):
timestep = cp.configs.TECHNIQUES_ARMS[method]['timestep']
_, acc = cp.train.evaluate(net, loaders[timestep], device)
return acc
{'membrane_noise': 3.0, 'weight_noise': 0.1, 'weight_bits': 2, 'tau_mismatch': 0.3}
The four defects#
chronoprop.defects applies each defect to any network as a context manager, which restores the
network on exit. Here they act on one of the paper’s ChronoProp networks.
Weight noise maps each weight array onto the device’s range, chosen to minimize the expected weight error (outliers are clipped), and adds an error of 10% of that range to every synapse. Each draw is one chip,
\[\tilde W = \operatorname{clip}(W, -F, F) + \varepsilon, \qquad \varepsilon \sim \mathcal{N}\big(0, (\sigma_d F)^2\big),\]with device error \(\sigma_d = 0.10\) and the full scale \(F\) that minimizes \(\sum_i (|w_i| - F)_+^2 + n\,(\sigma_d F)^2\) over the array’s \(n\) synapses.
Quantization rounds each array to a symmetric grid of \(2^b - 1\) levels (3 at \(b = 2\) bits), again with the full scale \(F\) that minimizes the squared error,
\[W_q = \Delta \cdot \operatorname{clip}\big(\operatorname{round}(W/\Delta), -q, q\big), \qquad \Delta = F/q, \quad q = 2^{b-1} - 1\]Membrane noise adds Gaussian noise to every membrane potential at every step, \(U[t] \leftarrow U[t] + \sigma_s\, \xi_t\) with \(\xi_t \sim \mathcal{N}(0, 1)\). Its level is the standard deviation \(\sigma_{V\infty}\) it would cause in a resting membrane, in units of the threshold, so the per-step value is \(\sigma_s = \sigma_{V\infty}\sqrt{1 - \alpha_\text{mem}^2}\).
τ mismatch gives every neuron its own membrane time constant. The spread comes from the leak conductance, so each neuron’s membrane resistance scales with its τ,
\[\tau_i = f_i\, \tau, \quad R_i = f_i\, R, \qquad \ln f_i \sim \mathcal{N}\big(0, \ln(1 + \text{CV}^2)\big),\]a log-normal factor with median 1 and coefficient of variation CV.
net, _ = cp.pretrained.load_network('chronoprop', SEEDS[0], device)
exists = net.rf_mask.bool() # the input synapses that exist
def input_weights():
return net.weights_hidden.weight.detach()[exists].cpu()
trained = input_weights()
pick = torch.randperm(trained.numel(), generator=torch.Generator().manual_seed(0))[:4000]
torch.manual_seed(0)
with cp.defects.WeightNoise(net, levels['weight_noise']):
noisy = input_weights()
with cp.defects.WeightQuantization(net, levels['weight_bits']):
quantized = input_weights()
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(12, 3))
lim = trained.abs().max().item() * 1.05
panels = [(noisy, f"one chip, {levels['weight_noise']:.0%} weight noise"),
(quantized, f"{levels['weight_bits']}-bit weights")]
for ax, (on_chip, title) in zip((ax1, ax2), panels):
ax.plot(trained[pick], on_chip[pick], '.', ms=2, alpha=0.5, color='tab:blue')
ax.plot([-lim, lim], [-lim, lim], ':', color='0.5', lw=1)
ax.set_xlabel('trained input weight')
ax.set_ylabel('weight on the chip')
ax.set_title(title)
chip = cp.defects.tau_mismatch_chip(512, 20, levels['tau_mismatch'], seed=0)
ax3.hist(chip['tau_hidden'] * 1e3, bins=40, color='tab:blue')
ax3.set_title(f"one chip, τ mismatch CV {levels['tau_mismatch']:.0%}")
ax3.set_xlabel('membrane time constant τ (ms)')
ax3.set_ylabel('hidden neurons')
plt.tight_layout()
sigma = cp.defects.membrane_noise_step_sigma(levels['membrane_noise'], 10e-3, 1e-4)
print(f"membrane noise of {levels['membrane_noise']:g} thresholds = {sigma:.3f} per 0.1 ms step")
grid = sorted({round(w, 5) + 0.0 for w in quantized.tolist()}) # + 0.0 turns -0.0 into 0.0
print(f'weights on the 2-bit grid: {grid}')
membrane noise of 3 thresholds = 0.422 per 0.1 ms step
weights on the 2-bit grid: [-0.08112, 0.0, 0.08112]
Post-training perturbation (PTP)#
We first test the paper’s defect-free networks with each defect. Membrane noise, weight noise and
τ mismatch are random, so each network meets CHIPS independent draws. Quantization is
deterministic, so one test is enough.
def ptp(net, method, defect, level, chip):
torch.manual_seed(chip)
if defect == 'membrane_noise':
sigma = cp.defects.membrane_noise_step_sigma(level, 10e-3, net.dt)
on_chip = cp.defects.MembraneNoise(net, sigma)
elif defect == 'weight_noise':
on_chip = cp.defects.WeightNoise(net, level)
elif defect == 'weight_bits':
on_chip = cp.defects.WeightQuantization(net, level)
else:
on_chip = cp.defects.tau_mismatch(net, level, seed=chip, dt=net.dt)
with torch.no_grad(), on_chip:
return accuracy(net, method)
def seed_mean(table, method, defect):
return np.mean([table[method, defect, seed] for seed in SEEDS])
clean, retained_ptp = {}, {}
for method in names:
for seed in SEEDS:
net, _ = cp.pretrained.load_network(method, seed, device)
clean[method, seed] = accuracy(net, method)
for defect, level in levels.items():
chips = 1 if defect == 'weight_bits' else CHIPS # quantization is not random
accs = [ptp(net, method, defect, level, chip) for chip in range(chips)]
retained_ptp[method, defect, seed] = 100 * np.mean(accs) / clean[method, seed]
clean_mean = np.mean([clean[method, seed] for seed in SEEDS])
summary = ', '.join(f'{defect_names[d]} {seed_mean(retained_ptp, method, d):.1f}%'
for d in levels)
print(f'{names[method]:10} defect-free {clean_mean:.2f}% | retained: {summary}')
ChronoProp defect-free 93.12% | retained: membrane noise 21.7%, weight noise 73.3%, quantization 37.0%, τ mismatch 96.2%
BPTT defect-free 78.24% | retained: membrane noise 7.9%, weight noise 30.5%, quantization 17.6%, τ mismatch 90.2%
BPTT* defect-free 83.80% | retained: membrane noise 26.0%, weight noise 45.6%, quantization 11.1%, τ mismatch 97.2%
Hardware-in-the-loop training (HIL)#
Next, we test the networks the paper trained with each defect, at that defect. Membrane noise and weight noise are drawn afresh, so each network meets draws it never saw in training. Quantization uses the network’s own grid, and τ mismatch the chip it trained on, as on real hardware. Retained accuracy is relative to the same seed’s defect-free network.
retained_hil = {}
for method in names:
for defect in levels:
for seed in SEEDS:
net, record = cp.pretrained.load_network(method, seed, device, defect=defect)
chips = CHIPS if defect in ('membrane_noise', 'weight_noise') else 1
accs = []
for chip in range(chips):
torch.manual_seed(chip)
with record['defects'].evaluation(net, device):
accs.append(accuracy(net, method))
retained_hil[method, defect, seed] = 100 * np.mean(accs) / clean[method, seed]
summary = ', '.join(f'{defect_names[d]} {seed_mean(retained_hil, method, d):.1f}%'
for d in levels)
print(f'{names[method]:10} retained: {summary}')
ChronoProp retained: membrane noise 95.2%, weight noise 88.7%, quantization 92.7%, τ mismatch 99.6%
BPTT retained: membrane noise 50.4%, weight noise 35.4%, quantization 73.3%, τ mismatch 98.2%
BPTT* retained: membrane noise 90.3%, weight noise 80.4%, quantization 82.8%, τ mismatch 100.0%
Comparison with the paper#
The two figures show the paper’s results (lines and bands, mean ± s.d. over 10 networks and their chips) and the networks tested here (dots, mean over 3 networks) at the levels above, first for HIL and then for PTP.
fig6 = cp.configs.reference('fig6')
colors = {'chronoprop': 'tab:blue', 'bptt': 'tab:red', 'bptt_star': 'salmon'}
scale = {'membrane_noise': 1, 'weight_noise': 100, 'weight_bits': 1, 'tau_mismatch': 100}
xlabels = {'membrane_noise': 'membrane noise SD (× threshold)',
'weight_noise': 'device error (% of full scale)',
'weight_bits': 'weight precision (bits)',
'tau_mismatch': 'CV of τ (%)'}
settings = {'hil': ('trained with the defect (HIL)', retained_hil),
'ptp': ('defect only at test (PTP)', retained_ptp)}
for route, (title, retained) in settings.items():
fig, axes = plt.subplots(2, 2, figsize=(9, 6.5), sharey=True)
for ax, defect in zip(axes.flat, levels):
for method in names:
color = colors[method]
rows = fig6['arms'][method][defect][route]
x = np.array([r['level'] for r in rows]) * scale[defect]
mean = np.array([r['mean'] for r in rows])
sd = np.array([r['sd'] for r in rows])
ax.plot(x, mean, color=color, lw=1.2, label=f'{names[method]}, paper')
ax.fill_between(x, mean - sd, mean + sd, color=color, alpha=0.15, lw=0)
ax.plot(levels[defect] * scale[defect], seed_mean(retained, method, defect), 'o',
ms=8, color=color, mec='k', label=f'{names[method]}, here')
ax.set_title(defect_names[defect])
ax.set_xlabel(xlabels[defect])
ax.set_ylim(0, 106)
ax.spines[['top', 'right']].set_visible(False)
if defect == 'weight_bits':
ax.invert_xaxis()
for ax in axes[:, 0]:
ax.set_ylabel('retained accuracy (%)')
axes[1, 1].legend(fontsize=8, ncol=3, loc='lower left', frameon=False)
fig.suptitle(title)
plt.tight_layout()
Summary#
Trained with the defect present (HIL), ChronoProp kept between 89 and 100% of its defect-free accuracy under all four defects, more than BPTT and BPTT* under membrane noise, weight noise and quantization. All three methods were robust to τ mismatch. Met only at test (PTP), every defect cost each method more, which is why training through the defect pays. Because ChronoProp needs only spike counts from a chip in the loop, it can learn the chip’s own defects. The 3 networks per method tested here lie close to the paper’s results over all 10.