Skip to content
Part 10 of 20

Brain Decoding (Drift-Diffusion Sampler)

Krrish Choudhary·March 23, 2026

Source: nct_v2/brain_decoding.py Lines: 914 Classes: 4

Neuroscience Foundation

Standard language model decoding strategies, greedy search, beam search, top-kk sampling, nucleus (top-pp) sampling, are engineering heuristics with no biological basis. They impose external constraints on the sampling process without regard for the model’s internal state or confidence. The brain makes decisions through a fundamentally different mechanism: evidence accumulation.

In the primate prefrontal and lateral intraparietal cortex, neural populations representing different decision alternatives gradually accumulate evidence in favor of their preferred option (Gold & Shadlen, 2007; Ratcliff & McKoon, 2008). This accumulation is noisy (stochastic), biased by prior expectations, and terminates when any population’s activity crosses a decision threshold. The first population to cross wins, and its associated action is executed. This mechanism explains both the speed and accuracy of decisions, including the well-documented speed-accuracy tradeoff: lowering the threshold produces faster but less accurate decisions.

The drift-diffusion model (DDM) formalizes this process mathematically and accounts for reaction time distributions and error rates across dozens of cognitive paradigms, from simple perceptual discrimination to complex lexical decisions. NCT adapts this model for token selection during text generation.

NCT implements three biologically-grounded decoding mechanisms that work together: drift-diffusion evidence accumulation, inhibition of return for repetition avoidance, and σ2\sigma^2-adaptive temperature control.

Drift-Diffusion Sampler

Theorem 9 (Evidence Accumulation with DA-Modulated Threshold). For each generation step, evidence accumulates as the margin between the top and second logits, plus stochastic noise: e(t)=e(t−1)+(logitstop−logits2nd)⏟drift (evidence strength)+N(0,σnoise)⏟diffusion (noise)e(t) = e(t-1) + \underbrace{(\text{logits}_{\text{top}} - \text{logits}_{\text{2nd}})}_{\text{drift (evidence strength)}} + \underbrace{\mathcal{N}(0, \sigma_{\text{noise}})}_{\text{diffusion (noise)}} A token is committed when evidence exceeds a DA-modulated, time-collapsing threshold: θ(t)=θbase⋅(1+DA⋅urgency(t)),urgency(t)=1−e−t/τu\theta(t) = \theta_{\text{base}} \cdot (1 + \text{DA} \cdot \text{urgency}(t)), \qquad \text{urgency}(t) = 1 - e^{-t/\tau_u}

The threshold dynamics create biologically faithful behavior:

  • Low DA (Parkinson’s analog): high threshold →\rightarrow slow, conservative decisions

  • High DA (mania analog): low threshold →\rightarrow fast, impulsive decisions

  • Urgency signal: threshold collapses over time, preventing indefinite deliberation

Inhibition of Return

Definition 2 (Repetition Avoidance via Decaying Suppression). An exponentially decaying suppression trace is applied to recently-generated token logits: suppress[t]={s0=−5.0at generation stepα⋅suppress[t−1]each subsequent step, α=0.85\text{suppress}[t] = \begin{cases} s_0 = -5.0 & \text{at generation step} \\ \alpha \cdot \text{suppress}[t-1] & \text{each subsequent step, } \alpha = 0.85 \end{cases} logitstadj=logitst+suppress[t]\text{logits}_t^{\text{adj}} = \text{logits}_t + \text{suppress}[t] This makes the model “tired” of tokens it just produced, preventing repetition loops. The suppression decays exponentially, allowing re-use after sufficient intervening tokens.

σ2\sigma^2-Adaptive Temperature

Proposition 2 (σ2\sigma^2-Controlled Sampling Diversity). The model’s own prediction precision directly controls sampling temperature: Teff=Tbase⋅11+αT⋅max⁡(0,σˉref2−σˉ2)T_{\text{eff}} = T_{\text{base}} \cdot \frac{1}{1 + \alpha_T \cdot \max(0, \bar{\sigma}^2_{\text{ref}} - \bar{\sigma}^2)} High precision (low σ2\sigma^2, confident) →\rightarrow lower temperature →\rightarrow deterministic output. Low precision (high σ2\sigma^2, uncertain) →\rightarrow higher temperature →\rightarrow exploratory output. This creates natural variation in generation style: the model is precise on well-understood content and creative on novel topics.

Brain decoding pipeline: logits are adjusted by inhibition of return (suppress recent tokens) and σ^2-adaptive temperature, then passed to the drift-diffusion sampler which accumulates evidence until a DA-modulated threshold is crossed.
Figure 15. Brain decoding pipeline: logits are adjusted by inhibition of return (suppress recent tokens) and σ2\sigma^2-adaptive temperature, then passed to the drift-diffusion sampler which accumulates evidence until a DA-modulated threshold is crossed.
(Illustrated) Brain decoding pipeline: logits are adjusted by inhibition of return (suppress recent tokens) and σ^2-adaptive temperature, then passed to the drift-diffusion sampler which accumulates evide...
Figure 16. (Illustrated) Brain decoding pipeline: logits are adjusted by inhibition of return (suppress recent tokens) and σ2\sigma^2-adaptive temperature, then passed to the drift-diffusion sampler which accumulates evide...

BrainDecoder Orchestrator

The BrainDecoder class orchestrates all three mechanisms plus:

  • Extraction of σ2\sigma^2, DA, NE, ACh signals from the forward pass

  • Speculative generation: generate KK candidates in parallel, verify with teacher model, accept longest correct prefix

  • Context window management for long sequences

Source Code

Python
914 lines
# ===========================================================================
# Brain Decoding (Drift-Diffusion)
# Source: nct_v2/brain_decoding.py
# ===========================================================================

"""
NCT V10.2 Brain-Inspired Decoding — Theorems 63, 64, 65.

Replaces temperature/top-p/top-k sampling with biologically grounded
neural decision making. The brain does NOT "sample from a softmax" — it
accumulates evidence, crosses a threshold, and commits.

Three new theorems:

  Theorem 63: Drift-Diffusion Decoding
    Evidence accumulates for top-K candidates through a noisy drift-diffusion
    process. Decision occurs when evidence crosses a collapsing threshold.
    - drift_i = logit_i (evidence from model)
    - noise σ = f(stochastic resonance) — biological diversity source
    - threshold θ(t) = θ_0 × exp(-t/τ_urgency) — collapsing bound
    - θ_0 modulated by: σ² (precision → evidence quality) and DA (exploration)
    - Reduces to argmax when σ → 0, θ_0 → 0 (standard greedy)
    - Reduces to temperature sampling when noise dominates (proof below)

  Theorem 64: Inhibition of Return for Token Production
    Recently produced tokens receive decaying inhibition — a biological
    mechanism for repetition avoidance without ad-hoc penalty hacks.
    - IOR_w(t) = A × exp(-t/τ_IOR) for t steps since last production of w
    - Modified logits: logit'_w = logit_w - IOR_w
    - τ_IOR ≈ 25 tokens (IOR spans ~one phrase, then recovers)
    - Strong evidence overcomes IOR (intentional repetition preserved)

  Theorem 65: Confidence-Gated Deliberation
    Tokens are classified into System 1 (fast, confident) and System 2
    (slow, uncertain) based on evidence margin at initial assessment.
    - Confidence C = (a₁ - a₂) / σ (margin between top-2 scaled by noise)
    - High confidence → decide in 1 step (System 1: function words, idioms)
    - Low confidence → full drift-diffusion deliberation (System 2: content words)
    - Naturally produces variable thinking time per token

Neuroscience basis:
  - Drift-Diffusion Model: Ratcliff & McKoon 2008 (canonical decision model)
  - Speed-Accuracy Tradeoff: Heitz 2014, Wickelgren 1977
  - DA and exploration: Frank et al. 2009, Humphries et al. 2012
  - Evidence accumulation: Gold & Shadlen 2007, Churchland et al. 2008
  - Confidence/metacognition: Kiani & Shadlen 2009, Fleming & Daw 2017
  - Inhibition of return: Klein 2000, Posner & Cohen 1984
  - Winner-take-all competition: Usher & McClelland 2001, Wang 2002
  - Urgency/collapsing bounds: Cisek et al. 2009
  - Self-monitoring: Levelt 1989, Nozari et al. 2011

Disease mapping:
  - Parkinson's (DA depletion): threshold too high → slow, conservative output
    → NCT: low DA → high threshold → reduced exploration, repetitive text
  - ADHD (NE/DA dysregulation): threshold too low → impulsive, incoherent
    → NCT: noisy DA → unstable threshold → erratic token selection
  - OCD (ACC hyperactivity): excessive conflict → over-deliberation
    → NCT: high ACC conflict → too many diffusion steps → slow, indecisive
  - Aphasia (Broca's): impaired evidence accumulation → word-finding difficulty
    → NCT: weak drift signal → threshold rarely crossed → generation stalls

Mathematical properties:
  - Drift-diffusion is the OPTIMAL decision process under Gaussian noise
    (Wald & Wolfowitz 1948: sequential probability ratio test)
  - Expected decision time: E[T] ≈ θ_0 / max(drift) for strong evidence
  - Error rate: P(error) ∝ exp(-2 × θ × Δdrift / σ²) where Δdrift = top-2 gap
  - DA-modulated threshold: implements optimal exploration-exploitation tradeoff
    (Daw et al. 2006: Bayesian optimal with uncertainty bonus)
  - IOR with exponential decay: produces repetition statistics matching
    human speech production (Jaeger & Snider 2013: uniform information density)
  - Confidence C ~ standard normal under null (equal candidates) →
    natural p-value for "how unusual is this confidence level"

Integration with NCT V10.2:
  - σ² (PWPC Thm 28) → evidence quality: σ²_noise = f(σ²_model)
  - Tonic DA (Thm 47) → threshold: θ_0 = base × (1 + β_da × (0.5 - DA))
  - ACC conflict (Thm 39) → deliberation depth: max_steps ∝ conflict
  - Stochastic resonance (Thm 48) → noise source: uses model's own noise level
  - PhonologicalLoop (Thm 36) → working memory of recent tokens for IOR
  - SurpriseWeightingGate → importance-modulated threshold
  - ProspectiveHPCHead → multi-step lookahead verification (optional)

Parameters:
  - DriftDiffusionSampler: θ_base, τ_urgency, max_steps, K_candidates
  - InhibitionOfReturn: A (strength), τ_IOR (decay time constant)
  - BrainDecoder: orchestrator, zero learnable params (all from NCT signals)
"""



# ═══════════════════════════════════════════════════════════════════════════
# Configuration
# ═══════════════════════════════════════════════════════════════════════════

@dataclass
class BrainDecodingConfig:
    """Configuration for brain-inspired decoding.

    All parameters have neuroscience-motivated defaults. Zero manual tuning
    needed — the NCT signals (σ², DA, ACC) control everything adaptively.
    """
    # ── Drift-Diffusion (Thm 63) ────────────────────────────────────────
    theta_base: float = 3.0       # Base decision threshold (higher = more cautious)
    tau_urgency: float = 8.0      # Urgency time constant (steps until threshold halves)
    max_steps: int = 15           # Maximum deliberation steps before forced decision
    K_candidates: int = 64        # Number of top candidates for evidence accumulation
    sigma_noise_base: float = 0.3 # Base noise level (σ in diffusion process)

    # ── DA modulation ───────────────────────────────────────────────────
    beta_da: float = 0.6          # DA → threshold coupling strength
    # θ_effective = θ_base × (1 + β_da × (0.5 - DA))
    # DA = 0.5 (neutral): θ = θ_base (no change)
    # DA = 0.8 (high surprise): θ = θ_base × 0.82 (lower → explore)
    # DA = 0.2 (low surprise): θ = θ_base × 1.18 (higher → exploit)

    # ── Precision modulation ────────────────────────────────────────────
    sigma2_noise_scale: float = 1.0  # How much σ² modulates diffusion noise
    # σ_effective = σ_base × sqrt(σ²_model × scale)
    # High σ² (uncertain) → more noise → slower convergence → more deliberation
    # Low σ² (confident) → less noise → faster convergence → quick decision

    # ── ACC conflict modulation ─────────────────────────────────────────
    conflict_steps_scale: float = 10.0  # Extra steps per unit conflict
    # max_steps_effective = max_steps + conflict × conflict_steps_scale
    # High conflict (0.7) → +7 steps → much more deliberation
    # Low conflict (0.1) → +1 step → nearly immediate

    # ── Inhibition of Return (Thm 64) ──────────────────────────────────
    ior_strength: float = 2.0     # Inhibition magnitude on recently produced tokens
    ior_tau: float = 25.0         # IOR decay time constant (tokens)
    # After producing token w: IOR_w = 2.0
    # After 25 more tokens: IOR_w ≈ 2.0 × exp(-1) ≈ 0.74
    # After 50 tokens: IOR_w ≈ 2.0 × exp(-2) ≈ 0.27 (nearly recovered)

    # ── Confidence-Gated Deliberation (Thm 65) ─────────────────────────
    confidence_threshold: float = 2.5  # Margin/σ threshold for System 1 vs 2
    # C = (logit_1 - logit_2) / σ_noise
    # C > 2.5: System 1 (decide immediately, ~99% confident)
    # C < 2.5: System 2 (full drift-diffusion deliberation)

    # ── Speculative decoding (ProspectiveHPC, optional) ─────────────────
    use_speculative: bool = False  # Enable multi-token speculative decoding
    speculative_steps: int = 4    # How many tokens to speculate ahead
    speculative_threshold: float = 0.8  # Acceptance probability threshold


# ═══════════════════════════════════════════════════════════════════════════
# Theorem 64: Inhibition of Return
# ═══════════════════════════════════════════════════════════════════════════

class InhibitionOfReturn:
    """
    Biological repetition avoidance via decaying inhibition trace.

    The brain avoids re-attending to recently processed items through
    Inhibition of Return (IOR), a fundamental property of attentional
    selection (Klein 2000, Posner & Cohen 1984).

    In language production, recently produced words are harder to produce
    again — not through an ad-hoc penalty, but through genuine neural
    inhibition that decays exponentially (matching refractory periods).

    Mathematical formulation:
      On producing token w at step t_0:
        IOR_w := A                    (set inhibition to strength A)
      At each subsequent step t > t_0:
        IOR_w *= exp(-1/τ_IOR)        (exponential decay)
      Modified logits:
        logit'_w = logit_w - IOR_w    (subtractive inhibition)

    Properties:
      - Recently produced tokens have reduced logits (less likely to repeat)
      - Decay is exponential: IOR_w(Δt) = A × exp(-Δt/τ_IOR)
      - τ_IOR ≈ 25 tokens: inhibition spans ~one phrase, then recovers
      - Intentional repetition overcomes IOR through strong evidence (high logit)
      - Unlike repetition penalty: IOR is LOCAL (decays), frequency-aware,
        and biologically motivated
      - Limit: as A → 0, IOR → 0 (standard sampling recovered)
      - Limit: as τ_IOR → ∞, IOR → constant penalty (degenerate)

    Disease mapping:
      - OCD (perseveration): IOR too weak → compulsive repetition
      - Anomia (word-finding difficulty): IOR too strong → can't reuse words
    """

    def __init__(self, vocab_size: int, strength: float = 2.0, tau: float = 25.0):
        self.vocab_size = vocab_size
        self.strength = strength
        self.tau = tau
        self.decay_factor = math.exp(-1.0 / tau)
        # IOR trace for each token in vocabulary
        self.trace = None  # Lazily initialized on first use
        self._device = None

    def reset(self, device: torch.device):
        """Reset IOR trace (call at start of new generation)."""
        self.trace = torch.zeros(self.vocab_size, device=device)
        self._device = device

    def step(self, produced_token: int):
        """Update IOR trace after producing a token."""
        if self.trace is None:
            return
        # Decay all existing inhibitions
        self.trace.mul_(self.decay_factor)
        # Set fresh inhibition for the produced token
        self.trace[produced_token] = self.strength

    def apply(self, logits: torch.Tensor) -> torch.Tensor:
        """Apply IOR inhibition to logits. logits: (B, V) or (V,)."""
        if self.trace is None or self.strength == 0:
            return logits
        if logits.dim() == 2:
            return logits - self.trace.unsqueeze(0)  # (1, V) broadcast
        return logits - self.trace


# ═══════════════════════════════════════════════════════════════════════════
# Theorem 63: Drift-Diffusion Decoding
# ═══════════════════════════════════════════════════════════════════════════

class DriftDiffusionSampler:
    """
    Evidence accumulation with collapsing threshold for token selection.

    The canonical model of speeded decision making (Ratcliff & McKoon 2008).
    For each candidate token, evidence accumulates through a noisy random
    walk. The first candidate to cross the decision threshold is selected.

    Mathematical formulation:
      For K candidates with logits l_1 ≥ l_2 ≥ ... ≥ l_K:

      Evidence accumulation (discrete-time approximation):
        a_i(t+1) = a_i(t) + drift_i + σ × ξ_i(t)
        where:
          a_i(0) = 0                  (no prior evidence)
          drift_i = l_i / scale       (normalized evidence rate)
          σ = σ_base × √(σ²_model)   (precision-modulated noise)
          ξ_i(t) ~ N(0, 1)           (independent Gaussian noise)

      Collapsing threshold:
        θ(t) = θ_0 × exp(-t / τ_urgency)
        where:
          θ_0 = θ_base × (1 + β_da × (0.5 - DA))  (DA-modulated)
          τ_urgency modulated by ACC conflict

      Decision rule:
        Select i* = argmin_i {t : a_i(t) > θ(t)}
        If no crossing by max_steps: select argmax_i a_i(T)

    Proofs:
      1. Reduces to argmax when σ → 0:
         With zero noise, a_i(t) = t × drift_i. The candidate with
         highest drift (= highest logit) crosses first. QED.

      2. Reduces to temperature sampling when θ_0 → 0:
         With threshold ≈ 0, the first candidate to have positive
         accumulation wins. P(i first) ∝ exp(drift_i/σ²) by
         extreme value theory. This is softmax(logits/σ²). QED.

      3. Error rate bound:
         P(error) ≤ exp(-2θ × Δdrift / σ²) where Δdrift = l_1 - l_2
         (from Wald's identity for sequential probability ratio test).

      4. Optimal under Gaussian noise:
         Drift-diffusion is the continuous-time limit of SPRT, which is
         optimal (minimizes expected samples for given error rate) by
         Wald-Wolfowitz theorem (1948). QED.

    Disease mapping:
      - Parkinson's: high threshold → slow conservative output
      - ADHD: noisy accumulation → impulsive incoherent output
      - Schizophrenia: corrupted drift signal → loose associations
    """

    def __init__(self, config: BrainDecodingConfig):
        self.cfg = config

    def sample(
        self,
        logits: torch.Tensor,          # (B, V) raw logits from model
        sigma2: float = 1.0,           # Model's precision (from PWPC)
        tonic_da: float = 0.5,         # Tonic dopamine level
        conflict: float = 0.0,         # ACC conflict level
        ior_trace: torch.Tensor = None, # (V,) IOR inhibition trace
    ) -> Tuple[torch.Tensor, Dict]:
        """
        Run drift-diffusion evidence accumulation to select tokens.

        Args:
            logits: (B, V) raw model logits
            sigma2: scalar, model's uncertainty estimate (σ² from PWPC)
            tonic_da: scalar in (0,1), tonic dopamine level
            conflict: scalar in [0, 0.875], ACC conflict level
            ior_trace: (V,) inhibition of return trace (subtracted from logits)

        Returns:
            selected: (B,) selected token indices
            metadata: dict with deliberation statistics
        """
        B, V = logits.shape
        device = logits.device
        cfg = self.cfg

        # Apply IOR before candidate selection
        if ior_trace is not None:
            logits = logits - ior_trace.unsqueeze(0)

        # ── Select top-K candidates ─────────────────────────────────────
        K = min(cfg.K_candidates, V)
        topk_logits, topk_indices = logits.topk(K, dim=-1)  # (B, K)

        # ── Compute modulated parameters ────────────────────────────────
        # DA → threshold: high DA = high surprise → explore → lower threshold
        theta_0 = cfg.theta_base * (1.0 + cfg.beta_da * (0.5 - tonic_da))
        theta_0 = max(theta_0, 0.1)  # floor: always some threshold

        # σ² → noise: high uncertainty → more noise → slower convergence
        sigma_noise = cfg.sigma_noise_base * math.sqrt(
            max(sigma2 * cfg.sigma2_noise_scale, 0.01)
        )

        # ACC conflict → max steps: high conflict → more deliberation
        max_steps = int(cfg.max_steps + conflict * cfg.conflict_steps_scale)
        max_steps = min(max_steps, 50)  # cap to prevent infinite loops

        # Normalize logits to drift rates (scale by noise to make units comparable)
        # drift_i ∝ logit_i / σ_noise (higher logit → faster evidence accumulation)
        drift = topk_logits / max(sigma_noise * 5.0, 0.1)  # (B, K)

        # ── Confidence check: System 1 vs System 2 (Thm 65) ────────────
        # Margin between top-2 candidates relative to noise
        if K >= 2:
            margin = (topk_logits[:, 0] - topk_logits[:, 1])  # (B,)
            confidence = margin / max(sigma_noise, 0.01)  # (B,)
        else:
            confidence = torch.full((B,), float('inf'), device=device)

        # System 1: confident tokens → immediate selection (no deliberation)
        system1_mask = confidence > cfg.confidence_threshold  # (B,)

        # For System 1 items: just take argmax (no diffusion needed)
        selected = topk_indices[:, 0].clone()  # (B,) — start with top candidate
        deliberation_steps = torch.zeros(B, device=device)

        # For System 2 items: run drift-diffusion
        system2_mask = ~system1_mask
        n_system2 = system2_mask.sum().item()

        if n_system2 > 0:
            # Extract System 2 batch
            s2_drift = drift[system2_mask]  # (n2, K)
            n2 = s2_drift.shape[0]

            # Evidence accumulation
            accumulator = torch.zeros(n2, K, device=device)  # (n2, K)
            s2_selected = torch.zeros(n2, dtype=torch.long, device=device)
            s2_steps = torch.zeros(n2, device=device)
            s2_decided = torch.zeros(n2, dtype=torch.bool, device=device)

            for t in range(max_steps):
                # Collapsing threshold: θ(t) = θ_0 × exp(-t/τ_urgency)
                theta_t = theta_0 * math.exp(-t / cfg.tau_urgency)

                # Accumulate evidence: a(t+1) = a(t) + drift + noise
                noise = torch.randn(n2, K, device=device) * sigma_noise
                accumulator = accumulator + s2_drift + noise

                # Check threshold crossing for undecided items
                max_evidence, max_idx = accumulator.max(dim=-1)  # (n2,), (n2,)
                crossed = (max_evidence > theta_t) & ~s2_decided  # (n2,)

                if crossed.any():
                    s2_selected[crossed] = max_idx[crossed]
                    s2_steps[crossed] = t + 1
                    s2_decided[crossed] = True

                if s2_decided.all():
                    break

            # Force-decide remaining undecided (pick highest accumulator)
            if not s2_decided.all():
                undecided = ~s2_decided
                _, forced_idx = accumulator[undecided].max(dim=-1)
                s2_selected[undecided] = forced_idx
                s2_steps[undecided] = max_steps

            # Map back from top-K indices to vocabulary indices
            s2_topk_indices = topk_indices[system2_mask]  # (n2, K)
            s2_vocab_tokens = s2_topk_indices[
                torch.arange(n2, device=device), s2_selected
            ]  # (n2,)

            # Write back into full batch
            selected[system2_mask] = s2_vocab_tokens
            deliberation_steps[system2_mask] = s2_steps

        # ── Compile metadata ────────────────────────────────────────────
        metadata = {
            'deliberation_steps': deliberation_steps,       # (B,) steps per token
            'system1_frac': system1_mask.float().mean().item(),  # fraction System 1
            'theta_0': theta_0,                              # effective base threshold
            'sigma_noise': sigma_noise,                      # effective noise level
            'max_steps_used': max_steps,                     # effective max steps
            'confidence': confidence,                        # (B,) per-token confidence
            'tonic_da': tonic_da,                           # DA level used
            'sigma2': sigma2,                                # precision used
            'conflict': conflict,                            # ACC conflict used
        }

        return selected, metadata


# ═══════════════════════════════════════════════════════════════════════════
# BrainDecoder — Full generation pipeline orchestrating all NCT signals
# ═══════════════════════════════════════════════════════════════════════════

class BrainDecoder:
    """
    Brain-inspired text generation for NCT V10.2.

    Orchestrates all NCT neuromodulatory signals into a biologically
    grounded decoding pipeline that replaces temperature/top-p/top-k.

    Signal flow:
      model.forward(tokens)
        → logits                    (evidence for each candidate)
        → sigma2_up_list[-1]        (PWPC precision → noise modulation)
        → model.tonic_da.ema_da     (tonic DA → threshold modulation)
        → model.acc_conflict._conflict  (ACC → deliberation depth)
        → IOR trace                 (repetition avoidance)
        → DriftDiffusionSampler     (evidence accumulation → decision)
        → selected token + metadata

    The decoder has ZERO learnable parameters. It reads NCT's trained
    signals and converts them into biologically grounded decisions.

    Usage:
      decoder = BrainDecoder(model, config=BrainDecodingConfig())
      tokens, metadata = decoder.generate(prompt_tokens, max_new_tokens=100)

    Comparison with standard decoding:
      Standard:  logits → temperature scale → top-k mask → softmax → multinomial
      Brain:     logits → IOR → top-K candidates → σ²-modulated noise →
                 DA-modulated threshold → drift-diffusion → confidence gate →
                 decision with metadata
    """

    def __init__(self, model: nn.Module, config: BrainDecodingConfig = None):
        """
        Args:
            model: NCTv102Model (or any NCT model with forward returning 9-tuple)
            config: BrainDecodingConfig (uses defaults if None)
        """
        self.model = model
        self.cfg = config or BrainDecodingConfig()
        self.sampler = DriftDiffusionSampler(self.cfg)
        self.ior = InhibitionOfReturn(
            vocab_size=model.cfg.V,
            strength=self.cfg.ior_strength,
            tau=self.cfg.ior_tau,
        )

    def _extract_signals(
        self,
        sigma2_up_list: list,
    ) -> Tuple[float, float, float]:
        """
        Extract neuromodulatory signals from model after forward pass.

        Returns:
            sigma2: scalar, mean precision of last-token in top layer
            tonic_da: scalar, tonic dopamine level (0-1)
            conflict: scalar, ACC conflict level (0-0.875)
        """
        model = self.model

        # σ² from PWPC top layer, last token
        if sigma2_up_list and sigma2_up_list[-1] is not None:
            sigma2 = sigma2_up_list[-1][:, -1, :].mean().item()
        else:
            sigma2 = 1.0  # neutral default

        # Tonic DA from TonicDATemperature (Thm 47)
        if hasattr(model, 'tonic_da') and hasattr(model.tonic_da, 'ema_da'):
            tonic_da = model.tonic_da.ema_da.detach().item()
        else:
            tonic_da = 0.5  # neutral

        # ACC conflict (Thm 39)
        if hasattr(model, 'acc_conflict') and hasattr(model.acc_conflict, '_conflict'):
            conflict = model.acc_conflict._conflict
            if isinstance(conflict, torch.Tensor):
                conflict = conflict.item()
        else:
            conflict = 0.0  # no conflict

        return sigma2, tonic_da, conflict

    @torch.no_grad()
    def generate(
        self,
        prompt_tokens: torch.Tensor,  # (1, T) or (B, T)
        max_new_tokens: int = 100,
        return_metadata: bool = False,
    ) -> Tuple[torch.Tensor, Optional[List[Dict]]]:
        """
        Generate tokens using brain-inspired decoding.

        Args:
            prompt_tokens: (B, T) input token IDs
            max_new_tokens: number of tokens to generate
            return_metadata: if True, return per-step metadata

        Returns:
            tokens: (B, T + max_new_tokens) complete token sequence
            metadata: list of per-step dicts (if return_metadata=True)
        """
        model = self.model
        was_training = model.training
        model.eval()
        cfg = model.cfg

        device = prompt_tokens.device
        tokens = prompt_tokens.clone()
        B = tokens.shape[0]

        # Reset IOR trace
        self.ior.reset(device)

        # Collect per-step metadata
        step_metadata = [] if return_metadata else None

        for step in range(max_new_tokens):
            # Truncate to max sequence length
            ctx = tokens[:, -cfg.max_seq_len:]

            # Full forward pass — extracts all 9 return values
            fwd_out = model.forward(ctx)
            logits = fwd_out[0]                  # (B, T, V)
            sigma2_up_list = fwd_out[4]          # list[L] of (B, T, 1)

            # Last-token logits only
            logits_last = logits[:, -1, :].float()  # (B, V)

            # Extract NCT signals
            sigma2, tonic_da, conflict = self._extract_signals(sigma2_up_list)

            # Run drift-diffusion sampling
            selected, meta = self.sampler.sample(
                logits=logits_last,
                sigma2=sigma2,
                tonic_da=tonic_da,
                conflict=conflict,
                ior_trace=self.ior.trace,
            )  # selected: (B,)

            # Update IOR trace (use first batch item — for B=1 generation)
            self.ior.step(selected[0].item())

            # Append selected token
            tokens = torch.cat([tokens, selected.unsqueeze(1)], dim=1)

            if return_metadata:
                step_metadata.append(meta)

        if was_training:
            model.train()

        if return_metadata:
            return tokens, step_metadata
        return tokens, None

    @torch.no_grad()
    def generate_with_speculative(
        self,
        prompt_tokens: torch.Tensor,
        max_new_tokens: int = 100,
    ) -> Tuple[torch.Tensor, Dict]:
        """
        Speculative decoding using ProspectiveHPCHead (Thm 10).

        Uses the model's 8-step future predictions to draft candidate
        tokens, then verifies them against the full model. Accepted
        tokens are committed as a batch (faster generation).

        This mimics the brain's phrase-level planning: the articulatory
        system prepares entire phrases before execution, with
        self-monitoring catching errors before articulation (Levelt 1989).

        Args:
            prompt_tokens: (1, T) input token IDs (B=1 only for speculative)
            max_new_tokens: number of tokens to generate

        Returns:
            tokens: (1, T + generated) complete sequence
            stats: dict with acceptance rate, speculation depth, etc.
        """
        model = self.model
        was_training = model.training
        model.eval()
        cfg = model.cfg
        device = prompt_tokens.device

        tokens = prompt_tokens.clone()
        self.ior.reset(device)

        total_accepted = 0
        total_speculated = 0
        total_tokens_generated = 0
        spec_steps = self.cfg.speculative_steps

        while total_tokens_generated < max_new_tokens:
            ctx = tokens[:, -cfg.max_seq_len:]
            fwd_out = model.forward(ctx)

            logits = fwd_out[0]                 # (1, T, V)
            hpc_out = fwd_out[6]                # (1, T, d)
            sigma2_up_list = fwd_out[4]

            sigma2, tonic_da, conflict = self._extract_signals(sigma2_up_list)

            # Step 1: Draft candidates using ProspectiveHPC predictions
            # ProspectiveHPCHead is at model.prosp_hpc (V10+)
            # Final norm is at model.norm (RMSNorm)
            draft_tokens = []

            # Save IOR state before speculative drafting — drafting updates
            # the trace, but rejected tokens should not contaminate it.
            ior_saved = self.ior.trace.clone() if self.ior.trace is not None else None

            if (hasattr(model, 'prosp_hpc') and hpc_out is not None
                    and hasattr(model, 'norm')):
                hpc_last = hpc_out[:, -1, :]  # (1, d)

                for k in range(min(spec_steps, 8)):
                    if k < len(model.prosp_hpc.W_prosp):
                        # ProspectiveHPC predicts future residual states
                        X_pred = model.prosp_hpc.W_prosp[k](
                            model.prosp_hpc.norm(hpc_last)
                        )  # (1, d)
                        draft_logits = model.lm_head(model.norm(X_pred))  # (1, V)

                        # Use brain decoding for draft selection too
                        selected, _ = self.sampler.sample(
                            logits=draft_logits.float(),
                            sigma2=sigma2,
                            tonic_da=tonic_da,
                            conflict=conflict,
                            ior_trace=self.ior.trace,
                        )
                        draft_tokens.append(selected[0].item())
                        self.ior.step(selected[0].item())

            # If no ProspectiveHPC, fallback to single-token generation
            if not draft_tokens:
                logits_last = logits[:, -1, :].float()
                selected, _ = self.sampler.sample(
                    logits=logits_last,
                    sigma2=sigma2,
                    tonic_da=tonic_da,
                    conflict=conflict,
                    ior_trace=self.ior.trace,
                )
                tokens = torch.cat([tokens, selected.unsqueeze(1)], dim=1)
                self.ior.step(selected[0].item())
                total_tokens_generated += 1
                continue

            # Restore IOR to pre-draft state — only accepted tokens will be re-applied
            if ior_saved is not None:
                self.ior.trace = ior_saved

            # Step 2: Verify drafts against full model
            # Append all draft tokens to context
            draft_tensor = torch.tensor(
                draft_tokens, device=device
            ).unsqueeze(0)  # (1, spec_steps)
            extended = torch.cat([tokens, draft_tensor], dim=1)

            # Run full model on extended context
            ctx_verify = extended[:, -cfg.max_seq_len:]
            verify_out = model.forward(ctx_verify)
            verify_logits = verify_out[0]  # (1, T_ext, V)

            # Account for truncation offset: if extended was truncated,
            # positions shifted by the number of tokens removed from front
            offset = max(0, extended.shape[1] - cfg.max_seq_len)

            # Check each draft token against full model's predictions
            n_accepted = 0
            prompt_len = tokens.shape[1]
            for k in range(len(draft_tokens)):
                # Position in verify_logits: logits at pos predict token at pos+1
                # Draft token k sits at original position prompt_len + k
                # In verify_logits (after truncation): prompt_len + k - offset - 1
                pos = prompt_len + k - 1 - offset
                if pos < 0 or pos >= verify_logits.shape[1]:
                    break

                verify_probs = F.softmax(verify_logits[0, pos, :].float(), dim=-1)
                draft_prob = verify_probs[draft_tokens[k]].item()

                # Accept if probability is above threshold
                if draft_prob > self.cfg.speculative_threshold / cfg.V:
                    n_accepted += 1
                else:
                    break  # Reject from first mismatch onward

            total_speculated += len(draft_tokens)
            total_accepted += n_accepted

            # Re-apply IOR only for accepted tokens (not rejected drafts)
            if n_accepted > 0:
                for t in draft_tokens[:n_accepted]:
                    self.ior.step(t)
                accepted = torch.tensor(
                    draft_tokens[:n_accepted], device=device
                ).unsqueeze(0)
                tokens = torch.cat([tokens, accepted], dim=1)
                total_tokens_generated += n_accepted
            else:
                # All rejected — fall back to brain-decoded single token
                logits_last = logits[:, -1, :].float()
                selected, _ = self.sampler.sample(
                    logits=logits_last,
                    sigma2=sigma2,
                    tonic_da=tonic_da,
                    conflict=conflict,
                    ior_trace=self.ior.trace,
                )
                tokens = torch.cat([tokens, selected.unsqueeze(1)], dim=1)
                self.ior.step(selected[0].item())
                total_tokens_generated += 1

        if was_training:
            model.train()

        stats = {
            'total_tokens': total_tokens_generated,
            'total_speculated': total_speculated,
            'total_accepted': total_accepted,
            'acceptance_rate': total_accepted / max(total_speculated, 1),
        }
        return tokens, stats


# ═══════════════════════════════════════════════════════════════════════════
# Convenience: standard generate() for backward compatibility
# ═══════════════════════════════════════════════════════════════════════════

def generate_standard(
    model: nn.Module,
    prompt_tokens: torch.Tensor,
    max_new_tokens: int = 50,
    temperature: float = 1.0,
    top_k: int = 40,
) -> list:
    """Standard autoregressive generation (temperature/top-k)."""
    was_training = model.training
    model.eval()
    tokens = prompt_tokens.clone()
    cfg = model.cfg

    with torch.no_grad():
        for _ in range(max_new_tokens):
            ctx = tokens[:, -cfg.max_seq_len:]
            logits, *_ = model.forward(ctx)
            logits_last = logits[:, -1, :] / max(temperature, 1e-6)
            if top_k > 0:
                topk_vals, _ = logits_last.topk(
                    min(top_k, logits_last.size(-1)), dim=-1
                )
                logits_last[logits_last < topk_vals[:, -1:]] = float('-inf')
            probs = F.softmax(logits_last.float(), dim=-1)
            next_tok = torch.multinomial(probs, 1)
            tokens = torch.cat([tokens, next_tok], dim=1)

    if was_training:
        model.train()
    return tokens[0].tolist()


# ═══════════════════════════════════════════════════════════════════════════
# Analysis utilities
# ═══════════════════════════════════════════════════════════════════════════

def summarize_generation_metadata(metadata_list: List[Dict]) -> Dict:
    """
    Summarize per-step generation metadata into aggregate statistics.

    Returns:
        dict with:
          - system1_frac: fraction of tokens decided by System 1
          - mean_deliberation: average deliberation steps (System 2 only)
          - mean_confidence: average confidence across all tokens
          - mean_theta: average effective threshold
          - mean_sigma_noise: average noise level
          - da_range: (min, max) tonic DA during generation
          - conflict_range: (min, max) ACC conflict during generation
    """
    if not metadata_list:
        return {}

    system1_fracs = [m['system1_frac'] for m in metadata_list]
    delib_steps = torch.cat([m['deliberation_steps'] for m in metadata_list])
    confidences = torch.cat([m['confidence'] for m in metadata_list])
    thetas = [m['theta_0'] for m in metadata_list]
    sigmas = [m['sigma_noise'] for m in metadata_list]
    das = [m['tonic_da'] for m in metadata_list]
    conflicts = [m['conflict'] for m in metadata_list]

    # System 2 deliberation steps only
    s2_steps = delib_steps[delib_steps > 0]

    return {
        'system1_frac': sum(system1_fracs) / len(system1_fracs),
        'mean_deliberation': s2_steps.mean().item() if len(s2_steps) > 0 else 0.0,
        'max_deliberation': s2_steps.max().item() if len(s2_steps) > 0 else 0,
        'mean_confidence': confidences.mean().item(),
        'mean_theta': sum(thetas) / len(thetas),
        'mean_sigma_noise': sum(sigmas) / len(sigmas),
        'da_range': (min(das), max(das)),
        'conflict_range': (min(conflicts), max(conflicts)),
        'n_tokens': len(metadata_list),
    }


def compare_decoders(
    model: nn.Module,
    prompt_tokens: torch.Tensor,
    tokenizer,
    max_new_tokens: int = 50,
    brain_config: BrainDecodingConfig = None,
    temperatures: List[float] = None,
) -> Dict:
    """
    Compare brain-inspired decoding against standard temperature sampling.

    Generates text with both methods and reports:
      - Generated text
      - Repetition rate (n-gram overlap)
      - Distinct-n scores (diversity)
      - Per-token statistics (for brain decoder)

    Args:
        model: NCT model
        prompt_tokens: (1, T) prompt
        tokenizer: for decoding tokens to text
        max_new_tokens: tokens to generate
        brain_config: BrainDecodingConfig
        temperatures: list of temperatures for standard sampling

    Returns:
        dict with results for each method
    """
    if temperatures is None:
        temperatures = [0.7, 1.0, 1.3]

    results = {}
    device = prompt_tokens.device

    # ── Brain-inspired decoding ─────────────────────────────────────────
    decoder = BrainDecoder(model, config=brain_config)
    brain_tokens, brain_meta = decoder.generate(
        prompt_tokens, max_new_tokens=max_new_tokens, return_metadata=True
    )
    brain_text = tokenizer.decode(brain_tokens[0].tolist())
    brain_summary = summarize_generation_metadata(brain_meta)

    results['brain'] = {
        'text': brain_text,
        'tokens': brain_tokens[0].tolist(),
        'metadata': brain_summary,
        'repetition_rate': _repetition_rate(brain_tokens[0].tolist(), n=3),
        'distinct_1': _distinct_n(brain_tokens[0].tolist(), n=1),
        'distinct_2': _distinct_n(brain_tokens[0].tolist(), n=2),
    }

    # ── Standard temperature sampling ───────────────────────────────────
    for temp in temperatures:
        std_tokens = generate_standard(
            model, prompt_tokens,
            max_new_tokens=max_new_tokens,
            temperature=temp, top_k=40,
        )
        std_text = tokenizer.decode(std_tokens)

        results[f'temp_{temp}'] = {
            'text': std_text,
            'tokens': std_tokens,
            'repetition_rate': _repetition_rate(std_tokens, n=3),
            'distinct_1': _distinct_n(std_tokens, n=1),
            'distinct_2': _distinct_n(std_tokens, n=2),
        }

    return results


def _repetition_rate(tokens: list, n: int = 3) -> float:
    """Fraction of n-grams that are repeated at least once."""
    if len(tokens) < n:
        return 0.0
    ngrams = [tuple(tokens[i:i+n]) for i in range(len(tokens) - n + 1)]
    unique = set(ngrams)
    return 1.0 - len(unique) / len(ngrams) if ngrams else 0.0


def _distinct_n(tokens: list, n: int = 1) -> float:
    """Distinct-n metric: unique n-grams / total n-grams."""
    if len(tokens) < n:
        return 0.0
    ngrams = [tuple(tokens[i:i+n]) for i in range(len(tokens) - n + 1)]
    return len(set(ngrams)) / len(ngrams) if ngrams else 0.0