Skip to content

Brain-Inspired AI and Embodied Intelligence

Modern AI is no longer merely borrowing loose metaphors from neuroscience, because deep mathematical dualities now link variational inference, associative memory, Transformers, spiking dynamics, and continual learning directly to principles of brain function. This file explores active inference, Modern Hopfield Networks and their equivalence to self-attention, spiking neural networks with surrogate gradients, synaptic consolidation for continual learning, and why embodiment drives the next frontier of NeuroAI.

  • Imagine an archaeologist discovering that two ancient scripts unearthed on opposite sides of the planet are actually the exact same language written in different alphabets. Something remarkably similar has unfolded between theoretical neuroscience and modern machine learning. The brain's variational free energy turns out to be the Variational Autoencoder ELBO, continuous associative memory retrieval turns out to be Transformer self-attention, and dendritic spine stabilisation turns out to be Fisher-weighted Bayesian regularisation.

  • These mathematical bridges sit at the centre of the NeuroAI virtuous loop. Biological principles inspire more sample-efficient, adaptable, low-power AI systems, while frontier AI architectures hand neuroscientists crisp, falsifiable computational models of cortex, hippocampus, and sensorimotor control.

The Free Energy Principle and Active Inference

  • Picture walking into a pitch-black bedroom and feeling something soft brush past your ankle. A jolt of surprise hits you because your brain expected empty air. You have exactly two ways to make that surprise vanish. You can update your internal belief ("ah, that is just my cat"), which is perception, or you can reach over and switch on the bedside lamp so your eyes receive clear, predictable sensory input, which is action.

  • Karl Friston's Free Energy Principle (FEP) elevates this everyday intuition into a unifying law for living and artificial agents. To survive in a changing environment, an organism must keep its sensory observations \(o\) within expected, viable bounds, meaning it must minimise surprisal (self-information from Chapter 05), written \(-\log p(o)\).

  • Evaluating exact Bayesian posteriors \(p(s \mid o)\) and marginal evidence \(p(o) = \int p(o, s)\,ds\) over hidden world states \(s\) is intractable (Chapter 05). Instead, the brain maintains a tractable internal belief distribution \(q(s)\) and minimises a computable upper bound called variational free energy \(F\).

\[F[q, o] = D_{\text{KL}}\!\left(q(s) \,\|\, p(s \mid o)\right) - \log p(o) = \mathbb{E}_{q(s)}\!\left[\log q(s) - \log p(o, s)\right]\]
  • Look closely at every piece of this equation.
  • The first term \(D_{\text{KL}}(q(s) \,\|\, p(s \mid o)) \ge 0\) is the Kullback-Leibler divergence from Chapter 05, measuring how far the brain's approximate belief \(q(s)\) sits from the true Bayesian posterior. Because KL divergence is never negative, \(F \ge -\log p(o)\) is always a valid upper bound on surprise.
  • Negating \(F\) immediately recovers the Evidence Lower Bound (ELBO) used to train Variational Autoencoders in Chapter 06, showing that maximising the ELBO and minimising variational free energy are literally the same optimisation.
  • Splitting the joint generative model as \(p(o, s) = p(o \mid s) p(s)\) yields an even more intuitive trade-off between simplicity and sensory fit.
\[F[q, o] = \underbrace{D_{\text{KL}}\!\left(q(s) \,\|\, p(s)\right)}_{\text{Complexity (Occam's razor)}} - \underbrace{\mathbb{E}_{q(s)}\!\left[\log p(o \mid s)\right]}_{\text{Accuracy (fit to senses)}}\]
  • Good perception explains the sensory data accurately while keeping internal beliefs as simple and close to prior expectations \(p(s)\) as possible.

Active inference perception-action loop where the internal generative model minimises variational free energy either by updating beliefs during perception or by selecting actions that change the world to match predictions during active inference

  • Active Inference closes the loop by letting the agent also choose future action policies \(\pi\) that minimise expected free energy \(G(\pi)\) over anticipated observations.
\[G(\pi) = \underbrace{\mathbb{E}_{q(o, s \mid \pi)}\!\left[\log q(s \mid \pi) - \log q(s \mid o, \pi)\right]}_{-\text{Epistemic value (information gain)}} - \underbrace{\mathbb{E}_{q(o \mid \pi)}\!\left[\log \tilde{p}(o)\right]}_{\text{Pragmatic value (goal preference)}}\]
  • Here \(\tilde{p}(o)\) encodes preferred sensory states (such as warmth, nourishment, or reaching a target). The remarkable payoff is that curiosity (epistemic value, like switching on the lamp to resolve uncertainty) and goal-seeking (pragmatic value, like maximising reward in Chapter 06 reinforcement learning) emerge naturally from one single objective, without bolting on ad-hoc exploration bonuses.

Associative Memory and Modern Hopfield Networks

  • Catch a faint whiff of roasted cinnamon in a crowded street and an entire childhood kitchen snaps back into focus, bringing back voices, warm light, and tiled floors all at once. Unlike computer RAM, which looks up bytes by numeric address, biological memory is content-addressable (associative), meaning a partial or noisy sensory cue automatically reconstructs the complete stored pattern.

Classical Hopfield Networks and Capacity Limits

  • In 1982, physicist John Hopfield (awarded the 2024 Nobel Prize in Physics) modelled associative memory as a recurrent network of \(N\) binary neurons \(\mathbf{s} \in \{-1, +1\}^N\) storing \(M\) memory patterns \(\{\mathbf{x}_1, \dots, \mathbf{x}_M\}\) via symmetric Hebbian outer products \(W = \frac{1}{N}\sum_{\mu=1}^{M} \mathbf{x}_\mu \mathbf{x}_\mu^T\) (with zero diagonal). Every network state carries a scalar energy defined by
\[E(\mathbf{s}) = -\frac{1}{2} \mathbf{s}^T W \mathbf{s}\]
  • Think of a marble rolling across a hilly landscape carved with valleys at every stored memory. Asynchronous neuron updates \(s_i \leftarrow \operatorname{sign}\!\left(\sum_j W_{ij} s_j\right)\) strictly decrease \(E(\mathbf{s})\) until the state settles at the bottom of the nearest valley, forming an attractor that recovers the clean memory from a corrupted cue.

  • Classical Hopfield networks suffer, however, from a harsh capacity ceiling. Because pairwise quadratic interactions overlap, crosstalk between patterns triggers spurious mixed attractors once \(M\) exceeds roughly \(0.138 N\), so a network of 1,000 neurons can reliably store only about 138 patterns.

Modern Hopfield Networks and Transformer Self-Attention

  • What if we deepen and sharpen the memory valleys so nearby memories stop blurring into one another? Building on Krotov and Hopfield (2016), Ramsauer et al. (2020) formulated Modern Hopfield Networks over continuous state vectors \(\boldsymbol{\xi} \in \mathbb{R}^d\) and a matrix of \(M\) stored patterns \(X = [\mathbf{x}_1, \dots, \mathbf{x}_M] \in \mathbb{R}^{d \times M}\) using a sharp log-sum-exp energy function.
\[E(\boldsymbol{\xi}) = -\frac{1}{\beta} \log\!\left(\sum_{\mu=1}^{M} \exp\!\left(\beta \, \mathbf{x}_\mu^T \boldsymbol{\xi}\right)\right) + \frac{1}{2} \boldsymbol{\xi}^T \boldsymbol{\xi} + \text{const}\]
  • Here \(\beta > 0\) is an inverse temperature controlling how tightly the energy landscape peaks around individual memories. Capacity skyrockets from linear \(O(N)\) to exponential \(O(c^d)\), allowing millions of high-dimensional patterns to coexist with tiny retrieval error while converging in a single step.

  • Minimising this energy via the Concave-Convex Procedure yields the exact one-step Modern Hopfield update rule.

\[\boldsymbol{\xi}^{\text{new}} = X \operatorname{softmax}\!\left(\beta \, X^T \boldsymbol{\xi}\right)\]
  • Pause and compare that equation side by side with Transformer scaled dot-product attention from Chapter 07 (with query \(\mathbf{q}\), keys \(K\), values \(V\), and scaling \(\beta = 1/\sqrt{d_k}\)).
\[\operatorname{Attention}(\mathbf{q}, K, V) = V \operatorname{softmax}\!\left(\frac{K^T \mathbf{q}}{\sqrt{d_k}}\right)\]

Mathematical duality between Modern Hopfield Networks and Transformer self-attention where a noisy query state compares against stored patterns via dot product and softmax with inverse temperature beta equal to 1 over sqrt(d_k), retrieving a weighted memory update

  • They are mathematically identical. When queries, keys, and values are linearly projected (\(Q = R W_Q\), \(K = Y W_K\), \(V = Y W_V\)) and \(\beta = 1/\sqrt{d_k}\), a Transformer self-attention head is literally performing one-step continuous Modern Hopfield retrieval. Keys act as stored memory addresses, queries act as partial cues, values supply the retrieved content, and \(\beta\) dials between retrieving a single razor-sharp memory (large \(\beta\)) or a smooth metastable blend of related memories (small \(\beta\)).

Spiking Neural Networks and Surrogate Gradients

  • Think of the difference between a smooth ramp and a staircase. Walking up a staircase is crisp and unmistakable, yet if you ask differential calculus for the slope of a step, the derivative is zero on every flat tread and infinite right at the vertical riser.

  • Spiking Neural Networks (SNNs) communicate through binary, event-driven spikes rather than continuous floating-point activations. In the discrete-time Leaky Integrate-and-Fire (LIF) neuron model (introduced earlier in Chapter 12), membrane potential \(u[t]\) leaks by decay factor \(\lambda = \exp(-\Delta t / \tau_m) \in (0, 1)\), integrates incoming synaptic current \(I[t] = W \mathbf{s}_{\text{in}}[t]\), fires a spike whenever it crosses threshold \(\theta\), and then resets.

\[u[t] = \lambda \, u[t-1] + I[t] - \theta \, s[t-1], \qquad s[t] = \Theta\!\left(u[t] - \theta\right)\]
  • Here \(\Theta(\cdot)\) is the Heaviside step function (\(1\) if \(u[t] \ge \theta\), else \(0\)). That discontinuous step is the staircase, where \(\partial s[t] / \partial u[t]\) is zero almost everywhere and starves standard backpropagation through time (BPTT) of useful gradients.

  • Surrogate Gradients (Zenke and Ganguli, 2018; Neftci et al., 2019) break this deadlock with an elegant trick. You keep the exact binary spike \(s[t] = \Theta(u[t] - \theta)\) during the forward pass, so the network remains genuinely spiking. During the backward pass, you replace the ill-behaved Dirac delta derivative with a smooth, localised surrogate derivative, such as the derivative of a fast sigmoid.

\[\frac{\partial s[t]}{\partial u[t]} \approx \frac{\gamma}{\left(1 + \gamma \left|u[t] - \theta\right|\right)^2}\]
  • Here \(\gamma > 0\) sets the sharpness of the surrogate window around threshold \(\theta\). Neurons whose membrane voltage sits close to threshold receive strong learning signals, while deeply silent neurons receive almost none.

  • Investing in SNNs pays off whenever energy efficiency matters. Because binary spikes turn dense multiply-accumulate (MAC) operations into sparse accumulate-only (AC) additions, a processor simply adds a synaptic weight whenever a spike arrives and does nothing otherwise. Paired with asynchronous event cameras and neuromorphic silicon such as Intel Loihi 2 (Chapter 26), surrogate-trained SNNs promise dramatic milliwatt power savings for always-on edge sensing and robotics.

Continual Learning, Replay, and Synaptic Consolidation

  • Imagine learning to speak Spanish after spending ten years fluent in French. Your brain acquires Spanish vocabulary and grammar without wiping out French. Train a standard neural network sequentially on Task A and then on Task B, however, and gradient descent greedily overwrites the weights that solved Task A, a severe failure mode called catastrophic forgetting.

  • Biological brains maintain lifelong continual learning through two tightly coupled strategies that have directly inspired modern AI.

  • Complementary Learning Systems (CLS) and Hippocampal Replay were proposed by McClelland et al. (1995), splitting mammalian memory across two speeds. The hippocampus rapidly encodes fresh episodic experiences during waking life, and during quiet rest and sleep it replays compressed neural sequences to the slower neocortex, interleaving new memories alongside old ones so cortical weights adapt gradually without distortion. In AI, this principle inspired experience replay in Deep Q-Networks (Chapter 06) and generative replay buffers in continual learning.

  • Synaptic Consolidation and Elastic Weight Consolidation (EWC) draw directly on cortical microstructure. Two-photon microscopy reveals that after an animal masters a motor skill, specific dendritic spines storing that skill become physically stabilised and resist remodelling during later learning. Kirkpatrick et al. (2017) translated this biological mechanism into Elastic Weight Consolidation (EWC) using Bayesian inference (Chapter 05) and the diagonal Fisher information \(F_i\) (Chapters 04 and 05) to form a regularised training loss.

\[\mathcal{L}_{\text{EWC}}(\theta) = \mathcal{L}_B(\theta) + \frac{\lambda}{2} \sum_i F_i \left(\theta_i - \theta_{A,i}^*\right)^2\]
  • Here \(\mathcal{L}_B(\theta)\) is the loss on the new Task B, \(\theta_{A,i}^*\) is the optimal value of parameter \(i\) learned on Task A, \(\lambda > 0\) controls memory retention strength, and \(F_i = \mathbb{E}\!\left[\left(\partial \log p(y \mid x, \theta_A^*) / \partial \theta_i\right)^2\right]\) measures how sensitive Task A's performance is to perturbing weight \(\theta_i\).

  • Picture anchoring each weight \(\theta_i\) to its Task A solution with a virtual elastic spring of stiffness \(F_i\). Weights that were crucial for Task A carry stiff springs (\(F_i \gg 0\)) and barely move, protecting old knowledge, while redundant weights carry slack springs (\(F_i \approx 0\)) and flex freely to master Task B.

Embodied Intelligence and the NeuroAI Virtuous Loop

  • Picture a chess engine running on a pocket phone that can defeat every human grandmaster on Earth. Yet ask a state-of-the-art robot to reach into a cluttered kitchen drawer, pick up a single slippery grape without squashing it, and drop it into a lunchbox, and it remains an open frontier problem.

  • Robotics pioneer Hans Moravec captured this irony in Moravec's Paradox (1988), observing that it is comparatively easy to make computers exhibit adult-level performance on intelligence tests or playing checkers, yet difficult or impossible to give them the skills of a one-year-old when it comes to perception and mobility. Evolution explains why. Symbolic algebra and chess are cultural inventions mere thousands of years old, whereas real-time vision, balance, locomotion, and dexterous touch have been sculpted by over 500 million years of relentless physical selection.

  • This brings us to embodied intelligence. Biological brains did not evolve to sit inside a server rack predicting static text tokens in isolation. They evolved to steer living bodies through noisy, uncertain, physical worlds in continuous closed sensorimotor loops. Movement shapes sensation (turning your head reveals hidden depth, and pressing a mug reveals its weight and friction), and grounding concepts in physical cause-and-effect is what gives animals their remarkable sample efficiency and common sense.

  • Before we close Chapter 12 with physical Brain-Machine Interfaces in Section 6, notice how these embodied principles also set up the exact trajectory of the chapters ahead.

  • Chapter 13 (Multimodal Learning) explores how modern AI fuses vision, language, audio, and sensor streams into unified representations, echoing multisensory integration across mammalian association cortex.
  • Chapter 14 (Autonomous Systems) puts perception, world models, and motor policies into physical bodies, spanning robot learning, Vision-Language-Action models, self-driving vehicles, and space robotics.

Take-Home

  • Active inference unifies perception and action by minimising variational free energy \(F\) (the negative VAE ELBO), reducing surprise either by updating internal beliefs to fit observations or by acting on the world to gather information and realise goals.
  • Transformer attention is associative memory, because one update step of a continuous Modern Hopfield Network (\(\boldsymbol{\xi}^{\text{new}} = X \operatorname{softmax}(\beta X^T \boldsymbol{\xi})\)) is mathematically identical to scaled dot-product self-attention with \(\beta = 1/\sqrt{d_k}\), unlocking exponential storage capacity.
  • Surrogate gradients make spiking networks trainable by replacing the non-differentiable spike threshold derivative with a smooth localised surrogate during the backward pass, enabling end-to-end training of sparse, addition-only SNNs.
  • Brains resist catastrophic forgetting via replay and consolidation, using hippocampal replay to interleave experiences and Fisher-weighted synaptic stabilisation (modelled by EWC) to protect critical synapses with stiff virtual springs.
  • Embodiment is the deep test of intelligence, as Moravec's paradox reminds us that closed-loop multimodal sensorimotor control (explored next in Chapters 13 and 14) is evolution's hardest achievement.

Coding Tasks (use CoLab or notebook)

  1. Build a continuous Modern Hopfield Network and verify numerically that its one-step update \(\boldsymbol{\xi}^{\text{new}} = X \operatorname{softmax}(\beta X^T \boldsymbol{\xi})\) is identical to Transformer scaled dot-product attention (\(K = V = X\), \(\beta = 1/\sqrt{d}\)). Measure noisy cue recovery across inverse temperatures \(\beta\).

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    def hopfield_update(xi, X, beta):
        """One-step Modern Hopfield retrieval: X is (d, M), xi is (d,)."""
        weights = jax.nn.softmax(beta * (X.T @ xi))
        return X @ weights, weights
    
    def scaled_dot_product_attention(q, K, V):
        """Standard Transformer attention for a single query q (d,), K/V (d, M)."""
        d_k = K.shape[0]
        scores = (K.T @ q) / jnp.sqrt(d_k)
        attn = jax.nn.softmax(scores)
        return V @ attn, attn
    
    # Store M=30 random unit-norm memory patterns in d=16 dimensions
    key = jax.random.PRNGKey(42)
    k1, k2 = jax.random.split(key)
    d, M = 16, 30
    X = jax.random.normal(k1, (d, M))
    X = X / jnp.linalg.norm(X, axis=0, keepdims=True)
    
    # Corrupt pattern 0 with Gaussian noise
    target = X[:, 0]
    cue = target + 0.15 * jax.random.normal(k2, (d,))
    
    # Verify exact equivalence with Transformer attention at beta = 1 / sqrt(d)
    beta_attn = 1.0 / jnp.sqrt(d)
    xi_hop, _ = hopfield_update(cue, X, beta_attn)
    xi_att, _ = scaled_dot_product_attention(cue, X, X)
    print(f"Max abs diff (Modern Hopfield vs Attention): {float(jnp.max(jnp.abs(xi_hop - xi_att))):.2e}")
    
    # Sweep inverse temperature beta to see sharp retrieval vs metastable blending
    betas = [0.5, 1.0, 2.0, 4.0, 8.0, 16.0]
    cos_sims, peak_weights = [], []
    for b in betas:
        retrieved, w = hopfield_update(cue, X, b)
        cos = jnp.dot(retrieved, target) / (jnp.linalg.norm(retrieved) * jnp.linalg.norm(target))
        cos_sims.append(float(cos))
        peak_weights.append(float(w[0]))
    
    print(f"Cue cosine similarity before retrieval: {float(jnp.dot(cue, target) / jnp.linalg.norm(cue)):.3f}")
    print(f"Retrieved cosine similarity at beta=16: {cos_sims[-1]:.4f} (weight on target={peak_weights[-1]:.4f})")
    
    fig, axes = plt.subplots(1, 2, figsize=(10, 4))
    axes[0].plot(betas, cos_sims, marker="o", color="#27ae60", lw=2, label="Cosine sim to target")
    axes[0].plot(betas, peak_weights, marker="s", color="#3498db", lw=2, linestyle="--", label="Softmax weight w[0]")
    axes[0].set_xlabel("Inverse Temperature beta"); axes[0].set_ylim(0, 1.08)
    axes[0].set_title("Modern Hopfield Retrieval Sharpness"); axes[0].legend(); axes[0].grid(alpha=0.3)
    
    _, w_sharp = hopfield_update(cue, X, 12.0)
    axes[1].bar(range(M), w_sharp, color="#9b59b6", alpha=0.8)
    axes[1].set_xlabel("Stored Pattern Index"); axes[1].set_ylabel("Retrieval Weight")
    axes[1].set_title("One-Step Retrieval Weights (beta=12)"); axes[1].grid(alpha=0.3)
    plt.tight_layout(); plt.show()
    

  2. Train a Leaky Integrate-and-Fire (LIF) Spiking Neural Network with a fast-sigmoid surrogate gradient to distinguish low-rate versus high-rate input spike trains over \(T=25\) time steps. Plot the loss curve and inspect a neuron's membrane potential and spikes.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Synthetic temporal spike-train dataset: class 0 vs class 1 active channels
    key = jax.random.PRNGKey(3)
    k1, k2, k3 = jax.random.split(key, 3)
    N, T, D_in = 80, 25, 8
    u0 = jax.random.uniform(k1, (N // 2, T, D_in))
    u1 = jax.random.uniform(k2, (N // 2, T, D_in))
    p0 = jnp.array([0.35, 0.35, 0.35, 0.35, 0.08, 0.08, 0.08, 0.08])
    p1 = jnp.array([0.08, 0.08, 0.08, 0.08, 0.35, 0.35, 0.35, 0.35])
    X_spikes = jnp.concatenate([(u0 < p0).astype(jnp.float32), (u1 < p1).astype(jnp.float32)], axis=0)
    Y_rate = jnp.concatenate([jnp.full((N // 2, 1), 0.05), jnp.full((N // 2, 1), 0.45)], axis=0)
    Y_cls = jnp.concatenate([jnp.zeros((N // 2, 1)), jnp.ones((N // 2, 1))], axis=0)
    
    # Single-layer LIF classifier with 1 output spiking neuron -> rate readout
    W = jax.random.normal(k3, (D_in, 1)) * 0.25
    lam, theta, gamma, lr = 0.85, 1.0, 4.0, 0.35
    losses = []
    
    for step in range(120):
        # Forward pass through T discrete LIF steps (store states for surrogate BPTT)
        u = jnp.zeros((N, 1))
        s_prev = jnp.zeros((N, 1))
        u_hist, s_hist = [], []
        for t in range(T):
            I_t = X_spikes[:, t, :] @ W
            u = lam * u + I_t - theta * s_prev
            s = (u >= theta).astype(jnp.float32)  # Exact non-differentiable spike!
            u_hist.append(u); s_hist.append(s)
            s_prev = s
    
        spike_rate = sum(s_hist) / T
        loss = jnp.mean((spike_rate - Y_rate) ** 2)
        losses.append(float(loss))
    
        # Backward pass with fast-sigmoid surrogate derivative: gamma / (1 + gamma |u - theta|)^2
        dL_ds = (2.0 / (N * T)) * (spike_rate - Y_rate)
        dW = jnp.zeros_like(W)
        du_next = jnp.zeros((N, 1))
        for t in range(T - 1, -1, -1):
            surrogate = gamma / (1.0 + gamma * jnp.abs(u_hist[t] - theta)) ** 2
            du = (dL_ds - theta * du_next) * surrogate + lam * du_next
            dW = dW + X_spikes[:, t, :].T @ du
            du_next = du
        W = W - lr * dW
    
    acc = float(jnp.mean((spike_rate > 0.25) == (Y_cls > 0.5)))
    print(f"Initial MSE: {losses[0]:.4f} -> Final MSE: {losses[-1]:.4f} | Spike-rate Acc: {acc:.1%}")
    
    fig, axes = plt.subplots(1, 2, figsize=(10, 4))
    axes[0].plot(losses, color="#e74c3c", lw=2)
    axes[0].set_xlabel("Training Step"); axes[0].set_ylabel("Spike-Rate MSE Loss")
    axes[0].set_title("LIF SNN Trained with Surrogate Gradients"); axes[0].grid(alpha=0.3)
    
    u_sample = [float(u_hist[t][-1, 0]) for t in range(T)]
    s_sample = [float(s_hist[t][-1, 0]) for t in range(T)]
    axes[1].plot(u_sample, color="#3498db", lw=2, label="Membrane u[t]")
    axes[1].axhline(theta, color="#e74c3c", linestyle="--", label="Threshold theta")
    spike_times = [t for t, sp in enumerate(s_sample) if sp > 0.5]
    axes[1].scatter(spike_times, [theta + 0.12] * len(spike_times), color="#27ae60", marker="|", s=140, lw=2.5, label="Output spikes")
    axes[1].set_xlabel("Time Step t"); axes[1].set_ylabel("Potential u[t]")
    axes[1].set_title("LIF Membrane Dynamics (Class 1 Sample)"); axes[1].legend(); axes[1].grid(alpha=0.3)
    plt.tight_layout(); plt.show()
    

  3. Demonstrate Elastic Weight Consolidation (EWC) versus vanilla SGD on two sequential binary classification tasks (Task A then Task B). Compute the exact expected diagonal Fisher information after Task A, then watch EWC protect Task A accuracy while still learning Task B.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Two sequential binary tasks in distinct 2D regions (plus bias column)
    key = jax.random.PRNGKey(21)
    k1, k2, k3, k4 = jax.random.split(key, 4)
    N = 120
    XA_raw = jax.random.normal(k1, (N, 2)) * 0.6 + jnp.array([-2.2, 0.0])
    XA = jnp.concatenate([XA_raw, jnp.ones((N, 1))], axis=1)
    YA = (XA_raw[:, 1] > 0.0).astype(jnp.float32).reshape(N, 1)
    
    XB_raw = jax.random.normal(k2, (N, 2)) * 0.6 + jnp.array([2.2, 0.0])
    XB = jnp.concatenate([XB_raw, jnp.ones((N, 1))], axis=1)
    YB = (XB_raw[:, 1] < 0.0).astype(jnp.float32).reshape(N, 1)
    
    def predict(W1, W2, X):
        return jax.nn.sigmoid(jnp.tanh(X @ W1) @ W2)
    
    def grads_bce(W1, W2, X, Y):
        h = jnp.tanh(X @ W1)
        p = jax.nn.sigmoid(h @ W2)
        d2 = (p - Y) / X.shape[0]
        d1 = (d2 @ W2.T) * (1.0 - h ** 2)
        return X.T @ d1, h.T @ d2
    
    # 1. Train on Task A first
    H = 24
    W1 = jax.random.normal(k3, (3, H)) * 0.6
    W2 = jax.random.normal(k4, (H, 1)) * 0.6
    for _ in range(200):
        g1, g2 = grads_bce(W1, W2, XA, YA)
        W1 = W1 - 0.25 * g1
        W2 = W2 - 0.25 * g2
    
    W1_A, W2_A = W1.copy(), W2.copy()
    
    # 2. Exact expected diagonal Fisher on Task A: E_{y~p}[(d log p / d theta)^2] = p(1-p) * (dz/dtheta)^2
    hA = jnp.tanh(XA @ W1_A)
    pA = jax.nn.sigmoid(hA @ W2_A)
    varA = pA * (1.0 - pA)
    F2 = (hA ** 2).T @ varA / N
    d_h = (1.0 - hA ** 2) * W2_A.T
    F1 = ((XA ** 2).T @ (varA * (d_h ** 2))) / N
    
    # 3. Train on Task B: vanilla SGD vs EWC
    W1_sgd, W2_sgd = W1_A.copy(), W2_A.copy()
    W1_ewc, W2_ewc = W1_A.copy(), W2_A.copy()
    lam_ewc, lr_b = 40.0, 0.03
    
    sgd_accA, sgd_accB, ewc_accA, ewc_accB = [], [], [], []
    for step in range(500):
        # Vanilla SGD on Task B
        g1, g2 = grads_bce(W1_sgd, W2_sgd, XB, YB)
        W1_sgd = W1_sgd - lr_b * g1
        W2_sgd = W2_sgd - lr_b * g2
    
        # EWC on Task B: add Fisher-weighted spring gradient lambda * F * (theta - theta_A*)
        e1, e2 = grads_bce(W1_ewc, W2_ewc, XB, YB)
        W1_ewc = W1_ewc - lr_b * (e1 + lam_ewc * F1 * (W1_ewc - W1_A))
        W2_ewc = W2_ewc - lr_b * (e2 + lam_ewc * F2 * (W2_ewc - W2_A))
    
        sgd_accA.append(float(jnp.mean((predict(W1_sgd, W2_sgd, XA) > 0.5) == YA)))
        sgd_accB.append(float(jnp.mean((predict(W1_sgd, W2_sgd, XB) > 0.5) == YB)))
        ewc_accA.append(float(jnp.mean((predict(W1_ewc, W2_ewc, XA) > 0.5) == YA)))
        ewc_accB.append(float(jnp.mean((predict(W1_ewc, W2_ewc, XB) > 0.5) == YB)))
    
    print(f"Vanilla SGD -> Task A: {sgd_accA[-1]:.1%}, Task B: {sgd_accB[-1]:.1%}")
    print(f"EWC         -> Task A: {ewc_accA[-1]:.1%}, Task B: {ewc_accB[-1]:.1%}")
    
    plt.figure(figsize=(8, 4))
    plt.plot(sgd_accA, color="#e74c3c", lw=2, linestyle="--", label="Vanilla SGD: Task A (forgetting)")
    plt.plot(sgd_accB, color="#f39c12", lw=2, linestyle=":", label="Vanilla SGD: Task B")
    plt.plot(ewc_accA, color="#27ae60", lw=2.5, label="EWC: Task A (protected)")
    plt.plot(ewc_accB, color="#3498db", lw=2.5, label="EWC: Task B (learned)")
    plt.xlabel("Task B Training Step"); plt.ylabel("Accuracy"); plt.ylim(0.0, 1.05)
    plt.title("Elastic Weight Consolidation Prevents Catastrophic Forgetting")
    plt.legend(); plt.grid(alpha=0.3); plt.tight_layout(); plt.show()