Cortical Column: The Fundamental Compute Unit
Source: nct_v2/v11_column.py Lines: 1,435 Classes: 11
Neuroscience Foundation
The cortical column is the fundamental repeating computational unit of the mammalian neocortex, first identified by Vernon Mountcastle in his landmark 1957 study of the somatosensory cortex and later formalized in his 1997 review. Each column is a vertical cylinder spanning all six cortical layers, approximately 300–500m in diameter, containing approximately 80–120 neurons organized in a stereotyped circuit with distinct layer functions. The same basic circuit is replicated across the entire cortical surface, an estimated 150,000 columns in the human neocortex, from primary visual cortex (V1) to prefrontal cortex, differing primarily in the density and connectivity of its components rather than its fundamental architecture.
Douglas and Martin (2004) described the canonical cortical circuit, identifying the key information flow: Layer 4 receives thalamic input (the “sensory” layer), Layer 2/3 performs lateral integration and sends projections to other cortical areas (the “association” layer), Layer 5 generates output to subcortical structures (the “motor” layer), and Layer 6 provides feedback to the thalamus (the “modulatory” layer). Harris and Shepherd (2015) updated this model with modern understanding of cell-type diversity, showing that each layer contains multiple distinct cell types (excitatory pyramidal cells, inhibitory interneurons of several subtypes) with specific connectivity patterns.
NCT implements this circuit as the CorticalColumn class, which replaces a single transformer block. Unlike a transformer block (which contains only self-attention + FFN + LayerNorm = 3 components), a cortical column contains six distinct computational layers, three interneuron types (VIP, SST, PV/Chandelier), three-timescale working memory (NMDA, silent trace, phonological loop), oscillatory dynamics with nested PAC, and homeostatic regulation (BCM + metaplasticity), 11 submodules totaling 7.5M parameters per column in the default configuration. Each submodule is gated and identity-at-init, and the full column data flow mirrors the biological circuit described by Douglas, Martin, Harris, and Shepherd.
Data Flow
The biological data flow through a cortical column, with biologically correct placement of interneurons:
Layer 4: Thalamic Input
Definition 3 (Layer 4). The thalamic input layer projects feedforward input from inter-column dimension to intra-column dimension:
Initialization: If (default), (identity matrix, pure pass-through). Otherwise, Kaiming normal initialization. This corresponds to the stellate cells in biological L4 that relay thalamic input with minimal transformation.
Layer 2/3: Windowed Hebbian Association (Theorem B)
This is the core computational layer, replacing self-attention entirely. It implements Theorem B: Hebbian + anti-Hebbian learning converges to the PCA subspace, providing self-organizing representations without any supervised signal.
Theorem 10 (Windowed Hebbian Association Replaces Self-Attention). Let be a sequence of token representations. The L2/3 windowed Hebbian association computes, for each position and head : with complexity compared to for self-attention. For and , this is cheaper.
Complexity proof. Self-attention computes over all pairs. L2/3 computes associations only within a causal window of size . Per position: comparisons dimensions heads . Over positions: . ◻
The five steps of the L2/3 mechanism:
Step 1, Content-addressable recall: where is initialized as identity (self-recall) and updated by Hebbian learning. This answers: “what does this pattern remind the column of?”
Step 2, Local window context: Gather for (causal, zero-padded). Window size tokens = 2 theta cycles.
Step 3, Distance-weighted context: where initialized at (uniform weighting at init).
Step 4, k-WTA + anti-Hebbian: Retain only top 15% of activations (sparse coding). Anti-Hebbian lateral weights (init ) enforce decorrelation.
Step 5, Output: (init ) projects combined output. Gate with .

Proposition 3 (Hebbian Update Rule). The association weights are updated by: This combination converges to the PCA subspace (Pehlevan & Chklovskii, 2019), self-organizing representations without any supervised signal.
L2/3 also implements structural plasticity (Theorem E): synaptic density tracking, growth where PE is persistently high (), and pruning where gates approach zero (), checked every 1,000 steps.

Working Memory: Three Timescales (NMDA, Silent, Phonological)
Theorem 11 (Multi-Timescale Working Memory). NCT implements three biologically-grounded WM systems operating at different temporal scales:
1. NMDA Attractor Slots (Luck & Vogel, 1997): competitive slots with learned exponential decay: Decay bias , giving half-life tokens.
2. Activity-Silent Trace (Mongillo et al., 2008): Tsodyks-Markram short-term plasticity dynamics: where , .

3. Phonological Loop: Circular buffer with passive decay and rehearsal: slots (Miller’s ), rehearsal strength .
All three subsystems are gated (gate init ), identity-at-init (), and maintain persistent state across forward passes (unlike transformer layers, which are stateless).
Oscillatory Dynamics: Nested PAC
Theorem 12 (Phase-Amplitude Coupling). Cross-frequency coupling modulates column activity at four nested timescales: where with learnable periods: tokens, , .
Coupling strengths: at init (theta-gamma PAC present at rest, Jensen & Colgin 2007), at init.
Phase-content interaction through rank-32 projection:
Output: . initialized , small but nonzero so oscillations provide signal from the start.
Interneurons: VIP, SST, PV/Chandelier
Three interneuron types implement distinct inhibitory functions at biologically correct positions:
| Type | Placement | Function | Disease if Missing |
|---|---|---|---|
| VIP | Before L2/3 | Disinhibits SST (novelty gate) | Autism (ASD) |
| SST | Before L2/3 | Dendritic inhibition () | – |
| PV/Chandelier | After WM, before L5 | Axo-axonic output veto | Epilepsy |
VIP disinhibition: When top-down signals indicate novelty, VIP neurons inhibit SST neurons, which disinhibits the pyramidal cells, a double negative that opens the gate for new information. This is the brain’s mechanism for attention: “this is new and important, let it through.”
PV/Chandelier veto: A straight-through hard gate with bias initialized at 5.0 (, nearly always open). The Chandelier cell can completely silence a pyramidal cell’s output by vetoing at the axon initial segment. This prevents erroneous outputs when the column is uncertain.
BCM Homeostasis and Metaplasticity
Theorem 13 (BCM Sliding Threshold (Bienenstock, Cooper, Munro 1982)). The BCM threshold tracks mean squared postsynaptic activity: The Hebbian update is modulated: when , potentiation occurs (strengthen active synapses). When , depression occurs (weaken inactive synapses). This prevents runaway Hebbian learning, without BCM, strong synapses would grow without bound.
Proposition 4 (Metaplasticity (Abraham & Bear, 1996)). The effective learning rate adapts based on recent plasticity history: High recent plasticity reduces the learning rate (stabilization). Low recent plasticity increases it (exploration). This is the brain’s mechanism for “learning to learn differently”, the plasticity of plasticity.
Layer 5: Dendritic FFN + Prediction + Precision
Theorem 14 (Dendritic Two-Compartment Computation). L5 implements gated computation with separate basal (feedforward) and apical (feedback) compartments:
The gated linear unit (GLU) architecture means that the apical compartment (top-down feedback) can gate the basal compartment (bottom-up input). This is biologically faithful: calcium spikes in apical dendrites can gate somatic output, controlling whether a neuron responds to its feedforward input based on contextual feedback.
Prediction head: generates the top-down prediction for the column below.
Precision output: with so that .
Lateral Column Connections
Horizontal connections between adjacent columns () via low-rank send/receive projections:
Disease mapping: schizophrenia (disconnection syndrome) disrupted lateral connections fragmented perception and thought disorder. initialized at (no lateral communication at init).
Column Output
The column returns a ColumnOutput dataclass containing seven fields, each serving a specific role in the NCT learning and communication framework:
| Field | Shape | Role |
|---|---|---|
output | Sent to next column via thalamic routing. Includes residual connection: . | |
prediction | Top-down prediction for the column below. Used to compute PC error . | |
thal_feedback | L6 feedback signal sent to thalamic relay. Modulates routing for subsequent inputs. | |
state | Internal column state (post-oscillation, pre-L5). Used for monitoring and diagnostics. | |
sigma2 | Prediction precision from L5. Passed to next column’s L5 as prior. Used for PC learning weight, surprise tagging, and -adaptive decoding. | |
l23_input | Input to L2/3 (after L1 modulation + interneuron gating). Needed for Hebbian update: in . | |
l23_output | Output of L2/3 settling. Needed for Hebbian update: in . |
The residual connection ensures that even with all gates near zero (identity-at-init), the column passes information through unchanged. If , a learned residual projection adapts the dimension.
Source Code
# ===========================================================================
# Cortical Column — The Fundamental Compute Unit
# Source: nct_v2/v11_column.py
# ===========================================================================
"""
NCT V11: Cortical Column — The Fundamental Compute Unit
========================================================
Replaces transformer blocks with a biologically-grounded 6-layer cortical column.
Architecture:
L1: Top-down modulation (apical dendrites, feedback from higher columns)
L2/3: Lateral association (self-organizing attention via Hebbian learning)
L4: Thalamic input (feedforward processing, the "sensory" layer)
L5: Output + prediction (per-position computation + top-down prediction)
L6: Thalamic feedback (modulates relay for future input)
Plus: Interneurons (VIP/SST/PV), Working Memory (NMDA/Silent/Phono),
Oscillatory dynamics, BCM homeostasis.
All modules are identity-at-init: gate_raw=-2.0, W_out=0.
"""
# [bundled] from .v11_config import V11Config
# ═══════════════════════════════════════════════════════════════════════
# Column Output
# ═══════════════════════════════════════════════════════════════════════
@dataclass
class ColumnOutput:
"""Output from a single cortical column."""
output: torch.Tensor # [B, T, D_model] — sent to next column
prediction: torch.Tensor # [B, T, D_model] — top-down prediction for column below
thal_feedback: torch.Tensor # [B, T, D_model] — sent to thalamus
state: torch.Tensor # [B, T, D_col] — internal column state (for learning)
sigma2: torch.Tensor # [B, T, 1] — prediction precision
l23_input: torch.Tensor # [B, T, D_col] — L2/3 input (for Hebbian update)
l23_output: torch.Tensor # [B, T, D_col] — L2/3 output (for Hebbian update)
# ═══════════════════════════════════════════════════════════════════════
# RMSNorm (lightweight normalization)
# ═══════════════════════════════════════════════════════════════════════
class RMSNorm(nn.Module):
def __init__(self, d: int, eps: float = 1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(d))
self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor:
rms = torch.sqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
return x / rms * self.weight
# ═══════════════════════════════════════════════════════════════════════
# L4: Thalamic Input Layer
# ═══════════════════════════════════════════════════════════════════════
class L4_ThalamicInput(nn.Module):
"""
Layer 4: Receives feedforward input from thalamus.
The primary input layer of the cortical column.
In V1: orientation-selective simple cells.
In language: token-level feature extraction.
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.proj = nn.Linear(cfg.d_model, cfg.d_column, bias=False)
self.norm = RMSNorm(cfg.d_column)
# Identity at init: if d_model == d_column, start as identity
if cfg.d_model == cfg.d_column:
nn.init.eye_(self.proj.weight)
else:
nn.init.kaiming_normal_(self.proj.weight, nonlinearity='linear')
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""x: [B, T, D_model] → [B, T, D_col]"""
return self.norm(self.proj(x))
# ═══════════════════════════════════════════════════════════════════════
# L2/3: Lateral Association Layer (Replaces Self-Attention)
# ═══════════════════════════════════════════════════════════════════════
class L23_LateralAssociation(nn.Module):
"""
Layer 2/3: Windowed Hebbian Associative Recall — NOT attention.
Theorem B (Pehlevan & Chklovskii 2019):
Hebbian feedforward + anti-Hebbian lateral → PCA subspace convergence.
Mechanism (O(T×w×d), NOT O(T²)):
1. Direct association: a_t = W_assoc @ x_t — content-addressable recall
2. Local window gather: each position t looks at [t-w, t] (theta period)
3. Distance-weighted context: learned similarity within window
4. Combine + k-WTA lateral inhibition (competitive coding)
5. Association weights updated by Hebbian rule: ΔW = η * (X^T X) / N
No Q/K dot-product. No causal mask. No softmax attention.
Causality is implicit: window only looks backward [t-w, t].
W_assoc: content-addressable memory (Hebbian-learned, not trained by backprop).
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.cfg = cfg
self.d_col = cfg.d_column
self.n_heads = cfg.n_assoc_heads
self.d_head = cfg.d_head
self.window_size = cfg.assoc_window_size
# Per-head association matrix: content-addressable recall
# a_t = W_assoc[h] @ x_t — what this pattern reminds the column of
# Initialized as identity → recalls the input itself
self.W_assoc = nn.Parameter(torch.zeros(self.n_heads, self.d_head, self.d_head))
for h in range(self.n_heads):
nn.init.eye_(self.W_assoc[h])
# Value projection (what information to extract from window context)
self.W_val = nn.Linear(cfg.d_column, cfg.d_column, bias=False)
nn.init.eye_(self.W_val.weight)
# Distance weighting for local window: per-head [H, D_h]
# At init (zeros): all window positions weighted equally → uniform average
self.W_dist = nn.Parameter(torch.zeros(self.n_heads, self.d_head))
# Output projection (combines heads)
self.W_out = nn.Linear(cfg.d_column, cfg.d_column, bias=False)
nn.init.zeros_(self.W_out.weight) # Identity at init via residual
# Anti-Hebbian lateral weights for feature competition
self.W_lateral = nn.Parameter(torch.zeros(self.n_heads, self.d_head, self.d_head))
# k-WTA parameters
self.k_wta_ratio = cfg.k_wta_ratio
# Gate
self.gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
self.norm = RMSNorm(cfg.d_column)
self.dropout = nn.Dropout(cfg.assoc_dropout)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Windowed Hebbian Associative Recall — O(T × w × d), NOT O(T²).
x: [B, T, D_col]
Returns: [B, T, D_col] association output (to be added as residual)
Mechanism:
1. Direct association: a_t = W_assoc @ x_t (content-addressable recall)
2. Local window gather: each position looks back w positions (theta period)
3. Distance-weighted context: learned similarity within window
4. Combine: W_out(association + context)
5. k-WTA + lateral inhibition (competitive coding)
No Q/K dot-product. No causal mask. No RoPE.
Causality is implicit: window only looks backward [t-w, t].
"""
B, T, D = x.shape
gate = torch.sigmoid(self.gate_raw)
w = self.window_size
x_norm = self.norm(x)
# Reshape to multi-head: [B, T, H, D_h] → [B, H, T, D_h]
x_heads = x_norm.view(B, T, self.n_heads, self.d_head).transpose(1, 2)
# 1. Direct association (content-addressable recall per head)
assoc = torch.matmul(x_heads, self.W_assoc) # [B, H, T, D_h]
# 2. Local window context (theta-period temporal binding)
v = self.W_val(x_norm)
v_heads = v.view(B, T, self.n_heads, self.d_head).transpose(1, 2) # [B, H, T, D_h]
# Pad on left for causal window: position t sees [t-w, ..., t]
x_pad = F.pad(x_heads, (0, 0, w, 0)) # [B, H, T+w, D_h]
v_pad = F.pad(v_heads, (0, 0, w, 0)) # [B, H, T+w, D_h]
# Unfold to get windows: [B, H, T, D_h, w+1]
x_win = x_pad.unfold(2, w + 1, 1) # [B, H, T, D_h, w+1]
v_win = v_pad.unfold(2, w + 1, 1) # [B, H, T, D_h, w+1]
# Permute to [B, H, T, w+1, D_h]
x_win = x_win.permute(0, 1, 2, 4, 3)
v_win = v_win.permute(0, 1, 2, 4, 3)
# 3. Distance-weighted context
# Compute feature-wise difference between current position and each window position
x_curr = x_heads.unsqueeze(3) # [B, H, T, 1, D_h]
diff = x_curr - x_win # [B, H, T, w+1, D_h]
# Learned distance weighting: dot(diff, W_dist[h]) → scalar per window position
# W_dist[h] shape: [D_h], broadcast to [1, H, 1, 1, D_h]
w_dist = self.W_dist[None, :, None, None, :] # [1, H, 1, 1, D_h]
scores = (diff * w_dist).sum(dim=-1) # [B, H, T, w+1]
# Softplus → non-negative weights, then normalize
weights = F.softplus(scores) # [B, H, T, w+1]
weights = weights / (weights.sum(dim=-1, keepdim=True) + 1e-8)
weights = self.dropout(weights)
# Weighted sum of values in window
context = (weights.unsqueeze(-1) * v_win).sum(dim=3) # [B, H, T, D_h]
# 4. Combine association + windowed context
combined = assoc + context # [B, H, T, D_h]
# 5. Lateral inhibition (anti-Hebbian decorrelation)
if self.W_lateral.abs().max() > 1e-8: # Skip if zero (init)
lateral = torch.matmul(combined, self.W_lateral) # [B, H, T, D_h]
combined = combined - lateral
# 6. k-WTA sparsity on features per head (competitive activation coding)
k = max(1, int(self.d_head * self.k_wta_ratio))
topk_vals, topk_idx = combined.topk(k, dim=-1)
mask = torch.zeros_like(combined)
mask.scatter_(-1, topk_idx, 1.0)
combined = combined * mask
# 7. Reshape back: [B, H, T, D_h] → [B, T, D]
combined = combined.transpose(1, 2).contiguous().view(B, T, D)
# Output projection
out = self.W_out(combined)
return gate * out
# ── Structural Plasticity (Theorem E) ─────────────────────────
# Synaptogenesis + pruning on lateral weights.
def init_structural_plasticity(self):
"""Initialize structural plasticity masks and counters.
Called once after construction if structural_plasticity=True.
"""
d = self.d_head
n = self.n_heads
# Binary mask: 1 = active connection, 0 = pruned
self.register_buffer(
'assoc_mask', torch.ones(n, d, d)
)
# Counter: steps since weight was below pruning threshold
self.register_buffer(
'below_thresh_count', torch.zeros(n, d, d, dtype=torch.long)
)
self._structural_init = True
@torch.no_grad()
def structural_plasticity_step(
self,
error_magnitude: float,
prune_threshold: float = 0.01,
growth_threshold: float = 2.0,
prune_interval: int = 1000,
):
"""
Structural plasticity: prune weak connections, grow new ones where needed.
Theorem E: The brain continuously prunes and grows synapses.
- Pruning: connections with |w| < threshold for sustained periods die
- Synaptogenesis: high prediction error triggers new random connections
Args:
error_magnitude: mean PE across tokens (drives synaptogenesis)
prune_threshold: weight magnitude below which connections can be pruned
growth_threshold: error above which new connections sprout
prune_interval: steps below threshold before permanent pruning
"""
if not hasattr(self, '_structural_init'):
return
mask = self.assoc_mask
counts = self.below_thresh_count
for h in range(self.n_heads):
w = self.W_assoc.data[h]
# Track how long each weight has been below threshold
below = (w.abs() < prune_threshold) & (mask[h] > 0)
counts[h][below] += 1
counts[h][~below] = 0
# Prune: connections below threshold for prune_interval steps
to_prune = counts[h] >= prune_interval
if to_prune.any():
mask[h][to_prune] = 0
w[to_prune] = 0
counts[h][to_prune] = 0
# Apply mask to ensure pruned connections stay dead
w *= mask[h]
self.W_assoc.data[h] = w
# Synaptogenesis: high error → grow new connections
if error_magnitude > growth_threshold:
for h in range(self.n_heads):
pruned = mask[h] == 0
n_pruned = pruned.sum().item()
if n_pruned == 0:
continue
# Restore a fraction of pruned connections with small random weights
n_restore = max(1, int(n_pruned * 0.05)) # 5% of pruned per event
pruned_indices = pruned.nonzero()
perm = torch.randperm(len(pruned_indices), device=mask.device)[:n_restore]
for idx in pruned_indices[perm]:
r, c = idx[0].item(), idx[1].item()
mask[h, r, c] = 1
self.W_assoc.data[h, r, c] = torch.randn(1, device=mask.device).item() * 0.01
def get_connection_density(self) -> float:
"""Return fraction of active connections (1.0 = fully connected)."""
if not hasattr(self, '_structural_init'):
return 1.0
return self.assoc_mask.float().mean().item()
@torch.no_grad()
def hebbian_update(self, x: torch.Tensor, lr: Optional[float] = None):
"""
Hebbian learning update for W_assoc and W_lateral.
Called after forward pass with the same input.
ΔW_assoc = η * (X^T X) / N (strengthen correlated features)
ΔW_lateral = η * (Y^T Y) / N (decorrelate outputs, anti-Hebbian)
"""
if lr is None:
lr = self.cfg.hebbian_lr
B, T, D = x.shape
N = B * T
x_heads = x.view(B, T, self.n_heads, self.d_head).transpose(1, 2)
for h in range(self.n_heads):
x_h = x_heads[:, h].reshape(-1, self.d_head) # [BT, D_h]
# Hebbian: ΔW = η * correlation matrix
corr = (x_h.T @ x_h) / N
# Remove diagonal (self-correlations add instability)
corr.fill_diagonal_(0)
self.W_assoc.data[h] += lr * corr
# Respect structural plasticity mask
if hasattr(self, '_structural_init'):
self.W_assoc.data[h] *= self.assoc_mask[h]
# Normalize to prevent explosion
norm = self.W_assoc.data[h].norm()
if norm > 5.0:
self.W_assoc.data[h] *= 5.0 / norm
@torch.no_grad()
def anti_hebbian_update(self, y: torch.Tensor, lr: Optional[float] = None):
"""
Anti-Hebbian update for lateral weights (decorrelation).
y is the output of the association layer.
ΔW_lat = η * (Y^T Y) / N - η * I (decorrelate, preserve norm)
"""
if lr is None:
lr = self.cfg.hebbian_lr
B, T, D = y.shape
N = B * T
y_heads = y.view(B, T, self.n_heads, self.d_head).transpose(1, 2)
for h in range(self.n_heads):
y_h = y_heads[:, h].reshape(-1, self.d_head)
decorr = (y_h.T @ y_h) / N
# Target: identity covariance (decorrelated outputs)
decorr -= torch.eye(self.d_head, device=y.device)
self.W_lateral.data[h] += lr * decorr
norm = self.W_lateral.data[h].norm()
if norm > 3.0:
self.W_lateral.data[h] *= 3.0 / norm
@torch.no_grad()
def hebbian_update_bcm(self, pre_input: torch.Tensor, post_output: torch.Tensor,
bcm_theta: torch.Tensor, lr: Optional[float] = None):
"""
BCM-modulated Hebbian update for W_assoc.
Δw ∝ y(y - θ_BCM)x — potentiate above threshold, depress below.
pre_input: [B, T, D_col] — input to L2/3 (pre-synaptic)
post_output: [B, T, D_col] — output of L2/3 (post-synaptic)
bcm_theta: scalar tensor — BCM sliding threshold
"""
if lr is None:
lr = self.cfg.hebbian_lr
B, T, D = pre_input.shape
N = B * T
pre_heads = pre_input.view(B, T, self.n_heads, self.d_head).transpose(1, 2)
post_heads = post_output.view(B, T, self.n_heads, self.d_head).transpose(1, 2)
for h in range(self.n_heads):
pre_h = pre_heads[:, h].reshape(-1, self.d_head) # [BT, D_h]
post_h = post_heads[:, h].reshape(-1, self.d_head) # [BT, D_h]
# BCM modulation: y(y - sqrt(θ))x
bcm_mod = post_h * (post_h - bcm_theta.sqrt()) # [BT, D_h]
update = (bcm_mod.T @ pre_h) / N # [D_h, D_h]
update.fill_diagonal_(0)
self.W_assoc.data[h] += lr * update
# Respect structural plasticity mask
if hasattr(self, '_structural_init'):
self.W_assoc.data[h] *= self.assoc_mask[h]
norm = self.W_assoc.data[h].norm()
if norm > 5.0:
self.W_assoc.data[h] *= 5.0 / norm
@torch.no_grad()
def hebbian_update_error_modulated(
self,
pre_input: torch.Tensor,
post_output: torch.Tensor,
error: torch.Tensor,
bcm_theta: torch.Tensor,
lr: Optional[float] = None,
error_weight: float = 0.5,
):
"""
Error-driven Hebbian: BCM × prediction_error_magnitude × (pre^T × post).
The brain's Hebbian learning is NOT blind correlation — it's modulated
by prediction error. High error = more plasticity (learn from mistakes).
error_weight: 0 = pure BCM (blind), 1 = fully error-driven
"""
if lr is None:
lr = self.cfg.hebbian_lr
B, T, D = pre_input.shape
N = B * T
# Per-token error magnitude [B, T, 1]
error_mag = error.detach().norm(dim=-1, keepdim=True) # [B, T, 1]
# Normalize to mean 1 to avoid scaling issues
error_scale = error_mag / (error_mag.mean() + 1e-8)
pre_heads = pre_input.view(B, T, self.n_heads, self.d_head).transpose(1, 2)
post_heads = post_output.view(B, T, self.n_heads, self.d_head).transpose(1, 2)
# Broadcast error scale to heads: [B, 1, T, 1]
err_heads = error_scale.unsqueeze(1)
for h in range(self.n_heads):
pre_h = pre_heads[:, h] # [B, T, D_h]
post_h = post_heads[:, h] # [B, T, D_h]
err_h = err_heads[:, 0] # [B, T, 1]
# BCM modulation: y(y - sqrt(θ))
bcm_mod = post_h * (post_h - bcm_theta.sqrt()) # [B, T, D_h]
# Error modulation: blend blind BCM with error-weighted BCM
# When error_weight=0: pure BCM. When error_weight=1: error × BCM
modulated = bcm_mod * ((1.0 - error_weight) + error_weight * err_h)
# Hebbian update
modulated_flat = modulated.reshape(-1, self.d_head) # [BT, D_h]
pre_flat = pre_h.reshape(-1, self.d_head)
update = (modulated_flat.T @ pre_flat) / N
update.fill_diagonal_(0)
self.W_assoc.data[h] += lr * update
# Respect structural plasticity mask
if hasattr(self, '_structural_init'):
self.W_assoc.data[h] *= self.assoc_mask[h]
norm = self.W_assoc.data[h].norm()
if norm > 5.0:
self.W_assoc.data[h] *= 5.0 / norm
# ═══════════════════════════════════════════════════════════════════════
# L1: Top-Down Modulation Layer
# ═══════════════════════════════════════════════════════════════════════
class L1_TopDownModulation(nn.Module):
"""
Layer 1: Receives top-down feedback from higher cortical areas.
Modulates column processing via apical dendrites.
In the brain: L1 contains apical dendrite tufts from L5 pyramidal cells
of the same column, plus axons from higher areas. Top-down signals
modulate (but don't drive) the column's processing.
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.proj = nn.Linear(cfg.d_model, cfg.d_column, bias=False)
nn.init.zeros_(self.proj.weight) # No top-down initially
self.gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
self.norm = RMSNorm(cfg.d_column)
def forward(self, td_context: torch.Tensor) -> torch.Tensor:
"""
td_context: [B, T, D_model] — top-down from higher column
Returns: [B, T, D_col] — modulatory signal (added to L4 output)
"""
gate = torch.sigmoid(self.gate_raw)
return gate * self.norm(self.proj(td_context))
# ═══════════════════════════════════════════════════════════════════════
# L5: Output + Prediction Generation
# ═══════════════════════════════════════════════════════════════════════
class L5_OutputPrediction(nn.Module):
"""
Layer 5: Output computation + top-down prediction generation.
Two functions:
1. Compute output for next column (like FFN: up-project → SwiGLU → down-project)
2. Generate top-down prediction for the column below (predictive coding)
The prediction is the KEY to local learning:
ε_l = actual_input_l - prediction_from_{l+1}
This error drives local weight updates (Theorem A).
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.dendritic = cfg.l5_dendritic
self.kwta = cfg.l5_kwta
self.k_wta_ratio = cfg.k_wta_ratio
# Output computation (SwiGLU FFN — SiLU ≈ biological f-I curve)
self.W_up = nn.Linear(cfg.d_column, cfg.d_ff, bias=False)
self.W_gate = nn.Linear(cfg.d_column, cfg.d_ff, bias=False)
self.W_down = nn.Linear(cfg.d_ff, cfg.d_model, bias=False)
nn.init.zeros_(self.W_down.weight) # Identity at init via residual
# Dendritic computation (basal + apical gating)
if self.dendritic:
# Basal dendritic gate: bottom-up context from L4 input
# bias=3.0 → sigmoid(3)≈0.95 → nearly open at init
self.W_dend = nn.Linear(cfg.d_column, cfg.d_ff, bias=True)
nn.init.zeros_(self.W_dend.weight)
nn.init.constant_(self.W_dend.bias, 3.0)
# Apical dendritic gate: top-down context from L1
self.W_apical = nn.Linear(cfg.d_column, cfg.d_ff, bias=True)
nn.init.zeros_(self.W_apical.weight)
nn.init.constant_(self.W_apical.bias, 3.0)
# σ²-adaptive modulation: prediction uncertainty modulates dendrites
self.W_sigma_adapt = nn.Linear(1, cfg.d_ff, bias=False)
nn.init.zeros_(self.W_sigma_adapt.weight)
# Prediction head: generates prediction of input to column below
self.W_predict = nn.Linear(cfg.d_column, cfg.d_model, bias=False)
nn.init.zeros_(self.W_predict.weight) # No predictions initially → max error → max learning
# Precision estimation (σ² for this column's predictions)
self.W_sigma = nn.Linear(cfg.d_column, 1, bias=True)
nn.init.zeros_(self.W_sigma.weight)
_sigma2_bias = math.log(math.exp(cfg.sigma2_init) - 1) if cfg.sigma2_init > 0.01 else 0.0
nn.init.constant_(self.W_sigma.bias, _sigma2_bias)
self.norm = RMSNorm(cfg.d_column)
self.dropout = nn.Dropout(cfg.dropout)
def forward(self, h: torch.Tensor,
l4_input: Optional[torch.Tensor] = None,
td_context: Optional[torch.Tensor] = None,
sigma2_prev: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Dendritic FFN: SwiGLU core + basal/apical dendritic gating + k-WTA sparsity.
h: [B, T, D_col] — column state after L2/3
l4_input: [B, T, D_col] — bottom-up from L4 (basal dendrite context)
td_context: [B, T, D_col] — top-down from L1 (apical dendrite context)
sigma2_prev: [B, T, 1] — previous column's prediction precision
Returns:
output: [B, T, D_model] — sent to next column
prediction: [B, T, D_model] — top-down prediction for column below
sigma2: [B, T, 1] — prediction precision
"""
h_norm = self.norm(h)
# SwiGLU core (SiLU ≈ biological frequency-current curve)
ff = F.silu(self.W_gate(h_norm)) * self.W_up(h_norm) # [B, T, d_ff]
# Dendritic gating
if self.dendritic:
# Basal dendritic gate (bottom-up: what the input says to compute)
if l4_input is not None:
dend_logit = self.W_dend(l4_input) # [B, T, d_ff]
else:
# Use bias only — sigmoid(3.0)≈0.95 → nearly open
dend_logit = self.W_dend.bias.unsqueeze(0).unsqueeze(0).expand_as(ff)
# σ²-adaptive: high uncertainty → modulate dendritic gate
if sigma2_prev is not None:
dend_logit = dend_logit + self.W_sigma_adapt(sigma2_prev)
ff = ff * torch.sigmoid(dend_logit)
# Apical dendritic gate (top-down: what higher areas expect)
if td_context is not None:
ff = ff * torch.sigmoid(self.W_apical(td_context))
# k-WTA sparsity (cortical-level sparse coding)
if self.kwta:
k = max(1, int(ff.shape[-1] * self.k_wta_ratio))
topk_vals, topk_idx = ff.topk(k, dim=-1)
mask = torch.zeros_like(ff)
mask.scatter_(-1, topk_idx, 1.0)
ff = ff * mask
output = self.W_down(self.dropout(ff))
# Top-down prediction
prediction = self.W_predict(h_norm)
# Per-token precision: σ²(h) = softplus(W_sigma(h)) + ε
sigma2 = F.softplus(self.W_sigma(h_norm)) + 1e-6 # [B, T, 1]
return output, prediction, sigma2
# ═══════════════════════════════════════════════════════════════════════
# L6: Thalamic Feedback
# ═══════════════════════════════════════════════════════════════════════
class L6_ThalamicFeedback(nn.Module):
"""
Layer 6: Projects back to thalamus.
Modulates thalamic relay for future input processing.
In the brain: L6 corticothalamic neurons sharpen thalamic responses
and control the "gain" of thalamic relay for the next processing cycle.
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.proj = nn.Linear(cfg.d_column, cfg.d_model, bias=False)
nn.init.zeros_(self.proj.weight) # No feedback initially
self.gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
def forward(self, h: torch.Tensor) -> torch.Tensor:
"""
h: [B, T, D_col] — column state
Returns: [B, T, D_model] — thalamic feedback signal
"""
gate = torch.sigmoid(self.gate_raw)
return gate * self.proj(h)
# ═══════════════════════════════════════════════════════════════════════
# Column Interneurons (VIP → SST → PV/Chandelier)
# ═══════════════════════════════════════════════════════════════════════
class ColumnInterneurons(nn.Module):
"""
Interneurons within a cortical column.
Circuit: VIP ─⊣ SST ─⊣ Pyramidal (apical)
PV ─⊣ Pyramidal (axon initial segment)
VIP (Thm 38): Disinhibition — releases SST suppression when input is novel
SST (Thm 46): Input gate — suppresses apical dendrites (top-down influence)
PV (Thm 41): Output veto — axon initial segment gating
All identity-at-init: gate_raw = -2.0, output weights = 0.
"""
def __init__(self, cfg: V11Config):
super().__init__()
d = cfg.d_column
d_i = cfg.d_inhibitory
# VIP: Vasoactive Intestinal Peptide interneuron (disinhibition)
self.vip_enabled = cfg.vip_enabled
if cfg.vip_enabled:
self.vip_in = nn.Linear(d, d_i, bias=False)
self.vip_out = nn.Linear(d_i, d, bias=False)
nn.init.zeros_(self.vip_out.weight)
self.vip_gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
self.vip_norm = RMSNorm(d)
# SST: Somatostatin interneuron (Martinotti cell, input gate)
self.sst_enabled = cfg.sst_enabled
if cfg.sst_enabled:
self.sst_in = nn.Linear(d, d_i, bias=False)
self.sst_out = nn.Linear(d_i, d, bias=False)
nn.init.zeros_(self.sst_out.weight)
self.sst_gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
self.sst_tonic = 0.10 # Intrinsic Na+ currents (constant)
self.sst_norm = RMSNorm(d)
# PV: Parvalbumin interneuron (Chandelier cell, output veto)
self.pv_enabled = cfg.pv_enabled
if cfg.pv_enabled:
self.pv_in = nn.Linear(d, d_i, bias=False)
self.pv_score = nn.Linear(d_i, 1, bias=True)
nn.init.zeros_(self.pv_score.weight)
nn.init.constant_(self.pv_score.bias, 5.0) # Nearly open at init
self.pv_gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
self.pv_norm = RMSNorm(d)
def apply_dendritic_inhibition(self, h: torch.Tensor,
td_signal: Optional[torch.Tensor] = None) -> torch.Tensor:
"""
SST + VIP: Pre-L2/3 apical dendrite gating.
VIP detects novelty in top-down signal → disinhibits SST.
SST suppresses apical dendrites (input gating).
Applied BEFORE L2/3 (correct biological placement).
"""
# VIP disinhibition (reads top-down novelty)
vip_disinhibition = None
if self.vip_enabled and td_signal is not None:
vip_g = torch.sigmoid(self.vip_gate_raw)
vip_act = torch.sigmoid(self.vip_out(F.gelu(self.vip_in(self.vip_norm(td_signal)))))
vip_disinhibition = vip_g * vip_act # [B, T, D]
# SST dendritic inhibition
if self.sst_enabled:
sst_g = torch.sigmoid(self.sst_gate_raw)
sst_act = torch.sigmoid(self.sst_out(F.gelu(self.sst_in(self.sst_norm(h)))))
sst_total = self.sst_tonic + (1.0 - self.sst_tonic) * sst_g * sst_act
# VIP → SST disinhibition
if vip_disinhibition is not None:
sst_effective = sst_total * (1.0 - vip_disinhibition)
else:
sst_effective = sst_total
h = h * (1.0 - sst_effective)
return h
def apply_output_veto(self, h: torch.Tensor) -> torch.Tensor:
"""
PV/Chandelier: Post-computation axon initial segment veto.
Applied AFTER working memory/oscillations, BEFORE L5 output.
Correct biological placement: PV gates whether the pyramidal cell fires.
"""
if self.pv_enabled:
pv_g = torch.sigmoid(self.pv_gate_raw)
pv_logits = self.pv_score(F.gelu(self.pv_in(self.pv_norm(h)))) # [B, T, 1]
pass_prob = torch.sigmoid(pv_logits) # Near 1.0 at init (bias=5.0)
# Straight-through: hard gate forward, soft gradient backward
hard_pass = (pass_prob > 0.5).float()
pass_gate = hard_pass - pass_prob.detach() + pass_prob
h = h * ((1.0 - pv_g) + pv_g * pass_gate)
return h
def forward(self, h: torch.Tensor, td_signal: Optional[torch.Tensor] = None) -> torch.Tensor:
"""Backward-compatible: applies both stages. Use split methods for correct placement."""
h = self.apply_dendritic_inhibition(h, td_signal)
h = self.apply_output_veto(h)
return h
# ═══════════════════════════════════════════════════════════════════════
# Column Working Memory
# ═══════════════════════════════════════════════════════════════════════
class ColumnWorkingMemory(nn.Module):
"""
Working memory within a cortical column.
Three timescales (brain WM hierarchy):
1. NMDA attractor slots (Thm 31): Slow decay (~277 tokens), 4 competitive slots
2. Activity-silent trace (Thm 35): Tsodyks-Markram facilitation/depression
3. Phonological loop (Thm 36): Decay + rehearsal, 8 slots
All gated and identity-at-init.
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.cfg = cfg
d = cfg.d_column
# Persistent WM state (volatile — like real WM, not saved to disk)
# Persists across sequential forward calls, resets on batch size change.
self._nmda_state: Optional[torch.Tensor] = None # [B, K, d_slot]
self._silent_u: Optional[torch.Tensor] = None # [B, d_trace]
self._silent_x: Optional[torch.Tensor] = None # [B, d_trace]
self._phono_state: Optional[torch.Tensor] = None # [B, K, d_slot]
self._phono_ptr: int = 0
self._last_batch_size: int = -1
if not cfg.wm_enabled:
return
# ── NMDA Attractor Slots ────────────────────────────────────
K = cfg.nmda_slots
d_slot = cfg.nmda_d_slot
self.nmda_K = K
self.nmda_d_slot = d_slot
self.nmda_write = nn.Linear(d, d_slot, bias=False)
self.nmda_read = nn.Linear(d_slot, d, bias=False)
nn.init.zeros_(self.nmda_read.weight)
self.nmda_score = nn.Linear(d, K, bias=False)
self.nmda_decay_bias = nn.Parameter(torch.full((K,), cfg.nmda_decay_init))
self.nmda_gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
self.nmda_norm = RMSNorm(d)
# ── Activity-Silent Trace ───────────────────────────────────
d_trace = cfg.silent_d_trace
self.silent_d_trace = d_trace
self.silent_store = nn.Linear(d, d_trace, bias=False)
self.silent_retrieve = nn.Linear(d_trace, d, bias=False)
nn.init.zeros_(self.silent_retrieve.weight)
self.silent_write_gate = nn.Linear(d, 1, bias=True)
nn.init.constant_(self.silent_write_gate.bias, -1.0)
self.silent_facil_decay = nn.Parameter(torch.tensor(cfg.silent_facil_init))
self.silent_depress_decay = nn.Parameter(torch.tensor(cfg.silent_depress_init))
self.silent_depress_frac = nn.Parameter(torch.tensor(-2.0))
self.silent_gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
self.silent_norm = RMSNorm(d)
# ── Phonological Loop ───────────────────────────────────────
K_p = cfg.phono_capacity
d_p = cfg.phono_d_slot
self.phono_K = K_p
self.phono_d_slot = d_p
self.phono_write = nn.Linear(d, d_p, bias=False)
self.phono_query = nn.Linear(d, d_p, bias=False)
self.phono_read = nn.Linear(d_p, d, bias=False)
nn.init.zeros_(self.phono_read.weight)
self.phono_write_gate = nn.Linear(d, 1, bias=True)
nn.init.constant_(self.phono_write_gate.bias, -2.0)
self.phono_decay = nn.Parameter(torch.tensor(4.0)) # sigmoid(4)≈0.982
self.phono_rehearsal_str = nn.Parameter(torch.tensor(-1.0)) # sigmoid(-1)≈0.27
self.phono_gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
self.phono_norm = RMSNorm(d)
def reset_wm(self):
"""Reset working memory state. Call on new context/document."""
self._nmda_state = None
self._silent_u = None
self._silent_x = None
self._phono_state = None
self._phono_ptr = 0
self._last_batch_size = -1
@staticmethod
def _scatter_slot(slots: torch.Tensor, idx: int, new_val: torch.Tensor) -> torch.Tensor:
"""Functionally update slots[:, idx] = new_val without in-place ops.
slots: [B, K, D], new_val: [B, D] → [B, K, D]"""
K = slots.shape[1]
mask = torch.zeros(K, device=slots.device, dtype=slots.dtype)
mask[idx] = 1.0
mask = mask.view(1, K, 1) # [1, K, 1]
return slots * (1.0 - mask) + new_val.unsqueeze(1) * mask
def forward(self, h: torch.Tensor) -> torch.Tensor:
"""
h: [B, T, D_col]
Returns: [B, T, D_col] — h with WM contributions added
All operations are functional (no in-place) to support autograd backward.
"""
if not self.cfg.wm_enabled:
return h
B, T, D = h.shape
# Reset persistent state if batch size changed (new context)
if B != self._last_batch_size:
self.reset_wm()
self._last_batch_size = B
# ── NMDA Attractor Slots ────────────────────────────────────
nmda_g = torch.sigmoid(self.nmda_gate_raw)
if nmda_g > 0.01:
decay = torch.sigmoid(self.nmda_decay_bias) # [K]
# Persistent: use stored state if available (cross-sequence WM)
if self._nmda_state is not None and self._nmda_state.shape[0] == B:
slots = self._nmda_state.detach().to(h.device)
else:
slots = torch.zeros(B, self.nmda_K, self.nmda_d_slot, device=h.device)
wm_outputs = []
for t in range(T):
h_t = self.nmda_norm(h[:, t]) # [B, D]
# Slot competition
scores = self.nmda_score(h_t) # [B, K]
write_prob = F.softmax(scores, dim=-1) # [B, K]
# Write — vectorized over K (each slot update is independent)
content = self.nmda_write(h_t) # [B, d_slot]
w = write_prob.unsqueeze(-1) # [B, K, 1]
slots = decay.view(1, -1, 1) * slots + w * content.unsqueeze(1)
# Read (attention over slots)
read_scores = torch.bmm(
slots, content.unsqueeze(-1)
).squeeze(-1) # [B, K]
read_weights = F.softmax(read_scores, dim=-1) # [B, K]
read = torch.bmm(read_weights.unsqueeze(1), slots).squeeze(1) # [B, d_slot]
wm_outputs.append(self.nmda_read(read))
wm_out = torch.stack(wm_outputs, dim=1) # [B, T, D]
h = h + nmda_g * wm_out
# Persist NMDA state for next forward call
self._nmda_state = slots.detach()
# ── Activity-Silent Trace ───────────────────────────────────
silent_g = torch.sigmoid(self.silent_gate_raw)
if silent_g > 0.01:
facil_a = torch.sigmoid(self.silent_facil_decay)
depress_a = torch.sigmoid(self.silent_depress_decay)
depress_f = torch.sigmoid(self.silent_depress_frac) * 0.5
# Persistent: use stored state if available
if self._silent_u is not None and self._silent_u.shape[0] == B:
u = self._silent_u.detach().to(h.device)
x = self._silent_x.detach().to(h.device)
else:
u = torch.zeros(B, self.silent_d_trace, device=h.device) # Facilitation
x = torch.ones(B, self.silent_d_trace, device=h.device) # Depression (available)
trace_outputs = []
for t in range(T):
h_t = self.silent_norm(h[:, t])
write_g = torch.sigmoid(self.silent_write_gate(h_t)) # [B, 1]
content = self.silent_store(h_t) # [B, d_trace]
# Tsodyks-Markram dynamics
release = u * x # Effective release
trace_outputs.append(self.silent_retrieve(release))
# Update facilitation: u → facil_a * u + (1-u) * write_g * |content|
u = facil_a * u + (1.0 - u) * write_g * torch.abs(content)
# Update depression: x → depress_a * x + (1-x)/tau - depress_f * u * x
x = depress_a * x + (1.0 - depress_a) * (1.0 - x) - depress_f * u * x
x = x.clamp(min=0.0, max=1.0)
trace_out = torch.stack(trace_outputs, dim=1) # [B, T, D]
h = h + silent_g * trace_out
# Persist Silent state for next forward call
self._silent_u = u.detach()
self._silent_x = x.detach()
# ── Phonological Loop ───────────────────────────────────────
phono_g = torch.sigmoid(self.phono_gate_raw)
if phono_g > 0.01:
p_decay = torch.sigmoid(self.phono_decay)
r_str = torch.sigmoid(self.phono_rehearsal_str)
# Persistent: use stored state if available
if self._phono_state is not None and self._phono_state.shape[0] == B:
slots = self._phono_state.detach().to(h.device)
write_ptr = self._phono_ptr
else:
slots = torch.zeros(B, self.phono_K, self.phono_d_slot, device=h.device)
write_ptr = 0
phono_outputs = []
for t in range(T):
h_t = self.phono_norm(h[:, t])
w_gate = torch.sigmoid(self.phono_write_gate(h_t)) # [B, 1]
# Passive decay (functional — creates new tensor)
slots = p_decay * slots
# Rehearsal (functional scatter update)
if t > 0:
most_recent = write_ptr - 1 if write_ptr > 0 else self.phono_K - 1
rehearsed = slots[:, most_recent] + r_str * slots[:, most_recent]
slots = self._scatter_slot(slots, most_recent, rehearsed)
# Write (functional scatter update)
content = self.phono_write(h_t) # [B, d_slot]
idx = write_ptr % self.phono_K
new_slot = slots[:, idx] * (1.0 - w_gate) + w_gate * content
slots = self._scatter_slot(slots, idx, new_slot)
write_ptr = (write_ptr + 1) % self.phono_K
# Read (query-based attention)
query = self.phono_query(h_t) # [B, d_slot]
read_scores = torch.bmm(
slots, query.unsqueeze(-1)
).squeeze(-1) # [B, K]
read_weights = F.softmax(read_scores, dim=-1)
read = torch.bmm(read_weights.unsqueeze(1), slots).squeeze(1)
phono_outputs.append(self.phono_read(read))
phono_out = torch.stack(phono_outputs, dim=1) # [B, T, D]
h = h + phono_g * phono_out
# Persist Phono state for next forward call
self._phono_state = slots.detach()
self._phono_ptr = write_ptr
return h
# ═══════════════════════════════════════════════════════════════════════
# Column Oscillatory Dynamics
# ═══════════════════════════════════════════════════════════════════════
class ColumnOscillations(nn.Module):
"""
Oscillatory dynamics within a cortical column (Thm 53-55).
Nested oscillations: gamma → theta → alpha → delta
Cross-frequency phase-amplitude coupling (PAC):
A_gamma = 1 + κ1*cos(φ_θ) + κ2*cos(φ_δ) - κ3*(1+cos(φ_α))/2
Periods are learnable via bare softplus (positive guarantee).
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.enabled = cfg.oscillations_enabled
if not self.enabled:
return
d = cfg.d_column
r = 32 # Rank-reduced interaction
# Learnable periods
self.period_theta_raw = nn.Parameter(torch.tensor(math.log(math.exp(cfg.theta_period) - 1)))
self.period_alpha_raw = nn.Parameter(torch.tensor(math.log(math.exp(cfg.alpha_period) - 1)))
self.period_delta_raw = nn.Parameter(torch.tensor(math.log(math.exp(cfg.delta_period) - 1)))
# PAC coupling strengths — theta-gamma coupling starts active (small)
# Jensen & Colgin 2007: theta-gamma PAC is present even at rest
self.kappa1_raw = nn.Parameter(torch.tensor(0.3)) # theta-gamma (primary)
self.kappa2_raw = nn.Parameter(torch.tensor(0.0)) # delta-gamma
self.kappa3_raw = nn.Parameter(torch.tensor(0.0)) # alpha suppression
# Phase-content interaction
self.W_content = nn.Linear(d, r, bias=False)
self.W_phase = nn.Linear(6, r, bias=False) # sin/cos for theta, alpha, delta
self.W_out = nn.Linear(r, d, bias=False)
nn.init.normal_(self.W_out.weight, std=0.01) # Small non-zero → oscillations provide signal
self.gate_raw = nn.Parameter(torch.tensor(cfg.gate_init))
def forward(self, h: torch.Tensor) -> torch.Tensor:
"""h: [B, T, D_col] → [B, T, D_col]"""
if not self.enabled:
return h
B, T, D = h.shape
gate = torch.sigmoid(self.gate_raw)
# Compute periods
P_theta = F.softplus(self.period_theta_raw)
P_alpha = F.softplus(self.period_alpha_raw)
P_delta = F.softplus(self.period_delta_raw)
# Compute phases for each position
t = torch.arange(T, device=h.device, dtype=h.dtype)
phi_theta = 2 * math.pi * t / P_theta
phi_alpha = 2 * math.pi * t / P_alpha
phi_delta = 2 * math.pi * t / P_delta
# Phase features [T, 6]
phase_features = torch.stack([
phi_theta.sin(), phi_theta.cos(),
phi_alpha.sin(), phi_alpha.cos(),
phi_delta.sin(), phi_delta.cos(),
], dim=-1)
# PAC amplitude modulation
kappa1 = torch.tanh(self.kappa1_raw)
kappa2 = torch.tanh(self.kappa2_raw)
kappa3 = torch.tanh(self.kappa3_raw)
A_gamma = 1.0 + kappa1 * phi_theta.cos() + kappa2 * phi_delta.cos() \
- kappa3 * (1.0 + phi_alpha.cos()) / 2.0 # [T]
# Phase-content interaction
content = self.W_content(h) # [B, T, r]
phase_proj = self.W_phase(phase_features).unsqueeze(0) # [1, T, r]
interaction = torch.tanh(content + phase_proj) # [B, T, r]
modulation = self.W_out(interaction) # [B, T, D]
# Apply with PAC amplitude
A = A_gamma.unsqueeze(0).unsqueeze(-1) # [1, T, 1]
return h + gate * A * modulation
# ═══════════════════════════════════════════════════════════════════════
# BCM Homeostasis
# ═══════════════════════════════════════════════════════════════════════
class BCMHomeostasis(nn.Module):
"""
Bienenstock-Cooper-Munro homeostatic plasticity (Thm 7).
Sliding threshold: θ_BCM tracks mean postsynaptic activity.
Learning rule: Δw ∝ y(y - θ_BCM)x
- y > θ_BCM: potentiation (strengthen active synapses)
- y < θ_BCM: depression (weaken inactive synapses)
Prevents runaway Hebbian learning. Essential for stability.
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.enabled = cfg.bcm_enabled
if not self.enabled:
return
self.tau = cfg.bcm_tau
# Sliding threshold (tracked, not learned)
self.register_buffer('theta_bcm', torch.tensor(1.0))
self.register_buffer('_n_updates', torch.tensor(0, dtype=torch.long))
@torch.no_grad()
def update_threshold(self, activity: torch.Tensor):
"""Update BCM threshold from mean squared activity."""
if not self.enabled:
return
mean_sq = activity.pow(2).mean()
if torch.isfinite(mean_sq):
alpha = 1.0 / self.tau
self.theta_bcm.lerp_(mean_sq, alpha)
self._n_updates += 1
# BCM modulation is applied directly in L23.hebbian_update_bcm()
# which uses self.theta_bcm as the sliding threshold.
# ═══════════════════════════════════════════════════════════════════════
# Metaplasticity
# ═══════════════════════════════════════════════════════════════════════
class Metaplasticity(nn.Module):
"""
Metaplasticity — learning to learn (Thm 42).
Adjusts learning rates based on recent plasticity history.
High recent plasticity → lower learning rate (stabilize).
Low recent plasticity → higher learning rate (explore).
Bienenstock 1982, Abraham & Bear 1996.
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.enabled = cfg.metaplasticity_enabled
if not self.enabled:
return
self.register_buffer('plasticity_ema', torch.tensor(1.0))
self.tau = 500.0 # Slow timescale
@torch.no_grad()
def update(self, weight_change_magnitude: float):
"""Track recent plasticity."""
if not self.enabled:
return
val = torch.tensor(weight_change_magnitude, device=self.plasticity_ema.device)
if torch.isfinite(val):
self.plasticity_ema.lerp_(val, 1.0 / self.tau)
def get_lr_multiplier(self) -> float:
"""Return learning rate multiplier based on recent plasticity."""
if not self.enabled:
return 1.0
# Inverse relationship: high plasticity → low LR
return 1.0 / (1.0 + self.plasticity_ema.item())
# ═══════════════════════════════════════════════════════════════════════
# Lateral Column Connections (Horizontal Connections)
# ═══════════════════════════════════════════════════════════════════════
class LateralColumnConnection(nn.Module):
"""
Horizontal connections between cortical columns at the same hierarchical level.
In the brain, columns don't ONLY communicate top-down/bottom-up.
Dense horizontal connections in L2/3 span 2-3mm, connecting columns
processing related features. These enable:
- Feature binding across columns (perceptual grouping)
- Surround suppression (competition between similar representations)
- Synchronization (coordinated gamma oscillations)
Disease mapping:
Schizophrenia (disconnection syndrome) → disrupted lateral connections
→ inability to bind features → fragmented perception / thought disorder
Autism → altered lateral connectivity → weak central coherence
Architecture:
Each column sends a message to its neighbors (adjacent columns).
Messages are low-rank projections gated by gamma oscillations.
Receiving column integrates lateral input via L2/3.
Identity at init: W_send=0 → no lateral communication initially.
After training: columns coordinate via learned lateral signals.
"""
def __init__(self, cfg: V11Config):
super().__init__()
d = cfg.d_model
n = cfg.n_columns
r = max(d // 8, 32) # Low-rank bottleneck (efficient)
# Each column has a send and receive projection
# Only connect to immediate neighbors (sparse, not fully connected)
self.W_send = nn.ModuleList([nn.Linear(d, r, bias=False) for _ in range(n)])
self.W_recv = nn.ModuleList([nn.Linear(r, d, bias=False) for _ in range(n)])
# Identity at init: no lateral signal
for w in self.W_send:
nn.init.zeros_(w.weight)
for w in self.W_recv:
nn.init.normal_(w.weight, std=0.01)
# Per-column gate
self.gate_raws = nn.ParameterList([
nn.Parameter(torch.tensor(cfg.gate_init)) for _ in range(n)
])
def forward(self, column_outputs: list) -> List[torch.Tensor]:
"""
Compute lateral signals between adjacent columns.
Args:
column_outputs: list of ColumnOutput from all columns
Returns:
lateral_signals: list of [B, T, D] — lateral modulation per column
"""
n = len(column_outputs)
lateral_signals = []
for i in range(n):
gate = torch.sigmoid(self.gate_raws[i])
# Collect messages from neighbors (i-1, i+1)
neighbor_msgs = []
if i > 0:
msg = self.W_send[i - 1](column_outputs[i - 1].output)
neighbor_msgs.append(msg)
if i < n - 1:
msg = self.W_send[i + 1](column_outputs[i + 1].output)
neighbor_msgs.append(msg)
if not neighbor_msgs:
lateral_signals.append(torch.zeros_like(column_outputs[i].output))
continue
# Average neighbor messages (could be 1 or 2 neighbors)
avg_msg = sum(neighbor_msgs) / len(neighbor_msgs)
# Receive and gate
lateral = self.W_recv[i](avg_msg)
lateral_signals.append(gate * lateral)
return lateral_signals
# ═══════════════════════════════════════════════════════════════════════
# Full Cortical Column
# ═══════════════════════════════════════════════════════════════════════
class CorticalColumn(nn.Module):
"""
A single cortical column — the fundamental compute unit of NCT V11.
Replaces a transformer block.
6 layers with distinct neuroscience-grounded functions:
L4: Thalamic input (feedforward)
L1: Top-down modulation (apical context)
L2/3: Lateral association (windowed Hebbian recall, O(T×w))
Interneurons: VIP → SST → PV
Working memory: NMDA + Silent + Phono
Oscillations: Nested PAC
L5: Output + prediction generation
L6: Thalamic feedback
All components are identity-at-init.
Data flow:
ff_input → L4 → (+L1 top-down) → L2/3 → Interneurons → WM → Osc → L5 → output
→ prediction
L6 → thal_feedback
"""
def __init__(self, cfg: V11Config, column_idx: int):
super().__init__()
self.cfg = cfg
self.column_idx = column_idx
# Core layers
self.L4 = L4_ThalamicInput(cfg)
self.L1 = L1_TopDownModulation(cfg)
self.L23 = L23_LateralAssociation(cfg)
self.L5 = L5_OutputPrediction(cfg)
self.L6 = L6_ThalamicFeedback(cfg)
# Interneurons
self.interneurons = ColumnInterneurons(cfg)
# Working memory
self.wm = ColumnWorkingMemory(cfg)
# Oscillations
self.oscillations = ColumnOscillations(cfg)
# BCM homeostasis (per-column)
self.bcm = BCMHomeostasis(cfg)
# Metaplasticity (per-column)
self.metaplasticity = Metaplasticity(cfg)
# Structural plasticity (Theorem E)
if cfg.structural_plasticity:
self.L23.init_structural_plasticity()
# Residual projection (if d_column != d_model)
if cfg.d_column != cfg.d_model:
self.residual_proj = nn.Linear(cfg.d_model, cfg.d_model, bias=False)
else:
self.residual_proj = None
def forward(
self,
ff_input: torch.Tensor,
td_context: Optional[torch.Tensor] = None,
sigma2_prev: Optional[torch.Tensor] = None,
) -> ColumnOutput:
"""
Forward pass through the cortical column.
Biological data flow (corrected interneuron placement):
L4 → L1 → SST+VIP → L2/3(settle) → WM → Osc → PV → L5 → output
Args:
ff_input: [B, T, D_model] — feedforward from lower column (via thalamus)
td_context: [B, T, D_model] — top-down from higher column's prediction
sigma2_prev: [B, T, 1] — previous column's prediction precision (for L5)
No RoPE: L2/3 uses Windowed Hebbian Association (O(T×w), not attention).
Causality is implicit in the backward-looking window.
"""
# L4: Thalamic input processing
l4_out = self.L4(ff_input) # [B, T, D_col]
h = l4_out
# L1: Top-down modulation (if available)
td_signal = None
if td_context is not None:
td_signal = self.L1(td_context)
h = h + td_signal # Apical modulation
# SST + VIP: Dendritic inhibition (BEFORE L2/3 — apical gate)
h = self.interneurons.apply_dendritic_inhibition(h, td_signal=td_signal)
# L2/3: Windowed Hebbian Association (no RoPE, no O(T²) attention)
l23_input = h
for _ in range(self.cfg.n_settle_steps):
l23_out = self.L23(h)
h = l23_input + l23_out # Re-anchor to input each step (settling)
l23_output = h
# Working memory
h = self.wm(h)
# Oscillatory dynamics
h = self.oscillations(h)
# PV/Chandelier: Output veto (AFTER computation, BEFORE L5 — axon initial segment)
h = self.interneurons.apply_output_veto(h)
# L5: Dendritic FFN + prediction (receives L4 bottom-up + L1 top-down + σ²)
output_delta, prediction, sigma2 = self.L5(
h, l4_input=l4_out, td_context=td_signal, sigma2_prev=sigma2_prev
)
# Store h_norm for analytical PC gradient (accessed by PredictiveCodingOptimizer)
self._last_l5_h_norm = self.L5.norm(h).detach()
# Output with residual connection (+ residual_proj if dimensions differ)
if self.residual_proj is not None:
output = self.residual_proj(ff_input) + output_delta
else:
output = ff_input + output_delta
# L6: Thalamic feedback
thal_feedback = self.L6(h)
return ColumnOutput(
output=output,
prediction=prediction,
thal_feedback=thal_feedback,
state=h,
sigma2=sigma2,
l23_input=l23_input,
l23_output=l23_output,
)
def get_gate_values(self) -> dict:
"""Return all gate values for monitoring."""
i = self.column_idx
gates = {
f'col{i}_l23': torch.sigmoid(self.L23.gate_raw).item(),
f'col{i}_l1': torch.sigmoid(self.L1.gate_raw).item(),
f'col{i}_l6': torch.sigmoid(self.L6.gate_raw).item(),
}
if self.cfg.vip_enabled:
gates[f'col{i}_vip'] = torch.sigmoid(self.interneurons.vip_gate_raw).item()
if self.cfg.sst_enabled:
gates[f'col{i}_sst'] = torch.sigmoid(self.interneurons.sst_gate_raw).item()
if self.cfg.pv_enabled:
gates[f'col{i}_pv'] = torch.sigmoid(self.interneurons.pv_gate_raw).item()
# WM gates (were missing — now monitored)
if self.cfg.wm_enabled:
gates[f'col{i}_nmda'] = torch.sigmoid(self.wm.nmda_gate_raw).item()
gates[f'col{i}_silent'] = torch.sigmoid(self.wm.silent_gate_raw).item()
gates[f'col{i}_phono'] = torch.sigmoid(self.wm.phono_gate_raw).item()
# Oscillation gate (was missing)
if self.cfg.oscillations_enabled:
gates[f'col{i}_osc'] = torch.sigmoid(self.oscillations.gate_raw).item()
# L5 dendritic gates
if self.cfg.l5_dendritic:
# Report mean dendritic gate activation (bias-only at init)
gates[f'col{i}_dend_bias'] = torch.sigmoid(self.L5.W_dend.bias.mean()).item()
gates[f'col{i}_apical_bias'] = torch.sigmoid(self.L5.W_apical.bias.mean()).item()
# Structural plasticity density
if self.cfg.structural_plasticity:
gates[f'col{i}_density'] = self.L23.get_connection_density()
return gates