Skip to content
Part 11 of 20

Cortical Column: The Fundamental Compute Unit

Krrish Choudhary·March 23, 2026

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–500μ\mum 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 ∼\sim7.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:

L4⏟input→L1⏟feedback→SST+VIP⏟pre-L2/3→L2/3⏟association→WM⏟persistence→Osc⏟timing→PV⏟post-comp→L5⏟output→L6⏟modulation\underbrace{\text{L4}}_{\text{input}} \rightarrow \underbrace{\text{L1}}_{\text{feedback}} \rightarrow \underbrace{\text{SST+VIP}}_{\text{pre-L2/3}} \rightarrow \underbrace{\text{L2/3}}_{\text{association}} \rightarrow \underbrace{\text{WM}}_{\text{persistence}} \rightarrow \underbrace{\text{Osc}}_{\text{timing}} \rightarrow \underbrace{\text{PV}}_{\text{post-comp}} \rightarrow \underbrace{\text{L5}}_{\text{output}} \rightarrow \underbrace{\text{L6}}_{\text{modulation}}
Complete data flow through a single cortical column. All nine processing stages are shown with their equations and initialization values. Stage numbers () indicate the biological processing order. The residual connection (left, dashed) bypasses all computation, ensuring identity-at-init when all gates σ(g_0!=!-2) approx 0.12. BCM homeostasis, metaplasticity, and synaptic scaling (left panel) regulate Hebbian learning in L2/3. L5 produces three outputs: the column representation h_i, a top-down prediction hatx_i-1 for predictive coding, and precision σ^2 for uncertainty-aware processing.
Figure 17. Complete data flow through a single cortical column. All nine processing stages are shown with their equations and initialization values. Stage numbers () indicate the biological processing order. The residual connection (left, dashed) bypasses all computation, ensuring identity-at-init when all gates σ(g0 ⁣= ⁣−2)≈0.12\sigma(g_0\!=\!{-2}) \approx 0.12. BCM homeostasis, metaplasticity, and synaptic scaling (left panel) regulate Hebbian learning in L2/3. L5 produces three outputs: the column representation hi\mathbf{h}_i, a top-down prediction x^i−1\hat{\mathbf{x}}_{i-1} for predictive coding, and precision σ2\sigma^2 for uncertainty-aware processing.
(Illustrated) Complete data flow through a single cortical column. All nine processing stages are shown with their equations and initialization values. The residual connection (dashed) bypasses all computation...
Figure 18. (Illustrated) Complete data flow through a single cortical column. All nine processing stages are shown with their equations and initialization values. The residual connection (dashed) bypasses all computation...

Layer 4: Thalamic Input

Definition 3 (Layer 4). The thalamic input layer projects feedforward input from inter-column dimension to intra-column dimension: hL4=RMSNorm(WL4xin),WL4∈Rdcol×dmodel\mathbf{h}_{\text{L4}} = \text{RMSNorm}(W_{\text{L4}} \mathbf{x}_{\text{in}}), \qquad W_{\text{L4}} \in \mathbb{R}^{d_{\text{col}} \times d_{\text{model}}}

Initialization: If dcol=dmodeld_{\text{col}} = d_{\text{model}} (default), WL4=IW_{\text{L4}} = I (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 X∈RT×d\mathbf{X} \in \mathbb{R}^{T \times d} be a sequence of token representations. The L2/3 windowed Hebbian association computes, for each position tt and head hh: yth=Wassochxth+∑j=t−wtexp⁡(wdh⋅∣xth−xjh∣)∑k=t−wtexp⁡(wdh⋅∣xth−xkh∣)⋅Wvalxjh\mathbf{y}_t^h = W_{\text{assoc}}^h \mathbf{x}_t^h + \sum_{j=t-w}^{t} \frac{\exp(\mathbf{w}_d^h \cdot |\mathbf{x}_t^h - \mathbf{x}_j^h|)}{\sum_{k=t-w}^{t} \exp(\mathbf{w}_d^h \cdot |\mathbf{x}_t^h - \mathbf{x}_k^h|)} \cdot W_{\text{val}} \mathbf{x}_j^h with complexity O(T⋅w⋅d)O(T \cdot w \cdot d) compared to O(T2⋅d)O(T^2 \cdot d) for self-attention. For T=4096T = 4096 and w=16w = 16, this is 256×256\times cheaper.

Complexity proof. Self-attention computes QK⊤QK^\top over all T2T^2 pairs. L2/3 computes associations only within a causal window of size w+1w+1. Per position: w+1w+1 comparisons ×dh\times d_h dimensions ×H\times H heads =O(w⋅d)= O(w \cdot d). Over TT positions: O(T⋅w⋅d)O(T \cdot w \cdot d). ◻

The five steps of the L2/3 mechanism:

Step 1, Content-addressable recall: ath=Wassochxth\mathbf{a}_t^h = W_{\text{assoc}}^h \mathbf{x}_t^h where Wassoch∈Rdh×dhW_{\text{assoc}}^h \in \mathbb{R}^{d_h \times d_h} 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 vjh=Wvalxjh\mathbf{v}_j^h = W_{\text{val}} \mathbf{x}_j^h for j∈[t−w,t]j \in [t-w, t] (causal, zero-padded). Window size w=16w = 16 tokens = 2 theta cycles.

Step 3, Distance-weighted context: αtjh=softmax(wdh⋅∣xth−xjh∣)\alpha_{tj}^h = \text{softmax}(\mathbf{w}_d^h \cdot |\mathbf{x}_t^h - \mathbf{x}_j^h|) where wdh∈Rdh\mathbf{w}_d^h \in \mathbb{R}^{d_h} initialized at 0\mathbf{0} (uniform weighting at init).

Step 4, k-WTA + anti-Hebbian: Retain only top 15% of activations (sparse coding). Anti-Hebbian lateral weights WlathW_{\text{lat}}^h (init 0\mathbf{0}) enforce decorrelation.

Step 5, Output: WoutW_{\text{out}} (init 0\mathbf{0}) projects combined output. Gate σ(gL2/3)\sigma(g_{\text{L2/3}}) with g0=−2.0g_0 = -2.0.

L2/3 Windowed Hebbian Association, 5-step mechanism replacing self-attention.
Figure 19. L2/3 Windowed Hebbian Association, 5-step mechanism replacing self-attention.
(Illustrated) L2/3 Windowed Hebbian Association, 5-step mechanism replacing self-attention.
Figure 20. (Illustrated) L2/3 Windowed Hebbian Association, 5-step mechanism replacing self-attention.

Proposition 3 (Hebbian Update Rule). The association weights are updated by: ΔWassoch=ηH⋅yh(yh−θBCM)⋅(xh)⊤(Hebbian + BCM)ΔWlath=−ηH⋅yh(yh)⊤(anti-Hebbian)\begin{aligned} \Delta W_{\text{assoc}}^h &= \eta_H \cdot \mathbf{y}^h (\mathbf{y}^h - \theta_{\text{BCM}}) \cdot (\mathbf{x}^h)^\top \qquad &\text{(Hebbian + BCM)} \\ \Delta W_{\text{lat}}^h &= -\eta_H \cdot \mathbf{y}^h (\mathbf{y}^h)^\top \qquad &\text{(anti-Hebbian)} \end{aligned} 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 (∥ϵ∥>2.0\|\boldsymbol{\epsilon}\| > 2.0), and pruning where gates approach zero (σ(g)<0.01\sigma(g) < 0.01), checked every 1,000 steps.

Structural plasticity: grow connections where PE is high, prune where gates are near zero.
Figure 21. Structural plasticity: grow connections where PE is high, prune where gates are near zero.
(Illustrated) Structural plasticity: grow connections where PE is high, prune where gates are near zero.
Figure 22. (Illustrated) Structural plasticity: grow connections where PE is high, prune where gates are near zero.

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): K=4K = 4 competitive slots with learned exponential decay: slotst+1=σ(βk)⏟decay⋅slotst+softmax(Wsht)⏟write weight⋅Wwht⏟content\text{slots}_{t+1} = \underbrace{\sigma(\beta_k)}_{\text{decay}} \cdot \text{slots}_t + \underbrace{\text{softmax}(W_s \mathbf{h}_t)}_{\text{write weight}} \cdot \underbrace{W_w \mathbf{h}_t}_{\text{content}} Decay bias βk,init=6.0⇒σ(6)≈0.9975\beta_{k,\text{init}} = 6.0 \Rightarrow \sigma(6) \approx 0.9975, giving half-life ≈277\approx 277 tokens.

NMDA attractor slot dynamics: 4 competitive slots with exponential decay (α approx 0.9975, half-life approx 277 tokens). Write via softmax competition over slots. Read via query-based attention. State persists across sequential forward passes.
Figure 23. NMDA attractor slot dynamics: 4 competitive slots with exponential decay (α≈0.9975\alpha \approx 0.9975, half-life ≈277\approx 277 tokens). Write via softmax competition over slots. Read via query-based attention. State persists across sequential forward passes.
(Illustrated) NMDA attractor slot dynamics: 4 competitive slots with exponential decay (α approx 0.9975, half-life approx 277 tokens). Write via softmax competition over slots. Read via query-based at...
Figure 24. (Illustrated) NMDA attractor slot dynamics: 4 competitive slots with exponential decay (α≈0.9975\alpha \approx 0.9975, half-life ≈277\approx 277 tokens). Write via softmax competition over slots. Read via query-based at...

2. Activity-Silent Trace (Mongillo et al., 2008): Tsodyks-Markram short-term plasticity dynamics: releaset=ut⋅xtut+1=αfut+(1−ut)⋅wg⋅∣contentt∣(facilitation)xt+1=αdxt+(1−αd)(1−xt)−δfutxt(depression)\begin{aligned} \text{release}_t &= u_t \cdot x_t \\ u_{t+1} &= \alpha_f u_t + (1 - u_t) \cdot w_g \cdot |\text{content}_t| \qquad &(\text{facilitation}) \\ x_{t+1} &= \alpha_d x_t + (1 - \alpha_d)(1 - x_t) - \delta_f u_t x_t \qquad &(\text{depression}) \end{aligned} where αf=σ(4.6)≈0.990\alpha_f = \sigma(4.6) \approx 0.990, αd=σ(2.5)≈0.924\alpha_d = \sigma(2.5) \approx 0.924.

Tsodyks-Markram activity-silent trace: facilitation variable u builds up with input (slow decay α_f = 0.990), depression variable x depletes (faster recovery α_d = 0.924). The effective release u times x captures the interaction. Information is stored in synaptic weights rather than sustained firing, hence “activity-silent.”
Figure 25. Tsodyks-Markram activity-silent trace: facilitation variable uu builds up with input (slow decay αf=0.990\alpha_f = 0.990), depression variable xx depletes (faster recovery αd=0.924\alpha_d = 0.924). The effective release u×xu \times x captures the interaction. Information is stored in synaptic weights rather than sustained firing, hence “activity-silent.”
(Illustrated) Tsodyks-Markram activity-silent trace: facilitation variable u builds up with input (slow decay α_f = 0.990), depression variable x depletes (faster recovery α_d = 0.924). The eff...
Figure 26. (Illustrated) Tsodyks-Markram activity-silent trace: facilitation variable uu builds up with input (slow decay αf=0.990\alpha_f = 0.990), depression variable xx depletes (faster recovery αd=0.924\alpha_d = 0.924). The eff...

3. Phonological Loop: Circular buffer with passive decay and rehearsal: slotst+1=pdecay⋅slotst+write(ht,ptr),pdecay=σ(4.0)≈0.982\text{slots}_{t+1} = p_{\text{decay}} \cdot \text{slots}_t + \text{write}(\mathbf{h}_t, \text{ptr}), \qquad p_{\text{decay}} = \sigma(4.0) \approx 0.982 Kp=8K_p = 8 slots (Miller’s 7±27 \pm 2), rehearsal strength r=σ(−1.0)≈0.27r = \sigma(-1.0) \approx 0.27.

Phonological loop: 8-slot circular buffer with passive exponential decay (times 0.982 per step) and active rehearsal of the most recent slot (times 0.27). Write pointer advances modulo 8. Read via query-based attention over all slots. Models the brain’s verbal working memory (“inner speech”).
Figure 27. Phonological loop: 8-slot circular buffer with passive exponential decay (×0.982\times 0.982 per step) and active rehearsal of the most recent slot (×0.27\times 0.27). Write pointer advances modulo 8. Read via query-based attention over all slots. Models the brain’s verbal working memory (“inner speech”).
(Illustrated) Phonological loop: 8-slot circular buffer with passive exponential decay (times 0.982 per step) and active rehearsal of the most recent slot (times 0.27). Write pointer advances modulo 8. Rea...
Figure 28. (Illustrated) Phonological loop: 8-slot circular buffer with passive exponential decay (×0.982\times 0.982 per step) and active rehearsal of the most recent slot (×0.27\times 0.27). Write pointer advances modulo 8. Rea...

All three subsystems are gated (gate init −2.0-2.0), identity-at-init (Wread=0W_{\text{read}} = \mathbf{0}), and maintain persistent state across forward passes (unlike transformer layers, which are stateless).

Working memory hierarchy: three biological timescales. NMDA attractor slots provide slow, sustained storage (half-life approx277 tokens). Activity-silent traces use synaptic facilitation/depression for medium-term storage. The phonological loop provides fast, capacity-limited rehearsal (8 slots, matching Miller’s 7pm2). All three are persistent, gated, and identity-at-init.
Figure 29. Working memory hierarchy: three biological timescales. NMDA attractor slots provide slow, sustained storage (half-life ≈\approx277 tokens). Activity-silent traces use synaptic facilitation/depression for medium-term storage. The phonological loop provides fast, capacity-limited rehearsal (8 slots, matching Miller’s 7±27\pm2). All three are persistent, gated, and identity-at-init.
(Illustrated) Working memory hierarchy: three biological timescales. NMDA attractor slots provide slow, sustained storage (half-life approx277 tokens). Activity-silent traces use synaptic facilitation/depress...
Figure 30. (Illustrated) Working memory hierarchy: three biological timescales. NMDA attractor slots provide slow, sustained storage (half-life ≈\approx277 tokens). Activity-silent traces use synaptic facilitation/depress...

Oscillatory Dynamics: Nested PAC

Theorem 12 (Phase-Amplitude Coupling). Cross-frequency coupling modulates column activity at four nested timescales: Aγ(t)=1+κ1cos⁡ϕθ(t)⏟theta-gamma+κ2cos⁡ϕδ(t)⏟delta-gamma−κ31+cos⁡ϕα(t)2⏟alpha suppressionA_\gamma(t) = 1 + \underbrace{\kappa_1 \cos\phi_\theta(t)}_{\text{theta-gamma}} + \underbrace{\kappa_2 \cos\phi_\delta(t)}_{\text{delta-gamma}} - \underbrace{\kappa_3 \frac{1 + \cos\phi_\alpha(t)}{2}}_{\text{alpha suppression}} where ϕb(t)=2πt/softplus(Pbraw)\phi_b(t) = 2\pi t / \text{softplus}(P_b^{\text{raw}}) with learnable periods: Pθ=8P_\theta = 8 tokens, Pα=20P_\alpha = 20, Pδ=64P_\delta = 64.

Coupling strengths: κ1=tanh⁡(0.3)≈0.29\kappa_1 = \tanh(0.3) \approx 0.29 at init (theta-gamma PAC present at rest, Jensen & Colgin 2007), κ2=κ3=0\kappa_2 = \kappa_3 = 0 at init.

Phase-content interaction through rank-32 projection:

mod=Wouttanh⁡(Wcontenth+Wphase[sin⁡ϕθ,cos⁡ϕθ,sin⁡ϕα,cos⁡ϕα,sin⁡ϕδ,cos⁡ϕδ])\text{mod} = W_{\text{out}} \tanh(W_{\text{content}} \mathbf{h} + W_{\text{phase}} [\sin\phi_\theta, \cos\phi_\theta, \sin\phi_\alpha, \cos\phi_\alpha, \sin\phi_\delta, \cos\phi_\delta])

Output: h←h+σ(gosc)⋅Aγ⋅mod\mathbf{h} \leftarrow \mathbf{h} + \sigma(g_{\text{osc}}) \cdot A_\gamma \cdot \text{mod}. WoutW_{\text{out}} initialized N(0,0.01)\mathcal{N}(0, 0.01), small but nonzero so oscillations provide signal from the start.

Nested PAC: gamma amplitude modulated by theta phase (kappa_1 = 0.3), with optional delta and alpha coupling. All periods learnable.
Figure 31. Nested PAC: gamma amplitude modulated by theta phase (κ1=0.3\kappa_1 = 0.3), with optional delta and alpha coupling. All periods learnable.
(Illustrated) Nested PAC: gamma amplitude modulated by theta phase (kappa_1 = 0.3), with optional delta and alpha coupling. All periods learnable.
Figure 32. (Illustrated) Nested PAC: gamma amplitude modulated by theta phase (κ1=0.3\kappa_1 = 0.3), with optional delta and alpha coupling. All periods learnable.

Interneurons: VIP, SST, PV/Chandelier

Three interneuron types implement distinct inhibitory functions at biologically correct positions:

Interneuron types, placement, and function.
TypePlacementFunctionDisease if Missing
VIPBefore L2/3Disinhibits SST (novelty gate)Autism (ASD)
SSTBefore L2/3Dendritic inhibition (stonic=0.10s_{\text{tonic}} = 0.10)–
PV/ChandelierAfter WM, before L5Axo-axonic output vetoEpilepsy

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 (σ(5)≈0.993\sigma(5) \approx 0.993, 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.

Interneuron circuit: VIP detects top-down novelty and disinhibits SST (double negative = opens gate). SST provides tonic + gated dendritic inhibition before L2/3. PV/Chandelier vetoes output after working memory and oscillations, before L5. Placement is biologically correct.
Figure 33. Interneuron circuit: VIP detects top-down novelty and disinhibits SST (double negative = opens gate). SST provides tonic + gated dendritic inhibition before L2/3. PV/Chandelier vetoes output after working memory and oscillations, before L5. Placement is biologically correct.
(Illustrated) Interneuron circuit: VIP detects top-down novelty and disinhibits SST (double negative = opens gate). SST provides tonic + gated dendritic inhibition before L2/3. PV/Chandelier vetoes output after ...
Figure 34. (Illustrated) Interneuron circuit: VIP detects top-down novelty and disinhibits SST (double negative = opens gate). SST provides tonic + gated dendritic inhibition before L2/3. PV/Chandelier vetoes output after ...

BCM Homeostasis and Metaplasticity

Theorem 13 (BCM Sliding Threshold (Bienenstock, Cooper, Munro 1982)). The BCM threshold θBCM\theta_{\text{BCM}} tracks mean squared postsynaptic activity: θBCM←(1−1τBCM)θBCM+1τBCMy2‾,τBCM=1000\theta_{\text{BCM}} \leftarrow \left(1 - \frac{1}{\tau_{\text{BCM}}}\right) \theta_{\text{BCM}} + \frac{1}{\tau_{\text{BCM}}} \overline{y^2}, \qquad \tau_{\text{BCM}} = 1000 The Hebbian update is modulated: when y>θBCMy > \theta_{\text{BCM}}, potentiation occurs (strengthen active synapses). When y<θBCMy < \theta_{\text{BCM}}, depression occurs (weaken inactive synapses). This prevents runaway Hebbian learning, without BCM, strong synapses would grow without bound.

BCM sliding threshold: the threshold θ_BCM divides activity into depression (below) and potentiation (above) zones. The threshold itself slides to track mean squared activity (τ = 1000), ensuring homeostatic balance. Without BCM, Hebbian learning would cause runaway potentiation.
Figure 35. BCM sliding threshold: the threshold θBCM\theta_{\text{BCM}} divides activity into depression (below) and potentiation (above) zones. The threshold itself slides to track mean squared activity (τ=1000\tau = 1000), ensuring homeostatic balance. Without BCM, Hebbian learning would cause runaway potentiation.
(Illustrated) BCM sliding threshold: the threshold θ_BCM divides activity into depression (below) and potentiation (above) zones. The threshold itself slides to track mean squared activity...
Figure 36. (Illustrated) BCM sliding threshold: the threshold θBCM\theta_{\text{BCM}} divides activity into depression (below) and potentiation (above) zones. The threshold itself slides to track mean squared activity...

Proposition 4 (Metaplasticity (Abraham & Bear, 1996)). The effective learning rate adapts based on recent plasticity history: ηeff=η1+plasticity_ema,plasticity_ema←(1−1500)plasticity_ema+1500∣ΔW∣\eta_{\text{eff}} = \frac{\eta}{1 + \text{plasticity\_ema}}, \qquad \text{plasticity\_ema} \leftarrow \left(1 - \frac{1}{500}\right) \text{plasticity\_ema} + \frac{1}{500} |\Delta W| 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.

Metaplasticity: the effective learning rate is inversely proportional to recent plasticity. High recent weight changes rightarrow reduce LR (stabilize). Low recent changes rightarrow increase LR (explore). This prevents oscillation between over- and under-learning.
Figure 37. Metaplasticity: the effective learning rate is inversely proportional to recent plasticity. High recent weight changes →\rightarrow reduce LR (stabilize). Low recent changes →\rightarrow increase LR (explore). This prevents oscillation between over- and under-learning.
(Illustrated) Metaplasticity: the effective learning rate is inversely proportional to recent plasticity. High recent weight changes rightarrow reduce LR (stabilize). Low recent changes rightarrow increase...
Figure 38. (Illustrated) Metaplasticity: the effective learning rate is inversely proportional to recent plasticity. High recent weight changes →\rightarrow reduce LR (stabilize). Low recent changes →\rightarrow increase...

Layer 5: Dendritic FFN + Prediction + Precision

Theorem 14 (Dendritic Two-Compartment Computation). L5 implements gated computation with separate basal (feedforward) and apical (feedback) compartments: hbasal=RMSNorm(h)hapical=hL4+ctdf=GELU(Wuphb+Wgatehb⊙Wapicalha)yL5=Wout⋅kWTA(f)\begin{aligned} \mathbf{h}_{\text{basal}} &= \text{RMSNorm}(\mathbf{h}) \\ \mathbf{h}_{\text{apical}} &= \mathbf{h}_{\text{L4}} + \mathbf{c}_{\text{td}} \\ \mathbf{f} &= \text{GELU}(W_{\text{up}} \mathbf{h}_b + W_{\text{gate}} \mathbf{h}_b \odot W_{\text{apical}} \mathbf{h}_a) \\ \mathbf{y}_{\text{L5}} &= W_{\text{out}} \cdot \text{kWTA}(\mathbf{f}) \end{aligned}

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.

L5 dendritic two-compartment computation. The basal compartment (feedforward) is gated by the apical compartment (top-down feedback) via a GLU mechanism. This means top-down context can control whether a neuron responds to its feedforward input, matching calcium spike gating in biological apical dendrites. Output passes through k-WTA sparsity (15% active) before producing the column output, top-down prediction, and precision.
Figure 39. L5 dendritic two-compartment computation. The basal compartment (feedforward) is gated by the apical compartment (top-down feedback) via a GLU mechanism. This means top-down context can control whether a neuron responds to its feedforward input, matching calcium spike gating in biological apical dendrites. Output passes through k-WTA sparsity (15% active) before producing the column output, top-down prediction, and precision.
(Illustrated) L5 dendritic two-compartment computation. The basal compartment (feedforward) is gated by the apical compartment (top-down feedback) via a GLU mechanism. This means top-down context can control whe...
Figure 40. (Illustrated) L5 dendritic two-compartment computation. The basal compartment (feedforward) is gated by the apical compartment (top-down feedback) via a GLU mechanism. This means top-down context can control whe...

Prediction head: x^i−1=WpredRMSNorm(h)\hat{\mathbf{x}}_{i-1} = W_{\text{pred}} \text{RMSNorm}(\mathbf{h}) generates the top-down prediction for the column below.

Precision output: σ2=softplus(WσRMSNorm(h)+bσ)\sigma^2 = \text{softplus}(W_\sigma \text{RMSNorm}(\mathbf{h}) + b_\sigma) with bσ,init=log⁡(e1.0−1)b_{\sigma,\text{init}} = \log(e^{1.0} - 1) so that softplus(b)=1.0\text{softplus}(b) = 1.0.

Lateral Column Connections

Horizontal connections between adjacent columns (i±1i \pm 1) via low-rank send/receive projections:

li=σ(gi)⋅Wrecv,i⋅1∣N(i)∣∑j∈N(i)Wsend,jhj,r=max⁡(d/8,32)\mathbf{l}_i = \sigma(g_i) \cdot W_{\text{recv},i} \cdot \frac{1}{|\mathcal{N}(i)|} \sum_{j \in \mathcal{N}(i)} W_{\text{send},j} \mathbf{h}_j, \qquad r = \max(d/8, 32)

Disease mapping: schizophrenia (disconnection syndrome) →\rightarrow disrupted lateral connections →\rightarrow fragmented perception and thought disorder. WsendW_{\text{send}} initialized at 0\mathbf{0} (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:

ColumnOutput fields and their roles in the NCT system.
FieldShapeRole
output[B,T,d][B, T, d]Sent to next column via thalamic routing. Includes residual connection: hout=xin+yL5\mathbf{h}_{\text{out}} = \mathbf{x}_{\text{in}} + \mathbf{y}_{\text{L5}}.
prediction[B,T,d][B, T, d]Top-down prediction x^i−1\hat{\mathbf{x}}_{i-1} for the column below. Used to compute PC error ϵi\boldsymbol{\epsilon}_i.
thal_feedback[B,T,d][B, T, d]L6 feedback signal sent to thalamic relay. Modulates routing for subsequent inputs.
state[B,T,dc][B, T, d_c]Internal column state (post-oscillation, pre-L5). Used for monitoring and diagnostics.
sigma2[B,T,1][B, T, 1]Prediction precision from L5. Passed to next column’s L5 as prior. Used for PC learning weight, surprise tagging, and σ2\sigma^2-adaptive decoding.
l23_input[B,T,dc][B, T, d_c]Input to L2/3 (after L1 modulation + interneuron gating). Needed for Hebbian update: x\mathbf{x} in ΔW=ηyx⊤\Delta W = \eta \mathbf{y} \mathbf{x}^\top.
l23_output[B,T,dc][B, T, d_c]Output of L2/3 settling. Needed for Hebbian update: y\mathbf{y} in ΔW=ηyx⊤\Delta W = \eta \mathbf{y} \mathbf{x}^\top.

The residual connection ensures that even with all gates near zero (identity-at-init), the column passes information through unchanged. If dcol≠dmodeld_{\text{col}} \neq d_{\text{model}}, a learned residual projection Wresidual∈Rd×dW_{\text{residual}} \in \mathbb{R}^{d \times d} adapts the dimension.

Source Code

Python
1,435 lines
# ===========================================================================
# 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