Full Model (CorticalColumnNetwork)
Source: nct_v2/v11_model.py Lines: 1,025
Overview
The CorticalColumnNetwork class is the top-level module that assembles all NCT components into a single nn.Module. It instantiates 13 major subsystems: the brain embedding pipeline (V11BrainEmbedding with its 4 stages), grid cell position encoding, cortical columns (each containing 11 submodules), the thalamic routing system with TRN gating, hippocampal episodic memory with surprise tagging, basal ganglia reward-modulated selection, cerebellar temporal prediction, brainstem neuromodulation (4 signals), lateral column connections, global workspace with surprise-weighted broadcast, self-assessment with ACC conflict monitoring, the brain LM head (weight-tied with embedding), and the integrated learning manager (PC + Hebbian + neuromod + wake-sleep + developmental staging).
The model also maintains internal state for self-repair (best-state rollback if loss diverges), tool use registration (lazy initialization of BG-based tool selector), and stateful tracking of the last forward pass’s column outputs, predictions, precisions, errors, and neuromodulatory state, enabling local learning updates without re-running the forward pass.
V11BrainEmbedding
The V11BrainEmbedding class wraps the 4-stage brain embedding pipeline into a single module compatible with the V11 config interface. It chains the four stages in sequence:
The weight property returns the base embedding weights ( from Stage 1) for weight tying with the LM head. The base embedding is initialized with ; all subsequent stages are identity-at-init and progressively activate during training as their gates learn to open.
Forward Pass: 11 Stages
Theorem 26 (Complete Forward Pass). The forward pass proceeds through 11 stages:
Stage 1, Embedding:
Stage 2, Position:
Stage 3, Bottom-up pass: For each column :
Stage 4, Predictions: Column 0 predicts embedding ; column predicts column ’s output.
Stage 5, Errors: for each column.
Stage 6, Lateral + Workspace: Compute lateral signals between adjacent columns; global workspace broadcasts highest-surprise column.
Stage 7, Metacognition: Self-assessment computes conflict extra PC steps.
Stage 8, PC inference (no gradients): Re-run all columns with top-down + workspace + lateral context for up to additional iterations. Break early when relative error change .
Stage 9, Neuromodulation: Brainstem computes DA/NE/5-HT/ACh from top column output.
Stage 10, Subcortical: BG modulates output with DA; cerebellum computes temporal prediction loss; hippocampus adds episodic memory and tags surprises.
Stage 11, Output: . NTP loss via cross-entropy. PC loss summed over columns.
Loss Function
The total loss combines four terms:
In PC/Hebbian modes, gradients propagate only to the LM head (not through columns). All column weight updates come from local PC/Hebbian rules.
Self-Repair Mechanism
Definition 7 (Self-Repair via Best-State Rollback). The model periodically saves its best state (lowest loss seen). If the current loss exceeds the best loss, the model:
Rolls back all parameters to the saved best state
Reduces the learning rate by 50%
Increments the rollback counter
This prevents catastrophic divergence during continuous learning, a form of metacognitive self-regulation absent in transformers.
Key Methods
The model provides 11+ methods beyond forward():
local_learning_step(): Apply PC + Hebbian updates using stored forward-pass state (column outputs, predictions, errors, precisions, neuromod state). No additional forward pass needed.
sleep_phase(): Hippocampal replay + synaptic downscaling (). Uses stored HPC memories.
generate(prompt, max_new_tokens): Auto-regressive text generation with optional brain decoding (drift-diffusion sampler, inhibition of return, -adaptive temperature).
count_parameters(): Per-component parameter breakdown (embedding, columns, thalamus, HPC, BG, CB, brainstem, LM head, grid pos, lateral, workspace, self-assessment).
register_tools(schemas): Register tool schemas for agentic tool use via the basal ganglia D1/D2 pathways.
get_gate_values(): Aggregate gate values from all columns for monitoring.
reset_working_memory(): Clear all persistent WM state (NMDA, silent, phono) across all columns.
Source Code
# ===========================================================================
# Cortical Column Network — Full Model
# Source: nct_v2/v11_model.py
# ===========================================================================
"""
NCT V11: Cortical Column Network — Full Model
================================================
The complete brain-analog architecture replacing the transformer.
Architecture:
Embedding → Thalamus → [Column 0 → Column 1 → ... → Column N-1] → LM Head
Each column: L4 → L1 → L2/3 → Interneurons → WM → Oscillations → L5 → L6
Subcortical: Thalamus (routing), Hippocampus (memory), Basal Ganglia (reward),
Cerebellum (temporal prediction), Brainstem (neuromodulation)
Learning: Predictive coding (vertical) + Hebbian (lateral) + Neuromod gating
Operation: Continuous wake-sleep cycle
Forward pass:
1. Bottom-up: input → embed → columns[0] → ... → columns[N-1] → logits
2. Top-down predictions: each column predicts the level below
3. Prediction errors: ε_l = actual_l - prediction_{l+1}
4. Inference: iterate representations to minimize errors (PC)
5. Learning: local updates (PC + Hebbian + neuromod-gated)
"""
# [bundled] from .v11_config import V11Config
# [bundled] from .v11_column import CorticalColumn, ColumnOutput, RMSNorm, LateralColumnConnection
# [bundled] from .v11_systems import (
# [bundled] from .v11_learning import V11LearningManager
# [bundled] from .brain_embeddings import HubAndSpokeProjection, SparseDistributedProjection, MorphemeCompositionGate
# [bundled] from .brain_position import GridCellPositionEncoding
# [bundled] from .brain_lm_head import BrainLMHead
# [bundled] from .brain_decoding import DriftDiffusionSampler, InhibitionOfReturn, BrainDecodingConfig
# ═══════════════════════════════════════════════════════════════════════
# V11 Brain Embedding (Theorems 56-58)
# ═══════════════════════════════════════════════════════════════════════
class V11BrainEmbedding(nn.Module):
"""Brain-inspired embedding replacing nn.Embedding (Thm 56-58).
4-stage cascade matching brain processing timeline:
Stage 1 (0ms): Token ID → base embedding lookup
Stage 2 (170ms): Morphological composition — dual-route lexical/sublexical (Thm 58)
Stage 3 (250ms): Hub-spoke cross-modal integration — ATL binding (Thm 56)
Stage 4 (300ms): Sparse distributed activation — neocortical coding (Thm 57)
All stages are gated and identity-at-init.
Weight tying: lm_head ties to self.base_embed.weight.
"""
def __init__(self, cfg: V11Config):
super().__init__()
d = cfg.d_model
V = cfg.vocab_size
# Stage 1: Base embedding (standard lookup)
self.base_embed = nn.Embedding(V, d)
# Stage 2: Dual-route morphological composition (Thm 58)
self.morpheme_gate = MorphemeCompositionGate(V, d, kernel_size=3)
# Stage 3: Hub-and-spoke semantic integration (Thm 56)
self.hub_spoke = HubAndSpokeProjection(d, S=6)
# Stage 4: Sparse distributed activation (Thm 57)
self.sparse_proj = SparseDistributedProjection(d, expansion=2, sparsity=0.02)
nn.init.normal_(self.base_embed.weight, std=0.02)
@property
def weight(self):
"""For weight tying with lm_head: return base embedding weights."""
return self.base_embed.weight
def forward(self, token_ids: torch.Tensor) -> torch.Tensor:
"""token_ids: [B, T] → [B, T, d_model]"""
e = self.base_embed(token_ids)
e = self.morpheme_gate(e, token_ids)
e = self.hub_spoke(e)
e = self.sparse_proj(e)
return e
# ═══════════════════════════════════════════════════════════════════════
# Cortical Column Network (Full Model)
# ═══════════════════════════════════════════════════════════════════════
class CorticalColumnNetwork(nn.Module):
"""
The complete NCT V11 model: a cortical column network.
Replaces the transformer with a biologically-grounded architecture.
"""
def __init__(self, cfg: V11Config):
super().__init__()
self.cfg = cfg
# ── Token Embedding (Thm 56-58: Brain Embedding) ─────────────
self.embed = V11BrainEmbedding(cfg)
self.embed_norm = RMSNorm(cfg.d_model)
self.embed_dropout = nn.Dropout(cfg.dropout)
# ── Positional Encoding (Thm 59/61/62: Grid-Cell) ────────────
# Learnable grid-cell frequencies, per-head scales, boundary remapping
self.grid_pos = GridCellPositionEncoding(
max_seq_len=cfg.max_seq_len,
d_h=cfg.d_head,
n_heads=cfg.n_assoc_heads,
d_model=cfg.d_model,
)
# ── Cortical Columns (hierarchical stack) ────────────────────
self.columns = nn.ModuleList([
CorticalColumn(cfg, column_idx=i) for i in range(cfg.n_columns)
])
# ── Subcortical Systems ──────────────────────────────────────
self.thalamus = Thalamus(cfg)
self.hippocampus = Hippocampus(cfg)
self.basal_ganglia = BasalGanglia(cfg)
self.cerebellum = Cerebellum(cfg)
self.brainstem = Brainstem(cfg)
# ── LM Head (Thm 63: Brain Lexical Production) ─────────────
# WEAVER++ competition + production delta + frequency bias
self.lm_head_norm = RMSNorm(cfg.d_model)
self.lm_head = BrainLMHead(cfg.d_model, cfg.vocab_size, rank=32, competition_rank=64)
# Tie embeddings: BrainLMHead uses base embedding weights for shared semantics
self.lm_head.weight = self.embed.weight
# ── Lateral Column Connections (Horizontal) ────────────────
self.lateral = LateralColumnConnection(cfg)
# ── Global Workspace (Baars 1988) ──────────────────────────
self.workspace = CorticalWorkspace(cfg)
# ── Self-Assessment & Metacognition ─────────────────────────
self.self_assessment = SelfAssessment(cfg)
# ── Tool Interface (Thm 71: BG D1/D2 Tool Selection) ──────
# Initialized lazily via register_tools(). Allows world interaction.
self._tool_selector: Optional[nn.Module] = None
self._tool_schemas: List = []
# ── Learning Manager ─────────────────────────────────────────
self.learning_manager = V11LearningManager(cfg)
# ── State tracking ───────────────────────────────────────────
self._last_column_outputs: Optional[List[ColumnOutput]] = None
self._last_predictions: Optional[List[torch.Tensor]] = None
self._last_targets: Optional[List[torch.Tensor]] = None
self._last_precisions: Optional[List[torch.Tensor]] = None
self._last_neuromod: Optional[NeuromodState] = None
self._last_errors: Optional[List[torch.Tensor]] = None
# ── Self-repair: best-state rollback ─────────────────────────
# Save best state periodically. If loss diverges, roll back.
self._best_state: Optional[dict] = None
self._best_loss: float = float('inf')
self._rollback_count: int = 0
self._steps_since_best: int = 0
# Initialize
self._init_weights()
def _init_weights(self):
"""Initialize weights following NCT principles."""
# Embedding init handled by V11BrainEmbedding.__init__
pass
def count_parameters(self) -> Dict[str, int]:
"""Count parameters by component."""
counts = {}
counts['embedding'] = sum(p.numel() for p in self.embed.parameters())
counts['columns'] = sum(p.numel() for p in self.columns.parameters())
counts['thalamus'] = sum(p.numel() for p in self.thalamus.parameters())
counts['hippocampus'] = sum(p.numel() for p in self.hippocampus.parameters())
counts['basal_ganglia'] = sum(p.numel() for p in self.basal_ganglia.parameters())
counts['cerebellum'] = sum(p.numel() for p in self.cerebellum.parameters())
counts['brainstem'] = sum(p.numel() for p in self.brainstem.parameters())
counts['lm_head'] = sum(p.numel() for p in self.lm_head_norm.parameters()) + \
sum(p.numel() for p in self.lm_head.parameters())
counts['grid_pos'] = sum(p.numel() for p in self.grid_pos.parameters())
counts['lateral'] = sum(p.numel() for p in self.lateral.parameters())
counts['workspace'] = sum(p.numel() for p in self.workspace.parameters())
counts['self_assessment'] = sum(p.numel() for p in self.self_assessment.parameters())
counts['total'] = sum(p.numel() for p in self.parameters())
counts['trainable'] = sum(p.numel() for p in self.parameters() if p.requires_grad)
return counts
# ─────────────────────────────────────────────────────────────────
# Forward Pass
# ─────────────────────────────────────────────────────────────────
def forward(
self,
input_ids: torch.Tensor,
targets: Optional[torch.Tensor] = None,
) -> Dict[str, torch.Tensor]:
"""
Full forward pass through the cortical column network.
Args:
input_ids: [B, T] — token IDs
targets: [B, T] — target token IDs (for NTP loss)
Returns: dict with:
logits: [B, T, V]
loss: scalar (if targets provided)
pc_loss: scalar (predictive coding loss)
cb_loss: scalar (cerebellar prediction loss)
metrics: dict of monitoring values
"""
B, T = input_ids.shape
device = input_ids.device
# ── 1. Embedding (Thm 56-58: Brain Embedding) ─────────────
x = self.embed(input_ids) # [B, T, D] — morpheme → hub-spoke → sparse
x = self.embed_norm(x)
x = self.embed_dropout(x)
# ── 1b. Position Information ────────────────────────────────
# L2/3 now uses Windowed Hebbian Association — no RoPE needed.
# Position is encoded through THREE brain mechanisms:
# 1. Windowed context: implicit local position within theta period
# 2. Oscillatory dynamics: nested PAC gives absolute phase position
# 3. Grid-cell encoding: additive position signal to embeddings
# Grid-cell features are added (not rotated) since there's no attention.
rope_cos, rope_sin = self.grid_pos(T, device, x.dtype, X=x)
# Additive position encoding: use sin component as position signal
# Grid-cell output: [B, H, T, D_h] → average over heads → [B, T, D_h]
if rope_sin.dim() == 4: # [B, H, T, D_h]
pos_signal = rope_sin.mean(dim=1) # [B, T, D_h]
elif rope_sin.dim() == 3: # [H, T, D_h]
pos_signal = rope_sin.mean(dim=0).unsqueeze(0) # [1, T, D_h]
else:
pos_signal = rope_sin[:T].unsqueeze(0) # [1, T, D_h]
d_h = pos_signal.shape[-1]
d_model = x.shape[-1]
# Tile to match d_model: repeat to fill
n_tiles = d_model // d_h
if n_tiles > 1 and d_h * n_tiles == d_model:
pos_embed = pos_signal.repeat(1, 1, n_tiles) # [B, T, D_model]
elif d_h < d_model:
pos_embed = F.pad(pos_signal, (0, d_model - d_h)) # [B, T, D_model]
else:
pos_embed = pos_signal[..., :d_model] # [B, T, D_model]
x = x + 0.1 * pos_embed # Scaled additive position (small at init)
# Reset TRN loss accumulator for this forward pass
if self.cfg.thalamic_enabled:
self.thalamus.reset_loss()
# ── 2. Bottom-Up Pass (through all columns) ──────────────────
column_outputs: List[ColumnOutput] = []
thal_feedbacks: List[Optional[torch.Tensor]] = [None] * self.cfg.n_columns
h = x
sigma2_prev = None # First column has no prior precision
for i, col in enumerate(self.columns):
# Route through thalamus (with L6 feedback from previous pass if available)
h_thal = self.thalamus.route(h, column_idx=i, thal_feedback=thal_feedbacks[i])
# Column forward (no RoPE — L2/3 is windowed Hebbian, not attention)
out = col(ff_input=h_thal, td_context=None, sigma2_prev=sigma2_prev)
column_outputs.append(out)
# Store thalamic feedback for inference iterations
thal_feedbacks[i] = out.thal_feedback
sigma2_prev = out.sigma2 # Pass precision to next column's L5
h = out.output
# ── 3. Compute Top-Down Predictions ──────────────────────────
# Each column predicts the input to the column below
predictions = []
prediction_targets = []
prediction_precisions = []
for l in range(self.cfg.n_columns):
if l == 0:
# Column 0 predicts the embedding
prediction_targets.append(x.detach())
else:
# Column l's input is column l-1's output
prediction_targets.append(column_outputs[l - 1].output.detach())
predictions.append(column_outputs[l].prediction)
prediction_precisions.append(column_outputs[l].sigma2)
# ── 4. Compute Prediction Errors ─────────────────────────────
errors = []
for l in range(self.cfg.n_columns):
error = prediction_targets[l] - predictions[l]
errors.append(error)
# ── 5a. Lateral Column Communication (Horizontal) ─────────────
# Adjacent columns exchange information directly (not just via hierarchy)
lateral_signals = self.lateral(column_outputs)
# ── 5a2. Global Workspace Broadcast (Baars 1988) ──────────────
# Highest-surprise column broadcasts to all — provides global context
ws_modulations = self.workspace.broadcast(column_outputs, errors)
# ── 5b. Metacognitive Monitoring (ACC-like conflict) ──────────
# When columns disagree, allocate more inference steps (think harder)
conflict = self.self_assessment.compute_conflict(column_outputs)
extra_steps = self.self_assessment.extra_pc_steps(conflict)
# ── 5c. Predictive Coding Inference (adaptive convergence) ──────
# Brain iterates until prediction errors settle. We iterate up to
# pc_max_steps + extra_steps (from conflict), breaking early once
# error change < threshold.
# Workspace modulations provide global top-down context per column.
pc_steps_taken = 1 # Already did 1 pass above
prev_error_norm = sum(e.pow(2).mean() for e in errors)
max_steps = self.cfg.pc_max_steps + extra_steps
min_steps = self.cfg.pc_min_steps
conv_threshold = self.cfg.pc_convergence_threshold
# PC inference iterations run WITHOUT gradients — biologically correct.
# Neural settling is dynamical relaxation, not gradient descent.
# Gradients are only needed for the FINAL state (computed after this loop).
# PC weight updates use analytical local gradients (PredictiveCodingOptimizer),
# not autograd. This saves O(N_columns × N_steps) activation memory.
with torch.no_grad():
for step in range(max_steps - 1):
h = x
# Re-run columns with top-down + workspace + lateral + L6 feedback
new_outputs = []
sigma2_prev_iter = None
for i, col in enumerate(self.columns):
# Top-down context = workspace + lateral + prediction from above
td_ctx = ws_modulations[i] + lateral_signals[i]
if i < self.cfg.n_columns - 1:
td_ctx = td_ctx + column_outputs[i + 1].prediction
# Route through thalamus WITH L6 feedback from previous iteration
h_thal = self.thalamus.route(
h, column_idx=i, thal_feedback=thal_feedbacks[i]
)
out = col(ff_input=h_thal, td_context=td_ctx,
sigma2_prev=sigma2_prev_iter)
new_outputs.append(out)
thal_feedbacks[i] = out.thal_feedback # Update L6 feedback
sigma2_prev_iter = out.sigma2
h = out.output
# Update stored outputs
column_outputs = new_outputs
# Recompute predictions and errors
predictions = [out.prediction for out in column_outputs]
prediction_precisions = [out.sigma2 for out in column_outputs]
errors = [
prediction_targets[l] - predictions[l]
for l in range(self.cfg.n_columns)
]
# Re-compute lateral + workspace with updated outputs/errors
lateral_signals = self.lateral(column_outputs)
ws_modulations = self.workspace.broadcast(column_outputs, errors)
pc_steps_taken += 1
# Check convergence: has the total error stopped changing?
# Use RELATIVE threshold (error_delta / prev_error < threshold)
# to avoid the absolute threshold never triggering on large errors.
curr_error_norm = sum(e.pow(2).mean() for e in errors)
error_delta = abs(prev_error_norm - curr_error_norm)
if isinstance(error_delta, torch.Tensor):
error_delta = error_delta.item()
if isinstance(prev_error_norm, torch.Tensor):
prev_val = prev_error_norm.item()
else:
prev_val = prev_error_norm
# Relative convergence: < 1% change in error
relative_delta = error_delta / (prev_val + 1e-8)
prev_error_norm = curr_error_norm
# Early stop: converged after minimum steps
if pc_steps_taken >= min_steps and relative_delta < conv_threshold:
break
# ── 6. Brainstem: Compute Neuromodulatory State ──────────────
# Use top column's output for global state computation
top_output = column_outputs[-1].output
mean_error = torch.stack([e.abs().mean() for e in errors]).mean()
neuromod = self.brainstem.compute_state(
top_output,
prediction_error=errors[-1] if errors else None,
)
# ── 7. Basal Ganglia: DA modulation ──────────────────────────
if self.cfg.bg_enabled:
h = self.basal_ganglia(column_outputs[-1].output, neuromod.dopamine)
# Update tonic DA EMA (was never called — now wired)
self.basal_ganglia.update_tonic_da(neuromod.dopamine)
else:
h = column_outputs[-1].output
# ── 8. Cerebellum: Temporal prediction ───────────────────────
cb_loss = torch.tensor(0.0, device=device)
if self.cfg.cerebellum_enabled:
h, cb_loss = self.cerebellum(h)
# ── 9. Hippocampus: Episodic memory ──────────────────────────
if self.cfg.hpc_enabled:
# Use mean precision from all columns
mean_sigma2 = sum(out.sigma2 for out in column_outputs) / len(column_outputs)
h = self.hippocampus(h, mean_sigma2)
# Tag surprising events for replay
if self.training:
self.hippocampus.encode_episode(
h, errors[-1] if errors else torch.zeros_like(h),
mean_sigma2,
)
# ── 10. LM Head ─────────────────────────────────────────────
h_normed = self.lm_head_norm(h)
logits = self.lm_head(h_normed) # [B, T, V]
# ── 11. Compute Losses ───────────────────────────────────────
result = {'logits': logits, 'hidden_state': h_normed.detach(), 'targets': targets}
# NTP loss (standard cross-entropy)
if targets is not None:
ntp_loss = F.cross_entropy(
logits.reshape(-1, self.cfg.vocab_size),
targets.reshape(-1),
ignore_index=-1,
)
result['loss'] = ntp_loss
# Predictive coding loss (local)
_, pc_loss = self.learning_manager.pc_optimizer.compute_column_losses(
predictions, prediction_targets, prediction_precisions
)
result['pc_loss'] = pc_loss
result['cb_loss'] = cb_loss
# TRN bimodality loss (accumulated during thalamic routing)
trn_loss = self.thalamus.compute_loss() if self.cfg.thalamic_enabled else torch.tensor(0.0, device=device)
result['trn_loss'] = trn_loss
# ── 12. Store state for learning ─────────────────────────────
self._last_column_outputs = column_outputs
self._last_predictions = predictions
self._last_targets = prediction_targets
self._last_precisions = prediction_precisions
self._last_neuromod = neuromod
self._last_errors = errors
# ── 13. Self-Assessment Health Check ────────────────────────
self.self_assessment.update_health(column_outputs, pc_steps_taken)
if self.training and self.self_assessment._health_updates % 100 == 0:
health = self.self_assessment.check_health(self.columns)
# ── 14. Metrics ──────────────────────────────────────────────
metrics = {}
metrics['pc_steps'] = pc_steps_taken
metrics['conflict'] = conflict
metrics['mean_pred_error'] = mean_error.item() if isinstance(mean_error, torch.Tensor) else mean_error
metrics['da_mean'] = neuromod.dopamine.mean().item()
metrics['ne_mean'] = neuromod.norepinephrine.mean().item()
metrics['ach_mean'] = neuromod.acetylcholine.mean().item()
metrics['tonic_da'] = neuromod.tonic_da
metrics['hpc_memory_size'] = self.hippocampus.memory_size if self.cfg.hpc_enabled else 0
# Precision stats
all_sigma2 = torch.cat([out.sigma2 for out in column_outputs], dim=-1)
metrics['sigma2_mean'] = all_sigma2.mean().item()
metrics['sigma2_std'] = all_sigma2.std().item()
# Gate values from first and last columns
metrics.update(self.columns[0].get_gate_values())
metrics.update(self.columns[-1].get_gate_values())
# Self-assessment metrics
metrics.update(self.self_assessment.get_metrics())
result['metrics'] = metrics
return result
# ─────────────────────────────────────────────────────────────────
# Learning Interface
# ─────────────────────────────────────────────────────────────────
def local_learning_step(self, ewc_guard=None) -> Dict[str, float]:
"""
Perform local learning (PC + Hebbian + neuromod).
Must be called after forward() which stores the needed state.
Args:
ewc_guard: Optional ContinualLearningGuard for EWC elastic pull.
Returns: dict of learning metrics
"""
if self._last_column_outputs is None:
return {}
return self.learning_manager.wake_step(
columns=self.columns,
column_outputs=self._last_column_outputs,
predictions=self._last_predictions,
targets=self._last_targets,
precisions=self._last_precisions,
neuromod=self._last_neuromod,
errors=self._last_errors,
ewc_guard=ewc_guard,
)
def sleep_phase(self) -> Dict[str, float]:
"""
Run sleep phase: replay + downscaling + consolidation.
Called when wake_sleep scheduler says it's time.
Returns: dict of sleep metrics
"""
device = next(self.parameters()).device
return self.learning_manager.sleep_phase(
model=self,
hippocampus=self.hippocampus,
columns=self.columns,
device=device,
)
def learn_from_experience(self, input_ids: torch.Tensor, targets: Optional[torch.Tensor] = None) -> Dict[str, float]:
"""
Process AND learn from a single experience in one call.
This is the "always-on learning" interface: the brain doesn't separate
forward() from learning. Every experience updates the system.
Returns: combined forward + learning metrics.
"""
result = self.forward(input_ids, targets)
learn_metrics = self.local_learning_step()
result['learning_metrics'] = learn_metrics
return result
def should_sleep(self) -> bool:
"""Check if it's time for sleep."""
return self.learning_manager.should_sleep()
# ─────────────────────────────────────────────────────────────────
# Backprop Mode (for comparison / hybrid training)
# ─────────────────────────────────────────────────────────────────
def backprop_step(
self,
input_ids: torch.Tensor,
targets: torch.Tensor,
optimizer: torch.optim.Optimizer,
) -> Dict[str, float]:
"""
Standard backprop training step (for comparison or hybrid mode).
Uses global loss and standard optimizer.
Returns: dict with loss, ppl, etc.
"""
result = self.forward(input_ids, targets)
loss = result['loss']
# Add auxiliary losses: PC + cerebellar + TRN bimodality
total_loss = loss + 0.1 * result['pc_loss'] + 0.01 * result['cb_loss'] + 0.01 * result['trn_loss']
optimizer.zero_grad()
total_loss.backward()
# Gradient clipping
nn.utils.clip_grad_norm_(self.parameters(), self.cfg.max_grad_norm)
optimizer.step()
return {
'loss': loss.item(),
'pc_loss': result['pc_loss'].item(),
'cb_loss': result['cb_loss'].item(),
'trn_loss': result['trn_loss'].item(),
'ppl': math.exp(min(loss.item(), 20)),
**result['metrics'],
}
# ─────────────────────────────────────────────────────────────────
# Generation
# ─────────────────────────────────────────────────────────────────
@torch.no_grad()
def generate(
self,
input_ids: torch.Tensor,
max_new_tokens: int = 100,
use_brain_decoding: bool = True,
) -> torch.Tensor:
"""
Brain-inspired autoregressive generation (Thm 63d-65).
Uses drift-diffusion evidence accumulation + inhibition of return
+ System 1/2 confidence gating. All controlled by NCT signals:
- σ² → noise modulation (uncertain → more deliberation)
- Tonic DA → threshold (high DA → lower threshold → explore)
- IOR → repetition avoidance (decaying inhibition on recent tokens)
Falls back to standard temperature sampling if use_brain_decoding=False.
Args:
input_ids: [B, T] — prompt tokens
max_new_tokens: number of tokens to generate
use_brain_decoding: use drift-diffusion (True) or standard sampling (False)
Returns: [B, T + max_new_tokens] — full sequence with generated tokens
"""
self.eval()
generated = input_ids.clone()
if use_brain_decoding:
# Initialize brain decoding components
decode_cfg = BrainDecodingConfig()
sampler = DriftDiffusionSampler(decode_cfg)
ior = InhibitionOfReturn(self.cfg.vocab_size, decode_cfg.ior_strength, decode_cfg.ior_tau)
ior.reset(input_ids.device)
for _ in range(max_new_tokens):
context = generated[:, -self.cfg.max_seq_len:]
result = self.forward(context)
logits = result['logits'][:, -1, :].float() # [B, V]
# Extract NCT signals for modulation
sigma2 = result['metrics'].get('sigma2_mean', 1.0)
tonic_da = self.brainstem.tonic_da.item()
gen_conflict = result['metrics'].get('conflict', 0.0)
# Drift-diffusion sampling with IOR + conflict modulation
selected, _ = sampler.sample(
logits=logits,
sigma2=sigma2,
tonic_da=tonic_da,
conflict=gen_conflict,
ior_trace=ior.trace,
)
# Update IOR trace
ior.step(selected[0].item())
generated = torch.cat([generated, selected.unsqueeze(1)], dim=1)
else:
# Standard temperature/top-p fallback
for _ in range(max_new_tokens):
context = generated[:, -self.cfg.max_seq_len:]
result = self.forward(context)
logits = result['logits'][:, -1, :] / 0.8 # temperature
probs = F.softmax(logits.float(), dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
generated = torch.cat([generated, next_token], dim=1)
self.train()
return generated
# ─────────────────────────────────────────────────────────────────
# Tool Interface (Blocker 5: World Interaction)
# ─────────────────────────────────────────────────────────────────
def register_tools(self, tool_schemas: list):
"""
Register available tools for BG D1/D2 selection (Thm 71).
Args:
tool_schemas: List of ToolSchema objects from nct_v2/tool_use.py
After registration, generate_with_tools() can select and call tools.
This is the architecture-level wiring — training data teaches the
model WHEN to use each tool.
"""
# [bundled] from .tool_use import ToolSelector
self._tool_schemas = tool_schemas
n_tools = len(tool_schemas)
if n_tools == 0:
return
device = next(self.parameters()).device
self._tool_selector = ToolSelector(
d_model=self.cfg.d_model,
max_tools=max(n_tools, 4),
d_tool=min(128, self.cfg.d_model // 4),
).to(device)
@torch.no_grad()
def generate_with_tools(
self,
input_ids: torch.Tensor,
tool_executor: callable = None,
max_new_tokens: int = 200,
max_tool_calls: int = 5,
) -> dict:
"""
Generate text with optional tool calls.
The brain's agentic loop (Thm 73):
1. Generate tokens until tool-call detected or EOS
2. BG D1/D2 decides: call tool or continue generating
3. If tool called: execute, inject result, continue generating
4. Repeat until done or max_tool_calls exhausted
Args:
input_ids: [1, T] prompt tokens
tool_executor: callable(tool_name, arguments) -> str
max_new_tokens: max tokens to generate
max_tool_calls: max number of tool invocations
Returns:
dict with 'generated_ids', 'text_segments', 'tool_calls', 'tool_results'
"""
# [bundled] from .tool_use import ToolCallFormat
self.eval()
generated = input_ids.clone()
tool_calls_made = []
tool_results = []
tokens_generated = 0
for _ in range(max_new_tokens):
context = generated[:, -self.cfg.max_seq_len:]
result = self.forward(context)
logits = result['logits'][:, -1, :].float()
# Standard sampling
probs = F.softmax(logits / 0.7, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
generated = torch.cat([generated, next_token], dim=1)
tokens_generated += 1
# Check if tool selector wants to intervene
if (self._tool_selector is not None
and tool_executor is not None
and len(tool_calls_made) < max_tool_calls):
hidden = result['logits'] # Use logits-level representation
h_pool = result.get('hidden_state', logits)
if h_pool is not None and h_pool.dim() == 3:
h_pool = h_pool[:, -1:, :] # Last position
sigma2 = result['metrics'].get('sigma2_mean', 1.0)
tonic_da = self.brainstem.tonic_da.item()
selection = self._tool_selector(
h_pool, sigma2=sigma2, tonic_da=tonic_da,
n_active_tools=len(self._tool_schemas),
)
if selection['selected_tool'] is not None:
tool_idx = selection['selected_tool']
if tool_idx < len(self._tool_schemas):
schema = self._tool_schemas[tool_idx]
# Execute tool
try:
tool_result = tool_executor(schema.name, {})
tool_calls_made.append(schema.name)
tool_results.append(tool_result)
except Exception:
pass
self.train()
return {
'generated_ids': generated,
'tokens_generated': tokens_generated,
'tool_calls': tool_calls_made,
'tool_results': tool_results,
}
# ─────────────────────────────────────────────────────────────────
# Persistence — Save/Load ALL Brain State
# ─────────────────────────────────────────────────────────────────
def save_state(self, path: str):
"""
Save the COMPLETE brain state to disk.
Unlike a standard model checkpoint that only saves weights, this saves
everything a living brain needs to resume exactly where it left off:
- All model parameters and buffers (nn.Module state_dict)
- Hippocampal episodic memory buffer (CPU tensors)
- BCM homeostatic thresholds (per-column sliding thresholds)
- Metaplasticity EMA (learning-rate-of-learning-rate state)
- Developmental program step (which critical period stage)
- Learning manager internal state (wake-sleep counters)
- Lateral connection state (already in state_dict)
- Config (to recreate architecture)
The autonomous loop state (EWC importance, performance history,
consolidation knowledge) is saved separately via save_autonomous_state()
since the autonomous loop wraps the model.
Usage:
model.save_state('brain_checkpoint.pt')
# ... later ...
model = CorticalColumnNetwork(cfg)
model.load_state('brain_checkpoint.pt')
"""
state = {
# 1. All nn.Module parameters and buffers
'model_state_dict': self.state_dict(),
# 2. Hippocampal episodic memory (non-parameter state)
'hippocampal_memories': [
{k: v.clone() for k, v in mem.items()}
for mem in self.hippocampus._memory_buffer
],
'hippocampal_surprises': list(self.hippocampus._surprise_buffer),
# 3. Developmental program step
'developmental_step': self.learning_manager.development._current_step,
# 4. Wake-sleep scheduler state
'wake_steps': self.learning_manager.wake_sleep.wake_steps,
'sleep_phases': self.learning_manager.wake_sleep.sleep_phases,
'total_steps': self.learning_manager.wake_sleep.total_steps,
# 5. Hebbian optimizer state (BCM thresholds tracked per-column)
'hebbian_lr': self.learning_manager.hebbian_optimizer.lr,
# 6. Config (for architecture recreation)
'config': {
field.name: getattr(self.cfg, field.name)
for field in self.cfg.__dataclass_fields__.values()
},
# 7. Version marker
'v11_version': 1,
}
torch.save(state, path)
def load_state(self, path: str, strict: bool = True):
"""
Restore COMPLETE brain state from disk.
Loads everything saved by save_state(), restoring the brain
to the exact state it was in when saved.
Args:
path: Path to the saved state file.
strict: If True, requires exact parameter name match.
If False, ignores missing/unexpected keys (useful for
loading partial states or after architecture changes).
"""
state = torch.load(path, map_location='cpu', weights_only=False)
# 1. Model parameters and buffers
if strict:
self.load_state_dict(state['model_state_dict'])
else:
self.load_state_dict(state['model_state_dict'], strict=False)
# 2. Hippocampal episodic memory
if 'hippocampal_memories' in state:
restored = []
for mem in state['hippocampal_memories']:
entry = {}
for k, v in mem.items():
v = v.clone()
# Normalize to [1, T, D] — old checkpoints stored [B, T, D]
if v.dim() >= 3 and v.shape[0] > 1:
v = v.mean(dim=0, keepdim=True)
entry[k] = v
restored.append(entry)
self.hippocampus._memory_buffer = restored
self.hippocampus._surprise_buffer = list(state.get('hippocampal_surprises', []))
# 3. Developmental program step
if 'developmental_step' in state:
self.learning_manager.development._current_step = state['developmental_step']
# 4. Wake-sleep scheduler state
if 'wake_steps' in state:
self.learning_manager.wake_sleep.wake_steps = state['wake_steps']
if 'sleep_phases' in state:
self.learning_manager.wake_sleep.sleep_phases = state['sleep_phases']
if 'total_steps' in state:
self.learning_manager.wake_sleep.total_steps = state['total_steps']
# 5. Hebbian optimizer LR
if 'hebbian_lr' in state:
self.learning_manager.hebbian_optimizer.lr = state['hebbian_lr']
# ─────────────────────────────────────────────────────────────────
# Self-Repair: Weight Rollback + Adaptive Sleep
# ─────────────────────────────────────────────────────────────────
@torch.no_grad()
def checkpoint_best(self, loss: float):
"""
Save current state as best if loss improved.
Called periodically during training. If loss diverges > 2x best,
triggers rollback.
Also monitors weight norms across all columns for explosion detection.
Graduated response:
- Mild (norm > 50): emergency downscaling for that column
- Severe (norm > 200 or loss > 2x best for 100+ steps): full rollback
Brain analogy: the brain's error-monitoring system (ACC + DA)
detects when something has gone wrong and reverts to last-known-good
strategy (habit system in basal ganglia takes over from PFC).
"""
self._steps_since_best += 1
# ── Weight norm explosion detection (graduated response) ──
# Check every column's total parameter norm
max_col_norm = 0.0
for i, col in enumerate(self.columns):
col_norm = sum(p.data.norm().item() ** 2 for p in col.parameters()) ** 0.5
max_col_norm = max(max_col_norm, col_norm)
# Mild explosion: emergency downscaling for this column
if col_norm > 50.0:
scale = 50.0 / col_norm
for p in col.parameters():
p.data.mul_(scale)
# Severe explosion: regardless of loss, trigger rollback
if max_col_norm > 200.0 and self._best_state is not None:
return self._trigger_rollback(loss)
if loss < self._best_loss:
self._best_loss = loss
self._best_state = {k: v.cpu().clone() for k, v in self.state_dict().items()}
self._steps_since_best = 0
return {'checkpointed': True, 'best_loss': loss}
# Divergence detection: loss > 2x best AND sustained (100+ steps since best)
if loss > self._best_loss * 2.0 and self._steps_since_best > 100:
return self._trigger_rollback(loss)
return {'checkpointed': False}
@torch.no_grad()
def _trigger_rollback(self, current_loss: float) -> dict:
"""
Emergency rollback to best-known state.
Also increases sleep frequency (adaptive sleep) to consolidate.
"""
if self._best_state is None:
return {'rollback': False, 'reason': 'no_best_state'}
self._rollback_count += 1
# Restore best weights
self.load_state_dict(self._best_state)
self._steps_since_best = 0
# Adaptive sleep: after rollback, increase sleep frequency
# (brain under stress needs more consolidation)
old_interval = self.learning_manager.wake_sleep.cfg.sleep_interval
new_interval = max(10, old_interval // 2)
self.learning_manager.wake_sleep.cfg.sleep_interval = new_interval
return {
'rollback': True,
'rollback_count': self._rollback_count,
'from_loss': current_loss,
'to_loss': self._best_loss,
'sleep_interval': f'{old_interval} → {new_interval}',
}
# ─────────────────────────────────────────────────────────────────
# Utilities
# ─────────────────────────────────────────────────────────────────
def get_optimizer_groups(self, lr: Optional[float] = None) -> List[dict]:
"""
Get parameter groups for optimizer (if using backprop mode).
Groups:
- base: all regular parameters (1x LR)
- gates: gate_raw parameters (20x LR, fast learning)
- sigma2: precision parameters (1x LR, careful)
"""
if lr is None:
lr = self.cfg.base_lr
base_params = []
gate_params = []
sigma2_params = []
for name, param in self.named_parameters():
if not param.requires_grad:
continue
if 'gate_raw' in name:
gate_params.append(param)
elif 'sigma2' in name:
sigma2_params.append(param)
else:
base_params.append(param)
return [
{'params': base_params, 'lr': lr, 'weight_decay': self.cfg.weight_decay},
{'params': gate_params, 'lr': lr * self.cfg.gate_lr_mult, 'weight_decay': 0.0},
{'params': sigma2_params, 'lr': lr, 'weight_decay': 0.0},
]
# ═══════════════════════════════════════════════════════════════════════
# Model Factory
# ═══════════════════════════════════════════════════════════════════════
def create_v11_model(cfg: Optional[V11Config] = None, **kwargs) -> CorticalColumnNetwork:
"""
Create a V11 Cortical Column Network.
Usage:
model = create_v11_model() # Default config
model = create_v11_model(V11Config(d_model=1024, n_columns=16)) # Custom
model = create_v11_model(d_model=256, n_columns=6) # kwargs override
"""
if cfg is None:
cfg = V11Config(**kwargs)
else: