Skip to content

Biologically Plausible Learning and Plasticity

Backpropagation powers modern deep learning, yet biological brains learn continuously from sparse, noisy experience without sending exact weight-transposed error gradients backwards through synapses. This file examines why standard backpropagation is biologically implausible and explores how local synaptic plasticity, neuromodulated three-factor rules, feedback alignment, predictive coding, and energy-efficient spiking dynamics bridge neuroscience and machine learning.

  • Imagine an orchestra of 86 billion musicians playing in a pitch-black concert hall. Nobody has a score, nobody can hear more than a handful of immediate neighbours, and no conductor can sprint over to whisper the exact mathematical derivative of the audience's applause with respect to every violinist's wrist angle. Yet somehow, after a few rehearsals, the symphony becomes effortless. That is the puzzle of learning in the human brain.

  • At the heart of this puzzle sits the credit assignment problem (first introduced in Chapter 06). When a network makes a mistake at its output, such as misidentifying a face or mistiming a reach, which of the trillions of synapses deep inside the hierarchy were responsible, and should each synapse strengthen or weaken?

  • Artificial neural networks solve credit assignment cleanly via backpropagation, which is reverse-mode automatic differentiation built on the chain rule from Chapter 03. Backpropagation is astonishingly effective on silicon GPUs, yet ever since Francis Crick's famous 1989 critique, neuroscientists have pointed out that real cortical wetware almost certainly cannot execute textbook backpropagation verbatim.

Why Backpropagation Is Biologically Implausible

  • Picture trying to reverse a bustling one-way motorway so that every driver reverses along the exact lane, at the exact speed, that another driver took ten seconds ago, without ever looking in a mirror. Standard backpropagation asks biological synapses to perform several equally implausible feats at once.

Comparison of standard backpropagation and biologically plausible local learning where backpropagation relies on transposed weights, global error signals, and locked phases, whereas biological learning uses local pre- and postsynaptic activity, separate feedback pathways, and neuromodulatory broadcasts

  • The weight transport (symmetric weights) problem is the most famous objection. In backpropagation (Chapter 06), the error signal \(\boldsymbol{\delta}_l\) at hidden layer \(l\) is computed by pulling the upper-layer error \(\boldsymbol{\delta}_{l+1}\) backwards through the exact transpose of the forward weight matrix \(W_{l+1}\).
\[\boldsymbol{\delta}_l = \left(W_{l+1}^T \boldsymbol{\delta}_{l+1}\right) \odot f'(\mathbf{a}_l)\]
  • Here \(\mathbf{a}_l\) is the pre-activation vector at layer \(l\), \(f'(\mathbf{a}_l)\) is the element-wise activation derivative, and \(\odot\) denotes the Hadamard product (Chapter 02). A biological synapse, however, is a one-way chemical valve. Neurotransmitters cross from the presynaptic axon terminal to the postsynaptic dendritic spine, never in reverse. Even if a separate backward axon projects from layer \(l+1\) down to layer \(l\), there is no known biological wire that measures the precise strength of forward synapse \(w_{ij}\) and copies it onto backward synapse \(w_{ji}\).

  • Update locking and separate phases impose a second major barrier. Backpropagation enforces a strict global clock, where the network must finish a full forward pass, freeze every intermediate activation in memory until a loss is evaluated at the top, and then run a distinct backward pass before modifying any weights. Biological neurons operate continuously in real time, because the world does not pause while your visual cortex holds activations in a buffer.

  • Non-local error signals conflict with basic synaptic physics. A real synapse is a microscopic junction roughly 20 nanometres wide. The only information physically present at that junction is local presynaptic activity, local postsynaptic voltage or calcium concentration, and broadcast chemical neuromodulators, rather than a high-precision, signed global error vector routed down twenty layers.

  • Signed weights and Dale's law expose a further mismatch. Gradient descent freely flips an artificial weight from \(+0.4\) to \(-0.2\) during training. Real cortical neurons obey Dale's law, meaning each neuron releases either excitatory neurotransmitters (primarily glutamate) or inhibitory neurotransmitters (primarily GABA) at all of its outgoing synapses, so all weights leaving a given neuron share a fixed sign.

  • Discrete spikes and scarce labels widen the gap even more. Textbook backprop assumes smooth, differentiable activations and dense supervised labels on every example, whereas real neurons communicate via discrete, all-or-nothing action potentials and spend most of life learning without explicit teacher labels.

Local Synaptic Plasticity

  • Think of informal footpaths worn across a grassy park. No town planner draws a map or issues a global error signal. Instead, wherever people repeatedly walk from one gate to another, the grass flattens into a wider, faster path. Biological synapses reshape themselves using the same purely local principle, known as synaptic plasticity.

Hebb's Rule and Runaway Weights

  • In 1949, Donald Hebb proposed the foundational rule of associative plasticity, popularly summarised as "cells that fire together, wire together". If presynaptic neuron \(j\) with firing rate \(x_j\) repeatedly helps activate postsynaptic neuron \(i\) with firing rate \(y_i\), the synapse \(w_{ij}\) strengthens in proportion to their product.
\[\Delta w_{ij} = \eta \, x_j \, y_i\]
  • Here \(\eta > 0\) is the learning rate. Notice how completely local this rule is, because synapse \(w_{ij}\) needs only the activity on its own two sides (\(x_j\) and \(y_i\)).

  • Yet vanilla Hebbian learning has a fatal instability in which weights explode. Consider a single linear neuron \(y = \mathbf{w}^T \mathbf{x}\). Substituting \(y\) into the Hebbian update gives \(\Delta \mathbf{w} = \eta (\mathbf{x}\mathbf{x}^T)\mathbf{w}\). A slightly larger weight vector produces a larger output \(y\), which drives an even larger weight increase, creating a positive feedback loop that sends \(\|\mathbf{w}\|_2 \to \infty\) exponentially unless something reigns it in.

Oja's Rule and Online PCA in a Single Neuron

  • Picture pruning a garden hedge every time it grows too tall. If the pruning strength scales smoothly with how tall the hedge already is, the hedge naturally settles at a tidy, fixed height. In 1982, Erkki Oja showed that adding a purely local weight-decay term proportional to \(y^2 \mathbf{w}\) stabilises Hebbian learning onto the unit sphere (\(\|\mathbf{w}\|_2 \to 1\)).
\[\Delta \mathbf{w} = \eta \, y \left(\mathbf{x} - y \mathbf{w}\right)\]
  • Here \(\mathbf{x} \in \mathbb{R}^d\) is the input vector, \(\mathbf{w} \in \mathbb{R}^d\) is the synaptic weight vector, and \(y = \mathbf{w}^T \mathbf{x}\) is the postsynaptic output. Every quantity inside the bracket (\(x_j\), \(y\), and \(w_j\)) remains strictly local to synapse \(j\).

  • Now watch the mathematical magic that ties directly back to Chapter 02 (eigenvalues and PCA). Taking the expectation of Oja's update over zero-mean inputs with covariance matrix \(C = \mathbb{E}[\mathbf{x}\mathbf{x}^T]\) gives

\[\mathbb{E}[\Delta \mathbf{w}] = \eta \left(C \mathbf{w} - (\mathbf{w}^T C \mathbf{w})\,\mathbf{w}\right)\]
  • At equilibrium (\(\mathbb{E}[\Delta \mathbf{w}] = \mathbf{0}\)), this rearranges to \(C \mathbf{w} = \lambda \mathbf{w}\) with \(\lambda = \mathbf{w}^T C \mathbf{w}\) and \(\|\mathbf{w}\|_2 = 1\), which is the exact eigenvalue equation. Stability analysis shows that \(\mathbf{w}\) converges to the first principal component (the eigenvector with the largest eigenvalue \(\lambda_{\max}\)). Without ever forming a covariance matrix or computing an SVD, a single local biological neuron extracts the dominant direction of variance online.

BCM Theory and the Sliding Threshold

  • Imagine setting the bar height for a high-jump athlete. If the bar stays too low, every jump succeeds and the athlete stops improving, whereas if it is too high, every jump fails. The sensible solution is a sliding bar that rises when the athlete has been clearing jumps easily and lowers during a slump.

  • BCM theory (Bienenstock, Cooper, and Munro, 1982) stabilises Hebbian plasticity in exactly this homeostatic way by introducing a dynamic modification threshold \(\theta_M\) that tracks the neuron's own recent squared firing rate.

\[\Delta \mathbf{w} = \eta \, y \left(y - \theta_M\right) \mathbf{x}, \qquad \theta_M = \mathbb{E}\!\left[y^2\right]\]
  • When the neuron fires vigorously above its recent history (\(y > \theta_M\)), active synapses undergo Long-Term Potentiation (LTP) (\(\Delta w > 0\)). When it fires weakly below the threshold (\(0 < y < \theta_M\)), active synapses undergo Long-Term Depression (LTD) (\(\Delta w < 0\)). Because \(\theta_M\) drifts upwards if the neuron fires too frequently, BCM prevents runaway saturation and naturally carves out sharp, selective receptive fields resembling orientation-selective neurons in primary visual cortex (V1).

Spike-Timing-Dependent Plasticity (STDP)

  • Think of pushing a child on a swing. A push arriving a split second before the swing rises reinforces the motion (causal help), while a push arriving after the swing has already swept past works against the rhythm (anti-causal interference).

  • Experiments by Bi and Poo (1998) revealed that biological synapses care deeply about millisecond spike order, not just average firing rates. Let \(\Delta t = t_{\text{post}} - t_{\text{pre}}\) be the time lag between a presynaptic spike and a postsynaptic spike. Under Spike-Timing-Dependent Plasticity (STDP), synaptic change follows an asymmetric timing window.

\[\Delta w(\Delta t) = \begin{cases} A_+ \exp\!\left(-\Delta t / \tau_+\right) & \text{if } \Delta t > 0 \quad (\text{pre before post, LTP}) \\ -A_- \exp\!\left(\Delta t / \tau_-\right) & \text{if } \Delta t < 0 \quad (\text{post before pre, LTD}) \end{cases}\]
  • Here \(A_+, A_- > 0\) set the maximum potentiation and depression amplitudes, and \(\tau_+, \tau_- \approx 10\text{ to }20\,\text{ms}\) define the causal coincidence window. If the presynaptic neuron fires just before the postsynaptic neuron, it likely helped cause the spike and is rewarded with LTP. If it fires just after, it arrived too late and is weakened via LTD.

Three-Factor Learning Rules and Eligibility Traces

  • Picture a footballer threading a clever through-ball across midfield, and five seconds later a teammate slams the ball into the top corner as the stadium erupts. Pure two-factor Hebbian plasticity (\(\text{pre} \times \text{post}\)) only captures statistical correlations. It has no idea whether the final outcome was a goal or a turnover, nor how to bridge that five-second delay.

  • Biological brains solve goal-directed, delayed credit assignment with three-factor learning rules (Frémaux and Gerstner, 2016). Instead of changing weights immediately when pre- and postsynaptic neurons coincide, the synapse leaves behind a decaying biochemical tag called an eligibility trace \(e_{ij}(t)\), much like a fading sticky note recording that this synapse recently helped trigger a spike.

\[\tau_e \frac{de_{ij}(t)}{dt} = -e_{ij}(t) + f\!\left(\text{pre}_j(t),\, \text{post}_i(t)\right), \qquad \Delta w_{ij}(t) = \eta \, M(t) \, e_{ij}(t)\]
  • Here \(\tau_e\) is the trace decay time constant (spanning hundreds of milliseconds to seconds), \(f(\text{pre}_j, \text{post}_i)\) is a local Hebbian or STDP coincidence term, and \(M(t)\) is a globally broadcast neuromodulator acting as the third factor.

  • Different neuromodulators broadcast different global learning signals across millions of synapses at once. Dopamine encodes reward prediction error \(\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t)\) (connecting directly to temporal-difference reinforcement learning in Chapter 06), acetylcholine signals attention and expected uncertainty, and noradrenaline broadcasts sudden surprise or arousal.

  • When the dopamine pulse \(M(t)\) arrives seconds after an action, only those synapses whose eligibility trace \(e_{ij}(t)\) is still warm undergo lasting change. Remarkably, three-factor rules are neuroscience's physical implementation of actor-critic and policy-gradient reinforcement learning (REINFORCE with eligibility traces).

Biologically Plausible Approximations to Backpropagation

  • Local plasticity and three-factor rules explain unsupervised feature learning and shallow reward learning, yet an obvious question remains. Can strictly local circuits train deep, multi-layer hierarchies with the accuracy of backpropagation? Over the past decade, NeuroAI has uncovered four remarkable mechanisms showing that deep credit assignment does not require exact weight transport.

Feedback Alignment and Direct Feedback Alignment

  • Imagine learning to steer a boat with a coach who calls out directions in an unfamiliar shorthand. At first, her shouts seem almost random, yet as you adjust your rudder habits to stop drifting off course, your steering gradually aligns with her shorthand, and soon you are slicing straight down the river.

  • In 2016, Timothy Lillicrap and colleagues discovered Feedback Alignment (FA). You keep the forward pass identical, but in the backward pass you replace the transposed forward matrix \(W_{l+1}^T\) with a completely fixed, random matrix \(B_{l+1}\) that is never updated.

\[\boldsymbol{\delta}_l^{\text{FA}} = \left(B_{l+1} \boldsymbol{\delta}_{l+1}\right) \odot f'(\mathbf{a}_l)\]
  • Surprisingly, the network still learns. Random feedback works because the forward weights \(W_{l+1}\) are updated using error signals shaped by \(B_{l+1}\), causing \(W_{l+1}\) to rotate gradually during training until it aligns with \(B_{l+1}^T\). Once the angle \(\theta\) between the FA update and the true backprop gradient drops below \(90^\circ\) (equivalently \(\boldsymbol{\delta}^T W B \boldsymbol{\delta} > 0\)), every step moves downhill on the loss surface.

  • Direct Feedback Alignment (DFA) (Nøkland, 2016) pushes this idea even further. Instead of chaining errors layer by layer from the top, it projects the global output error \(\mathbf{e}_{\text{out}}\) directly to every hidden layer \(l\) through its own fixed random matrix \(B_l\).

\[\boldsymbol{\delta}_l^{\text{DFA}} = \left(B_l \mathbf{e}_{\text{out}}\right) \odot f'(\mathbf{a}_l)\]
  • DFA removes both weight transport and backward layer-to-layer locking, allowing all hidden layers to update in parallel. Its main caveat is scale, because vanilla FA and DFA struggle on very deep convolutional networks such as ImageNet ResNets unless supplemented with local sign-alignment or weight-mirroring mechanisms.

Predictive Coding Networks

  • Think of a busy newsroom editor overseeing a hierarchy of reporters. The editor does not want every mundane fact repeated every minute. She forms an expectation of how the day's story is unfolding and only wants reporters to escalate surprising deviations from that expectation.

  • Predictive coding (Rao and Ballard, 1999; Whittington and Bogacz, 2017) proposes that the neocortex is organised as exactly such a hierarchical prediction machine. Each cortical layer \(l\) splits into two cooperating populations. Value neurons hold the current latent belief \(\mathbf{x}_l\), while error neurons measure the mismatch between \(\mathbf{x}_l\) and the top-down prediction sent from layer \(l+1\).

\[\boldsymbol{\epsilon}_l = \mathbf{x}_l - f\!\left(W_{l+1} \mathbf{x}_{l+1}\right)\]
  • Here \(W_{l+1}\) are the top-down generative synaptic weights and \(f(\cdot)\) is a smooth nonlinearity. The entire hierarchy shares a single global energy function, equal to the sum of squared local prediction errors across all layers.
\[E = \frac{1}{2} \sum_{l=0}^{L-1} \|\boldsymbol{\epsilon}_l\|_2^2\]

Predictive coding hierarchy where higher cortical layers send top-down predictions downwards while lower layers compute local prediction errors and pass only unexplained residuals upwards, updating both neural states and synaptic weights locally

  • Learning proceeds on two local timescales without any global backward pass.
  • During fast inference, neural activities relax while weights stay still. We clamp the sensory input \(\mathbf{x}_0\) (and the target \(\mathbf{x}_L\) during supervised training), then let hidden activities \(\mathbf{x}_l\) settle to minimise \(E\) via local gradient dynamics. $\(\dot{\mathbf{x}}_l = -\frac{\partial E}{\partial \mathbf{x}_l} = -\boldsymbol{\epsilon}_l + \left(W_l^T \boldsymbol{\epsilon}_{l-1}\right) \odot f'\!\left(W_l \mathbf{x}_l\right)\)$
  • During slow learning, once activities reach equilibrium, every weight matrix updates via a purely local Hebbian product of the adjacent error neuron and presynaptic value neuron. $\(\Delta W_l = -\eta \frac{\partial E}{\partial W_l} = \eta \left(\boldsymbol{\epsilon}_{l-1} \odot f'\!\left(W_l \mathbf{x}_l\right)\right) \mathbf{x}_l^T\)$

  • The landmark theorem of Whittington and Bogacz (2017) proved that in the limit of gentle output nudging and exact inference convergence, these strictly local predictive coding weight updates converge mathematically to exact backpropagation gradients. Better still, predictive coding unifies perception (fast state inference) and learning (slow synaptic plasticity) under a single energy principle, and works bidirectionally for both classification and generation.

Equilibrium Propagation and Forward-Forward Learning

  • Equilibrium Propagation (Scellier and Bengio, 2017) offers a related physics-based route for energy-based networks. First, you clamp the input and let the network relax to a free equilibrium \(\mathbf{s}^0\). Next, you gently nudge the output neurons towards the target by a tiny strength \(\beta > 0\) and let the network settle to a nudged equilibrium \(\mathbf{s}^\beta\). Remarkably, the exact loss gradient with respect to every synapse turns out to be the local contrastive Hebbian difference between the two equilibria.
\[\Delta W_{ij} \propto \frac{1}{\beta}\left(s_i^\beta s_j^\beta - s_i^0 s_j^0\right)\]
  • No separate backward pass is required, because the same physical circuit computes both phases, making Equilibrium Propagation an exciting blueprint for analogue and neuromorphic chips.

  • The Forward-Forward algorithm (Geoffrey Hinton, 2022) takes a different tack by replacing the forward-and-backward pass with two forward passes, one on genuine (positive) data and one on corrupted or label-mismatched (negative) data. Each layer independently optimises a local goodness score, such as its sum of squared activations \(g_l = \sum_i y_{l,i}^2\), pushing \(g_l\) above a threshold \(\theta\) for positive inputs and below \(\theta\) for negative inputs. By \(L_2\)-normalising each layer's activity vector before passing it to the next layer, the magnitude (goodness) is stripped away so deeper layers cannot cheat and must learn genuinely new higher-order features.

The 20-Watt Brain Lesson

  • Picture a modern AI training cluster, with racks of liquid-cooled GPUs consuming megawatts of electricity (enough to power a small town) to train and serve frontier models. Now touch your own forehead. The human brain sustains real-time multimodal perception, fluent language, dexterous motor control, and lifelong learning on roughly 20 watts, which is less power than a dim desk lamp.

  • Three biological design choices account for this staggering efficiency gap, and each directly informs modern AI systems engineering.

  • Memory-compute colocation avoids the von Neumann bottleneck explored in Chapters 16 and 19. Moving model weights from off-chip HBM memory to on-chip ALUs consumes orders of magnitude more energy than the floating-point multiplications themselves. In the brain, every synapse is both memory storage and local computation, so zero weights ever cross a memory bus.
  • Sparse, event-driven computation eliminates wasted arithmetic. Dense deep networks multiply every neuron by every weight on every clock cycle, even when activations are near zero. Cortical neurons fire sparsely (roughly 1 to 5 spikes per second on average) and asynchronously, so silence consumes almost no dynamic energy.
  • Local plasticity and low-precision analogue physics remove massive memory buffers. Biological synapses operate at roughly 3 to 5 bits of effective precision and learn locally without caching huge activation graphs for global backward passes.

  • These biological lessons are no longer merely academic curiosities. They directly motivate low-bit quantisation, activation sparsity, near-memory accelerators, and efficient AI inference covered in Chapters 19 and 20, as well as dedicated neuromorphic hardware in Chapter 26.

Take-Home

  • Standard backpropagation looks unbiological because it relies on exact weight symmetry (\(W^T\)), frozen forward and backward phases, non-local error signals, and sign-flipping weights that violate Dale's law.
  • Local plasticity is surprisingly powerful, since adding Oja's local normalisation to exploding Hebbian updates extracts the exact first principal component online, BCM's sliding threshold creates selective receptive fields, and STDP encodes millisecond causality.
  • Three-factor rules solve delayed rewards by pairing local pre- and postsynaptic eligibility traces with a broadcast neuromodulator (such as dopamine) to implement biologically plausible reinforcement learning across time delays.
  • Deep credit assignment can stay local through Feedback Alignment (where forward weights align to fixed random feedback \(B\)) and through Predictive Coding or Equilibrium Propagation (which recover exact backpropagation gradients from purely local energy minimisation).
  • The 20-watt blueprint shows how colocating memory and compute inside sparse, event-driven local circuits achieves orders-of-magnitude better energy efficiency than von Neumann accelerators.

Coding Tasks (use CoLab or notebook)

  1. Compare vanilla Hebbian learning with Oja's rule on correlated 2D data. Verify that vanilla Hebbian weights explode while Oja's local rule converges smoothly to the exact top principal component (computed via jnp.linalg.eigh).

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Generate correlated 2D zero-mean data along a tilted axis
    key = jax.random.PRNGKey(42)
    N = 200
    raw = jax.random.normal(key, (N, 2))
    cov_sqrt = jnp.array([[2.2, 0.9], [0.9, 0.7]])
    X = raw @ cov_sqrt.T
    X = X - jnp.mean(X, axis=0, keepdims=True)
    
    # Ground-truth top principal component from Chapter 02 eigendecomposition
    C = (X.T @ X) / N
    eigvals, eigvecs = jnp.linalg.eigh(C)
    top_pc = eigvecs[:, -1]
    
    # Run vanilla Hebbian vs Oja's rule online
    w_hebb = jnp.array([0.2, -0.8])
    w_oja = jnp.array([0.2, -0.8])
    eta = 0.01
    
    hebb_norms, oja_norms, oja_cos = [], [], []
    for epoch in range(2):
        for i in range(N):
            x = X[i]
            y_h = jnp.dot(w_hebb, x)
            w_hebb = w_hebb + eta * y_h * x
            y_o = jnp.dot(w_oja, x)
            w_oja = w_oja + eta * y_o * (x - y_o * w_oja)
    
            hebb_norms.append(float(jnp.linalg.norm(w_hebb)))
            oja_norms.append(float(jnp.linalg.norm(w_oja)))
            cos_sim = jnp.abs(jnp.dot(w_oja, top_pc) / (jnp.linalg.norm(w_oja) + 1e-8))
            oja_cos.append(float(cos_sim))
    
    print(f"True top PC:     {top_pc}")
    print(f"Oja learned w:   {w_oja}")
    print(f"Final |cos sim|: {oja_cos[-1]:.4f}, ||w_oja||={oja_norms[-1]:.4f}")
    print(f"Final ||w_hebb|| (exploded): {hebb_norms[-1]:.2e}")
    
    fig, axes = plt.subplots(1, 2, figsize=(10, 4))
    axes[0].scatter(X[:, 0], X[:, 1], alpha=0.25, s=12, color="#3498db", label="Data")
    axes[0].arrow(0, 0, float(top_pc[0])*3, float(top_pc[1])*3, head_width=0.18, color="#27ae60", lw=2.5, label="True PC1")
    axes[0].arrow(0, 0, float(w_oja[0])*2.6, float(w_oja[1])*2.6, head_width=0.15, color="#e74c3c", lw=2, linestyle="--", label="Oja w")
    axes[0].set_title("Oja's Rule Recovers Top Principal Component")
    axes[0].axis("equal"); axes[0].legend(); axes[0].grid(alpha=0.3)
    
    axes[1].plot(oja_cos, color="#27ae60", lw=2, label="|cos(w_oja, PC1)|")
    axes[1].plot(oja_norms, color="#3498db", lw=2, linestyle="--", label="||w_oja|| (stabilised -> 1)")
    axes[1].set_xlabel("Online Update Step"); axes[1].set_ylim(0, 1.15)
    axes[1].set_title("Oja Convergence vs Weight Stability")
    axes[1].legend(); axes[1].grid(alpha=0.3)
    plt.tight_layout(); plt.show()
    

  2. Compare Feedback Alignment (FA) against standard Backpropagation on a 2-layer nonlinear classification task (concentric rings). Track both training loss and the angle between the forward weights \(W_2^T\) and the fixed random feedback matrix \(B\), watching alignment drop well below \(90^\circ\).

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Concentric circles dataset (nonlinearly separable)
    key = jax.random.PRNGKey(7)
    k1, k2, k3, k4, k5 = jax.random.split(key, 5)
    N = 200
    angles = jax.random.uniform(k1, (N,), minval=0.0, maxval=2.0 * jnp.pi)
    radii = jnp.concatenate([
        0.5 + 0.12 * jax.random.normal(k2, (N // 2,)),
        1.4 + 0.12 * jax.random.normal(k3, (N // 2,))
    ])
    X = jnp.stack([radii * jnp.cos(angles), radii * jnp.sin(angles), jnp.ones(N)], axis=1)
    Y = jnp.concatenate([jnp.zeros((N // 2, 1)), jnp.ones((N // 2, 1))], axis=0)
    
    H = 24
    W1_bp = jax.random.normal(k4, (3, H)) * 0.6
    W2_bp = jax.random.normal(k5, (H, 1)) * 0.6
    W1_fa, W2_fa = W1_bp.copy(), W2_bp.copy()
    B_fixed = jax.random.normal(jax.random.PRNGKey(99), (1, H)) * 0.8  # Fixed random feedback!
    
    lr = 0.35
    bp_losses, fa_losses, align_angles = [], [], []
    
    for step in range(300):
        # --- Backpropagation ---
        a1 = X @ W1_bp
        h1 = jnp.tanh(a1)
        y_bp = jax.nn.sigmoid(h1 @ W2_bp)
        loss_bp = -jnp.mean(Y * jnp.log(y_bp + 1e-7) + (1 - Y) * jnp.log(1 - y_bp + 1e-7))
        d2 = (y_bp - Y) / N
        d1_bp = (d2 @ W2_bp.T) * (1.0 - h1 ** 2)
        W2_bp = W2_bp - lr * (h1.T @ d2)
        W1_bp = W1_bp - lr * (X.T @ d1_bp)
    
        # --- Feedback Alignment (uses fixed random B_fixed instead of W2^T) ---
        a1_f = X @ W1_fa
        h1_f = jnp.tanh(a1_f)
        y_fa = jax.nn.sigmoid(h1_f @ W2_fa)
        loss_fa = -jnp.mean(Y * jnp.log(y_fa + 1e-7) + (1 - Y) * jnp.log(1 - y_fa + 1e-7))
        d2_f = (y_fa - Y) / N
        d1_fa = (d2_f @ B_fixed) * (1.0 - h1_f ** 2)
        W2_fa = W2_fa - lr * (h1_f.T @ d2_f)
        W1_fa = W1_fa - lr * (X.T @ d1_fa)
    
        # Alignment angle between W2_fa^T and B_fixed (in degrees)
        cos_a = jnp.sum(W2_fa.T * B_fixed) / (jnp.linalg.norm(W2_fa) * jnp.linalg.norm(B_fixed) + 1e-8)
        angle_deg = float(jnp.degrees(jnp.arccos(jnp.clip(cos_a, -1.0, 1.0))))
        bp_losses.append(float(loss_bp)); fa_losses.append(float(loss_fa)); align_angles.append(angle_deg)
    
    print(f"Final BP loss: {bp_losses[-1]:.4f} | Final FA loss: {fa_losses[-1]:.4f}")
    print(f"Initial angle(W2^T, B): {align_angles[0]:.1f} deg -> Final: {align_angles[-1]:.1f} deg")
    
    fig, axes = plt.subplots(1, 2, figsize=(10, 4))
    axes[0].plot(bp_losses, color="#3498db", lw=2, label="Backpropagation")
    axes[0].plot(fa_losses, color="#27ae60", lw=2, linestyle="--", label="Feedback Alignment (random B)")
    axes[0].set_xlabel("Step"); axes[0].set_ylabel("Binary Cross-Entropy Loss")
    axes[0].set_title("FA Learns Without Weight Transport"); axes[0].legend(); axes[0].grid(alpha=0.3)
    
    axes[1].plot(align_angles, color="#9b59b6", lw=2, label="Angle(W2^T, B)")
    axes[1].axhline(90.0, color="#e74c3c", linestyle=":", label="90 deg descent boundary")
    axes[1].set_xlabel("Step"); axes[1].set_ylabel("Degrees")
    axes[1].set_title("Forward Weights Align to Fixed Random B"); axes[1].legend(); axes[1].grid(alpha=0.3)
    plt.tight_layout(); plt.show()
    

  3. Implement a 2-layer Predictive Coding Network (PCN) trained purely via fast local inference relaxation and slow local Hebbian weight updates (zero global backpropagation), and compare its learning curve against standard backpropagation on a nonlinear regression task.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Nonlinear regression task: y = sin(2x) + 0.3 cos(3x)
    key = jax.random.PRNGKey(11)
    k1, k2 = jax.random.split(key, 2)
    N = 64
    x_raw = jnp.linspace(-2.0, 2.0, N).reshape(N, 1)
    X = jnp.concatenate([x_raw, jnp.ones((N, 1))], axis=1)
    Y = jnp.sin(2.0 * x_raw) + 0.3 * jnp.cos(3.0 * x_raw)
    
    H = 20
    W1_pc = jax.random.normal(k1, (2, H)) * 0.5
    W2_pc = jax.random.normal(k2, (H, 1)) * 0.4
    W1_bp, W2_bp = W1_pc.copy(), W2_pc.copy()
    
    pc_losses, bp_losses, energy_trace = [], [], []
    eta_x = 0.1    # Fast inference step size
    eta_w = 0.08   # Slow synaptic learning rate
    beta_nudge = 0.05  # Gentle output nudging (Whittington & Bogacz limit)
    
    for epoch in range(300):
        # --- Predictive Coding Network (purely local updates) ---
        h_pred = jnp.tanh(X @ W1_pc)
        x1 = h_pred.copy()
        # Fast inference: relax hidden neurons x1 to minimise local prediction errors
        for t in range(30):
            y_pred = x1 @ W2_pc
            eps2 = beta_nudge * (Y - y_pred)   # Nudged output prediction error
            eps1 = x1 - h_pred                 # Hidden prediction error
            dx1 = -eps1 + eps2 @ W2_pc.T       # Local dynamics: adjacent layers only
            x1 = x1 + eta_x * dx1
            if epoch == 0:
                energy_trace.append(float(0.5 * jnp.mean(eps1**2) + 0.5 * jnp.mean((Y - y_pred)**2)))
    
        # Slow local Hebbian synaptic updates at equilibrium
        eps2 = Y - (x1 @ W2_pc)
        eps1 = (x1 - h_pred) / beta_nudge
        W2_pc = W2_pc + eta_w * (x1.T @ eps2) / N
        W1_pc = W1_pc + eta_w * (X.T @ (eps1 * (1.0 - h_pred**2))) / N
    
        pc_mse = float(jnp.mean((jnp.tanh(X @ W1_pc) @ W2_pc - Y) ** 2))
        pc_losses.append(pc_mse)
    
        # --- Standard Backpropagation comparison ---
        h_bp = jnp.tanh(X @ W1_bp)
        y_bp = h_bp @ W2_bp
        bp_mse = float(jnp.mean((y_bp - Y) ** 2))
        bp_losses.append(bp_mse)
        d2 = (y_bp - Y) / N
        d1 = (d2 @ W2_bp.T) * (1.0 - h_bp**2)
        W2_bp = W2_bp - eta_w * (h_bp.T @ d2)
        W1_bp = W1_bp - eta_w * (X.T @ d1)
    
    print(f"Final PCN MSE: {pc_losses[-1]:.5f} | Final Backprop MSE: {bp_losses[-1]:.5f}")
    
    fig, axes = plt.subplots(1, 2, figsize=(10, 4))
    axes[0].plot(bp_losses, color="#3498db", lw=2, label="Standard Backprop")
    axes[0].plot(pc_losses, color="#27ae60", lw=2, linestyle="--", label="Predictive Coding (local)")
    axes[0].set_xlabel("Epoch"); axes[0].set_ylabel("MSE Loss")
    axes[0].set_title("Local Predictive Coding Matches Backprop"); axes[0].legend(); axes[0].grid(alpha=0.3)
    
    axes[1].plot(energy_trace, color="#9b59b6", lw=2, marker="o", markersize=3)
    axes[1].set_xlabel("Fast Inference Iteration"); axes[1].set_ylabel("Prediction Error Energy E")
    axes[1].set_title("Epoch 0: Fast Local Energy Relaxation"); axes[1].grid(alpha=0.3)
    plt.tight_layout(); plt.show()