Skip to content
Part 17 of 20

Production Interface

Krrish Choudhary·March 23, 2026

Source: nct_v2/v11_production.py Lines: 567 Functions: 8 Classes: 3

Overview

This module bridges NCT’s brain-inspired architecture with real-world deployment infrastructure, providing five adapter systems that leverage NCT’s intrinsic brain signals for production-level decisions. The key insight: transformers require external systems for quantization sensitivity analysis, tool use routing, retrieval-augmented generation triggers, and compute allocation. NCT’s biological signals, prediction precision (σ2\sigma^2), dopaminergic exploration/exploitation (DA\text{DA}, tonic and phasic), ACC conflict monitoring, and hippocampal surprise tagging, provide these capabilities natively as byproducts of the forward pass.

The five adapter systems are: (1) σ2\sigma^2-guided quantization precision mapping, (2) FSDP2 distributed training with column-level sharding, (3) SFT/DPO alignment with σ2\sigma^2-adaptive loss weighting, (4) agentic tool use and retrieval triggered by brain signals, and (5) σ2\sigma^2-early-exit for adaptive column depth (variable compute per token). Each adapter extracts signals already computed during the standard forward pass, no additional modules or forward passes are needed.

Quantization (σ2\sigma^2-Guided Precision Mapping)

Theorem 34 (Brain-Signal-Guided Quantization). NCT parameters are mapped to precision levels based on their computational sensitivity, how much quantization noise each parameter can tolerate without degrading the brain mechanisms:

precision(θ)={FP16if θ∈{Wσ,decay rates,osc phases,grid-cell ω}INT8if θ∈{WL4,WL5,WL6,Wgate,Wintern,Wembed,WLM}INT4if θ∈{Wassoc,WFFN} (largest blocks, highest redundancy)\text{precision}(\theta) = \begin{cases} \text{FP16} & \text{if } \theta \in \{W_\sigma, \text{decay rates}, \text{osc phases}, \text{grid-cell } \omega\} \\ \text{INT8} & \text{if } \theta \in \{W_{\text{L4}}, W_{\text{L5}}, W_{\text{L6}}, W_{\text{gate}}, W_{\text{intern}}, W_{\text{embed}}, W_{\text{LM}}\} \\ \text{INT4} & \text{if } \theta \in \{W_{\text{assoc}}, W_{\text{FFN}}\} \text{ (largest blocks, highest redundancy)} \end{cases}

Rationale for FP16 on σ2\sigma^2: Precision weights directly control the PC learning signal (Δθ∝1/σ2\Delta\theta \propto 1/\sigma^2). Quantization noise in σ2\sigma^2 propagates multiplicatively into weight updates, making this the most quantization-sensitive parameter. Decay rates (σ(β)\sigma(\beta)) compound exponentially, small errors grow over hundreds of tokens. Oscillatory phases require sub-radian precision for correct PAC coupling.

Rationale for INT4 on WassocW_{\text{assoc}}: The L2/3 association weights are the largest single parameter block (H×dh×dhH \times d_h \times d_h per column ×N\times N columns). They are updated by Hebbian learning (which is inherently noisy), making them tolerant of quantization noise. Similarly, L5 FFN weights (d×dff×2d \times d_{\text{ff}} \times 2) have high redundancy.

Distributed Training (FSDP2)

Definition 9 (Column-Level FSDP Sharding). Each CorticalColumn is one FSDP unit. This ensures that all stateful components within a column (L2/3 Hebbian weights, working memory state, oscillatory phases, BCM threshold, metaplasticity EMA) reside on the same device and are never split across shards. The wrapping policy:

  1. Inner shard (per column): All 6 layers + interneurons + WM + oscillations + BCM + metaplasticity. Each column is fully_shard()’ed independently.

  2. Outer shard (model level): Embedding, LM head, thalamus, hippocampus, basal ganglia, cerebellum, brainstem, lateral connections, workspace, self-assessment. These are smaller and can be split across devices.

Mixed precision policy: param_dtype=bfloat16, reduce_dtype=float32 (accumulate gradients in full precision to prevent Hebbian update drift).

Alignment: SFT with σ2\sigma^2-Aware Weighting

Theorem 35 (σ2\sigma^2-Aware Supervised Fine-Tuning). Standard SFT applies uniform loss weight to all tokens. NCT’s SFT reduces loss weight on tokens where the model is genuinely uncertain: LSFT=∑t=1Tℓ(yt,y^t)⋅mt⋅wσ2∑t=1Tmt,wσ2=11+0.1⋅max⁡(0,σˉ2−2.0)\mathcal{L}_{\text{SFT}} = \frac{\sum_{t=1}^T \ell(y_t, \hat{y}_t) \cdot m_t \cdot w_{\sigma^2}}{\sum_{t=1}^T m_t}, \qquad w_{\sigma^2} = \frac{1}{1 + 0.1 \cdot \max(0, \bar{\sigma}^2 - 2.0)} where mtm_t is the response mask (1 for response tokens, 0 for prompt tokens) and σˉ2\bar{\sigma}^2 is the mean precision across columns. When σˉ2>2.0\bar{\sigma}^2 > 2.0 (uncertain), the weight decreases, the model is not penalized for being uncertain about genuinely ambiguous content. Auxiliary losses (PC + cerebellar) are maintained at 10% weight to preserve brain mechanisms during fine-tuning.

Alignment: DPO with σ2\sigma^2-Adaptive β\beta

Theorem 36 (σ2\sigma^2-Adaptive Direct Preference Optimization). Standard DPO uses a fixed temperature β\beta. NCT scales β\beta inversely with model uncertainty: βeff=βmax⁡(σˉ2,0.1)\beta_{\text{eff}} = \frac{\beta}{\max(\bar{\sigma}^2, 0.1)} LDPO=−log⁡σ(βeff⋅(log⁡πθ(yw∣x)πref(yw∣x)−log⁡πθ(yl∣x)πref(yl∣x)))\mathcal{L}_{\text{DPO}} = -\log\sigma\Big(\beta_{\text{eff}} \cdot \Big(\log\frac{\pi_\theta(y_w|x)}{\pi_{\text{ref}}(y_w|x)} - \log\frac{\pi_\theta(y_l|x)}{\pi_{\text{ref}}(y_l|x)}\Big)\Big) High certainty (low σ2\sigma^2): βeff\beta_{\text{eff}} is large →\rightarrow strong preference enforcement. The model is confident, so push hard toward the preferred output.

High uncertainty (high σ2\sigma^2): βeff\beta_{\text{eff}} is small →\rightarrow soft preference enforcement. The model is uncertain, so don’t force strong opinions on ambiguous content.

This is biologically motivated: the brain doesn’t form strong preferences about things it doesn’t understand. Premature certainty is a pathology, not a feature.

σ^2-adaptive production: a single brain signal (prediction precision) drives four deployment decisions. SFT reduces loss weight on uncertain tokens. DPO softens preferences on ambiguous content. Tool use activates when uncertain. Early exit skips columns when confident. All from one forward pass, zero additional compute.
Figure 83. σ2\sigma^2-adaptive production: a single brain signal (prediction precision) drives four deployment decisions. SFT reduces loss weight on uncertain tokens. DPO softens preferences on ambiguous content. Tool use activates when uncertain. Early exit skips columns when confident. All from one forward pass, zero additional compute.
(Illustrated) σ^2-adaptive production: a single brain signal (prediction precision) drives four deployment decisions. SFT reduces loss weight on uncertain tokens. DPO softens preferences on ambiguous cont...
Figure 84. (Illustrated) σ2\sigma^2-adaptive production: a single brain signal (prediction precision) drives four deployment decisions. SFT reduces loss weight on uncertain tokens. DPO softens preferences on ambiguous cont...

Tool Use (V11ToolAdapter)

NCT’s biological circuits provide native signals for agentic tool use:

should_use_tool(result)=(σ2>θtool0.3+tonic_DA)\text{should\_use\_tool}(\text{result}) = \left(\sigma^2 > \frac{\theta_{\text{tool}}}{0.3 + \text{tonic\_DA}}\right)

High σ2\sigma^2 + high tonic DA: Uncertain + exploring →\rightarrow try a tool (the BG “Go” pathway is activated). Low σ2\sigma^2: Confident in text generation →\rightarrow don’t interrupt with tool use. DA modulates the threshold: high DA lowers the threshold (more impulsive tool use, analogous to dopaminergic exploration). Tool confidence is computed from ACC conflict: high conflict = low confidence = maybe ask the user.

Retrieval (V11RetrievalAdapter)

The retrieval adapter implements σ2\sigma^2-gated retrieval-augmented generation (RAG). Unlike standard RAG systems that retrieve on every query (wasting latency and tokens), NCT retrieves only when the model is genuinely uncertain:

should_retrieve(result)=(σˉ2>θretrieval),θretrieval=2.0\text{should\_retrieve}(\text{result}) = (\bar{\sigma}^2 > \theta_{\text{retrieval}}), \qquad \theta_{\text{retrieval}} = 2.0

This is biologically motivated: the hippocampus supplements cortical knowledge specifically when the cortex cannot make a confident prediction on its own. A student who knows the answer doesn’t consult the textbook; one who is uncertain does. NCT replicates this behavior automatically via σ2\sigma^2.

The retrieval query is extracted from the last column’s output (hN−1[:,−1,:]∈Rd\mathbf{h}_{N-1}[:, -1, :] \in \mathbb{R}^d), the most abstract, goal-relevant representation in the hierarchy. This query can be passed to any standard retrieval system (vector database, BM25, or hybrid) to fetch relevant context, which is then prepended to the input for the next forward pass.

The adapter also provides get_retrieval_query(model, input_ids) which runs a forward pass and extracts the query embedding, and should_retrieve(result, sigma2_threshold) which inspects a forward result’s σ2\sigma^2 without requiring an additional forward pass.

σ2\sigma^2-Early Exit (Adaptive Column Depth)

Theorem 37 (σ2\sigma^2-Guided Early Exit). The brain doesn’t process every input to the same depth. Easy stimuli are resolved in early sensory cortices; hard stimuli propagate to prefrontal regions. NCT implements this: exit at column iifi≥Nmin⁡=2andσˉi2<θexit=0.3\text{exit at column } i \quad \text{if} \quad i \geq N_{\min} = 2 \quad \text{and} \quad \bar{\sigma}^2_i < \theta_{\text{exit}} = 0.3 When σ2\sigma^2 drops below threshold (the model is confident), remaining columns are skipped. The forward pass jumps directly to subcortical processing and the LM head. This saves compute proportional to N−iN - i skipped columns, with no quality loss on easy tokens (they don’t need deep processing).

For the default 12-column model, if the model exits at column 4 (confident after 4 columns), it saves 8/12=67%8/12 = 67\% of column compute on that token. The average savings depend on the input difficulty distribution.

Production Setup

A convenience function setup_v11_production(model) attaches all adapters:

model.tools = V11ToolAdapter(model)
model.retrieval = V11RetrievalAdapter(model)

After calling this, the model’s own brain signals drive tool use and retrieval decisions without any external routing logic.

Source Code

Python
569 lines
    print(f"\n{'=' * 60}")
    print(f"  V11 Scaling Report — {r['n_columns']} columns, d={r['d_model']}")
    print(f"{'=' * 60}")
    print(f"  Total params:          {r['total_params']:>12,}")
    print(f"  Local (columns):       {r['local_column_params']:>12,}  ({r['local_pct']:.1f}%)")
    print(f"  Global (routing):      {r['global_coordination_params']:>12,}  ({r['global_pct']:.1f}%)")
    print(f"  Fixed (embed/head):    {r['fixed_params']:>12,}  ({r['fixed_pct']:.1f}%)")
    print(f"  Subcortical:           {r['subcortical_params']:>12,}  ({r['subcortical_pct']:.1f}%)")
    print(f"  Mean params/column:    {r['mean_column_params']:>12,.0f}")
    print(f"{'─' * 60}")
    print(f"  Scaling Costs (estimated):")
    print(f"    Add 1 column:        ~{r['pct_cost_grow_1']:.1f}% of full retrain")
    print(f"    Split 1 column:      ~{r['pct_cost_split_1']:.1f}% of full retrain")
    print(f"    Full retrain:        100%")
    print(f"{'=' * 60}\n")



# ===========================================================================
# Production Interface (Continuous Operation)
# Source: nct_v2/v11_production.py
# ===========================================================================

"""
NCT V11: Production Integration
=================================

Wires V11 CorticalColumnNetwork into production infrastructure:
  - Quantization: σ²-guided mixed precision for V11's cortical columns
  - Distributed: FSDP2 wrapping policy for column-based architecture
  - Alignment: SFT/DPO using V11's local learning interface
  - Agentic: Tool use + retrieval using V11's BG + hippocampal signals
  - Inference: σ²-early-exit for adaptive column depth

Each section provides the adapter needed to use V11 with existing
infrastructure (quantize.py, tool_use.py, retrieval.py, agent.py).
"""



# [bundled] from .v11_config import V11Config


# ═══════════════════════════════════════════════════════════════════════
# 1. Quantization — V11-Specific Precision Mapping
# ═══════════════════════════════════════════════════════════════════════

def v11_quantization_config():
    """
    Return V11-specific quantization config for quantize.py's NCTQuantizer.

    V11 parameter categories mapped to precision levels:
      - FP16: σ² (W_sigma), decay rates, oscillatory phases, grid-cell periods
      - INT8: column projections (L4/L5/L6), interneuron weights, gates
      - INT4: L2/3 association weights (bulk, high redundancy)

    Usage:
        # [bundled] from nct_v2.quantize import NCTQuantizer
        # [bundled] from nct_v2.v11_production import v11_quantization_config, v11_precision_map

        config = v11_quantization_config()
        quantizer = NCTQuantizer()
        quantized_model = quantizer.quantize(model, config)
    """
    # [bundled] from .quantize import NCTQuantConfig, Precision

    return NCTQuantConfig(
        # L2/3 association (largest weight block — like attention, can compress)
        attention_weights=Precision.INT8,
        # L5 feedforward (like FFN — high redundancy)
        ffn_weights=Precision.INT4,
        # Embedding + LM head (shared weights)
        embedding_weights=Precision.INT8,
        lm_head_weights=Precision.INT8,
        # Precision-critical brain parameters
        sigma2_weights=Precision.FP16,       # σ² directly affects PC loss
        gate_params=Precision.INT8,           # sigmoid gates — 256 levels sufficient
        decay_rates=Precision.FP16,           # HPC/NMDA decay — exponential compounding
        neuromod_weights=Precision.INT8,      # DA/ACh/NE/5-HT projections
        oscillatory_phases=Precision.FP16,    # phase parameters need precision
        position_encoding=Precision.FP16,     # grid-cell periods/offsets
        dendritic_ffn=Precision.INT8,         # k-WTA ordering sensitive
        competition_weights=Precision.INT8,   # BrainLMHead WEAVER++
        production_delta=Precision.INT8,      # LM head delta
        # Quantization settings
        group_size=128,
        symmetric=False,
        use_gptq=True,
    )


def v11_precision_map(model: nn.Module) -> Dict[str, str]:
    """
    Map V11 parameter names to precision categories.

    Returns: {param_name: category} where category matches NCTQuantConfig fields.
    Used by NCTQuantizer.quantize() to apply per-parameter precision.
    """
    precision_map = {}
    for name, param in model.named_parameters():
        if 'W_sigma' in name or 'sigma2' in name:
            precision_map[name] = 'sigma2_weights'
        elif 'gate_raw' in name:
            precision_map[name] = 'gate_params'
        elif 'decay' in name:
            precision_map[name] = 'decay_rates'
        elif 'brainstem' in name or 'neuromod' in name:
            precision_map[name] = 'neuromod_weights'
        elif 'osc' in name or 'period' in name or 'phase' in name:
            precision_map[name] = 'oscillatory_phases'
        elif 'grid_pos' in name:
            precision_map[name] = 'position_encoding'
        elif 'embed' in name:
            precision_map[name] = 'embedding_weights'
        elif 'lm_head' in name:
            if 'competition' in name or 'delta' in name:
                precision_map[name] = 'competition_weights'
            else:
                precision_map[name] = 'lm_head_weights'
        elif 'L23' in name and 'W_assoc' in name:
            precision_map[name] = 'attention_weights'
        elif 'L5' in name and ('W_up' in name or 'W_down' in name):
            precision_map[name] = 'ffn_weights'
        elif 'interneurons' in name:
            precision_map[name] = 'dendritic_ffn'
        else:
            # Default: backbone INT8
            precision_map[name] = 'attention_weights'

    return precision_map


# ═══════════════════════════════════════════════════════════════════════
# 2. Distributed — FSDP2 Wrapping Policy for V11
# ═══════════════════════════════════════════════════════════════════════

def apply_fsdp_v11(model: nn.Module, mp_policy=None):
    """
    Apply FSDP2 (fully_shard) to V11 CorticalColumnNetwork.

    Wrapping strategy:
      - Each CorticalColumn is one FSDP unit (all 6 layers + interneurons + WM stay together)
      - Subcortical systems (thalamus, hippocampus, BG, cerebellum, brainstem) stay in outer unit
      - Embedding + LM head: outer unit (weight-tied)
      - Lateral connections + workspace: outer unit (small params)

    Usage:
        # [bundled] from nct_v2.v11_production import apply_fsdp_v11
        model = create_v11_model(cfg).cuda()
        apply_fsdp_v11(model)
        # Now model is FSDP-sharded
    """
    from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy

    if mp_policy is None:
        mp_policy = MixedPrecisionPolicy(
            param_dtype=torch.bfloat16,
            reduce_dtype=torch.float32,
        )

    # Wrap each cortical column as one FSDP unit
    # Columns are the bulk of parameters — sharding them gets the memory benefit.
    # Hooks, interneurons, WM within a column must NOT be split (stateful interaction).
    for col in model.columns:
        fully_shard(col, mp_policy=mp_policy)

    # Wrap full model (outer level catches embedding, subcortical, LM head)
    fully_shard(model, mp_policy=mp_policy)

    return model


# ═══════════════════════════════════════════════════════════════════════
# 3. Alignment — SFT/DPO Adapters for V11
# ═══════════════════════════════════════════════════════════════════════

def v11_sft_loss(
    model: nn.Module,
    input_ids: torch.Tensor,
    targets: torch.Tensor,
    response_mask: Optional[torch.Tensor] = None,
    aux_weight: float = 0.1,
) -> Tuple[torch.Tensor, Dict[str, float]]:
    """
    Compute SFT loss for V11 with brain-mechanism preservation.

    Features:
      - Response-only loss (only supervise the model's response, not the prompt)
      - σ²-aware weighting: uncertain tokens get reduced loss weight
      - Auxiliary losses at 10% weight to preserve brain mechanisms
      - PC loss + cerebellar loss maintained alongside NTP

    Args:
        model: CorticalColumnNetwork
        input_ids: [B, T] input token IDs
        targets: [B, T] target token IDs (-1 for prompt tokens)
        response_mask: [B, T] binary mask (1 = response token, 0 = prompt token)
        aux_weight: weight for auxiliary losses (PC + cerebellar)

    Returns: (total_loss, metrics_dict)
    """
    result = model(input_ids, targets)
    logits = result['logits']
    metrics = {}

    # NTP loss (response-only if mask provided)
    if response_mask is not None:
        # Only compute loss on response tokens
        ntp_loss = F.cross_entropy(
            logits.view(-1, logits.shape[-1]),
            targets.view(-1),
            ignore_index=-1,
            reduction='none',
        ).view(targets.shape)

        # σ²-aware weighting: high uncertainty = reduce loss weight slightly
        # Brain principle: don't force confidence on genuinely ambiguous content
        sigma2_mean = result['metrics'].get('sigma2_mean', 1.0)
        sigma2_weight = 1.0 / (1.0 + 0.1 * max(0, sigma2_mean - 2.0))

        ntp_loss = (ntp_loss * response_mask * sigma2_weight).sum() / response_mask.sum().clamp(min=1)
    else:
        ntp_loss = result.get('loss', F.cross_entropy(
            logits.view(-1, logits.shape[-1]),
            targets.view(-1),
            ignore_index=-1,
        ))

    # Auxiliary losses (preserve brain mechanisms during SFT)
    pc_loss = result.get('pc_loss', torch.tensor(0.0))
    cb_loss = result.get('cb_loss', torch.tensor(0.0))
    trn_loss = result.get('trn_loss', torch.tensor(0.0))

    total_loss = ntp_loss + aux_weight * (pc_loss + cb_loss + trn_loss)

    metrics['ntp_loss'] = ntp_loss.item()
    metrics['pc_loss'] = pc_loss.item() if isinstance(pc_loss, torch.Tensor) else pc_loss
    metrics['cb_loss'] = cb_loss.item() if isinstance(cb_loss, torch.Tensor) else cb_loss
    metrics['total_loss'] = total_loss.item()
    metrics['sigma2_mean'] = result['metrics'].get('sigma2_mean', 0.0)

    return total_loss, metrics


def v11_dpo_loss(
    policy_model: nn.Module,
    ref_model: nn.Module,
    chosen_ids: torch.Tensor,
    rejected_ids: torch.Tensor,
    chosen_targets: torch.Tensor,
    rejected_targets: torch.Tensor,
    beta: float = 0.1,
    adaptive_beta: bool = True,
) -> Tuple[torch.Tensor, Dict[str, float]]:
    """
    DPO loss for V11 with σ²-adaptive β (brain-inspired preference learning).

    When the model is uncertain (high σ²), we reduce β — don't force strong
    preferences on content the model genuinely finds ambiguous.

    Args:
        policy_model: current CorticalColumnNetwork being trained
        ref_model: frozen reference CorticalColumnNetwork
        chosen_ids/targets: preferred completion
        rejected_ids/targets: dispreferred completion
        beta: DPO temperature
        adaptive_beta: if True, scale β by 1/σ² (higher certainty → stronger preference)

    Returns: (dpo_loss, metrics_dict)
    """
    metrics = {}

    # Policy forward
    policy_chosen = policy_model(chosen_ids, chosen_targets)
    policy_rejected = policy_model(rejected_ids, rejected_targets)

    # Reference forward (no grad)
    with torch.no_grad():
        ref_chosen = ref_model(chosen_ids, chosen_targets)
        ref_rejected = ref_model(rejected_ids, rejected_targets)

    # Per-token log probabilities
    def get_logps(logits, targets):
        log_probs = F.log_softmax(logits.float(), dim=-1)
        mask = (targets != -1).float()
        per_token = torch.gather(log_probs, -1, targets.clamp(min=0).unsqueeze(-1)).squeeze(-1)
        return (per_token * mask).sum(dim=-1) / mask.sum(dim=-1).clamp(min=1)

    pi_chosen_lp = get_logps(policy_chosen['logits'], chosen_targets)
    pi_rejected_lp = get_logps(policy_rejected['logits'], rejected_targets)
    ref_chosen_lp = get_logps(ref_chosen['logits'], chosen_targets)
    ref_rejected_lp = get_logps(ref_rejected['logits'], rejected_targets)

    # σ²-adaptive β: higher certainty → stronger preference enforcement
    effective_beta = beta
    if adaptive_beta:
        sigma2_chosen = policy_chosen['metrics'].get('sigma2_mean', 1.0)
        sigma2_rejected = policy_rejected['metrics'].get('sigma2_mean', 1.0)
        avg_sigma2 = (sigma2_chosen + sigma2_rejected) / 2
        # Scale β inversely with uncertainty (β × 1/σ²)
        effective_beta = beta / max(avg_sigma2, 0.1)
        metrics['effective_beta'] = effective_beta

    # DPO loss: -log σ(β × (log π/ref_chosen - log π/ref_rejected))
    chosen_reward = pi_chosen_lp - ref_chosen_lp
    rejected_reward = pi_rejected_lp - ref_rejected_lp

    dpo_loss = -F.logsigmoid(effective_beta * (chosen_reward - rejected_reward)).mean()

    metrics['dpo_loss'] = dpo_loss.item()
    metrics['chosen_reward'] = chosen_reward.mean().item()
    metrics['rejected_reward'] = rejected_reward.mean().item()
    metrics['reward_margin'] = (chosen_reward - rejected_reward).mean().item()

    return dpo_loss, metrics


# ═══════════════════════════════════════════════════════════════════════
# 4. Agentic — Tool Selection + Retrieval using V11 Signals
# ═══════════════════════════════════════════════════════════════════════

class V11ToolAdapter:
    """
    Adapter connecting V11's BG/σ²/ACC signals to tool_use.py infrastructure.

    V11 already HAS the biological circuits for tool use:
      - BasalGanglia: D1 (GO) / D2 (NO-GO) action selection
      - σ² (per-column): confidence in tool selection
      - Hippocampus: tool schema storage (like NMDA slots in V10.2)
      - SelfAssessment/ACC: conflict detection when tools ambiguous

    This adapter extracts those signals from V11's forward result
    and provides them to the existing ToolSelector/NCTAgent infrastructure.
    """

    def __init__(self, model):
        self.model = model

    def extract_signals(self, result: dict) -> dict:
        """
        Extract V11 signals needed for tool selection.

        Returns dict compatible with tool_use.py's ToolSelector.select():
          - sigma2: uncertainty level (float)
          - tonic_da: exploration tendency (float)
          - acc_conflict: ambiguity level (float)
          - residual: final hidden state [B, T, D]
        """
        metrics = result.get('metrics', {})
        return {
            'sigma2': metrics.get('sigma2_mean', 1.0),
            'tonic_da': metrics.get('tonic_da', 0.5),
            'acc_conflict': metrics.get('conflict', 0.0),
            'residual': result['logits'],  # Last layer output before argmax
            'da_mean': metrics.get('da_mean', 0.5),
            'ne_mean': metrics.get('ne_mean', 0.5),
        }

    def should_use_tool(self, result: dict, threshold: float = 0.3) -> bool:
        """
        Brain-inspired tool use decision using V11's intrinsic signals.

        The basal ganglia implements GO/NO-GO for action selection.
        High DA + high σ² = uncertain + exploring → try a tool.
        Low σ² = confident in text generation → don't interrupt with tool.
        """
        signals = self.extract_signals(result)
        sigma2 = signals['sigma2']
        tonic_da = signals['tonic_da']

        # DA modulates threshold (high DA → lower threshold → more tool exploration)
        effective_threshold = threshold / max(0.3 + tonic_da, 0.1)

        # Tool use when uncertain enough
        return sigma2 > effective_threshold

    def get_tool_confidence(self, result: dict) -> float:
        """
        Confidence in tool selection (1.0 = very confident, 0.0 = uncertain).

        Uses ACC conflict: high conflict = low confidence = maybe ask user.
        """
        conflict = result.get('metrics', {}).get('conflict', 0.0)
        return max(0.0, 1.0 - conflict)


class V11RetrievalAdapter:
    """
    Adapter connecting V11's σ²/hippocampal signals to retrieval.py infrastructure.

    V11's hippocampus naturally implements retrieval:
      - High σ² → uncertain → retrieve external knowledge
      - Low σ² → confident → generate from cortical knowledge
      - Hippocampal pattern completion ≈ associative retrieval

    This adapter provides the gate signal for σ²-optimal retrieval (Thm 72).
    """

    def __init__(self, model):
        self.model = model

    def should_retrieve(self, result: dict, sigma2_threshold: float = 2.0) -> bool:
        """
        σ²-gated retrieval: only retrieve when model is uncertain.

        Brain principle: the hippocampus supplements cortical knowledge
        when the cortex can't make a confident prediction on its own.
        """
        sigma2 = result.get('metrics', {}).get('sigma2_mean', 1.0)
        return sigma2 > sigma2_threshold

    def get_retrieval_query(self, model, input_ids: torch.Tensor) -> torch.Tensor:
        """
        Extract query embedding for retrieval from V11's last column output.

        Uses the final column's representation as the retrieval query —
        this is the most abstract, goal-relevant representation.
        """
        result = model(input_ids)
        # Last token of last column = most processed representation
        # logits are the output, but we want pre-lm-head representation
        # Access via last column output stored during forward
        if model._last_column_outputs:
            return model._last_column_outputs[-1].output[:, -1, :]  # [B, D]
        return result['logits'][:, -1, :]  # fallback


# ═══════════════════════════════════════════════════════════════════════
# 5. Inference — σ²-Early-Exit for Adaptive Column Depth
# ═══════════════════════════════════════════════════════════════════════

class V11EarlyExitConfig:
    """Configuration for σ²-guided early exit in V11."""
    sigma2_threshold: float = 0.3   # Exit when σ² drops below this
    min_columns: int = 2            # Always run at least 2 columns
    enabled: bool = True


def v11_forward_with_early_exit(
    model,
    input_ids: torch.Tensor,
    targets=None,
    sigma2_threshold: float = 0.3,
    min_columns: int = 2,
) -> Dict[str, torch.Tensor]:
    """
    V11 forward with σ²-guided early exit.

    Brain principle: the brain doesn't process every input to the same depth.
    Easy inputs (low σ²) are resolved in early sensory areas.
    Hard inputs (high σ²) propagate to deeper prefrontal processing.

    This skips remaining columns once σ² drops below threshold,
    saving compute on easy tokens.

    Args:
        model: CorticalColumnNetwork
        input_ids: [B, T]
        targets: [B, T] optional
        sigma2_threshold: exit when mean σ² < this
        min_columns: always process at least this many columns

    Returns: same dict as standard forward, plus 'columns_used' metric
    """
    B, T = input_ids.shape
    device = input_ids.device
    cfg = model.cfg

    # Embedding
    x = model.embed(input_ids)
    x = model.embed_norm(x)
    x = model.embed_dropout(x)
    rope_cos, rope_sin = model.grid_pos(T, device, x.dtype, X=x)

    if cfg.thalamic_enabled:
        model.thalamus.reset_loss()

    # Process columns with early exit
    column_outputs = []
    thal_feedbacks = [None] * cfg.n_columns
    h = x
    columns_used = 0

    for i, col in enumerate(model.columns):
        h_thal = model.thalamus.route(h, column_idx=i, thal_feedback=thal_feedbacks[i])
        out = col(ff_input=h_thal, td_context=None,
                  rope_cos=rope_cos, rope_sin=rope_sin)
        column_outputs.append(out)
        thal_feedbacks[i] = out.thal_feedback
        h = out.output
        columns_used = i + 1

        # Early exit check: if σ² is low enough after minimum columns
        if i >= min_columns - 1:
            mean_sigma2 = out.sigma2.mean().item()
            if mean_sigma2 < sigma2_threshold:
                break

    # Skip remaining PC inference (early exit means we're confident)
    # Go directly to output

    # Brainstem neuromod
    top_output = column_outputs[-1].output
    errors = []
    for l in range(len(column_outputs)):
        target = x.detach() if l == 0 else column_outputs[l - 1].output.detach()
        errors.append(target - column_outputs[l].prediction)

    neuromod = model.brainstem.compute_state(
        top_output,
        prediction_error=errors[-1] if errors else None,
    )

    # BG + cerebellum + hippocampus
    if cfg.bg_enabled:
        h = model.basal_ganglia(h, neuromod.dopamine)
    if cfg.cerebellum_enabled:
        h, cb_loss = model.cerebellum(h)
    else:
        cb_loss = torch.tensor(0.0, device=device)
    if cfg.hpc_enabled:
        mean_sigma2_t = sum(out.sigma2 for out in column_outputs) / len(column_outputs)
        h = model.hippocampus(h, mean_sigma2_t)

    # LM head
    logits = model.lm_head(model.lm_head_norm(h))

    result = {'logits': logits, 'cb_loss': cb_loss}
    if targets is not None:
        result['loss'] = F.cross_entropy(
            logits.view(-1, cfg.vocab_size),
            targets.view(-1),
            ignore_index=-1,
        )

    # PC loss for columns that were used
    predictions = [out.prediction for out in column_outputs]
    pred_targets = [x.detach()] + [column_outputs[l].output.detach() for l in range(len(column_outputs) - 1)]
    precisions = [out.sigma2 for out in column_outputs]
    _, pc_loss = model.learning_manager.pc_optimizer.compute_column_losses(
        predictions, pred_targets, precisions
    )
    result['pc_loss'] = pc_loss

    # Metrics
    all_sigma2 = torch.cat([out.sigma2 for out in column_outputs], dim=-1)
    result['metrics'] = {
        'sigma2_mean': all_sigma2.mean().item(),
        'columns_used': columns_used,
        'columns_total': cfg.n_columns,
        'columns_saved': cfg.n_columns - columns_used,
        'da_mean': neuromod.dopamine.mean().item(),
        'tonic_da': neuromod.tonic_da,
    }

    return result


# ═══════════════════════════════════════════════════════════════════════
# Convenience: Full Production Setup
# ═══════════════════════════════════════════════════════════════════════

def setup_v11_production(model):
    """
    Attach all production adapters to a V11 model.

    After calling this, the model has:
      model.tools    — V11ToolAdapter
      model.retrieval — V11RetrievalAdapter