Local Learning Framework
Source: nct_v2/v11_learning.py Lines: 1,089 Classes: 6
Overview
NCT implements five complementary learning systems, none of which require global backpropagation through the column hierarchy. These systems are orchestrated by the V11LearningManager, which coordinates predictive coding updates, Hebbian plasticity, neuromodulatory gating, wake-sleep scheduling, and developmental staging.
Predictive Coding Optimizer (Theorem A)
Theorem 21 (Predictive Coding Replaces Backpropagation (Whittington & Bogacz, 2017)). Each column in the hierarchy generates a top-down prediction of the column below’s output. The prediction error is: Weight updates are strictly local, each column adjusts only its own parameters to minimize its own prediction error, weighted by learned precision :
The precision is itself learnable. When is small (the column expects its predictions to be precise), the learning signal is amplified, small errors are treated as significant. When is large (the column is uncertain), the learning signal is attenuated, errors are expected and tolerated. This implements precision-weighted prediction coding (PWPC), matching the brain’s ability to distinguish between genuinely surprising events and expected noise.
Inference iterations: PC inference proceeds iteratively, after an initial bottom-up pass, top-down predictions and lateral signals are fed back, and columns re-settle for up to iterations. These iterations run without gradients (biologically correct: neural settling is dynamical relaxation, not gradient descent). Only the final settled state is used for weight updates.
Proposition 5 (Per-Column Loss Decomposition). The total PC loss decomposes as a sum of independent per-column terms: Each column can compute its own loss and gradient independently, no cross-column gradient flow is needed. This is the key property that enables local learning.
Hebbian Optimizer (Theorem B)
Theorem 22 (Hebbian + Anti-Hebbian Convergence (Pehlevan & Chklovskii, 2019)). The L2/3 association weights are updated by a Hebbian rule with BCM homeostasis: Anti-Hebbian lateral weights enforce decorrelation: This combination provably converges to the PCA subspace of the input distribution, self-organizing representations without any supervised signal. The BCM threshold prevents runaway potentiation by providing a sliding activity threshold.
The Hebbian optimizer also updates local per-column parameters (L4, L1, L5 projections) using each column’s own prediction error as a local target:
This is a form of local target propagation: each column’s prediction error serves as its own teaching signal.
Neuromodulated Plasticity (Theorem C)
Theorem 23 (Neuromodulatory Gating of Learning (Schultz, 1997)). All learning is multiplicatively gated by four neuromodulatory signals computed by the brainstem: where is either the PC or Hebbian update. This implements reinforcement learning without backpropagation: dopamine provides policy-gradient-like reward signals, acetylcholine gates whether learning occurs at all, norepinephrine controls the magnitude of exploration noise, and serotonin modulates the effective time horizon (discount factor).
The plasticity coefficient is computed as:
Wake-Sleep Scheduler (Theorem D)
Theorem 24 (Synaptic Homeostasis Hypothesis (Tononi & Cirelli, 2006)). The wake-sleep cycle implements two complementary processes:
Wake phase: Process input, update weights via PC + Hebbian, tag surprising episodes in hippocampus.
Sleep phase: (1) Replay tagged episodes from HPC buffer (priority: surprise recency), replaying through columns with local learning. (2) Synaptic downscaling: where (1% reduction per sleep phase), preventing unbounded weight growth. (3) Consolidation: transfer frequently-replayed patterns from hippocampal episodic to neocortical semantic storage.
Sleep timing is controlled by the WakeSleepScheduler: sleep occurs every wake steps (default 100), with replay steps per sleep phase (default 50). Sleep pressure accumulates during wake and resets after sleep.
Developmental Program (Critical Periods)
Theorem 25 (Developmental Staging (Hensch, 2004)). The brain changes how it learns over time. NCT implements four developmental stages:
| Stage | Steps | LR | Inhib | Hebb wt | Struct |
|---|---|---|---|---|---|
| Sensory | 0–1K | 2.0 | 0.3 | 0.8 | 1.0 |
| Association | 1K–5K | 1.5 | 0.6 | 0.6 | 0.7 |
| Integration | 5K–20K | 1.0 | 0.9 | 0.4 | 0.3 |
| Refinement | 20K+ | 0.5 | 1.0 | 0.3 | 0.1 |
Early stages are Hebbian-dominated (absorb correlations). Late stages are PC-dominated (refine predictions). Inhibitory strength increases throughout, matching GABA maturation driving critical period closure. Sleep frequency increases in late stages (consolidation becomes the primary learning mechanism).
V11LearningManager: Orchestration
The V11LearningManager class coordinates all five systems. On each wake step:
Advance the developmental program clock
Get current stage parameters (LR multiplier, inhibitory strength, Hebbian weight)
Compute neuromodulatory plasticity coefficient
Apply Hebbian updates to L2/3 association weights (all columns)
Apply Hebbian updates to local per-column parameters
Apply PC updates to prediction weights
Check if sleep should occur (based on developmental-adjusted sleep interval)
If sleep: run replay + downscaling + consolidation
Source Code
# ===========================================================================
# Local Learning (Predictive Coding + Hebbian)
# Source: nct_v2/v11_learning.py
# ===========================================================================
"""
NCT V11: Local Learning Rules
===============================
Replaces global backprop with biologically-grounded local learning.
Three learning mechanisms:
1. Predictive Coding (Theorem A): Each column minimizes its own prediction error
via local gradients. Whittington & Bogacz (2017) proved equivalence to backprop.
2. Hebbian Learning (Theorem B): L2/3 associations self-organize via
Hebbian + anti-Hebbian rules. No gradients needed.
3. Neuromodulated Plasticity (Theorem C): DA/NE/5-HT/ACh gate all learning.
Plasticity = DA × ACh × f(NE, 5-HT).
Plus:
- Wake-Sleep Scheduler (Theorem D): Manages wake/sleep cycle
- BCM homeostasis: Prevents runaway Hebbian learning
- Metaplasticity: Learning-to-learn rate adjustment
"""
# [bundled] from .v11_config import V11Config
# [bundled] from .v11_column import CorticalColumn, ColumnOutput
# [bundled] from .v11_systems import NeuromodState
# ═══════════════════════════════════════════════════════════════════════
# Predictive Coding Optimizer
# ═══════════════════════════════════════════════════════════════════════
class PredictiveCodingOptimizer:
"""
Local learning via predictive coding (Theorem A).
Each column l generates a prediction of the column below it.
Error: ε_l = actual_input_l - prediction_from_{l+1}
Weight update: Δθ_l = -η × ε_l × ∂f/∂θ_l (local gradient)
Implementation: Each column has its own loss function:
L_l = ||ε_l||² / (2σ²_l) + log(σ²_l)
We call .backward() on each column's loss SEPARATELY.
Gradients don't flow between columns — they're LOCAL.
Whittington & Bogacz (2017) proved this is equivalent to backprop
at convergence. We use a fixed number of inference steps (not convergence)
because the brain operates in real-time.
"""
def __init__(self, cfg: V11Config):
self.cfg = cfg
self.lr = cfg.pc_learning_lr
def compute_column_losses(
self,
predictions: List[torch.Tensor],
targets: List[torch.Tensor],
precisions: List[torch.Tensor],
) -> Tuple[List[torch.Tensor], torch.Tensor]:
"""
Compute local predictive coding loss for each column.
predictions[l]: [B, T, D] — column l+1's prediction of column l's input
targets[l]: [B, T, D] — actual input at level l
precisions[l]: [B, T, 1] — σ² at level l
Returns:
losses: List of per-column losses (each is a scalar)
total_loss: Sum of all column losses (for monitoring)
"""
losses = []
total_loss = torch.tensor(0.0, device=targets[0].device)
for l in range(len(predictions)):
pred = predictions[l]
target = targets[l]
sigma2 = precisions[l].clamp(min=1e-6)
# Prediction error
error = target.detach() - pred # Detach target — local learning
# Precision-weighted MSE + log-precision (ELBO-like)
loss_l = (error.pow(2) / (2.0 * sigma2) + 0.5 * sigma2.log()).mean()
losses.append(loss_l)
total_loss = total_loss + loss_l
return losses, total_loss
@torch.no_grad()
def local_update(
self,
columns: nn.ModuleList,
predictions: List[torch.Tensor],
targets: List[torch.Tensor],
precisions: List[torch.Tensor],
plasticity_gate: Optional[torch.Tensor] = None,
):
"""
Truly local weight updates via predictive coding — ZERO autograd.
Each column updates its own W_predict and W_sigma using analytical
gradients computed directly from prediction errors. No .backward(),
no autograd graph, no global error propagation.
This is the Rao & Ballard (1999) / Whittington & Bogacz (2017) PC
update rule, computed in closed form.
For W_predict (linear): dW = -(error / σ²) @ input^T / N
For W_sigma (via softplus): dW = dL/dσ² × sigmoid(z) @ input^T / N
predictions[l]: prediction for level l (from column l)
targets[l]: actual value at level l
precisions[l]: σ² at level l
plasticity_gate: [B, T, 1] — neuromodulatory plasticity multiplier
"""
plasticity_mult = 1.0
if plasticity_gate is not None:
plasticity_mult = plasticity_gate.mean().item()
lr = self.lr * plasticity_mult
for l, col in enumerate(zip(columns)):
if isinstance(col, tuple):
col = col[0]
if l >= len(predictions):
break
pred = predictions[l]
target = targets[l].detach()
sigma2 = precisions[l].clamp(min=1e-6)
# Prediction error (local signal)
error = target - pred.detach() # [B, T, D_model]
# ── W_predict update: dW = -(error / σ²) @ h_norm^T / N ──────
# The column stores h_norm from last forward in L5
# prediction = W_predict(h_norm), so gradient is error @ h_norm^T
L5 = col.L5
# Reconstruct h_norm: we need the input that was fed to W_predict
# L5 stores it as part of the norm output — access via stored state
# Since we're in no_grad, we compute from the column output
h_norm = col._last_l5_h_norm if hasattr(col, '_last_l5_h_norm') else None
if h_norm is not None:
B, T, D_model = error.shape
D_col = h_norm.shape[-1]
N = B * T
# Weighted error by precision
weighted_error = error.float() / sigma2.float() # [B, T, D_model]
# W_predict gradient: [D_model, D_col]
we_flat = weighted_error.reshape(N, D_model)
h_flat = h_norm.float().reshape(N, D_col)
dW_predict = -(we_flat.T @ h_flat) / N # [D_model, D_col]
# Clip gradient norm
grad_norm = dW_predict.norm()
if grad_norm > self.cfg.max_grad_norm:
dW_predict = dW_predict * (self.cfg.max_grad_norm / grad_norm)
L5.W_predict.weight.data -= lr * dW_predict.to(L5.W_predict.weight.dtype)
# ── W_sigma update: dL/dσ² × sigmoid(z) @ h_norm^T / N ───────
# σ² = softplus(z) + ε where z = W_sigma(h_norm)
# dL/dσ² = -error²/(2σ²²) + 0.5/σ²
if h_norm is not None and hasattr(L5, 'W_sigma'):
error_sq = error.float().pow(2).sum(dim=-1, keepdim=True) # [B, T, 1]
sigma2_f = sigma2.float()
dL_dsigma2 = -error_sq / (2.0 * sigma2_f.pow(2)) + 0.5 / sigma2_f # [B, T, 1]
# Chain rule through softplus: dσ²/dz = sigmoid(z)
# z = W_sigma(h_norm) + bias → reconstruct z from σ²
# softplus(z) = σ² - ε → z = log(exp(σ² - ε) - 1) — but simpler to use sigmoid
# sigmoid(z) = 1 - exp(-softplus(z)) = 1 - exp(-(σ²-ε))
sigmoid_z = (1.0 - torch.exp(-(sigma2_f - 1e-6))).clamp(0.01, 0.99)
dL_dz = dL_dsigma2 * sigmoid_z # [B, T, 1]
# W_sigma: [1, D_col] with bias
dz_flat = dL_dz.reshape(N, 1).float()
h_flat = h_norm.float().reshape(N, D_col)
dW_sigma = (dz_flat.T @ h_flat) / N # [1, D_col]
db_sigma = dz_flat.mean(dim=0) # [1]
sigma_grad_norm = dW_sigma.norm()
if sigma_grad_norm > self.cfg.max_grad_norm:
scale = self.cfg.max_grad_norm / sigma_grad_norm
dW_sigma = dW_sigma * scale
db_sigma = db_sigma * scale
L5.W_sigma.weight.data -= lr * dW_sigma.to(L5.W_sigma.weight.dtype)
L5.W_sigma.bias.data -= lr * db_sigma.to(L5.W_sigma.bias.dtype)
# ═══════════════════════════════════════════════════════════════════════
# Hebbian Optimizer
# ═══════════════════════════════════════════════════════════════════════
class HebbianOptimizer:
"""
Hebbian learning for L2/3 lateral associations (Theorem B).
Updates W_assoc via: ΔW = η × BCM(X^T X) / N
Updates W_lateral via anti-Hebbian: ΔW = η × (Y^T Y - I) / N
BCM modulation prevents runaway learning:
Δw ∝ y(y - θ_BCM)x
y > θ_BCM → potentiation
y < θ_BCM → depression
No autograd needed — pure matrix operations.
"""
def __init__(self, cfg: V11Config):
self.cfg = cfg
self.lr = cfg.hebbian_lr
@torch.no_grad()
def update(
self,
columns: nn.ModuleList,
column_outputs: List[ColumnOutput],
plasticity_gate: Optional[torch.Tensor] = None,
errors: Optional[List[torch.Tensor]] = None,
):
"""
Perform Hebbian updates for all columns' L2/3 layers.
Three improvements over blind Hebbian:
1. BCM modulation (prevents runaway learning)
2. Metaplasticity LR (learning-to-learn)
3. Error-driven modulation (learn from mistakes, not just correlations)
4. σ²-adaptive LR (uncertain columns learn faster)
column_outputs: List of ColumnOutput from forward pass
plasticity_gate: [B, T, 1] neuromodulatory gating
errors: List of per-column prediction errors (for error-driven Hebbian)
"""
lr = self.lr
if plasticity_gate is not None:
lr = lr * plasticity_gate.mean().item()
for i, (col, out) in enumerate(zip(columns, column_outputs)):
# Metaplasticity LR multiplier
meta_mult = col.metaplasticity.get_lr_multiplier()
effective_lr = lr * meta_mult
# σ²-Adaptive LR: uncertain columns learn faster
# sigma2 is [B, T, 1] — use mean as scalar multiplier
sigma2_mean = out.sigma2.mean().item()
sigma2_mult = 1.0 + min(sigma2_mean, 10.0) # Cap at 11x to prevent explosion
effective_lr = effective_lr * sigma2_mult
# Error-driven Hebbian (if errors provided and BCM enabled)
error_for_col = errors[i] if errors is not None and i < len(errors) else None
if col.bcm.enabled and error_for_col is not None and self.cfg.error_hebbian_weight > 0:
col.L23.hebbian_update_error_modulated(
pre_input=out.l23_input,
post_output=out.l23_output,
error=error_for_col,
bcm_theta=col.bcm.theta_bcm,
lr=effective_lr,
error_weight=self.cfg.error_hebbian_weight,
)
elif col.bcm.enabled:
col.L23.hebbian_update_bcm(
pre_input=out.l23_input,
post_output=out.l23_output,
bcm_theta=col.bcm.theta_bcm,
lr=effective_lr,
)
else:
col.L23.hebbian_update(out.l23_input, lr=effective_lr)
# Anti-Hebbian update for W_lateral (decorrelation)
col.L23.anti_hebbian_update(out.l23_output, lr=effective_lr)
# BCM threshold update
activity = out.l23_output.abs().mean(dim=-1) # [B, T]
col.bcm.update_threshold(activity)
# Metaplasticity: track weight change magnitude
w_change = col.L23.W_assoc.abs().mean().item()
col.metaplasticity.update(w_change)
@torch.no_grad()
def update_local_params(
self,
columns: nn.ModuleList,
column_outputs: list,
errors: Optional[list] = None,
plasticity_gate: Optional[torch.Tensor] = None,
):
"""
Update ALL locally-learnable parameters beyond L2/3 W_assoc.
Fixes dead parameters: L1, L6, oscillations, interneurons, L5 dendritic.
Each uses biologically-grounded local learning rules — zero autograd.
L1: Prediction-error Hebbian — td_context × error correlation
L6: Thalamic feedback — column state × error correlation
Oscillations: Phase-error anti-correlation for PAC coupling
Interneurons: Activity-dependent error-modulated plasticity
L5 Dendritic: σ²-error correlation for adaptive gating thresholds
"""
if errors is None or len(errors) == 0:
return
base_lr = self.lr * 0.1 # Slower than L2/3 Hebbian (stability)
if plasticity_gate is not None:
base_lr = base_lr * plasticity_gate.mean().item()
for i, (col, out) in enumerate(zip(columns, column_outputs)):
error = errors[i] if i < len(errors) else None
if error is None:
continue
B, T, D_model = error.shape
D_col = out.state.shape[-1]
N = max(B * T, 1)
# Per-column adaptive LR
meta_mult = col.metaplasticity.get_lr_multiplier()
sigma2_mult = 1.0 + min(out.sigma2.mean().item(), 10.0)
lr = base_lr * meta_mult * sigma2_mult
error_flat = error.reshape(N, D_model).float()
error_mag = error.float().norm(dim=-1, keepdim=True).mean().item()
# ── L1: Top-Down Prediction Error Hebbian ──────────────────
# L1.proj maps D_model → D_col. Top-down context comes from
# higher column's prediction. Learn: strengthen td paths that
# correlate with what the column needs (= prediction error).
# ΔW = η × (error_in_col_space^T @ td_context) / N
#
# We don't have td_context stored directly, but l23_input
# includes L1 modulation. For the first iteration, use the
# column's own prediction error projected to column space.
if error_mag > 0.01: # Only learn when error is meaningful
# Project error to column space via L4 projection
err_col = F.linear(error.float(), col.L4.proj.weight.float()) # [B, T, D_col]
err_col_flat = err_col.reshape(N, D_col)
# L1.proj: [D_col, D_model]
# Use l23_input as proxy for what L1 received (it's L4 + L1 output)
l23_in_flat = out.l23_input.reshape(N, D_col).float()
# Hebbian: correlate error (in col space) with column input
# This teaches L1 to modulate in directions that track prediction error
dW_l1 = (err_col_flat.T @ l23_in_flat) / N # [D_col, D_col]
# But L1.proj is [D_col, D_model] — we need proper dimension
# Use the error itself as the post-synaptic signal
dW_l1_proper = (err_col_flat.T @ error_flat) / N # [D_col, D_model]
col.L1.proj.weight.data -= lr * dW_l1_proper.to(col.L1.proj.weight.dtype)
# Norm guard
w_norm = col.L1.proj.weight.data.norm()
if w_norm > 5.0:
col.L1.proj.weight.data *= 5.0 / w_norm
# L1 gate: open more when error is high (need more top-down context)
col.L1.gate_raw.data += lr * 0.01 * min(error_mag, 5.0)
col.L1.gate_raw.data.clamp_(max=2.0) # Don't exceed ~0.88 gate
# ── L6: Thalamic Feedback Learning ─────────────────────────
# L6.proj maps D_col → D_model. L6 sends feedback to thalamus.
# Learn: send signals that correlate with prediction error,
# so thalamus can better filter future input.
# ΔW = η × (error^T @ column_state) / N
state_flat = out.state.reshape(N, D_col).float()
dW_l6 = (error_flat.T @ state_flat) / N # [D_model, D_col]
col.L6.proj.weight.data -= lr * dW_l6.to(col.L6.proj.weight.dtype)
# Norm guard
w_norm = col.L6.proj.weight.data.norm()
if w_norm > 5.0:
col.L6.proj.weight.data *= 5.0 / w_norm
# L6 gate: open more with error
col.L6.gate_raw.data += lr * 0.01 * min(error_mag, 5.0)
col.L6.gate_raw.data.clamp_(max=2.0)
# ── Oscillation PAC Coupling ───────────────────────────────
# Kappa1/2/3 control phase-amplitude coupling strength.
# Learn: adjust coupling based on phase-error anti-correlation.
# If error peaks at specific phases → coupling at those phases
# is amplifying errors → reduce that coupling.
if col.oscillations.enabled:
osc = col.oscillations
osc_lr = lr * 0.1 # Extra slow (oscillation stability)
# Reconstruct phases
t_idx = torch.arange(T, device=error.device, dtype=error.dtype)
P_theta = F.softplus(osc.period_theta_raw)
P_alpha = F.softplus(osc.period_alpha_raw)
P_delta = F.softplus(osc.period_delta_raw)
phi_theta = 2 * math.pi * t_idx / P_theta
phi_alpha = 2 * math.pi * t_idx / P_alpha
phi_delta = 2 * math.pi * t_idx / P_delta
# Error magnitude per position [T]
error_per_t = error.float().norm(dim=-1).mean(dim=0) # [T]
error_norm = error_per_t / (error_per_t.mean() + 1e-8)
# Phase-error correlation
corr_theta = (error_norm * phi_theta.cos()).mean().item()
corr_delta = (error_norm * phi_delta.cos()).mean().item()
corr_alpha = (error_norm * phi_alpha.cos()).mean().item()
# Anti-correlate: reduce coupling where error aligns with phase
osc.kappa1_raw.data -= osc_lr * corr_theta
osc.kappa2_raw.data -= osc_lr * corr_delta
osc.kappa3_raw.data += osc_lr * corr_alpha # α suppression: increase
# Clamp kappas to prevent divergence
osc.kappa1_raw.data.clamp_(-2.0, 2.0)
osc.kappa2_raw.data.clamp_(-2.0, 2.0)
osc.kappa3_raw.data.clamp_(-2.0, 2.0)
# W_out: oscillation output projection [D_col, r]
# Recompute interaction for gradient
r = osc.W_content.weight.shape[0]
content = osc.W_content(out.state.float()) # [B, T, r]
phase_features = torch.stack([
phi_theta.sin(), phi_theta.cos(),
phi_alpha.sin(), phi_alpha.cos(),
phi_delta.sin(), phi_delta.cos(),
], dim=-1) # [T, 6]
phase_proj = osc.W_phase(phase_features).unsqueeze(0) # [1, T, r]
interaction = torch.tanh(content + phase_proj) # [B, T, r]
# dW_out ∝ (err_col^T @ interaction) / N
err_col_osc = F.linear(error.float(), col.L4.proj.weight.float())
err_col_osc_flat = err_col_osc.reshape(N, D_col)
inter_flat = interaction.reshape(N, r)
dW_out_osc = (err_col_osc_flat.T @ inter_flat) / N # [D_col, r]
osc.W_out.weight.data -= osc_lr * dW_out_osc.to(osc.W_out.weight.dtype)
# W_out norm guard
w_norm = osc.W_out.weight.data.norm()
if w_norm > 3.0:
osc.W_out.weight.data *= 3.0 / w_norm
# ── Interneuron Weights ────────────────────────────────────
inter = col.interneurons
inter_lr = lr * 0.05 # Very slow for inhibitory stability
# Per-token error magnitude (shared across interneuron updates)
err_mag_tok = error.float().norm(dim=-1, keepdim=True) # [B, T, 1]
# VIP: Learn to detect novelty → disinhibit when error is high
if inter.vip_enabled:
# VIP reads input, should fire more when prediction error is high
h_norm_vip = inter.vip_norm(out.l23_input.float())
h_flat_vip = h_norm_vip.reshape(N, D_col)
vip_act = F.gelu(inter.vip_in(h_flat_vip)) # [N, d_i]
# Error-modulated Hebbian: strengthen features that predict error
dW = (vip_act.T * err_mag_tok.reshape(N).unsqueeze(0)) @ h_flat_vip / N # [d_i, D_col]
inter.vip_in.weight.data += inter_lr * dW.to(inter.vip_in.weight.dtype)
# VIP gate: open more when error is high
inter.vip_gate_raw.data += inter_lr * 0.1 * min(error_mag, 5.0)
inter.vip_gate_raw.data.clamp_(max=2.0)
# SST: Learn better input suppression
if inter.sst_enabled:
# SST should strengthen when error is LOW (good inhibition)
h_norm_sst = inter.sst_norm(out.state.float()).reshape(N, D_col)
neg_err = 1.0 / (1.0 + err_mag_tok.reshape(N, 1)) # Low error → high
sst_act = F.gelu(inter.sst_in(h_norm_sst)) # [N, d_i]
dW_sst = ((sst_act * neg_err).T @ h_norm_sst) / N # [d_i, D_col]
inter.sst_in.weight.data += inter_lr * dW_sst.to(inter.sst_in.weight.dtype)
# PV: Learn veto threshold (stronger veto when output leads to error)
if inter.pv_enabled:
h_norm_pv = inter.pv_norm(out.state.float()).reshape(N, D_col)
pv_act = F.gelu(inter.pv_in(h_norm_pv))
err_weighted_pv = pv_act * err_mag_tok.reshape(N, 1)
dW_pv = (err_weighted_pv.T @ h_norm_pv) / N
inter.pv_in.weight.data += inter_lr * dW_pv.to(inter.pv_in.weight.dtype)
# ── L5 Dendritic Gate Adaptation ───────────────────────────
# W_dend.bias: threshold for dendritic gating
# High error → lower bias → more selective gating
if col.L5.dendritic:
dend_lr = lr * 0.01
# Adaptive threshold: tighten when error is high, relax when low
bias_delta = -min(error_mag, 5.0) * 0.1 + 0.05 # Net relaxation if error < 0.5
col.L5.W_dend.bias.data += dend_lr * bias_delta
col.L5.W_dend.bias.data.clamp_(-3.0, 8.0)
# W_sigma_adapt: learn σ²→dendritic correlation
sigma_err = out.sigma2.float().mean().item() * error_mag
col.L5.W_sigma_adapt.weight.data += dend_lr * sigma_err * 0.01
# ═══════════════════════════════════════════════════════════════════════
# Neuromodulated Plasticity
# ═══════════════════════════════════════════════════════════════════════
class NeuromodulatedPlasticity:
"""
Theorem C: All learning gated by neuromodulators.
Plasticity = DA × ACh × f(NE, 5-HT)
DA: gates WHETHER to learn (reward prediction error)
ACh: gates WHAT to learn (attentional selection)
NE: modulates HOW BROADLY to learn (exploration vs exploitation)
5-HT: modulates TIMESCALE (short vs long horizon)
This multiplier is applied to both PC and Hebbian updates.
"""
def __init__(self, cfg: V11Config):
self.cfg = cfg
def compute_plasticity(self, neuromod: NeuromodState) -> torch.Tensor:
"""
Compute plasticity multiplier from neuromodulatory state.
Returns: [B, T, 1] plasticity gate ∈ [0, 1]
"""
# Core plasticity: DA × ACh
plasticity = neuromod.dopamine * neuromod.acetylcholine
# NE modulates breadth (high NE → broader learning)
ne_factor = 0.5 + 0.5 * neuromod.norepinephrine
# 5-HT modulates timescale (high 5-HT → longer credit assignment)
serotonin_factor = 0.5 + 0.5 * neuromod.serotonin
return plasticity * ne_factor * serotonin_factor
# ═══════════════════════════════════════════════════════════════════════
# Wake-Sleep Scheduler
# ═══════════════════════════════════════════════════════════════════════
class WakeSleepScheduler:
"""
Theorem D: Autonomous wake-sleep cycle.
WAKE phase (online):
- Process input through columns
- Predictive coding: local weight updates
- Hebbian: L2/3 self-organization
- Hippocampus: tag surprising events
SLEEP phase (offline self-improvement):
- Replay high-surprise memories from hippocampus
- Synaptic downscaling (Tononi 2006): global renormalization
- Memory consolidation: strengthen replayed patterns
- Pruning: remove weak connections
The cycle runs autonomously: no human triggers.
"""
def __init__(self, cfg: V11Config):
self.cfg = cfg
self.wake_steps = 0
self.sleep_phases = 0
self.total_steps = 0
def should_sleep(self) -> bool:
"""Check if it's time for a sleep phase."""
if not self.cfg.wake_sleep_enabled:
return False
return self.wake_steps >= self.cfg.sleep_interval
def on_wake_step(self):
"""Called after each wake step."""
self.wake_steps += 1
self.total_steps += 1
def on_sleep_start(self):
"""Called when sleep phase begins."""
self.wake_steps = 0
self.sleep_phases += 1
# Parameters to protect from synaptic downscaling (they're "state" not "weights")
_DOWNSCALE_EXCLUDE = (
'gate_raw', # Gate set points
'bias', # Bias set points
'sigma2', # Precision parameters
'decay_bias', # Memory decay constants (HPC, NMDA)
'decay', # Decay parameters (phonological loop)
'period_', # Oscillatory period parameters
'kappa', # PAC coupling strengths
'ec50', # Receptor thresholds (BG D1/D2)
'slope', # Receptor steepness (BG D1/D2)
'facil_', # Facilitation parameters (silent trace)
'depress_', # Depression parameters (silent trace)
'theta_bcm', # BCM threshold (buffer, but protect if iterated)
'tonic_da', # Tonic DA EMA (buffer)
)
@torch.no_grad()
def synaptic_downscaling(self, model: nn.Module, strength: float = 1.0):
"""
Tononi's Synaptic Homeostasis Hypothesis (2006):
During sleep, all synaptic weights are multiplicatively downscaled.
Purpose: Prevents weight explosion from continuous Hebbian learning.
Preserves relative weight magnitudes (signal-to-noise).
Frees capacity for new learning in the next wake cycle.
Protected: gates, biases, precision, decay/period/receptor params.
Args:
strength: 1.0 = full sleep downscale. <1.0 = partial (micro-downscale
during wake for continuous homeostasis).
"""
# Effective scale: lerp between 1.0 (no change) and cfg value
scale = 1.0 - strength * (1.0 - self.cfg.synaptic_downscale)
for name, param in model.named_parameters():
# Skip protected parameters
if any(excl in name for excl in self._DOWNSCALE_EXCLUDE):
continue
# Downscale weights
if param.data.abs().max() > 1e-8:
param.data.mul_(scale)
def get_status(self) -> dict:
"""Return scheduler status for logging."""
return {
'wake_steps': self.wake_steps,
'sleep_phases': self.sleep_phases,
'total_steps': self.total_steps,
'next_sleep_in': max(0, self.cfg.sleep_interval - self.wake_steps),
}
# ═══════════════════════════════════════════════════════════════════════
# Developmental Program (Critical Periods)
# ═══════════════════════════════════════════════════════════════════════
class DevelopmentalProgram:
"""
The brain changes HOW it learns over time. This is not just "learning" —
it's learning to learn differently at different developmental stages.
Neuroscience:
- Hensch (2004): Critical periods are opened by inhibitory maturation
- Petanjek (2011): Prefrontal pruning continues until age 25
- Huttenlocher (1979): Synapse density peaks at age 2, halves by adulthood
- Takesian & Hensch (2013): GABA maturation triggers critical period onset
Disease mapping:
Amblyopia → missed visual critical period → permanent deficit
Language deprivation → missed language CP → impaired grammar acquisition
Fragile X → abnormal metaplasticity → no proper CP regulation
Stages (mapped to training steps):
1. SENSORY (0-1K steps): High learning rate, low inhibition, open to all input.
Like infant brain — rapidly absorbing everything. Hebbian dominance.
2. ASSOCIATION (1K-5K): Moderate LR, inhibitory maturation, lateral connections
strengthen. Like childhood — forming categorical boundaries.
3. INTEGRATION (5K-20K): Lower LR, strong inhibition, top-down predictions
dominate. Like adolescence — predictive model crystallizing.
4. REFINEMENT (20K+): Low LR, structural plasticity slows, sleep consolidation
becomes primary learning mechanism. Like adulthood — fine-tuning.
Each stage modulates: learning rate, inhibitory strength, sleep frequency,
structural plasticity rate, Hebbian vs PC balance.
Zero learnable params — purely algorithmic staging.
"""
def __init__(self, cfg: V11Config):
self.cfg = cfg
self.stage_boundaries = [0, 1000, 5000, 20000] # Step thresholds
self.stage_names = ['sensory', 'association', 'integration', 'refinement']
self._current_step = 0
# Store original sleep interval — cfg.sleep_interval gets mutated
self._base_sleep_interval = cfg.sleep_interval
@property
def current_stage(self) -> str:
for i in range(len(self.stage_boundaries) - 1, -1, -1):
if self._current_step >= self.stage_boundaries[i]:
return self.stage_names[min(i, len(self.stage_names) - 1)]
return self.stage_names[0]
@property
def stage_index(self) -> int:
for i in range(len(self.stage_boundaries) - 1, -1, -1):
if self._current_step >= self.stage_boundaries[i]:
return min(i, len(self.stage_names) - 1)
return 0
def step(self):
"""Advance developmental clock."""
self._current_step += 1
def get_lr_multiplier(self) -> float:
"""Learning rate multiplier based on developmental stage."""
# Sensory: 2x, Association: 1.5x, Integration: 1x, Refinement: 0.5x
multipliers = [2.0, 1.5, 1.0, 0.5]
return multipliers[self.stage_index]
def get_inhibitory_strength(self) -> float:
"""Inhibitory interneuron strength based on maturation.
Low early (everything gets through) → high late (strong filtering).
Hensch (2004): inhibitory maturation triggers critical period closure."""
strengths = [0.3, 0.6, 0.9, 1.0]
return strengths[self.stage_index]
def get_hebbian_weight(self) -> float:
"""Balance between Hebbian (blind) and error-driven (PC) learning.
Early: Hebbian dominates (learn correlations).
Late: Error-driven dominates (refine predictions)."""
weights = [0.8, 0.6, 0.4, 0.3]
return weights[self.stage_index]
def get_structural_plasticity_rate(self) -> float:
"""Structural plasticity rate. High early (rapid wiring), low late (stable).
Huttenlocher 1979: synapse density peaks at age 2."""
rates = [1.0, 0.7, 0.3, 0.1]
return rates[self.stage_index]
def get_sleep_interval(self) -> int:
"""Sleep frequency. Less frequent early (more wake learning), more frequent late
(consolidation becomes primary mechanism).
Uses ORIGINAL sleep interval as base (not the mutated cfg value)."""
base = self._base_sleep_interval
multipliers = [2.0, 1.5, 1.0, 0.7]
return max(10, int(base * multipliers[self.stage_index]))
def get_metrics(self) -> dict:
return {
'dev_stage': self.current_stage,
'dev_step': self._current_step,
'dev_lr_mult': self.get_lr_multiplier(),
'dev_inhib': self.get_inhibitory_strength(),
'dev_hebbian_weight': self.get_hebbian_weight(),
}
# ═══════════════════════════════════════════════════════════════════════
# Integrated Learning Manager
# ═══════════════════════════════════════════════════════════════════════
class V11LearningManager:
"""
Manages all learning in V11: PC + Hebbian + Neuromod + Wake-Sleep + Development.
This is the "brain's learning system" — coordinates all plasticity.
"""
def __init__(self, cfg: V11Config):
self.cfg = cfg
self.pc_optimizer = PredictiveCodingOptimizer(cfg)
self.hebbian_optimizer = HebbianOptimizer(cfg)
self.neuromod_plasticity = NeuromodulatedPlasticity(cfg)
self.wake_sleep = WakeSleepScheduler(cfg)
self.development = DevelopmentalProgram(cfg)
def wake_step(
self,
columns: nn.ModuleList,
column_outputs: List[ColumnOutput],
predictions: List[torch.Tensor],
targets: List[torch.Tensor],
precisions: List[torch.Tensor],
neuromod: NeuromodState,
errors: Optional[List[torch.Tensor]] = None,
ewc_guard=None,
) -> Dict[str, float]:
"""
Complete wake-phase learning step.
1. Compute neuromodulatory plasticity gate
2. Predictive coding updates (vertical connections)
3. Hebbian updates (lateral connections in L2/3) — error-driven + σ²-adaptive
4. Track wake step count
Returns: dict of learning metrics
"""
metrics = {}
# 0. Developmental modulation (critical periods)
dev_lr_mult = self.development.get_lr_multiplier()
dev_hebbian_w = self.development.get_hebbian_weight()
dev_inhib = self.development.get_inhibitory_strength()
dev_struct_rate = self.development.get_structural_plasticity_rate()
self.development.step()
metrics.update(self.development.get_metrics())
# 1. Neuromodulatory plasticity gate (modulated by developmental stage)
plasticity_gate = self.neuromod_plasticity.compute_plasticity(neuromod)
plasticity_gate = plasticity_gate * dev_lr_mult # Developmental LR modulation
metrics['plasticity_mean'] = plasticity_gate.mean().item()
# Apply developmental inhibitory maturation to interneurons
# Hensch (2004): inhibitory maturation triggers critical period closure
for col in columns:
if hasattr(col.interneurons, 'sst_tonic'):
# Scale SST tonic inhibition by developmental stage
col.interneurons.sst_tonic = 0.10 * dev_inhib / 1.0 # max 0.10 at full maturity
# 2. Predictive coding update
# PC local_update uses analytical gradients (no autograd). Since hybrid mode
# also uses analytical local output correction (no backprop), there's no
# conflict — both can fire. σ² evolution depends on PC updates.
if self.cfg.learning_mode in ('predictive_coding', 'hybrid'):
_, pc_loss = self.pc_optimizer.compute_column_losses(
predictions, targets, precisions
)
metrics['pc_loss'] = pc_loss.item()
# Analytical PC update: updates W_predict and W_sigma per column
self.pc_optimizer.local_update(
columns, predictions, targets, precisions, plasticity_gate
)
# 3. Hebbian update — error-driven + σ²-adaptive + BCM + metaplasticity
# dev_hebbian_w modulates Hebbian strength: high early (correlation), low late (error-driven)
if self.cfg.learning_mode in ('hebbian', 'hybrid'):
# Scale Hebbian LR by developmental Hebbian weight
orig_lr = self.hebbian_optimizer.lr
self.hebbian_optimizer.lr = orig_lr * dev_hebbian_w
self.hebbian_optimizer.update(
columns, column_outputs, plasticity_gate, errors=errors,
)
self.hebbian_optimizer.lr = orig_lr # Restore
metrics['hebbian_updated'] = True
# 3b. Local parameter updates for L1, L6, oscillations, interneurons, dendrites
# These parameters were previously "dead" — never updated by any learning rule.
# Now they learn via biologically-grounded local rules (zero autograd).
if self.cfg.learning_mode in ('hebbian', 'hybrid'):
orig_lr = self.hebbian_optimizer.lr
self.hebbian_optimizer.lr = orig_lr * dev_hebbian_w
self.hebbian_optimizer.update_local_params(
columns, column_outputs, errors=errors,
plasticity_gate=plasticity_gate,
)
self.hebbian_optimizer.lr = orig_lr
metrics['local_params_updated'] = True
# 4. Structural plasticity (Theorem E) — prune/grow at interval
# Modulated by developmental stage: high early (rapid wiring), low late (stable)
if self.cfg.structural_plasticity:
step = self.wake_sleep.wake_steps
if step > 0 and step % self.cfg.prune_interval == 0:
mean_err = 0.0
if errors:
mean_err = sum(e.abs().mean().item() for e in errors) / len(errors)
# Scale growth threshold inversely by dev rate (lower threshold = more growth in early stages)
effective_growth_thresh = self.cfg.growth_threshold / max(dev_struct_rate, 0.01)
for col in columns:
col.L23.structural_plasticity_step(
error_magnitude=mean_err,
prune_threshold=self.cfg.prune_threshold,
growth_threshold=effective_growth_thresh,
prune_interval=self.cfg.prune_interval,
)
metrics['structural_plasticity'] = True
metrics['density_col0'] = columns[0].L23.get_connection_density()
# 4b. Hebbian weight norm guard — prevent W_assoc explosion
# BCM handles the learning dynamics, but if for any reason weights
# grow beyond a safe norm, hard-clip them. This is the neural equivalent
# of synaptic saturation — there's a physical limit to synaptic strength.
HEBBIAN_MAX_NORM = 10.0
for i, col in enumerate(columns):
w_norm = col.L23.W_assoc.data.norm()
if w_norm > HEBBIAN_MAX_NORM:
col.L23.W_assoc.data.mul_(HEBBIAN_MAX_NORM / w_norm)
metrics[f'hebb_clipped_col{i}'] = True
# Also guard W_lateral
if hasattr(col.L23, 'W_lateral'):
wl_norm = col.L23.W_lateral.data.norm()
if wl_norm > HEBBIAN_MAX_NORM:
col.L23.W_lateral.data.mul_(HEBBIAN_MAX_NORM / wl_norm)
# 4c. EWC elastic pull — protect consolidated knowledge (Kirkpatrick 2017)
# After Hebbian/PC updates move weights, pull important params back toward anchors.
# Δθ_i -= λ × F_i × (θ_i - θ*_i) applied directly to parameters.
if ewc_guard is not None and ewc_guard._initialized:
ewc_lr = 1e-4 # Elastic pull strength
ewc_applied = 0
for name, param in columns.named_parameters() if hasattr(columns, 'named_parameters') else []:
full_name = name
if full_name in ewc_guard.importance and full_name in ewc_guard.anchor_params:
anchor = ewc_guard.anchor_params[full_name].to(param.device)
importance = ewc_guard.importance[full_name].to(param.device)
param.data -= ewc_lr * importance * (param.data - anchor)
ewc_applied += 1
if ewc_applied > 0:
metrics['ewc_params_constrained'] = ewc_applied
# 5. Micro-downscaling during wake (continuous homeostasis)
# The brain doesn't wait for sleep to regulate weights — continuous
# synaptic scaling operates alongside learning (Turrigiano 2008).
# Strength = 0.1 → 10% of full sleep downscale per wake step.
# This prevents Hebbian weight explosion between sleep phases.
if self.wake_sleep.wake_steps % 10 == 0: # Every 10 steps
import itertools
for col in columns:
for p in col.L23.parameters():
name = '' # L23 weights are always eligible
if p.data.abs().max() > 1e-8:
p.data.mul_(1.0 - 0.05 * (1.0 - self.cfg.synaptic_downscale))
# 6. σ² emergency guard — prevent precision divergence
# If σ² diverges, all PC learning breaks. Guard early.
for i, col in enumerate(columns):
sigma2_max = col.L5.W_sigma.bias.data.abs().max().item()
if sigma2_max > 20.0: # Emergency: σ² output logit too large
col.L5.W_sigma.bias.data.mul_(0.9) # Gently pull back
col.L5.W_sigma.weight.data.mul_(0.9)
metrics[f'sigma2_emergency_col{i}'] = True
# 7. Adjust sleep interval based on developmental stage
# Less sleep early (more wake learning), more sleep late (consolidation primary)
dev_sleep_interval = self.development.get_sleep_interval()
if dev_sleep_interval != self.cfg.sleep_interval:
self.wake_sleep.cfg.sleep_interval = dev_sleep_interval
metrics['dev_sleep_interval'] = dev_sleep_interval
# 8. Track wake step
self.wake_sleep.on_wake_step()
metrics['wake_step'] = self.wake_sleep.wake_steps
return metrics
def should_sleep(self) -> bool:
"""Check if sleep phase is due."""
return self.wake_sleep.should_sleep()
def sleep_phase(
self,
model: nn.Module,
hippocampus,
columns: nn.ModuleList,
device: torch.device,
) -> Dict[str, float]:
"""
Complete 3-phase sleep: replay → contrastive consolidation → downscaling.
Phase 1 — Generative replay: Run memories through columns, compute PC loss.
Goal: cortex learns to predict WITHOUT hippocampus.
Phase 2 — Contrastive consolidation: Real memory = potentiate,
corrupted memory = depress. Sharpens representations.
Phase 3 — Synaptic downscaling (Tononi 2006): global renormalization.
"""
metrics = {}
self.wake_sleep.on_sleep_start()
# Entire sleep phase runs under no_grad — all learning is analytical
# (PC local_update, hebbian_update, anti_hebbian_update all use .data).
# Column forwards during replay/consolidation don't need gradient tracking.
with torch.no_grad():
return self._sleep_phase_impl(model, hippocampus, columns, device, metrics)
def _sleep_phase_impl(self, model, hippocampus, columns, device, metrics):
"""Sleep implementation (always called under torch.no_grad)."""
# Replay from hippocampal memory
memories = hippocampus.replay(self.cfg.sleep_replay_steps, device)
metrics['replayed_memories'] = len(memories)
if len(memories) > 0:
replay_lr = self.cfg.hebbian_lr * 0.5 # Lower LR during sleep
pc_replay_lr = self.cfg.pc_learning_lr * 0.3 # Even lower for PC replay
# ── Phase 1: Generative replay with PC learning ────────────
# The brain consolidates by making cortex predict WITHOUT hippocampus.
# We replay memories through columns, compute PC prediction errors,
# and update prediction weights. This is TRUE consolidation:
# hippocampal memories → cortical predictions.
for mem in memories:
x = mem['x'] # [1, T, D] — batch-pooled at storage
error = mem.get('error', torch.zeros_like(x))
# Run memory through columns (generative replay)
h = x
replay_predictions = []
replay_outputs = []
for col in columns:
out = col(ff_input=h, td_context=None)
replay_predictions.append(out.prediction)
replay_outputs.append(out)
h = out.output
# PC learning on replayed memories — consolidation = cortex
# learns to predict without hippocampus
replay_targets = [x.detach()] + [
replay_outputs[l].output.detach()
for l in range(len(replay_outputs) - 1)
]
replay_precisions = [out.sigma2 for out in replay_outputs]
# Analytical PC update on replay (no autograd)
self.pc_optimizer.local_update(
columns, replay_predictions, replay_targets,
replay_precisions
)
# Hebbian consolidation (L2/3 associations)
for col in columns:
if col.bcm.enabled:
col.L23.hebbian_update_error_modulated(
pre_input=x, post_output=x,
error=error,
bcm_theta=col.bcm.theta_bcm,
lr=replay_lr,
error_weight=self.cfg.error_hebbian_weight,
)
else:
col.L23.hebbian_update(x, lr=replay_lr)
# ── Phase 2: Contrastive consolidation ────────────────────
# Real pattern → potentiate. Corrupted pattern → depress.
# This sharpens representations by creating contrastive signal.
noise_scale = self.cfg.sleep_contrastive_noise
contrastive_lr = replay_lr * 0.3 # Even gentler for contrastive
for mem in memories:
x = mem['x'] # [1, T, D] — batch-pooled at storage — real memory
# Generate corrupted version (negative)
noise = torch.randn_like(x) * noise_scale
x_corrupted = x + noise
for col in columns:
# Anti-Hebbian on corrupted: weakens noisy correlations
col.L23.anti_hebbian_update(x_corrupted, lr=contrastive_lr)
# Extra Hebbian on real: strengthens true correlations
if col.bcm.enabled:
col.L23.hebbian_update_bcm(
pre_input=x, post_output=x,
bcm_theta=col.bcm.theta_bcm,
lr=contrastive_lr,
)
metrics['replay_consolidated'] = True
metrics['contrastive_applied'] = True
# ── Phase 2.5: Hippocampal → Cortical consolidation (McClelland 1995) ──
# Extract semantic centroids from clustered episodes, then train cortex
# on these distilled patterns. This is the CLS transfer: hippocampus →
# neocortex, converting episodic → semantic memory during SWS.
semantic_memories = hippocampus.consolidate()
metrics['semantic_memories_extracted'] = len(semantic_memories)
if len(semantic_memories) > 0:
consolidation_lr = self.cfg.hebbian_lr * 0.3
for sem in semantic_memories:
pattern = sem['pattern'] # [D]
# Expand to [1, 1, D] for column processing
x = pattern.unsqueeze(0).unsqueeze(0).to(device)
# Run through columns — Hebbian learning on semantic patterns
h = x
for col in columns:
out = col(ff_input=h, td_context=None)
# Hebbian: strengthen cortical representation of semantic pattern
if col.bcm.enabled:
col.L23.hebbian_update_bcm(
pre_input=h, post_output=out.output,
bcm_theta=col.bcm.theta_bcm,
lr=consolidation_lr,
)
else:
col.L23.hebbian_update(h, out.output, lr=consolidation_lr)
h = out.output
metrics['semantic_consolidation_applied'] = True
# ── Phase 3: Synaptic downscaling (Tononi 2006) ──────────────
self.wake_sleep.synaptic_downscaling(model)
metrics['downscaled'] = True
# Update sleep count
metrics['sleep_phase'] = self.wake_sleep.sleep_phases
return metrics
def get_status(self) -> dict:
"""Complete learning system status."""
return self.wake_sleep.get_status()