Training Spiking Networks¶
Spiking neural networks promise extraordinary hardware efficiency, yet their sharp all-or-nothing threshold breaks textbook calculus right at the heart of backpropagation. This section explains why naive gradient descent stalls on discrete spikes, then walks through the three pillars of modern SNN training, namely ANN-to-SNN conversion, surrogate-gradient backpropagation through time, and forward-only online learning with e-prop alongside sparsity regularisation and hardware quantisation.
The Dead-Derivative Dilemma¶
-
Imagine hiking down a thick, fog-blanketed mountain path built entirely out of perfectly flat marble steps separated by sheer vertical cliffs. Every step under your boots is completely level, so feeling the ground beneath your feet gives you zero hint about which way goes downhill. Take one step right up to the cliff edge, and the slope suddenly turns vertical and infinite.
-
That exact mathematical staircase haunts every spiking neural network. Recall from Section 2 that a discrete-time LIF neuron fires a binary spike using the Heaviside step function \(S[t] = \Theta(U[t] - \theta)\). When we try to minimise a task loss \(\mathcal{L}\) with respect to synaptic weights \(W\) using Backpropagation Through Time (BPTT) (Chapter 06 and Chapter 07), the chain rule forces us to differentiate right through every spike event.
- Look at that middle factor. Whenever \(U[t] \neq \theta\) (which happens almost everywhere in continuous floating-point numbers), the step function is completely flat, so \(\frac{\partial S[t]}{\partial U[t]} = 0\). Right at the razor-thin threshold \(U[t] = \theta\), the derivative jumps to an infinite Dirac delta \(\delta(0) = \infty\). Multiply the entire gradient chain by zero and every synaptic update freezes dead in its tracks. Overcoming this non-differentiable spike bottleneck took decades of creative research and gave rise to three complementary training paradigms.
ANN-to-SNN Conversion¶
-
One remarkably practical way around the dead derivative is not to differentiate through spikes at all. Think of a sculptor who shapes a delicate figure in smooth, pliable clay where every curve can be refined effortlessly, and only after the sculpture looks flawless casts the finished piece into rigid bronze.
-
ANN-to-SNN conversion follows that exact two-stage blueprint. First, you train a conventional continuous ReLU artificial neural network using standard backpropagation on GPUs (typically replacing max pooling with average pooling and folding batch normalisation cleanly into the linear weights). Next, you copy those trained weights directly into a network of non-leaky (or lightly leaky) Integrate-and-Fire neurons with reset-by-subtraction, letting each spiking neuron's average firing rate \(r_i \in [0, 1]\) approximate the corresponding ReLU activation \(a_i \ge 0\).
-
Copying raw weights straight across, however, runs into an immediate scaling glitch. A ReLU unit can output \(a_i = 14.7\), whereas a discrete spiking neuron can fire at most once per time step (\(r_i \le 1\)). If a layer's activations stay far below threshold, neurons fall silent and lose signal; if activations explode far above threshold, firing rates clip at \(1\) and saturate.
-
Threshold balancing (often called data-based normalisation) fixes both failure modes in one clean sweep. You pass a small calibration batch through the trained ANN, record the maximum activation \(M_l\) (or a robust 99.9th percentile to ignore rare outliers) in each layer \(l\), and set that layer's firing threshold proportional to \(M_l\) (or equivalently rescale incoming weights by \(M_{l-1} / M_l\)). Every layer's firing rates now land neatly inside the sweet spot \([0, 1]\) with neither silence nor clipping.
-
Conversion shines on large static vision benchmarks such as ImageNet, routinely recovering within a fraction of a percent of full-precision ANN accuracy with zero spiking training overhead. Its catch is the accuracy versus latency trade-off. Because firing rates approximate continuous ReLU numbers with granularity \(1/T\), converted SNNs often need \(T = 64\text{ to }512\) time steps to reach peak accuracy, erasing much of their energy and latency advantage. Even more fundamentally, conversion cannot exploit genuine millisecond spike timing on dynamic event-camera streams, because the source ANN never learned temporal dynamics in the first place.
Backpropagation Through Time with Surrogate Gradients¶
-
What if we want to train spiking networks directly from scratch so they exploit crisp spike timing in just 4 to 16 time steps? That calls for a delightfully clever piece of mathematical engineering called the surrogate gradient trick (formalised by Neftci, Mostafa, and Zenke in 2019).
-
Picture practicing a tightrope walk over a swimming pool. During your actual walk across the wire (the forward pass), physics stays completely unforgiving, because you are either balanced on the rope (\(1\)) or splashing into the water (\(0\)). Yet when your coach reviews the video afterwards (the backward pass) to tell you how to adjust your ankles, she sketches a smooth bell-shaped sensitivity zone around the wire so small leans to the left or right translate into clear, gentle corrections.
-
Surrogate-gradient BPTT separates forward execution from backward differentiation in that exact way. On the forward pass, every neuron emits exact discrete binary spikes \(S[t] = \Theta(U[t] - \theta)\), keeping network behaviour 100% faithful to neuromorphic hardware. On the backward pass, whenever the chain rule encounters the undefined derivative \(\frac{\partial S[t]}{\partial U[t]}\), we substitute a smooth, finite, bell-shaped surrogate derivative \(\psi'(U[t] - \theta)\) centred right at the firing threshold.
- Two lightweight surrogate curves dominate modern SNN libraries because they are fast to compute and numerically rock-solid.
-
Here \(x = U[t] - \theta\) measures how close the membrane potential sits to firing threshold, while \(k\) or \(\alpha\) controls the sharpness of the window. Neurons whose voltage hovered close to threshold receive strong, informative gradient nudges to push them cleanly over or safely under the line, while deeply quiet neurons far below threshold get tiny updates so gradients stay localised.
-
Surprisingly, Zenke and Vogels (2021) discovered that surrogate-gradient training is remarkably robust to the exact curve shape, whether fast-sigmoid, arctan, triangular, or Gaussian, as long as the slope scale is chosen sensibly. Too wide a window leaks noisy gradients across silent neurons, while too steep a spike mimics the Dirac delta and destabilises updates. Armed with surrogate gradients, end-to-end SNNs learn complex audio, gesture, and event-camera tasks directly in tiny time budgets where ANN conversion completely breaks down.
Online Biologically Inspired Learning in Hardware¶
-
Surrogate-gradient BPTT unlocks impressive accuracy on GPUs, yet try running it directly on a tiny, battery-powered neuromorphic chip and you slam head-first into a wall we already met in Chapter 12.
-
Think of trying to adjust the lighting on a live stage play. Standard BPTT insists that you film the entire three-hour performance on high-speed tape, freeze every actor on stage at the final curtain, rewind the entire tape backwards minute by minute, and only then tweak the dimmer switches. Storing every membrane voltage \(U[t]\) and spike state \(S[t]\) across \(T\) time steps creates an \(O(T)\) temporal memory wall and update locking, completely incompatible with tiny on-chip SRAM and continuous real-world adaptation.
Hardware STDP for Unsupervised Plasticity¶
-
As we explored in Chapter 12, biological synapses adjust themselves strictly locally using Spike-Timing-Dependent Plasticity (STDP), strengthening synapse \(w_{ij}\) when presynaptic spike \(j\) arrives just before postsynaptic spike \(i\) (\(\Delta t > 0\)) and weakening it when arrival order reverses (\(\Delta t < 0\)).
-
Neuromorphic silicon implements STDP with astonishing simplicity by keeping just two fading local traces per neuron (a presynaptic trace \(x_j[t]\) and a postsynaptic trace \(y_i[t]\) that jump by \(1\) on each spike and decay exponentially). Whenever a postsynaptic spike fires, every active incoming synapse adds \(A_+ x_j[t]\); whenever a presynaptic spike arrives, it subtracts \(A_- y_i[t]\). That requires zero time-history buffers (\(O(1)\) memory in time), making on-chip STDP ideal for unsupervised feature extraction and rapid drift compensation, though pure two-factor STDP cannot solve deep supervised credit assignment on its own.
Bellec's e-prop and Forward-Only Eligibility Traces¶
- In 2020, Guillaume Bellec, Wolfgang Maass, and colleagues uncovered a mathematical bridge connecting textbook BPTT directly to biological three-factor learning rules (Chapter 12). Their algorithm, called e-prop (eligibility propagation), proves that the exact BPTT gradient through a recurrent spiking network can be rewritten as a sum over time of purely forward-computed local traces multiplied by instantaneous learning signals.
-
Look at how elegantly e-prop splits temporal credit assignment into two hardware-friendly halves.
- The local eligibility trace \(e_{ji}[t]\) lives right inside synapse \((j \to i)\) and marches strictly forward in time using only information physically available at that junction. For a standard LIF neuron with membrane decay \(\beta\), the presynaptic spike stream \(X_j[t]\) passes through a leaky filter \(\bar{x}_j[t] = \beta\,\bar{x}_j[t-1] + X_j[t]\), and multiplies the postsynaptic neuron's current surrogate derivative to yield \(e_{ji}[t] = \psi'(U_i[t] - \theta)\,\bar{x}_j[t]\). (For ALIF neurons, a second slow trace tracks the adaptive threshold, bridging delays spanning whole seconds.)
- The broadcast learning signal \(L_i[t]\) approximates the instantaneous effect of neuron \(i\)'s spike on the current task error \(E[t]\), sent immediately down to neuron \(i\) without travelling backwards in time (via readout weights \(B_{ki}\) or fixed random feedback alignment as in Chapter 12).
-
Because weights update continuously online via \(\Delta W_{ji}[t] = -\eta \, L_i[t] \, e_{ji}[t]\), e-prop obliterates BPTT's \(O(T)\) memory wall, cutting memory to \(O(1)\) in sequence length while matching BPTT accuracy across speech recognition, delayed working memory, and reinforcement learning benchmarks.
Spike-Rate Regularisation and Hardware-Aware Quantisation¶
-
Training an accurate spiking network in floating-point Python is only half the journey toward a real milliwatt chip. Imagine designing a solar-powered weather buoy floating in the North Atlantic. If your radio transmits nonstop, the battery dies by Tuesday; if your code demands 32-bit floats while the microcontroller only holds 8-bit integers, the model will not even fit in memory.
-
Spike-rate regularisation keeps the network's dynamic energy budget tightly under control. Left unchecked, surrogate-gradient descent happily cranks up firing rates to pack more numerical precision into every layer, bloating AC operations and AER bus traffic. Adding a gentle activity penalty to the task loss nudges every layer toward a sparse target firing rate \(r_{\text{target}}\) (say 2% to 10% spikes per step) while guarding against completely dead neurons.
-
Here \(\bar{r}_i = \frac{1}{T}\sum_{t=1}^{T} S_i[t]\) is neuron \(i\)'s mean firing rate over the episode and \(\lambda_{\text{reg}} > 0\) balances accuracy against energy. An alternative upper-bound hinge penalty \(\max(0, \bar{r}_i - r_{\max})^2\) caps excessive chatter without forcing quiet feature detectors to fire unnecessarily.
-
Hardware-aware quantisation bridges the remaining gap from floating-point simulation to tiny on-chip SRAM. Real neuromorphic cores typically store synaptic weights as 4-bit or 8-bit signed integers (and sometimes ternary \(\{-1, 0, +1\}\) values) to pack as many synapses as possible onto silicon. Simply rounding FP32 weights after training can knock neurons off their carefully balanced thresholds. Instead, Quantisation-Aware Training (QAT) simulates integer rounding \(W_q = \Delta_w \cdot \text{clip}\!\left(\text{round}(W / \Delta_w), -Q, Q\right)\) inside the forward pass (scaling thresholds \(\theta\) by the exact same step size \(\Delta_w\)), while letting floating-point master weights absorb smooth surrogate updates during training. When deployed, the entire network runs on pure low-bit integer additions with virtually zero accuracy drop.
Take-Home¶
- Discrete spikes break naive calculus, because the Heaviside threshold has zero derivative almost everywhere and an infinite Dirac delta right at \(U = \theta\), freezing standard gradient descent.
- ANN-to-SNN conversion copies trained ReLU weights onto integrate-and-fire neurons using threshold balancing, preserving static accuracy cleanly at the cost of longer time windows (\(T\)) and missed temporal dynamics.
- Surrogate-gradient BPTT keeps exact binary spikes on the forward pass while substituting a smooth fast-sigmoid or arctan derivative on the backward pass, enabling accurate temporal SNNs in just a handful of steps.
- Bellec's e-prop brings learning onto neuromorphic chips by decomposing temporal gradients into forward local eligibility traces times instantaneous broadcast learning signals, eliminating BPTT's \(O(T)\) memory wall.
- Spike-rate regularisation and quantisation-aware training sculpt sparse, low-bit integer SNNs that fit cleanly inside tiny milliwatt SRAM budgets without losing accuracy.
Coding Tasks (use CoLab or notebook)¶
-
Train a small 2-layer ReLU ANN on a 2D two-arcs classification task (adding a constant
1.0spike channel so the network stays bias-free), convert it into an Integrate-and-Fire SNN via threshold balancing, and sweep \(T \in \{4, 8, 16, 32, 64, 128\}\) to plot the accuracy-versus-latency curve.import jax import jax.numpy as jnp import matplotlib.pyplot as plt # 2D two-arcs dataset scaled to [0, 1] plus a constant 1.0 input channel (bias-free SNN) key = jax.random.PRNGKey(12) k1, k2, k3, k4 = jax.random.split(key, 4) N_half = 100 ang = jnp.linspace(0.0, jnp.pi, N_half) X0 = jnp.stack([jnp.cos(ang), jnp.sin(ang)], axis=1) + 0.12 * jax.random.normal(k1, (N_half, 2)) X1 = jnp.stack([1.0 - jnp.cos(ang), 0.45 - jnp.sin(ang)], axis=1) + 0.12 * jax.random.normal(k2, (N_half, 2)) X_raw = jnp.concatenate([X0, X1], axis=0) X_01 = (X_raw - jnp.min(X_raw, axis=0)) / (jnp.max(X_raw, axis=0) - jnp.min(X_raw, axis=0) + 1e-6) X_in = jnp.concatenate([X_01, jnp.ones((2 * N_half, 1))], axis=1) Y = jnp.concatenate([jnp.zeros(N_half, dtype=jnp.int32), jnp.ones(N_half, dtype=jnp.int32)]) Y_oh = jnp.stack([1.0 - Y, Y.astype(jnp.float32)], axis=1) # Train bias-free 2-layer ReLU ANN H = 32 W1 = jax.random.normal(k3, (3, H)) * 0.5 W2 = jax.random.normal(k4, (H, 2)) * 0.4 for _ in range(800): h = jax.nn.relu(X_in @ W1) probs = jax.nn.softmax(h @ W2, axis=1) d_log = (probs - Y_oh) / len(Y) dW2 = h.T @ d_log dW1 = X_in.T @ ((d_log @ W2.T) * (h > 0.0)) W1 = W1 - 0.35 * dW1 W2 = W2 - 0.35 * dW2 ann_h = jax.nn.relu(X_in @ W1) ann_acc = float(jnp.mean(jnp.argmax(ann_h @ W2, axis=1) == Y)) # Data-based threshold balancing (99.9th percentile of hidden activations) theta1 = float(jnp.percentile(ann_h, 99.9)) W1_snn = W1 / theta1 T_list = [4, 8, 16, 32, 64, 128] snn_accs = [] eval_key = jax.random.PRNGKey(99) for T in T_list: eval_key, sk = jax.random.split(eval_key) u1, out_acc = jnp.zeros((len(Y), H)), jnp.zeros((len(Y), 2)) rand_in = jax.random.uniform(sk, (T, len(Y), 3)) for t in range(T): s_in = (rand_in[t] < X_in).astype(jnp.float32) u1 = u1 + s_in @ W1_snn s1 = (u1 >= 1.0).astype(jnp.float32) u1 = u1 - s1 out_acc = out_acc + s1 @ W2 snn_accs.append(float(jnp.mean(jnp.argmax(out_acc, axis=1) == Y))) print(f"T = {T:3d} steps -> Converted SNN accuracy: {snn_accs[-1]:.1%}") print(f"Source ReLU ANN accuracy: {ann_acc:.1%}") fig, axes = plt.subplots(1, 2, figsize=(11, 3.8)) axes[0].scatter(X_01[Y == 0, 0], X_01[Y == 0, 1], color="#3498db", s=20, label="Class 0") axes[0].scatter(X_01[Y == 1, 0], X_01[Y == 1, 1], color="#e74c3c", s=20, label="Class 1") axes[0].set_title("Normalised 2D Two-Arcs Dataset"); axes[0].legend() axes[1].plot(T_list, [a * 100 for a in snn_accs], "o-", color="#27ae60", lw=2.2, label="Converted IF SNN") axes[1].axhline(ann_acc * 100, color="#9b59b6", ls="--", lw=1.8, label=f"Source ANN ({ann_acc:.1%})") axes[1].set_xscale("log", base=2); axes[1].set_xlabel("Time Steps T (log2)") axes[1].set_ylabel("Accuracy (%)"); axes[1].set_title("ANN-to-SNN Accuracy vs Latency") axes[1].legend(); axes[1].grid(alpha=0.3); plt.tight_layout(); plt.show() -
Train a 2-layer spiking network from scratch via Surrogate-Gradient BPTT (exact Heaviside forward pass, fast-sigmoid surrogate backward pass) with spike-rate regularisation to distinguish temporal spike order (early-low/late-high vs early-high/late-low channels with identical total spike counts).
import jax import jax.numpy as jnp import matplotlib.pyplot as plt # Spatio-temporal order dataset: both classes share identical total spikes per channel key = jax.random.PRNGKey(7) T, N_in, N_hid, N_out, B = 24, 8, 16, 2, 64 k1, k2, k3, k4 = jax.random.split(key, 4) t_idx = jnp.arange(T)[:, None] early = (t_idx >= 3) & (t_idx <= 8) late = (t_idx >= 15) & (t_idx <= 20) ch_lo = jnp.arange(N_in)[None, :] < (N_in // 2) p0 = jnp.where((early & ch_lo) | (late & (~ch_lo)), 0.55, 0.04) p1 = jnp.where((early & (~ch_lo)) | (late & ch_lo), 0.55, 0.04) X0 = (jax.random.uniform(k1, (B // 2, T, N_in)) < p0[None, :, :]).astype(jnp.float32) X1 = (jax.random.uniform(k2, (B // 2, T, N_in)) < p1[None, :, :]).astype(jnp.float32) X_data = jnp.concatenate([X0, X1], axis=0) Y_cls = jnp.concatenate([jnp.zeros(B // 2, dtype=jnp.int32), jnp.ones(B // 2, dtype=jnp.int32)]) Y_oh = jnp.stack([1.0 - Y_cls, Y_cls.astype(jnp.float32)], axis=1) W1 = jax.random.normal(k3, (N_in, N_hid)) * 0.45 W2 = jax.random.normal(k4, (N_hid, N_out)) * 0.45 beta, beta_out, theta, k_surr = 0.85, 0.85, 1.0, 8.0 lam_reg, r_target, lr = 0.3, 0.09, 0.4 losses, accs, mean_rates = [], [], [] for _ in range(90): u, u_out = jnp.zeros((B, N_hid)), jnp.zeros((B, N_out)) u_list, s_list = [], [] for t in range(T): u = beta * u + X_data[:, t, :] @ W1 s = (u >= theta).astype(jnp.float32) u_list.append(u); s_list.append(s) u = u - s * theta u_out = beta_out * u_out + s @ W2 S_all = jnp.stack(s_list, axis=1) probs = jax.nn.softmax(u_out, axis=1) rate = jnp.mean(S_all) losses.append(float(-jnp.mean(jnp.sum(Y_oh * jnp.log(probs + 1e-7), axis=1)) + lam_reg * (rate - r_target) ** 2)) accs.append(float(jnp.mean(jnp.argmax(u_out, axis=1) == Y_cls))) mean_rates.append(float(rate)) # Surrogate-Gradient BPTT through leaky readout and hidden LIF states d_out = (probs - Y_oh) / B dS_reg = 2.0 * lam_reg * (rate - r_target) / (B * T * N_hid) dW1, dW2, du_next = jnp.zeros_like(W1), jnp.zeros_like(W2), jnp.zeros((B, N_hid)) for t in range(T - 1, -1, -1): decay_w = beta_out ** (T - 1 - t) dW2 = dW2 + (s_list[t].T @ d_out) * decay_w dS_t = (d_out @ W2.T) * decay_w + dS_reg psi = 1.0 / (1.0 + k_surr * jnp.abs(u_list[t] - theta)) ** 2 du_t = dS_t * psi + beta * du_next dW1 = dW1 + X_data[:, t, :].T @ du_t du_next = du_t W1 = W1 - lr * dW1 W2 = W2 - lr * dW2 print(f"Final SG-BPTT loss: {losses[-1]:.4f} | Accuracy: {accs[-1]:.1%} | Mean spike rate: {mean_rates[-1]:.3f}") fig, axes = plt.subplots(1, 2, figsize=(11, 3.8)) axes[0].plot(losses, color="#3498db", lw=2, label="Total Loss (CE + Reg)") axes[0].plot(accs, color="#27ae60", lw=2, ls="--", label="Accuracy") axes[0].set_xlabel("Epoch"); axes[0].set_title("Surrogate-Gradient BPTT on Spike Order") axes[0].legend(); axes[0].grid(alpha=0.3) axes[1].plot(mean_rates, color="#9b59b6", lw=2, label="Hidden Firing Rate") axes[1].axhline(r_target, color="#e74c3c", ls=":", lw=1.8, label=f"Target Sparsity ({r_target})") axes[1].set_xlabel("Epoch"); axes[1].set_ylabel("Spikes / Neuron / Step") axes[1].set_title("Spike-Rate Regularisation"); axes[1].legend(); axes[1].grid(alpha=0.3) plt.tight_layout(); plt.show() -
Implement Bellec's online e-prop (forward-only local eligibility traces times instantaneous broadcast error, \(O(1)\) temporal memory) alongside full offline Surrogate-Gradient BPTT on a temporal spiking regression task, comparing learning curves and gradient cosine alignment.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(33) k1, k2, k3 = jax.random.split(key, 3) T, N_in, N_hid = 50, 6, 20 t_grid = jnp.linspace(0.0, 1.0, T) p_in = 0.15 + 0.35 * jnp.sin(2.0 * jnp.pi * t_grid[:, None] + jnp.linspace(0, 2.5, N_in)[None, :]) ** 2 X_seq = (jax.random.uniform(k1, (T, N_in)) < p_in).astype(jnp.float32) y_target = 0.8 * jnp.exp(-0.5 * ((t_grid - 0.65) / 0.15) ** 2) + 0.3 * jnp.sin(2.0 * jnp.pi * t_grid) W_ep = jax.random.normal(k2, (N_in, N_hid)) * 0.5 Wo_ep = jax.random.normal(k3, (N_hid, 1)) * 0.25 W_bp, Wo_bp = W_ep.copy(), Wo_ep.copy() beta, theta, k_surr, lr_in, lr_out = 0.85, 1.0, 6.0, 0.12, 0.06 ep_losses, bp_losses, cos_sims = [], [], [] for _ in range(120): # 1. Online e-prop (forward-only, O(1) temporal memory) u, x_bar = jnp.zeros(N_hid), jnp.zeros(N_in) dW_ep, dWo_ep, y_ep = jnp.zeros_like(W_ep), jnp.zeros_like(Wo_ep), [] for t in range(T): x_t = X_seq[t] u = beta * u + x_t @ W_ep s = (u >= theta).astype(jnp.float32) psi = 1.0 / (1.0 + k_surr * jnp.abs(u - theta)) ** 2 x_bar = beta * x_bar + x_t y_t = float((s @ Wo_ep)[0]) err_t = (y_t - float(y_target[t])) / T dW_ep = dW_ep + jnp.outer(x_bar, psi * (err_t * Wo_ep[:, 0])) dWo_ep = dWo_ep + (err_t * s)[:, None] y_ep.append(y_t); u = u - s * theta ep_losses.append(float(jnp.mean((jnp.array(y_ep) - y_target) ** 2))) # 2. Offline SG-BPTT (caches all T membrane states) u_b, u_cache, s_cache, y_bp = jnp.zeros(N_hid), [], [], [] for t in range(T): u_b = beta * u_b + X_seq[t] @ W_bp s_b = (u_b >= theta).astype(jnp.float32) u_cache.append(u_b); s_cache.append(s_b) y_bp.append(float((s_b @ Wo_bp)[0])); u_b = u_b - s_b * theta bp_losses.append(float(jnp.mean((jnp.array(y_bp) - y_target) ** 2))) dW_bp, dWo_bp, du_next = jnp.zeros_like(W_bp), jnp.zeros_like(Wo_bp), jnp.zeros(N_hid) for t in range(T - 1, -1, -1): err_t = (y_bp[t] - float(y_target[t])) / T dWo_bp = dWo_bp + (err_t * s_cache[t])[:, None] psi_b = 1.0 / (1.0 + k_surr * jnp.abs(u_cache[t] - theta)) ** 2 du_t = (err_t * Wo_bp[:, 0]) * psi_b + beta * du_next dW_bp = dW_bp + jnp.outer(X_seq[t], du_t); du_next = du_t cos_sims.append(float(jnp.sum(dW_ep * dW_bp) / (jnp.linalg.norm(dW_ep) * jnp.linalg.norm(dW_bp) + 1e-8))) W_ep, Wo_ep = W_ep - lr_in * dW_ep, Wo_ep - lr_out * dWo_ep W_bp, Wo_bp = W_bp - lr_in * dW_bp, Wo_bp - lr_out * dWo_bp print(f"Final e-prop MSE: {ep_losses[-1]:.4f} | Final BPTT MSE: {bp_losses[-1]:.4f}") print(f"Mean gradient cosine similarity (e-prop vs BPTT): {float(jnp.mean(jnp.array(cos_sims))):.3f}") fig, axes = plt.subplots(1, 2, figsize=(11, 3.8)) axes[0].plot(bp_losses, color="#3498db", lw=2, label="Offline SG-BPTT (O(T) mem)") axes[0].plot(ep_losses, color="#27ae60", lw=2, ls="--", label="Online e-prop (O(1) mem)") axes[0].set_xlabel("Epoch"); axes[0].set_ylabel("MSE"); axes[0].set_title("e-prop Matches BPTT Online") axes[0].legend(); axes[0].grid(alpha=0.3) axes[1].plot(t_grid, y_target, color="#333333", lw=2.2, label="Target") axes[1].plot(t_grid, y_ep, color="#27ae60", lw=1.8, ls="--", label="e-prop Output") axes[1].plot(t_grid, y_bp, color="#3498db", lw=1.5, ls=":", label="BPTT Output") axes[1].set_xlabel("Normalised Time"); axes[1].set_title("Learned Temporal Spike Readout") axes[1].legend(); axes[1].grid(alpha=0.3); plt.tight_layout(); plt.show()