Subcortical Systems
Source: nct_v2/v11_systems.py Lines: 938 Classes: 9
Neuroscience Foundation
The neocortex does not operate in isolation. Every cortical area has reciprocal connections with subcortical structures that provide routing, memory consolidation, reward computation, temporal prediction, and global state regulation. In the human brain, these subcortical structures contain only 15% of all neurons but are essential for cognition, damage to any single structure produces a specific neurological syndrome.
NCT implements seven subcortical systems, each validated by its disease-mapping: removing the module produces a computational deficit analogous to the corresponding neurological disorder.
Thalamus + TRN
The thalamus is the brain’s routing hub, virtually all sensory information passes through it before reaching cortex. NCT implements relay groups (default for 12 columns), each shared by 3 adjacent columns.
Theorem 15 (Thalamic Relay with TRN Gating). Each relay group computes a gated residual: where , , and L6 feedback modulates the relay: .
Definition 4 (Thalamic Reticular Nucleus (TRN)). The TRN implements low-rank gating (): A bimodality loss encourages binary (open/closed) routing decisions: This loss is minimized when (gate closed) or (gate open), driving the thalamus toward discrete routing decisions rather than continuous mixing.

Hippocampus
The hippocampus is the brain’s episodic memory system, essential for forming new memories and consolidating them into long-term cortical storage. Patient HM, who had bilateral hippocampal removal, could not form new declarative memories, demonstrating the hippocampus’s critical role.
Theorem 16 (Hippocampal Trisynaptic Circuit). NCT’s hippocampus implements the three-stage circuit:
1. Dentate Gyrus (DG), Pattern Separation: The expansion ratio with ReLU produces sparse, orthogonal representations that minimize interference between stored memories.
2. CA3, Autoassociative Pattern Completion: Given a partial cue, CA3 retrieves the full stored pattern via associative recall.
3. CA1, Output to Cortex:
Definition 5 (Surprise Tagging for Replay). During training, episodes are tagged for sleep replay when the prediction error exceeds the surprise threshold: Tagged episodes are stored in a circular buffer (max 2,048 memories) with exponential decay: . During sleep, high-surprise episodes are preferentially replayed, strengthening the cortical representations of unexpected events.
Basal Ganglia
The basal ganglia implement reward-modulated action selection through two competing pathways with pharmacologically distinct dopamine receptor types.
Theorem 17 (D1/D2 Inverted-U Dopamine Response). The direct (D1/Go) and indirect (D2/NoGo) pathways have different dopamine sensitivities: The output is the competition between pathways:
At moderate DA (0.5), both pathways are partially active, balanced selection. At high DA (0.65), D1 dominates, impulsive, Go-biased (mania analog). At low DA (0.25), D2 dominates, conservative, NoGo-biased (Parkinson’s analog). The inverted-U emerges naturally from the different EC50 values.
Cerebellum
Theorem 18 (Cerebellar Forward Model). The cerebellum learns to predict the next hidden state: Prediction error provides an auxiliary training signal: This enables the system to anticipate upcoming processing demands and pre-activate relevant representations.
Brainstem: Neuromodulation (Theorem C)
Theorem 19 (Four Neuromodulatory Systems). The brainstem computes four global modulatory signals from the top column’s output: These multiplicatively gate all local learning (Theorem C): Tonic DA is tracked as an EMA () for baseline subtraction, implementing the difference between phasic (event-related) and tonic (background) dopamine signaling.
| System | Signal | Computational Role | Disease if Disrupted |
|---|---|---|---|
| Dopamine (DA) | Reward prediction error | Policy gradient, Go/NoGo | Parkinson’s (low), mania (high) |
| Norepinephrine (NE) | Arousal level | Exploration noise, gain control | ADHD (dysregulated) |
| Serotonin (5-HT) | Time horizon | Discount factor, patience | Depression (low) |
| Acetylcholine (ACh) | Attentional state | Plasticity gate (learn or not) | Alzheimer’s (low) |
Global Workspace (Baars 1988)
Theorem 20 (Surprise-Weighted Broadcast). Following Global Workspace Theory (Baars 1988, Dehaene & Naccache 2001), columns compete for broadcast access weighted by their prediction error (surprise): Each column reads the broadcast via its own projection: The broadcast is added to L1 top-down context on the next PC iteration, enabling cross-column coordination beyond local lateral connections. Bottleneck dimension: .
initialized at , no broadcast at initialization. The highest-surprise column “wins” access to the workspace, broadcasting its state to all other columns. This is the computational analog of conscious access: only information that is sufficiently surprising reaches global broadcast.
Self-Assessment (ACC Conflict Monitor)
Definition 6 (Metacognitive Conflict Detection). The anterior cingulate cortex (ACC) monitors for conflict between competing representations: High conflict triggers additional PC inference steps (up to extra, capped), implementing metacognitive “thinking harder when uncertain.” This is the computational basis for the feeling of effort during difficult cognitive tasks.
The Self-Assessment module also tracks model health: loss history, divergence detection ( best loss triggers rollback), and performance trends. This enables self-repair, a form of metacognitive monitoring absent in transformers.
Source Code
# ===========================================================================
# Subcortical Systems (Thalamus, HPC, BG, Cerebellum, Brainstem)
# Source: nct_v2/v11_systems.py
# ===========================================================================
"""
NCT V11: Subcortical Systems
==============================
The cortex doesn't operate alone. These subcortical systems provide:
- Thalamus: Routing, gating, synchronization between columns
- Hippocampus: Episodic memory, surprise tagging, sleep replay
- Basal Ganglia: DA-based reward learning, action selection
- Cerebellum: Temporal prediction, forward models
- Brainstem: NE/5-HT/ACh global state regulation
All systems interact with cortical columns via defined interfaces.
"""
# [bundled] from .v11_config import V11Config
# [bundled] from .v11_column import RMSNorm
# ═══════════════════════════════════════════════════════════════════════
# Neuromodulatory State
# ═══════════════════════════════════════════════════════════════════════
@dataclass
class NeuromodState:
"""Global neuromodulatory state broadcast to all columns."""
dopamine: torch.Tensor # [B, T, 1] — prediction error / reward
norepinephrine: torch.Tensor # [B, T, 1] — arousal / exploration
serotonin: torch.Tensor # [B, T, 1] — time horizon / patience
acetylcholine: torch.Tensor # [B, T, 1] — attention / plasticity gate
tonic_da: float # Scalar — slow DA average (exploration/exploitation)
# ═══════════════════════════════════════════════════════════════════════
# Thalamus (Routing Hub)
# ═══════════════════════════════════════════════════════════════════════
class ThalamicRelay(nn.Module):
"""
A single thalamic relay group.
Gates and routes information between columns.
Relay = W_out(gelu(W_in(x))) gated by reticular nucleus.
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.W_in = nn.Linear(cfg.d_model, cfg.d_relay, bias=False)
self.W_out = nn.Linear(cfg.d_relay, cfg.d_model, bias=False)
nn.init.zeros_(self.W_out.weight) # Identity at init
self.norm = RMSNorm(cfg.d_model)
self.gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
# forward() is not used — Thalamus.route() drives relays directly
# to support L6 feedback injection and TRN loss accumulation.
class ThalamicReticularNucleus(nn.Module):
"""
Thalamic Reticular Nucleus (TRN).
Thin shell around thalamus that gates relay neurons.
Computes relevance between pre-relay and post-relay signals.
TRN loss: bimodality loss r*(1-r) for binary decisions.
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.W_q = nn.Linear(cfg.d_model, cfg.d_trn, bias=False)
self.W_k = nn.Linear(cfg.d_model, cfg.d_trn, bias=False)
self.scale = cfg.d_trn ** -0.5
self.gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
def forward(self, x_pre: torch.Tensor, x_delta: torch.Tensor) -> torch.Tensor:
"""
x_pre: [B, T, D_model] — before relay
x_delta: [B, T, D_model] — relay output delta
Returns: [B, T, 1] — relevance gate (0=block, 1=pass)
"""
gate = torch.sigmoid(self.gate_raw)
q = self.W_q(x_pre) # [B, T, d_trn]
k = self.W_k(x_delta)
# Per-token relevance
relevance = torch.sigmoid(
(q * k).sum(dim=-1, keepdim=True) * self.scale
) # [B, T, 1]
# Lerp with gate: at init, relevance → 1 (pass everything)
return (1.0 - gate) * 1.0 + gate * relevance
# TRN bimodality loss is accumulated in Thalamus.route() → Thalamus.compute_loss().
class Thalamus(nn.Module):
"""
Complete thalamic system: relay groups + TRN.
Controls information flow between cortical columns.
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.cfg = cfg
self.enabled = cfg.thalamic_enabled
if not self.enabled:
return
self.n_groups = cfg.n_relay_groups
self.relays = nn.ModuleList([ThalamicRelay(cfg) for _ in range(self.n_groups)])
self.trn = ThalamicReticularNucleus(cfg)
# Accumulated TRN loss during forward pass
self._trn_loss_accum: List[torch.Tensor] = []
def reset_loss(self):
"""Reset TRN loss accumulator for a new forward pass."""
self._trn_loss_accum = []
def route(self, x: torch.Tensor, column_idx: int,
thal_feedback: Optional[torch.Tensor] = None) -> torch.Tensor:
"""
Route input through thalamic relay for a specific column.
x: [B, T, D_model] — input to be relayed
column_idx: which column is receiving
thal_feedback: [B, T, D_model] — L6 feedback from the column (modulates relay)
"""
if not self.enabled:
return x
group_idx = min(column_idx // self.cfg.columns_per_relay, self.n_groups - 1)
relay = self.relays[group_idx]
# Compute relay delta
relay_delta = relay.W_out(F.gelu(relay.W_in(relay.norm(x))))
# Modulate with L6 feedback (if available)
if thal_feedback is not None:
relay_delta = relay_delta + 0.1 * thal_feedback
# TRN gating
ret_gate = self.trn(x, relay_delta)
# Accumulate TRN bimodality loss: r*(1-r) encourages binary gating
trn_loss = (ret_gate * (1.0 - ret_gate)).mean()
self._trn_loss_accum.append(trn_loss)
# Apply gated relay
gate = torch.sigmoid(relay.gate_raw)
return x + gate * ret_gate * relay_delta
def compute_loss(self) -> torch.Tensor:
"""TRN bimodality loss accumulated during route() calls."""
if not self.enabled or len(self._trn_loss_accum) == 0:
return torch.tensor(0.0)
loss = sum(self._trn_loss_accum) / len(self._trn_loss_accum)
self._trn_loss_accum = [] # Reset for next forward pass
return loss
# ═══════════════════════════════════════════════════════════════════════
# Hippocampus (Episodic Memory + Replay)
# ═══════════════════════════════════════════════════════════════════════
class Hippocampus(nn.Module):
"""
Hippocampal system for episodic memory, surprise tagging, and sleep replay.
Components:
Dentate Gyrus (DG): Sparse expansion for pattern separation
CA3: Autoassociative memory for pattern completion
CA1: Output → cortex (relayed via subiculum)
Functions:
1. Encode: Tag high-surprise events during wake phase
2. Replay: Sample stored memories during sleep phase
3. Consolidate: Transfer episodic → semantic (cortical) memory
Theorem D: Wake-Sleep Cycle = Autonomous Self-Improvement
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.cfg = cfg
self.enabled = cfg.hpc_enabled
if not self.enabled:
return
d = cfg.d_model
d_sparse = cfg.hpc_d_sparse
# Dentate Gyrus: sparse expansion (pattern separation)
self.dg = nn.Linear(d, d_sparse, bias=False)
# CA3: autoassociative (pattern completion)
self.ca3_encode = nn.Linear(d_sparse, d, bias=False)
self.ca3_retrieve = nn.Linear(d, d_sparse, bias=False)
# CA1: output projection
self.ca1 = nn.Linear(d, d, bias=False)
nn.init.zeros_(self.ca1.weight)
# Write gate
self.write_gate = nn.Linear(d + 1, 1, bias=True) # +1 for sigma2
nn.init.constant_(self.write_gate.bias, 1.0) # Start open (σ(1)≈0.73), learn to be selective
# Decay (ultra-slow)
self.decay_bias = nn.Parameter(torch.tensor(cfg.hpc_decay_init))
# Normalization
self.norm = RMSNorm(d)
self.gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
# Episodic memory buffer (not a parameter, managed manually)
self._memory_buffer: List[Dict[str, torch.Tensor]] = []
self._surprise_buffer: List[float] = []
def forward(self, x: torch.Tensor, sigma2: torch.Tensor) -> torch.Tensor:
"""
Forward pass: DG → CA3 encode → CA3 retrieve (pattern completion) → CA1.
x: [B, T, D_model] — current representation
sigma2: [B, T, 1] — precision (used for write gating)
Returns: [B, T, D_model] — x with hippocampal contribution
"""
if not self.enabled:
return x
gate = torch.sigmoid(self.gate_raw)
h = self.norm(x)
# Sparse encoding via Dentate Gyrus (pattern separation)
sparse = F.relu(self.dg(h)) # [B, T, d_sparse]
# CA3 encode: sparse → dense
encoded = self.ca3_encode(sparse) # [B, T, D]
# CA3 retrieve: dense → sparse (pattern completion loop)
# Apply decay to retrieval (decay_bias controls memory persistence)
decay = torch.sigmoid(self.decay_bias) # Ultra-slow decay
retrieved_sparse = F.relu(self.ca3_retrieve(encoded)) * decay # [B, T, d_sparse]
# Re-encode completed pattern
completed = self.ca3_encode(retrieved_sparse) # [B, T, D]
# Output via CA1 (uses completed pattern, not raw encoding)
hpc_out = self.ca1(completed)
return x + gate * hpc_out
@torch.no_grad()
def encode_episode(self, x: torch.Tensor, prediction_error: torch.Tensor,
sigma2: torch.Tensor):
"""
Tag and store surprising events during wake phase.
Write-gated: adaptive write gate modulates storage probability.
x: [B, T, D_model] — representations to remember
prediction_error: [B, T, D_model] — prediction errors
sigma2: [B, T, 1] — precision
"""
if not self.enabled:
return
# Surprise = precision-weighted prediction error magnitude
surprise = (prediction_error.pow(2) / (sigma2 + 1e-6)).mean(dim=-1) # [B, T]
mean_surprise = surprise.mean().item()
# Adaptive write gate: σ²-modulated storage probability
write_input = torch.cat([x.mean(dim=1), sigma2.mean(dim=1)], dim=-1) # [B, D+1]
write_prob = torch.sigmoid(self.write_gate(write_input)).mean().item() # scalar
# Only store if surprising enough AND write gate permits
if mean_surprise * write_prob > self.cfg.hpc_surprise_threshold:
# Mean-pool over batch dim → [1, T, D] so memories are batch-size-agnostic.
# Prevents shape mismatches when batch size changes between
# encode (wake) and replay (sleep/dream/eval).
self._memory_buffer.append({
'x': x.detach().mean(dim=0, keepdim=True).cpu(),
'error': prediction_error.detach().mean(dim=0, keepdim=True).cpu(),
'sigma2': sigma2.detach().mean(dim=0, keepdim=True).cpu(),
})
self._surprise_buffer.append(mean_surprise)
# Evict oldest if buffer full
if len(self._memory_buffer) > self.cfg.hpc_memory_size:
self._memory_buffer.pop(0)
self._surprise_buffer.pop(0)
def replay(self, n_samples: int, device: torch.device) -> List[Dict[str, torch.Tensor]]:
"""
Sample from episodic memory for sleep replay.
Priority sampling: higher surprise → more likely replayed.
Returns: List of (x, error, sigma2) tuples on the specified device.
"""
if not self.enabled or len(self._memory_buffer) == 0:
return []
n_samples = min(n_samples, len(self._memory_buffer))
if self.cfg.replay_priority == 'surprise':
# Priority sampling by surprise
surprises = torch.tensor(self._surprise_buffer)
probs = F.softmax(surprises, dim=0)
indices = torch.multinomial(probs, n_samples, replacement=True)
elif self.cfg.replay_priority == 'recency':
# Recency bias
weights = torch.arange(len(self._memory_buffer), dtype=torch.float)
probs = F.softmax(weights, dim=0)
indices = torch.multinomial(probs, n_samples, replacement=True)
else:
# Uniform
indices = torch.randint(0, len(self._memory_buffer), (n_samples,))
results = []
for idx in indices:
mem = self._memory_buffer[idx.item()]
results.append({
'x': mem['x'].to(device),
'error': mem['error'].to(device),
'sigma2': mem['sigma2'].to(device),
})
return results
def clear_memory(self):
"""Clear episodic buffer (e.g., after consolidation)."""
self._memory_buffer.clear()
self._surprise_buffer.clear()
@torch.no_grad()
def consolidate(self, n_clusters: int = 8, min_cluster: int = 3) -> List[Dict[str, torch.Tensor]]:
"""
Episodic → Semantic consolidation (McClelland et al. 1995).
Complementary Learning Systems theory: hippocampus stores episodes fast,
cortex learns slowly from patterns across episodes. Consolidation extracts
the pattern (centroid) from clusters of similar memories, returns centroids
for cortical training, then removes the consolidated episodes.
This is what happens during deep sleep (SWS stage 3-4).
Returns: list of centroid patterns (semantic memories) for cortical training.
"""
if not self.enabled or len(self._memory_buffer) < n_clusters:
return []
# Stack all memories
all_x = torch.stack([m['x'].mean(dim=(0, 1)) for m in self._memory_buffer]) # [N, D]
# Simple k-means clustering (no sklearn dependency)
N, D = all_x.shape
k = min(n_clusters, N // min_cluster)
if k < 2:
return []
# Initialize centroids via k-means++
centroids = [all_x[torch.randint(N, (1,)).item()]]
for _ in range(k - 1):
dists = torch.stack([((all_x - c.unsqueeze(0)).pow(2)).sum(-1) for c in centroids])
min_dists = dists.min(dim=0).values
probs = min_dists / (min_dists.sum() + 1e-8)
idx = torch.multinomial(probs, 1).item()
centroids.append(all_x[idx])
centroids = torch.stack(centroids) # [k, D]
# Run k-means iterations
for _ in range(10):
# Assign
dists = torch.cdist(all_x, centroids) # [N, k]
assignments = dists.argmin(dim=-1) # [N]
# Update
new_centroids = torch.zeros_like(centroids)
for c in range(k):
members = all_x[assignments == c]
if len(members) > 0:
new_centroids[c] = members.mean(dim=0)
else:
new_centroids[c] = centroids[c]
centroids = new_centroids
# Extract centroids from clusters with enough members
semantic_memories = []
consolidated_indices = set()
for c in range(k):
member_mask = assignments == c
n_members = member_mask.sum().item()
if n_members >= min_cluster:
# This cluster is stable enough to extract a pattern
centroid = centroids[c]
# Store as a "semantic memory" (pattern without episode details)
device = self._memory_buffer[0]['x'].device if self._memory_buffer else 'cpu'
semantic_memories.append({
'pattern': centroid,
'n_episodes': n_members,
'mean_surprise': sum(
self._surprise_buffer[i] for i in range(N) if member_mask[i]
) / max(n_members, 1),
})
# Mark episodes for removal
for i in range(N):
if member_mask[i]:
consolidated_indices.add(i)
# Remove consolidated episodes (keep unconsolidated ones)
new_buffer = []
new_surprise = []
for i in range(len(self._memory_buffer)):
if i not in consolidated_indices:
new_buffer.append(self._memory_buffer[i])
new_surprise.append(self._surprise_buffer[i])
self._memory_buffer = new_buffer
self._surprise_buffer = new_surprise
return semantic_memories
@property
def memory_size(self) -> int:
return len(self._memory_buffer)
# ═══════════════════════════════════════════════════════════════════════
# Basal Ganglia (Action Selection + DA Reward)
# ═══════════════════════════════════════════════════════════════════════
class BasalGanglia(nn.Module):
"""
Basal Ganglia: DA-based reward learning and action selection.
Dual-pathway D1/D2 competition (Theorem C):
D1 (direct): High DA threshold → stabilize current representations
D2 (indirect): Low DA threshold → enable flexibility/switching
Boltzmann receptor kinetics: σ(slope * (DA - EC50))
The D1/D2 balance creates an emergent inverted-U for WM performance.
DA RPE (reward prediction error) is Phase 2 (RL integration).
Currently DA comes from Brainstem (prediction error → phasic DA).
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.cfg = cfg
self.enabled = cfg.bg_enabled
if not self.enabled:
return
d = cfg.d_model
d_bg = cfg.d_bg
# D1 pathway (direct, stabilizing)
self.d1_in = nn.Linear(d, d_bg, bias=False)
self.d1_out = nn.Linear(d_bg, d, bias=False)
nn.init.zeros_(self.d1_out.weight)
# D2 pathway (indirect, flexible)
self.d2_in = nn.Linear(d, d_bg, bias=False)
self.d2_out = nn.Linear(d_bg, d, bias=False)
nn.init.zeros_(self.d2_out.weight)
# Receptor parameters
self.d1_ec50 = nn.Parameter(torch.tensor(cfg.d1_ec50))
self.d1_slope = nn.Parameter(torch.tensor(cfg.d1_slope))
self.d2_ec50 = nn.Parameter(torch.tensor(cfg.d2_ec50))
self.d2_slope = nn.Parameter(torch.tensor(cfg.d2_slope))
# Gate
self.gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
self.norm = RMSNorm(d)
# Tonic DA EMA
self.register_buffer('tonic_da', torch.tensor(0.5))
def forward(self, x: torch.Tensor, da: torch.Tensor) -> torch.Tensor:
"""
x: [B, T, D_model]
da: [B, T, 1] — phasic dopamine (prediction error)
Returns: [B, T, D_model] — D1/D2 modulated representation
"""
if not self.enabled:
return x
gate = torch.sigmoid(self.gate_raw)
h = self.norm(x)
# D1 receptor activation (high threshold, stabilizing)
d1_act = torch.sigmoid(self.d1_slope * (da - self.d1_ec50))
d1_mod = self.d1_out(F.gelu(self.d1_in(h))) * d1_act
# D2 receptor activation (low threshold, flexible)
d2_act = torch.sigmoid(self.d2_slope * (da - self.d2_ec50))
d2_mod = self.d2_out(F.gelu(self.d2_in(h))) * d2_act
# D1 - D2 competition (direct - indirect pathways)
modulation = d1_mod - d2_mod
return x + gate * modulation
@torch.no_grad()
def update_tonic_da(self, phasic_da: torch.Tensor):
"""Update tonic DA EMA."""
if not self.enabled:
return
mean_da = phasic_da.mean()
if torch.isfinite(mean_da):
self.tonic_da.lerp_(mean_da, 1.0 - self.cfg.tonic_da_ema)
# RPE + learned value estimation is Phase 2 (RL integration).
# ═══════════════════════════════════════════════════════════════════════
# Cerebellum (Temporal Prediction)
# ═══════════════════════════════════════════════════════════════════════
class Cerebellum(nn.Module):
"""
Cerebellum: Temporal prediction and error correction.
Forward model: predicts X[t+1] from X[t].
When prediction fails, applies correction signal.
The cerebellum is the brain's "error correction chip" — it learns
precise temporal patterns and corrects deviations in real-time.
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.enabled = cfg.cerebellum_enabled
if not self.enabled:
return
d = cfg.d_model
d_cb = cfg.d_cerebellar
# Forward model (predict next timestep)
self.W_in = nn.Linear(d, d_cb, bias=False)
self.W_predict = nn.Linear(d_cb, d, bias=False)
# Error correction
self.W_error = nn.Linear(d, d, bias=False)
nn.init.zeros_(self.W_error.weight)
self.norm = RMSNorm(d)
self.gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
x: [B, T, D_model]
Returns:
corrected: [B, T, D_model] — x with cerebellar correction
cb_loss: scalar — cerebellar prediction error (for monitoring)
"""
if not self.enabled:
return x, torch.tensor(0.0, device=x.device)
gate = torch.sigmoid(self.gate_raw)
h = self.norm(x)
# Predict next timestep
cb_hidden = F.gelu(self.W_in(h))
prediction = self.W_predict(cb_hidden) # [B, T, D]
# Temporal error: predicted X[t+1] vs actual X[t+1]
if x.shape[1] > 1:
# prediction[:, :-1] should match x[:, 1:]
error = x[:, 1:] - prediction[:, :-1]
cb_loss = error.pow(2).mean()
# Apply correction to current timestep
# Pad error to match T dimension
padded_error = F.pad(error, (0, 0, 1, 0)) # [B, T, D]
correction = self.W_error(padded_error)
return x + gate * correction, cb_loss
else:
return x, torch.tensor(0.0, device=x.device)
# ═══════════════════════════════════════════════════════════════════════
# Brainstem (Global State Regulation)
# ═══════════════════════════════════════════════════════════════════════
class Brainstem(nn.Module):
"""
Brainstem: Global neuromodulatory state regulation.
Computes all four neuromodulatory signals (Theorem C):
DA (dopamine): Prediction error, reward (VTA/SNc)
NE (norepinephrine): Arousal, exploration (Locus Coeruleus)
5-HT (serotonin): Time horizon, patience (Raphe nuclei)
ACh (acetylcholine): Attention, plasticity gating (Basal forebrain)
These signals are broadcast globally to all cortical columns
and modulate learning, not just activation.
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.cfg = cfg
d = cfg.d_model
# DA: Dopamine (prediction error / reward)
if cfg.da_enabled:
self.da_proj = nn.Linear(d, 1, bias=True)
nn.init.zeros_(self.da_proj.weight)
nn.init.zeros_(self.da_proj.bias)
# NE: Norepinephrine (arousal / exploration)
if cfg.ne_enabled:
self.ne_proj = nn.Linear(d, 1, bias=True)
nn.init.zeros_(self.ne_proj.weight)
nn.init.constant_(self.ne_proj.bias, 0.5) # Moderate arousal baseline
# 5-HT: Serotonin (time horizon / patience)
if cfg.serotonin_enabled:
self.serotonin_proj = nn.Linear(d, 1, bias=True)
nn.init.zeros_(self.serotonin_proj.weight)
nn.init.constant_(self.serotonin_proj.bias, 0.5) # Moderate patience
# ACh: Acetylcholine (attention / plasticity gate)
if cfg.ach_enabled:
self.ach_proj = nn.Linear(d, 1, bias=True)
nn.init.zeros_(self.ach_proj.weight)
nn.init.constant_(self.ach_proj.bias, 0.5) # Moderate attention
self.norm = RMSNorm(d)
# Tonic DA EMA
self.register_buffer('tonic_da', torch.tensor(0.5))
def compute_state(
self,
x: torch.Tensor,
prediction_error: Optional[torch.Tensor] = None,
) -> NeuromodState:
"""
Compute global neuromodulatory state from current representations.
x: [B, T, D_model] — aggregate representation
prediction_error: [B, T, D_model] — current prediction errors (for DA)
Returns: NeuromodState with all four signals
"""
h = self.norm(x)
B, T, D = h.shape
# DA: based on prediction error magnitude
if self.cfg.da_enabled:
if prediction_error is not None:
pe_mag = prediction_error.pow(2).mean(dim=-1, keepdim=True) # [B, T, 1]
da = torch.sigmoid(self.da_proj(h) + pe_mag.sqrt())
else:
da = torch.sigmoid(self.da_proj(h))
else:
da = torch.full((B, T, 1), 0.5, device=x.device)
# NE: arousal from representation variance
if self.cfg.ne_enabled:
ne = torch.sigmoid(self.ne_proj(h))
else:
ne = torch.full((B, T, 1), 0.5, device=x.device)
# 5-HT: patience / time horizon
if self.cfg.serotonin_enabled:
serotonin = torch.sigmoid(self.serotonin_proj(h))
else:
serotonin = torch.full((B, T, 1), 0.5, device=x.device)
# ACh: attention depth
if self.cfg.ach_enabled:
ach = torch.sigmoid(self.ach_proj(h))
else:
ach = torch.full((B, T, 1), 0.5, device=x.device)
# Update tonic DA
tonic_da_val = self.tonic_da.item()
with torch.no_grad():
mean_da = da.mean()
if torch.isfinite(mean_da):
self.tonic_da.lerp_(mean_da, 1.0 - self.cfg.tonic_da_ema)
return NeuromodState(
dopamine=da,
norepinephrine=ne,
serotonin=serotonin,
acetylcholine=ach,
tonic_da=tonic_da_val,
)
# Plasticity gating is handled by NeuromodulatedPlasticity in v11_learning.py,
# which computes DA × ACh × f(NE, 5-HT) from the NeuromodState returned here.
# ═══════════════════════════════════════════════════════════════════════
# Global Workspace (Baars 1988 — Consciousness Broadcast)
# ═══════════════════════════════════════════════════════════════════════
class CorticalWorkspace(nn.Module):
"""
Global Workspace for cortical column network (Baars 1988, Dehaene & Naccache 2001).
The brain needs a mechanism for columns to communicate beyond local
lateral connections. The Global Workspace Theory posits:
1. Columns compete for broadcast access (ignition)
2. The winning column's representation is broadcast globally
3. All columns can read the broadcast (L1 top-down input)
Disease mapping:
Vegetative state → workspace failure → no global broadcast → unconscious processing only
Schizophrenia (disconnection) → noisy broadcast → thought disorder
Architecture:
Each column writes a candidate broadcast via W_write:
candidate_l = W_write_l(column_output_l)
Competition via surprise-weighted softmax:
weight_l = softmax(surprise_l / temperature)
Winner broadcast:
workspace = Σ_l weight_l × candidate_l
Each column reads via W_read:
modulation_l = W_read_l(workspace)
Applied as top-down context to L1 on the next iteration.
Identity at init: W_write=0, gate_raw=-2 → no broadcast initially.
After training: high-surprise columns broadcast, others listen.
Params: n_columns × (d_model × d_model + d_model × d_model) + 1 gate
For n=12, d=512: ~6.3M params (12 × 2 × 512²). Too expensive.
Use bottleneck: d_ws = d_model // 4 = 128 → 12 × 2 × 512 × 128 = ~1.6M.
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.cfg = cfg
d = cfg.d_model
n = cfg.n_columns
d_ws = max(d // 4, 64) # Workspace bottleneck dimension
# Per-column write projection (column → workspace)
self.W_write = nn.ModuleList([
nn.Linear(d, d_ws, bias=False) for _ in range(n)
])
# Per-column read projection (workspace → column modulation)
self.W_read = nn.ModuleList([
nn.Linear(d_ws, d, bias=False) for _ in range(n)
])
# Initialize write projections to zero → no broadcast at init
for w in self.W_write:
nn.init.zeros_(w.weight)
# Initialize read projections to small random → gradient flows
for r in self.W_read:
nn.init.normal_(r.weight, std=0.01)
# Ignition temperature (controls competition sharpness)
self.temperature = nn.Parameter(torch.tensor(1.0))
# Global gate
self.gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
def broadcast(
self,
column_outputs: list, # List[ColumnOutput] from forward
errors: list, # List[torch.Tensor] — prediction errors per column
) -> List[torch.Tensor]:
"""
Compute global workspace broadcast and return per-column modulations.
Args:
column_outputs: list of ColumnOutput from all columns
errors: prediction error per column [B, T, D]
Returns:
modulations: list of [B, T, D] tensors — top-down workspace signal per column
"""
gate = torch.sigmoid(self.gate_raw)
n = len(column_outputs)
# Compute surprise-based competition weights
# Surprise = mean squared error per column
surprises = []
for l in range(n):
surprise_l = errors[l].pow(2).mean(dim=-1, keepdim=True) # [B, T, 1]
surprises.append(surprise_l)
surprise_stack = torch.cat(surprises, dim=-1) # [B, T, n_columns]
# Softmax competition (higher surprise → more broadcast access)
temp = F.softplus(self.temperature)
weights = F.softmax(surprise_stack / temp, dim=-1) # [B, T, n]
# Each column writes a candidate
candidates = []
for l in range(n):
cand = self.W_write[l](column_outputs[l].output) # [B, T, d_ws]
candidates.append(cand)
candidates_stack = torch.stack(candidates, dim=-2) # [B, T, n, d_ws]
# Weighted broadcast
w = weights.unsqueeze(-1) # [B, T, n, 1]
workspace = (w * candidates_stack).sum(dim=-2) # [B, T, d_ws]
# Each column reads the broadcast
modulations = []
for l in range(n):
mod = self.W_read[l](workspace) # [B, T, D]
modulations.append(gate * mod)
return modulations
# ═══════════════════════════════════════════════════════════════════════
# Self-Assessment & Metacognitive Monitoring
# ═══════════════════════════════════════════════════════════════════════
class SelfAssessment(nn.Module):
"""
Metacognitive monitoring module — the model knows when it's struggling.
Disease mapping:
Anosognosia (parietal damage) → no self-awareness of deficits
OCD (ACC hyperactivity) → excessive conflict monitoring
Two mechanisms:
1. Column health monitoring: detect σ² divergence/collapse, PC non-convergence
2. Conflict detection: when columns disagree, increase PC inference steps
ACC-like conflict: variance across column predictions at the same level.
High variance → columns disagree → allocate more inference steps.
This is the neural basis of "thinking harder" on difficult inputs.
Zero learnable params — purely algorithmic monitoring.
"""
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
# Health thresholds
self.sigma2_max = 100.0 # σ² above this = diverging
self.sigma2_min = 0.001 # σ² below this = collapsed
# Conflict → extra PC steps mapping
self.conflict_threshold = 0.5 # Variance above this = high conflict
self.max_extra_steps = 2 # Maximum extra PC steps from conflict (capped for speed)
# Track health history (per column, running averages)
n = cfg.n_columns
self.register_buffer('sigma2_ema', torch.ones(n))
self.register_buffer('convergence_ema', torch.zeros(n)) # Fraction that hit max_steps
self.register_buffer('_health_updates', torch.tensor(0, dtype=torch.long))
@torch.no_grad()
def compute_conflict(self, column_outputs: list) -> float:
"""
Compute inter-column conflict (ACC-like).
When columns produce very different outputs for the same input,
the system needs more deliberation.
Returns: conflict score (0 = agreement, high = disagreement)
"""
if len(column_outputs) < 2:
return 0.0
# Stack column output means: [n_columns, D]
means = torch.stack([
out.output.mean(dim=(0, 1)) for out in column_outputs
]) # [n_columns, D]
# Variance across columns = disagreement
conflict = means.var(dim=0).mean().item()
return conflict if math.isfinite(conflict) else 0.0
def extra_pc_steps(self, conflict: float) -> int:
"""Map conflict to extra inference steps (0 to max_extra_steps)."""
if not math.isfinite(conflict) or conflict < self.conflict_threshold:
return 0
# Linear mapping from threshold to 2×threshold → 0 to max_extra_steps
excess = (conflict - self.conflict_threshold) / max(self.conflict_threshold, 1e-6)
return min(self.max_extra_steps, int(excess * self.max_extra_steps))
@torch.no_grad()
def update_health(self, column_outputs: list, pc_steps_taken: int):
"""Track per-column health metrics."""
n = len(column_outputs)
alpha = 0.01 # Slow EMA
for l in range(min(n, self.cfg.n_columns)):
sigma2_mean = column_outputs[l].sigma2.mean().item()
if math.isfinite(sigma2_mean):
self.sigma2_ema[l] = self.sigma2_ema[l] * (1 - alpha) + sigma2_mean * alpha
# Track convergence rate
hit_max = float(pc_steps_taken >= self.cfg.pc_max_steps)
for l in range(min(n, self.cfg.n_columns)):
self.convergence_ema[l] = self.convergence_ema[l] * (1 - alpha) + hit_max * alpha
self._health_updates += 1
@torch.no_grad()
def check_health(self, columns) -> dict:
"""
Check column health and take corrective action if needed.
Returns: dict of health status per column
"""
health = {}
for l in range(min(len(columns), self.cfg.n_columns)):
sigma2 = self.sigma2_ema[l].item()
conv_rate = self.convergence_ema[l].item()
status = 'healthy'
# σ² divergence detection
if sigma2 > self.sigma2_max:
status = 'sigma2_diverging'
# Emergency: scale down L5 output weights
with torch.no_grad():
columns[l].L5.W_out.weight.data *= 0.9
columns[l].L5.W_sigma.weight.data *= 0.9
# σ² collapse detection
elif sigma2 < self.sigma2_min:
status = 'sigma2_collapsed'
# Nudge σ² back up
with torch.no_grad():
columns[l].L5.W_sigma.bias.data += 0.1
# PC non-convergence (always hitting max_steps)
if conv_rate > 0.8:
status = 'pc_stalled' if status == 'healthy' else status + '+pc_stalled'
health[f'col{l}_health'] = status
return health
def get_metrics(self) -> dict:
"""Return monitoring metrics."""
return {
'sigma2_ema_min': self.sigma2_ema.min().item(),
'sigma2_ema_max': self.sigma2_ema.max().item(),
'convergence_rate': self.convergence_ema.mean().item(),
}