Skip to content
Part 15 of 20

Autonomous Operation

Krrish Choudhary·March 23, 2026

Source: nct_v2/v11_autonomous.py Lines: 1,830 Classes: 11

Neuroscience Foundation

The brain has no “training mode” vs “inference mode.” Every perception updates synapses. Every sleep consolidates memory. Every moment of boredom triggers curiosity. This module closes the autonomy loop, making NCT a living, self-improving system with eight autonomous subsystems.

The autonomous operation cycle. Wake processes input and learns. Sleep replays, downscales, dreams, and consolidates. Periodic tasks (self-play, curiosity) run during wake. Prenatal self-organization bootstraps the network before any external data.
Figure 65. The autonomous operation cycle. Wake processes input and learns. Sleep replays, downscales, dreams, and consolidates. Periodic tasks (self-play, curiosity) run during wake. Prenatal self-organization bootstraps the network before any external data.
(Illustrated) The autonomous operation cycle. Wake processes input and learns. Sleep replays, downscales, dreams, and consolidates. Periodic tasks (self-play, curiosity) run during wake. Prenatal self-organizati...
Figure 66. (Illustrated) The autonomous operation cycle. Wake processes input and learns. Sleep replays, downscales, dreams, and consolidates. Periodic tasks (self-play, curiosity) run during wake. Prenatal self-organizati...

Always-On Learning (AlwaysOnLearning)

After every forward pass, whether training, inference, or generation, local learning updates run. The effective learning rate is dynamically modulated:

ηeff=ηbase⋅ACh⋅(1+NE)⋅surprise_scale⋅(1−sleep_pressure)\eta_{\text{eff}} = \eta_{\text{base}} \cdot \text{ACh} \cdot (1 + \text{NE}) \cdot \text{surprise\_scale} \cdot (1 - \text{sleep\_pressure})

High acetylcholine (attending) →\rightarrow more learning. High norepinephrine (aroused) →\rightarrow more learning. High surprise →\rightarrow more learning. High sleep pressure (tired) →\rightarrow less wake learning.

Imagination Engine (ImaginationEngine)

Theorem 27 (Learning from Imagination). The brain learns not just from reality but from imagination. The engine:

  1. Retrieves a hippocampal memory as seed

  2. Auto-regressively generates a continuation (up to 16 tokens)

  3. Evaluates the imagined sequence (computes prediction error)

  4. If PE is high (novel imagination), tags for additional replay

This enables “dreaming”, learning from imagined scenarios, not just replayed experiences. The distinction from standard replay: imagination generates novel sequences not seen in training data.

Imagination engine (left): retrieve hippocampal memory, generate novel continuation, evaluate prediction error, tag high-PE imaginations for replay. Self-play (right): generate text, feed it back as input, evaluate own prediction error, learn from self-surprise. Both enable learning without external data.
Figure 67. Imagination engine (left): retrieve hippocampal memory, generate novel continuation, evaluate prediction error, tag high-PE imaginations for replay. Self-play (right): generate text, feed it back as input, evaluate own prediction error, learn from self-surprise. Both enable learning without external data.
(Illustrated) Imagination engine (left): retrieve hippocampal memory, generate novel continuation, evaluate prediction error, tag high-PE imaginations for replay. Self-play (right): generate text, feed it back a...
Figure 68. (Illustrated) Imagination engine (left): retrieve hippocampal memory, generate novel continuation, evaluate prediction error, tag high-PE imaginations for replay. Self-play (right): generate text, feed it back a...

Curiosity Drive (CuriosityDrive)

Theorem 28 (Expected Free Energy Minimization (Friston, 2010)). Inputs that would maximally reduce prediction uncertainty are prioritized: curiosity(x)=E[information_gain(x)]=H[σ2]−E[H[σ2∣x]]\text{curiosity}(\mathbf{x}) = \mathbb{E}[\text{information\_gain}(\mathbf{x})] = H[\sigma^2] - \mathbb{E}[H[\sigma^2 | \mathbf{x}]] In practice, the curiosity score is computed as the variance of σ2\sigma^2 across columns: inputs where columns disagree on their certainty are scored highest. The system can also generate “curious prompts” by sampling from high-uncertainty vocabulary items.

Curiosity drive (left): score inputs by σ^2 variance across columns, select the most informative batch, learn from it. Consolidation pipeline (right): track how many times each HPC memory has been replayed, promote frequently-replayed memories to cortical weights, free buffer space.
Figure 69. Curiosity drive (left): score inputs by σ2\sigma^2 variance across columns, select the most informative batch, learn from it. Consolidation pipeline (right): track how many times each HPC memory has been replayed, promote frequently-replayed memories to cortical weights, free buffer space.
(Illustrated) Curiosity drive (left): score inputs by σ^2 variance across columns, select the most informative batch, learn from it. Consolidation pipeline (right): track how many times each HPC memory ha...
Figure 70. (Illustrated) Curiosity drive (left): score inputs by σ2\sigma^2 variance across columns, select the most informative batch, learn from it. Consolidation pipeline (right): track how many times each HPC memory ha...

Self-Play (SelfPlay)

The brain processes its own speech (auditory cortex hears you speak), creating a generate →\rightarrow perceive →\rightarrow evaluate →\rightarrow learn feedback loop. NCT implements this as self-play:

Generate(xprompt)→xgen→Forward(xgen)→ϵself→Learn(ϵself)\text{Generate}(\mathbf{x}_{\text{prompt}}) \rightarrow \mathbf{x}_{\text{gen}} \rightarrow \text{Forward}(\mathbf{x}_{\text{gen}}) \rightarrow \boldsymbol{\epsilon}_{\text{self}} \rightarrow \text{Learn}(\boldsymbol{\epsilon}_{\text{self}})

Self-play loss measures how surprised the model is by its own output. High self-play loss = the model surprised itself = learning opportunity. Self-play activates every 10 steps after a 200-step warm-up. If last 3 self-play losses all exceed 15.0 (still producing gibberish), interval increases 5×5\times.

Disease mapping: inner speech deficits (schizophrenia) →\rightarrow inability to monitor own speech →\rightarrow thought insertion. Stuttering →\rightarrow failed forward model of own speech production.

Continual Learning Guard (ContinualLearningGuard)

EWC-like (Kirkpatrick et al., 2017) synaptic importance estimation:

LEWC=∑iλ2Fi(θi−θi∗)2\mathcal{L}_{\text{EWC}} = \sum_i \frac{\lambda}{2} F_i (\theta_i - \theta_i^*)^2

where FiF_i is the Fisher information (importance) of parameter ii and θi∗\theta_i^* is the optimal value from previous tasks. Parameters that were important for old tasks resist modification. Currently disabled on 6GB VRAM due to memory constraints (Fisher estimation requires storing per-parameter importance scores).

EWC synaptic importance: Fisher information identifies which parameters were important for old tasks. During new learning, important parameters are penalized for changing, preventing catastrophic forgetting.
Figure 71. EWC synaptic importance: Fisher information identifies which parameters were important for old tasks. During new learning, important parameters are penalized for changing, preventing catastrophic forgetting.
(Illustrated) EWC synaptic importance: Fisher information identifies which parameters were important for old tasks. During new learning, important parameters are penalized for changing, preventing catastrophic f...
Figure 72. (Illustrated) EWC synaptic importance: Fisher information identifies which parameters were important for old tasks. During new learning, important parameters are penalized for changing, preventing catastrophic f...

Consolidation Manager (ConsolidationManager)

The complementary learning systems theory (McClelland et al., 1995) posits that the brain uses two systems with different learning rates: the hippocampus learns quickly (one-shot episodic encoding) while the neocortex learns slowly (gradual statistical extraction). During sleep, the hippocampus “teaches” the neocortex by replaying stored episodes, gradually transferring knowledge from fast episodic storage to slow semantic storage.

The ConsolidationManager implements this transfer pipeline. It tracks how many times each hippocampal memory has been replayed during sleep phases. When a memory has been replayed at least Rmin⁡R_{\min} times (indicating it is a recurring, important pattern rather than a one-time anomaly), it is promoted: the cortical column weights are updated to represent this pattern natively (without hippocampal support), and the memory is removed from the HPC buffer to free capacity for new episodes. This produces the biological phenomenon of systems consolidation: recently learned facts depend on the hippocampus, but well-consolidated knowledge becomes hippocampus-independent.

Autonomous Loop (AutonomousLoop)

The main orchestrator managing the complete autonomous cycle without human intervention. On each step:

Wake: Process input →\rightarrow always-on learning →\rightarrow tag surprises →\rightarrow accumulate sleep pressure.

Periodic: Self-play (every 10 steps), curiosity-driven batch selection, health monitoring.

Sleep (when pressure exceeds threshold): Replay →\rightarrow downscale →\rightarrow imagination →\rightarrow consolidation →\rightarrow reset pressure.

Evaluate (periodic): Run validation, check for divergence, update self-assessment metrics.

The loop can run indefinitely in continuous mode, a never-ending self-improving cycle.

Prenatal Development (PrenatalDevelopment)

Theorem 29 (Prenatal Self-Organization). Before any external data, the network bootstraps through spontaneous activity, mirroring prenatal brain development:

1. Spontaneous Waves (30%): Momentum random walk in embedding space (Meister et al., 1991). Velocity v←0.9v+0.1N(0,0.05)\mathbf{v} \leftarrow 0.9\mathbf{v} + 0.1 \mathcal{N}(0, 0.05). Teaches L2/3 about local temporal structure: “nearby things are related.”

2. Motor Babbling (25%): Auto-regressive self-generation (Doya & Sejnowski, 1998). The model generates from its own predictions (capped at 16 tokens), creating a production-perception loop. Calibrates the generate →\rightarrow predict cycle.

3. Competitive Differentiation (25%): Structured patterns (repeated motifs, gradients, alternating sequences) force columns to specialize through competitive Hebbian learning. Each pattern type drives different statistical selectivity.

4. Oscillatory Calibration (20%): Multi-frequency sinusoidal input (Khazipov & Luhmann, 2006). Calibrates oscillatory periods (θ,α,δ\theta, \alpha, \delta) and coupling strengths (κ1,κ2,κ3\kappa_1, \kappa_2, \kappa_3).

After prenatal development, the network is not a blank slate, it has calibrated rhythms, differentiated columns, and functional prediction circuitry.

Prenatal self-organization: four types of spontaneous activity run before any external data. Each step randomly selects a phase type. Spontaneous waves teach local correlations, motor babbling calibrates the production-perception loop, competitive differentiation forces column specialization, and oscillatory calibration tunes the PAC coupling strengths.
Figure 73. Prenatal self-organization: four types of spontaneous activity run before any external data. Each step randomly selects a phase type. Spontaneous waves teach local correlations, motor babbling calibrates the production-perception loop, competitive differentiation forces column specialization, and oscillatory calibration tunes the PAC coupling strengths.
(Illustrated) Prenatal self-organization: four types of spontaneous activity run before any external data. Each step randomly selects a phase type. Spontaneous waves teach local correlations, motor babbling cali...
Figure 74. (Illustrated) Prenatal self-organization: four types of spontaneous activity run before any external data. Each step randomly selects a phase type. Spontaneous waves teach local correlations, motor babbling cali...

Source Code

Python
1,833 lines
        # Apply any kwargs overrides
        for k, v in kwargs.items():
            if hasattr(cfg, k):
                setattr(cfg, k, v)

    model = CorticalColumnNetwork(cfg)
    return model



# ===========================================================================
# Autonomous Operation (Wake-Sleep, Prenatal, Imagination)
# Source: nct_v2/v11_autonomous.py
# ===========================================================================

"""
NCT V11: Autonomous Operation — The Life of a Brain
=====================================================

The brain has no "training mode" vs "inference mode." It's ALWAYS learning.
Every perception updates synapses. Every sleep consolidates memory.
Every moment of boredom triggers curiosity.

This module closes the autonomy loop, making V11 a living, self-improving system:

  1. AlwaysOnLearning: Learn from every token processed (no train/eval distinction)
  2. ImaginationEngine: Generate synthetic experiences from memory, learn from dreams
  3. CuriosityDrive: Expected free energy → seek maximally informative inputs (Friston 2010)
  4. ConsolidationManager: Episodic → semantic transfer (McClelland et al. 1995)
  5. ContinualLearningGuard: Protect old knowledge while learning new (synaptic importance)
  6. AutonomousLoop: Orchestrates wake/sleep/dream/evaluate without human intervention

Disease mapping:
  - Alzheimer's → consolidation failure → forgetting
  - ADHD → curiosity dysregulation → can't focus
  - Insomnia → no sleep consolidation → degraded learning
  - Anosognosia → no self-evaluation → unaware of deficits
  - Depression → no curiosity drive → learned helplessness
"""




# ═══════════════════════════════════════════════════════════════════════
# 1. Always-On Learning
# ═══════════════════════════════════════════════════════════════════════

class AlwaysOnLearning:
    """
    The brain learns from EVERY experience. There is no eval() mode in biology.

    After every forward pass — whether training, inference, or generation —
    local learning updates run. PC adjusts predictions, Hebbian adjusts
    associations, neuromod gates everything.

    The learning rate is modulated by:
      - Acetylcholine (high attention → more learning)
      - Norepinephrine (high arousal → more learning)
      - Surprise (high PE → more learning)
      - Sleep pressure (close to sleep → less wake learning)

    This is the difference between a brain on a slab and a living brain.
    """

    def __init__(self, base_lr: float = 1e-4, sleep_pressure_decay: float = 0.999):
        self.base_lr = base_lr
        self.sleep_pressure = 0.0  # 0 = just woke up, 1 = need sleep
        self.sleep_pressure_decay = sleep_pressure_decay
        self.total_experiences = 0
        self._ewc_guard = None  # Set by AutonomousLoop when EWC is initialized

    def compute_lr(self, neuromod_state) -> float:
        """Compute effective learning rate from neuromodulatory state."""
        # ACh gates plasticity (attention → learning)
        ach = neuromod_state.acetylcholine.mean().item() if hasattr(neuromod_state, 'acetylcholine') else 0.5
        # NE gates arousal (surprise → learning)
        ne = neuromod_state.norepinephrine.mean().item() if hasattr(neuromod_state, 'norepinephrine') else 0.5
        # Sleep pressure reduces learning efficiency
        wake_efficiency = max(0.1, 1.0 - self.sleep_pressure)

        return self.base_lr * (0.5 + ach) * (0.5 + ne) * wake_efficiency

    def on_experience(self, model, result: dict):
        """
        Called after EVERY forward pass. Runs local learning.

        Sleep pressure accumulates proportional to prediction error —
        high surprise experiences are more "tiring" (adenosine analogy).
        """
        self.total_experiences += 1
        # Base pressure accumulation (1 - decay ≈ 0.001 per step)
        base_increment = 1.0 - self.sleep_pressure_decay
        # Surprise-scaled: high PE → faster pressure buildup
        pe = result.get('metrics', {}).get('mean_pred_error', 0.5)
        surprise_mult = 1.0 + min(pe, 5.0)  # 1x-6x based on surprise
        self.sleep_pressure = min(1.0, self.sleep_pressure + base_increment * surprise_mult)

        # Run local learning (PC + Hebbian + neuromod + EWC elastic pull)
        # Sleep pressure modulates learning efficiency: tired brain learns worse
        # (adenosine reduces LTP — Basheer et al. 2004)
        if model._last_column_outputs is not None:
            wake_efficiency = max(0.1, 1.0 - self.sleep_pressure)
            orig_lr = model.learning_manager.hebbian_optimizer.lr
            model.learning_manager.hebbian_optimizer.lr = orig_lr * wake_efficiency
            metrics = model.local_learning_step(ewc_guard=self._ewc_guard)
            model.learning_manager.hebbian_optimizer.lr = orig_lr  # Restore
            return metrics
        return {}

    def on_sleep(self):
        """Reset sleep pressure after sleep phase."""
        self.sleep_pressure = 0.0


# ═══════════════════════════════════════════════════════════════════════
# 2. Imagination Engine (Dream-Based Learning)
# ═══════════════════════════════════════════════════════════════════════

class ImaginationEngine:
    """
    The brain learns not just from reality but from imagination.

    During sleep and idle moments, the hippocampus provides memory cues.
    The cortex generates predictions from these cues (dreaming).
    Prediction errors during dreams update cortical weights.

    This is why sleep deprivation impairs learning — you lose dream-time.

    Mechanism:
      1. Sample hippocampal memory cue (partial pattern)
      2. Feed through cortical columns (like a prompt)
      3. Generate continuation (dream content)
      4. Compute PC loss on dreamed sequence
      5. Run local learning on dream errors

    Neuroscience: Replay + generative dreaming (Genzel et al. 2014, Lewis & Durrant 2011).
    """

    def __init__(self, dream_steps: int = 10, dream_noise: float = 0.05):
        self.dream_steps = dream_steps
        self.dream_noise = dream_noise
        self.total_dreams = 0

    def dream(self, model, hippocampus, device: torch.device) -> Dict[str, float]:
        """
        Generate and learn from imagined experiences.

        Dreams are NOT just monitoring — they're genuine learning. The brain
        learns during sleep by generating predictions from memory cues and
        updating weights based on prediction errors (Genzel et al. 2014).

        Two learning mechanisms during dreams:
          1. PC backward: prediction errors update L5 prediction weights
          2. Hebbian: dream activations strengthen cortical associations

        Returns: metrics about the dream phase.
        """
        memories = hippocampus.replay(n_samples=min(4, hippocampus.memory_size), device=device)
        if not memories:
            return {'dreams': 0}

        metrics = {'dreams': 0, 'dream_pc_loss': 0.0}
        dream_lr = 1e-4  # Dream learning rate — consolidation (offline replay potentiates)

        for mem in memories:
            x = mem['x']  # [1, T, D] — batch-pooled at storage
            if x.dim() < 3:
                continue

            # Add noise (dreams are noisy reconstructions)
            dream_input = x + torch.randn_like(x) * self.dream_noise

            # Run through columns WITH gradients (dreams teach)
            h = dream_input
            dream_outputs = []
            for col in model.columns:
                out = col(ff_input=h, td_context=None)
                dream_outputs.append(out)
                h = out.output

            # Compute prediction errors and LEARN from dreams
            if len(dream_outputs) >= 2:
                dream_pc_loss = 0.0
                pc_losses = []
                for l in range(len(dream_outputs)):
                    if l == 0:
                        target = dream_input.detach()
                    else:
                        target = dream_outputs[l - 1].output.detach()
                    pred = dream_outputs[l].prediction
                    sigma2 = dream_outputs[l].sigma2
                    error = target - pred
                    pc_loss_l = (error.pow(2) / (2 * sigma2 + 1e-6) + 0.5 * sigma2.log()).mean()
                    pc_losses.append(pc_loss_l)
                    dream_pc_loss += pc_loss_l.item()

                # Analytical PC update on dream predictions (no autograd)
                dream_predictions = [out.prediction for out in dream_outputs]
                dream_targets = [dream_input.detach()] + [
                    dream_outputs[l].output.detach()
                    for l in range(len(dream_outputs) - 1)
                ]
                dream_precisions = [out.sigma2 for out in dream_outputs]
                # [bundled] from .v11_learning import PredictiveCodingOptimizer
                # Use a lightweight local update — same analytical rule
                with torch.no_grad():
                    for l, col in enumerate(model.columns):
                        if l >= len(dream_predictions):
                            break
                        h_norm = col._last_l5_h_norm if hasattr(col, '_last_l5_h_norm') else None
                        if h_norm is None:
                            continue
                        error = dream_targets[l].detach() - dream_predictions[l].detach()
                        sigma2 = dream_precisions[l].clamp(min=1e-6)
                        B, T, D_model = error.shape
                        D_col = h_norm.shape[-1]
                        N = B * T
                        we = (error.float() / sigma2.float()).reshape(N, D_model)
                        hf = h_norm.float().reshape(N, D_col)
                        dW = -(we.T @ hf) / N
                        col.L5.W_predict.weight.data -= dream_lr * dW.to(col.L5.W_predict.weight.dtype)

                metrics['dream_pc_loss'] += dream_pc_loss / len(dream_outputs)
                metrics['dreams'] += 1

                # Hebbian learning from dream activations
                with torch.no_grad():
                    for i, col in enumerate(model.columns):
                        if hasattr(col, 'bcm') and col.bcm.enabled:
                            col.bcm.update_threshold(dream_outputs[i].l23_output)
                            col.L23.hebbian_update_bcm(
                                pre_input=dream_outputs[i].l23_input,
                                post_output=dream_outputs[i].l23_output,
                                bcm_theta=col.bcm.theta_bcm,
                                lr=dream_lr,
                            )

            self.total_dreams += 1

        if metrics['dreams'] > 0:
            metrics['dream_pc_loss'] /= metrics['dreams']

        return metrics


# ═══════════════════════════════════════════════════════════════════════
# 3. Curiosity Drive (Active Inference / Expected Free Energy)
# ═══════════════════════════════════════════════════════════════════════

class CuriosityDrive:
    """
    The brain doesn't passively process input — it SEEKS informative stimuli.

    Friston's Active Inference (2010): agents minimize expected free energy,
    which decomposes into:
      EFE = E[prediction_error] - E[information_gain]
    The information gain term IS curiosity. High expected σ² reduction = curious.

    Implementation:
      For each candidate input, estimate how much σ² would decrease.
      Select the candidate that maximizes expected information gain.
      This makes the model actively seek what it doesn't know.

    Disease mapping:
      ADHD → curiosity too high, unfocused → can't sustain attention on one thing
      Depression → curiosity too low → no exploration, learned helplessness
      Mania → curiosity dysregulated → everything seems novel

    Zero learnable params — purely algorithmic.
    """

    def __init__(self, curiosity_weight: float = 1.0, exploitation_weight: float = 0.5):
        self.curiosity_weight = curiosity_weight
        self.exploitation_weight = exploitation_weight
        self.curiosity_history: List[float] = []

    @torch.no_grad()
    def score_input(self, model, input_ids: torch.Tensor) -> float:
        """
        Score an input by expected information gain.

        EIG ≈ current_σ² - expected_posterior_σ²
        Approximation: inputs that produce high σ² are informative
        (the model is uncertain, so processing them teaches the most).

        Returns: curiosity score (higher = more informative)
        """
        result = model.forward(input_ids)
        sigma2_mean = result['metrics'].get('sigma2_mean', 1.0)
        pred_error = result['metrics'].get('mean_pred_error', 0.0)

        # High σ² = uncertain = informative to learn from
        # High prediction error = surprising = informative
        curiosity = self.curiosity_weight * sigma2_mean + self.exploitation_weight * pred_error
        self.curiosity_history.append(curiosity)
        return curiosity

    def select_batch(self, model, candidates: List[torch.Tensor], top_k: int = 1) -> List[int]:
        """
        Select the most informative inputs from candidates.

        Returns: indices of selected candidates (most curious first).
        """
        scores = []
        for i, cand in enumerate(candidates):
            score = self.score_input(model, cand)
            scores.append((score, i))

        scores.sort(reverse=True)  # Highest curiosity first
        return [idx for _, idx in scores[:top_k]]

    @property
    def mean_curiosity(self) -> float:
        if not self.curiosity_history:
            return 0.0
        recent = self.curiosity_history[-100:]
        return sum(recent) / len(recent)

    @torch.no_grad()
    def generate_curious_prompt(self, model, hippocampus, device: torch.device,
                                 prompt_len: int = 16) -> Optional[torch.Tensor]:
        """
        Active curiosity: generate a training prompt the model wants to learn from.

        Strategy: recombine hippocampal memory fragments, prioritizing high-surprise
        memories (the ones the model struggled with). This targets the model's weakest
        points — like a student reviewing the hardest problems.

        Three steps:
          1. Retrieve high-surprise memories from hippocampus
          2. Recombine fragments from multiple memories (cross-episode binding)
          3. Forward to get σ² → select positions where uncertainty is highest →
             use those token IDs as the prompt

        Returns: [1, prompt_len] token IDs, or None if no memories.
        """
        n_memories = min(3, hippocampus.memory_size)
        if n_memories == 0:
            return None

        # Retrieve memories prioritized by surprise (hardest experiences first)
        memories = hippocampus.replay(n_samples=n_memories, device=device)
        if not memories:
            return None

        # Collect all token-level representations from memories
        all_h = []
        for mem in memories:
            x = mem['x']  # [1, T, D] — batch-pooled at storage
            if x.dim() >= 3 and x.shape[1] >= 2:
                all_h.append(x)
        if not all_h:
            return None

        # Recombine: interleave fragments from different memories
        # This creates novel combinations — like dreaming across episodes
        combined = torch.cat(all_h, dim=1)  # [1, T_total, D]
        T_total = combined.shape[1]

        # Shuffle positions to create novel sequences (cross-episode recombination)
        perm = torch.randperm(T_total, device=device)
        combined = combined[:, perm, :]

        # Take first prompt_len positions
        h = combined[:, :min(prompt_len, T_total), :]

        # Forward through columns to get logits
        for col in model.columns:
            out = col(ff_input=h, td_context=None)
            h = out.output

        # Project to logits — use greedy argmax (no noise garbage)
        logits = model.lm_head(model.lm_head_norm(h))  # [1, L, V]
        prompt_tokens = logits.argmax(dim=-1)  # [1, L] — model's best guess

        # Pad if needed
        L = prompt_tokens.shape[1]
        if L < prompt_len:
            pad = torch.zeros(1, prompt_len - L, dtype=torch.long, device=device)
            prompt_tokens = torch.cat([prompt_tokens, pad], dim=1)
        else:
            prompt_tokens = prompt_tokens[:, :prompt_len]

        return prompt_tokens


# ═══════════════════════════════════════════════════════════════════════
# 4. Continual Learning Guard (Synaptic Importance)
# ═══════════════════════════════════════════════════════════════════════

# ═══════════════════════════════════════════════════════════════════════
# Self-Play: Learn from Own Output
# ═══════════════════════════════════════════════════════════════════════

class SelfPlay:
    """
    The brain learns not just from external input but from its OWN output.

    When you speak, your auditory cortex processes your own speech.
    When you write, your visual cortex reads what you wrote.
    This creates a feedback loop: generate → perceive → evaluate → learn.

    For language models, self-play means:
      1. Generate a continuation from a prompt
      2. Feed the generation BACK through the model as input
      3. Compute prediction error on the self-generated text
      4. If error is high → the model surprised itself → learn from it
      5. If error is low → the generation is consistent → reinforce patterns

    This is fundamentally different from standard training:
      - Standard: learn from human-written text (external)
      - Self-play: learn from own-generated text (internal)
      - Imagination: learn from noisy hippocampal replays (memory-based)

    Self-play enables GENUINE self-improvement: the model gets better by
    practicing, not just by consuming data.

    Disease mapping:
      Inner speech deficits (schizophrenia) → inability to monitor own speech
        → thought insertion / alien thoughts
      Stuttering → failed forward model of own speech production

    Zero learnable params — purely algorithmic.
    """

    def __init__(self, gen_length: int = 32, self_play_interval: int = 10):
        self.gen_length = gen_length
        self.self_play_interval = self_play_interval
        self.total_self_plays = 0
        self.self_play_losses: List[float] = []

    @torch.no_grad()
    def should_play(self, step: int) -> bool:
        # Don't self-play until minimum competence (warm-up prevents garbage learning)
        if step < 200:
            return False
        # After warm-up, also check that previous self-play improved
        # (if we have history and last 3 were all high-loss, slow down)
        if len(self.self_play_losses) >= 3:
            recent = self.self_play_losses[-3:]
            if all(l > 15.0 for l in recent):  # Still producing gibberish
                return step % (self.self_play_interval * 5) == 0  # 5x slower
        return step > 0 and step % self.self_play_interval == 0

    def play(self, model, prompt_ids: torch.Tensor, device: torch.device) -> Dict[str, float]:
        """
        Self-play: generate → re-process → learn from own output.

        Args:
            model: V11 model
            prompt_ids: [B, T_prompt] — seed prompt
            device: torch device

        Returns: metrics about self-play session.
        """
        metrics = {}

        # Phase 1: Generate text
        model.eval()
        with torch.no_grad():
            generated = model.generate(
                prompt_ids, max_new_tokens=self.gen_length, use_brain_decoding=True
            )
        model.train()

        if generated.shape[1] <= prompt_ids.shape[1]:
            return {'self_play': False}

        # Phase 2: Re-process the generated text as input
        # The model reads its own output — like hearing yourself speak
        gen_input = generated[:, :-1]
        gen_targets = generated[:, 1:]

        result = model.forward(gen_input, gen_targets)

        # Phase 3: Evaluate — how surprised is the model by its own output?
        if 'loss' in result:
            self_play_loss = result['loss'].item()
            metrics['self_play_loss'] = self_play_loss
            self.self_play_losses.append(self_play_loss)

            # Phase 4: Learn from own output via local learning
            # High loss = model surprised by own generation = opportunity to learn
            learn_metrics = model.local_learning_step()
            metrics.update({f'sp_{k}': v for k, v in learn_metrics.items()})

        self.total_self_plays += 1
        metrics['self_play'] = True
        metrics['total_self_plays'] = self.total_self_plays

        return metrics

    @property
    def mean_self_play_loss(self) -> float:
        if not self.self_play_losses:
            return float('nan')
        recent = self.self_play_losses[-50:]
        return sum(recent) / len(recent)


class ContinualLearningGuard:
    """
    Prevent catastrophic forgetting during continual learning.

    The brain doesn't forget everything old when learning something new.
    Key mechanisms:
      1. Synaptic consolidation: important synapses become harder to change
         (Clopath et al. 2008, EWC-like: Kirkpatrick et al. 2017)
      2. Complementary learning systems: hippocampus learns fast, cortex slow
         (McClelland et al. 1995 — already in V11 via hippocampus)
      3. Sleep replay: rehearse old memories to prevent forgetting
         (already in V11 via wake-sleep)

    This module implements mechanism 1: synaptic importance estimation.
    Parameters that were important for old tasks resist modification.

    Implementation:
      - After each "task" (or periodically), compute Fisher information
        approximation for each parameter (|grad|² over held-out data)
      - During learning, penalize changes to high-importance parameters
      - Importance decays slowly (old knowledge gradually becomes modifiable)

    Zero learnable params — importance is computed, not learned.
    """

    def __init__(self, lambda_ewc: float = 100.0, importance_decay: float = 0.999):
        self.lambda_ewc = lambda_ewc
        self.importance_decay = importance_decay
        self.importance: Dict[str, torch.Tensor] = {}
        self.anchor_params: Dict[str, torch.Tensor] = {}
        self._initialized = False

    @torch.no_grad()
    def estimate_importance(self, model: nn.Module, data_loader, n_batches: int = 10):
        """
        Estimate parameter importance via Fisher Information approximation.

        F_i ≈ E[∂L/∂θ_i)²] — how much the loss changes when θ_i changes.
        Parameters with high Fisher = important for current knowledge.
        """
        # Initialize or decay existing importance
        for name, param in model.named_parameters():
            if not param.requires_grad:
                continue
            if name in self.importance:
                self.importance[name] *= self.importance_decay
            else:
                self.importance[name] = torch.zeros_like(param)

        # Accumulate gradient magnitudes
        model.eval()
        n_seen = 0
        for batch_idx, batch in enumerate(data_loader):
            if batch_idx >= n_batches:
                break

            if isinstance(batch, dict):
                input_ids = batch['input_ids']
                targets = batch.get('targets', input_ids[:, 1:])
            else:
                input_ids = batch
                targets = batch[:, 1:]

            model.zero_grad()
            result = model(input_ids[:, :-1], targets)
            if 'loss' in result:
                result['loss'].backward()

            for name, param in model.named_parameters():
                if param.grad is not None:
                    self.importance[name] += param.grad.pow(2)

            n_seen += 1

        # Normalize
        if n_seen > 0:
            for name in self.importance:
                self.importance[name] /= n_seen

        # Store current params as anchors
        for name, param in model.named_parameters():
            if param.requires_grad:
                self.anchor_params[name] = param.data.clone()

        self._initialized = True
        model.train()

    def compute_penalty(self, model: nn.Module) -> torch.Tensor:
        """
        Compute EWC penalty: Σ_i F_i × (θ_i - θ*_i)²

        Returns: scalar penalty to add to loss.
        """
        if not self._initialized:
            return torch.tensor(0.0)

        penalty = torch.tensor(0.0, device=next(model.parameters()).device)
        for name, param in model.named_parameters():
            if name in self.importance and name in self.anchor_params:
                diff = param - self.anchor_params[name].to(param.device)
                penalty = penalty + (self.importance[name].to(param.device) * diff.pow(2)).sum()

        return 0.5 * self.lambda_ewc * penalty


# ═══════════════════════════════════════════════════════════════════════
# 5. Consolidation Manager
# ═══════════════════════════════════════════════════════════════════════

class ConsolidationManager:
    """
    Manages the episodic → semantic consolidation pipeline.

    McClelland et al. 1995: The brain has two learning systems:
      - Hippocampus: fast, episodic, specific (stores individual experiences)
      - Neocortex: slow, semantic, general (stores patterns across experiences)

    Consolidation transfers knowledge from hippocampus to cortex:
      1. Cluster similar hippocampal episodes
      2. Extract centroid pattern (the "gist")
      3. Train cortex on centroids slowly (interleaved with old knowledge)
      4. Delete consolidated episodes (they're now in cortex)

    This happens during deep sleep (SWS stages 3-4).
    """

    def __init__(self, consolidation_interval: int = 500, min_memories: int = 20):
        self.consolidation_interval = consolidation_interval
        self.min_memories = min_memories
        self.total_consolidations = 0
        self.semantic_knowledge: List[Dict] = []

    def should_consolidate(self, step: int, hippocampus) -> bool:
        """Check if it's time for consolidation."""
        return (
            step > 0
            and step % self.consolidation_interval == 0
            and hippocampus.memory_size >= self.min_memories
        )

    @torch.no_grad()
    def consolidate(self, model, hippocampus, columns, device) -> Dict[str, float]:
        """
        Run full consolidation: cluster → extract → train → forget.

        Returns: consolidation metrics.
        """
        # Phase 1: Cluster and extract semantic memories
        semantic_mems = hippocampus.consolidate(n_clusters=8, min_cluster=3)
        if not semantic_mems:
            return {'consolidated': 0}

        # Phase 2: Train cortex on extracted patterns
        # Each centroid is a semantic memory — run it through columns
        # and perform Hebbian learning (slow integration into cortical weights)
        n_consolidated = 0
        for sem_mem in semantic_mems:
            pattern = sem_mem['pattern'].to(device)  # [D]
            # Expand to [1, 1, D] for column processing
            pattern_input = pattern.unsqueeze(0).unsqueeze(0)

            # Slow cortical training: multiple passes over the pattern
            for _ in range(5):  # 5 passes per pattern (slow learning)
                h = pattern_input
                for col in columns:
                    out = col(ff_input=h, td_context=None)
                    # Hebbian update with very low LR (slow cortical integration)
                    col.L23.hebbian_update(out.l23_input, lr=1e-4)
                    h = out.output

            n_consolidated += 1

        self.total_consolidations += 1
        self.semantic_knowledge.extend(semantic_mems)

        return {
            'consolidated': n_consolidated,
            'episodes_removed': sum(m['n_episodes'] for m in semantic_mems),
            'memories_remaining': hippocampus.memory_size,
        }


# ═══════════════════════════════════════════════════════════════════════
# 6. Autonomous Loop — The Orchestrator
# ═══════════════════════════════════════════════════════════════════════

@dataclass
class AutonomousConfig:
    """Configuration for autonomous operation."""
    # Always-on learning
    always_learn: bool = True
    base_lr: float = 1e-4

    # Sleep schedule
    sleep_interval: int = 100       # Wake steps between sleep phases
    dream_steps: int = 10           # Dreams per sleep phase

    # Curiosity
    curiosity_enabled: bool = True
    curiosity_weight: float = 1.0

    # Consolidation
    consolidation_interval: int = 500
    min_memories_for_consolidation: int = 20

    # Continual learning
    ewc_enabled: bool = False  # Disabled: OOMs on 6GB GPUs (needs .backward())
    ewc_lambda: float = 100.0
    ewc_estimation_interval: int = 500  # Estimate importance every N steps

    # Self-play
    self_play_interval: int = 20    # Steps between self-play sessions

    # Self-evaluation
    eval_interval: int = 200        # Steps between self-evaluations


class AutonomousLoop:
    """
    The main orchestrator that makes V11 a living, self-improving system.

    Lifecycle (runs forever):
      WAKE → process input → always-on learning → accumulate sleep pressure
      → when sleep_pressure > threshold:
        SLEEP → replay → dream → consolidate → downscale → reset pressure
      → back to WAKE

    Self-evaluation runs periodically during wake:
      - Test on held-out hippocampal memories
      - Compare current vs previous performance
      - Adjust learning strategy if degrading

    Curiosity modulates input selection:
      - Score candidate inputs by expected information gain
      - Prefer inputs the model is most uncertain about

    This is the closed loop that makes V11 "unstoppable" — it continuously
    improves without human intervention, as long as data flows through it.
    """

    def __init__(self, model, config: Optional[AutonomousConfig] = None):
        if config is None:
            config = AutonomousConfig()
        self.config = config
        self.model = model

        # Components
        self.always_on = AlwaysOnLearning(
            base_lr=config.base_lr,
        )
        self.imagination = ImaginationEngine(dream_steps=config.dream_steps)
        self.curiosity = CuriosityDrive(curiosity_weight=config.curiosity_weight)
        self.consolidation = ConsolidationManager(
            consolidation_interval=config.consolidation_interval,
            min_memories=config.min_memories_for_consolidation,
        )
        self.continual_guard = ContinualLearningGuard(
            lambda_ewc=config.ewc_lambda,
        )
        # Wire EWC guard into always-on learning so elastic pull is applied during local learning
        self.always_on._ewc_guard = self.continual_guard
        self.self_play = SelfPlay(
            gen_length=32,
            self_play_interval=getattr(config, 'self_play_interval', 20),
        )

        # State
        self.global_step = 0
        self._last_input_ids: Optional[torch.Tensor] = None
        self.wake_steps_since_sleep = 0
        self.performance_history: List[float] = []
        self._state = 'wake'  # 'wake', 'sleep', 'dream', 'consolidate', 'evaluate'

    @property
    def state(self) -> str:
        return self._state

    def process(self, input_ids: torch.Tensor, targets: Optional[torch.Tensor] = None) -> Dict:
        """
        Process a single experience (the primary wake-phase operation).

        1. Forward pass
        2. Always-on learning (if enabled)
        3. Check if sleep is due
        4. Periodic self-evaluation

        Returns: forward result + autonomous metrics
        """
        self._state = 'wake'

        # Forward pass
        result = self.model.forward(input_ids, targets)

        # Always-on learning (the brain learns from every experience)
        auto_metrics = {}
        if self.config.always_learn:
            learn_metrics = self.always_on.on_experience(self.model, result)
            auto_metrics.update(learn_metrics)

        # EWC penalty (protect old knowledge)
        if self.config.ewc_enabled and self.continual_guard._initialized:
            ewc_penalty = self.continual_guard.compute_penalty(self.model)
            result['ewc_loss'] = ewc_penalty
            auto_metrics['ewc_penalty'] = ewc_penalty.item()

        # Track
        self.global_step += 1
        self.wake_steps_since_sleep += 1
        auto_metrics['sleep_pressure'] = self.always_on.sleep_pressure
        auto_metrics['global_step'] = self.global_step
        auto_metrics['state'] = 'wake'

        result['autonomous_metrics'] = auto_metrics
        return result

    def should_sleep(self) -> bool:
        """Check if sleep phase is due.

        The brain sleeps when adenosine accumulation (sleep pressure) is high enough,
        NOT on a fixed schedule. Step count is a fallback lower bound.

        Two conditions (either triggers sleep):
          1. Sleep pressure > 0.7 (adenosine model — primary)
          2. Wake steps >= sleep_interval (failsafe — prevents insomnia)
        """
        pressure_threshold = 0.7
        return (self.always_on.sleep_pressure >= pressure_threshold or
                self.wake_steps_since_sleep >= self.config.sleep_interval)

    def sleep_cycle(self, device: torch.device) -> Dict[str, float]:
        """
        Full sleep cycle: replay → dream → consolidate → downscale.

        This is the brain's offline learning phase.
        All learning during sleep is analytical (direct .data manipulation) —
        no autograd needed. torch.no_grad() prevents OOM from activation tensors.
        """
        metrics = {'phase': 'sleep'}

        with torch.no_grad():
            # Phase 1: Memory replay (from V11 learning manager)
            self._state = 'sleep'
            sleep_metrics = self.model.sleep_phase()
            metrics.update({f'sleep_{k}': v for k, v in sleep_metrics.items()})

            # Phase 2: Dream (imagination-based learning)
            self._state = 'dream'
            dream_metrics = self.imagination.dream(
                self.model, self.model.hippocampus, device
            )
            metrics.update({f'dream_{k}': v for k, v in dream_metrics.items()})

            # Phase 3: Consolidation (episodic → semantic)
            if self.consolidation.should_consolidate(self.global_step, self.model.hippocampus):
                self._state = 'consolidate'
                consol_metrics = self.consolidation.consolidate(
                    self.model, self.model.hippocampus, self.model.columns, device
                )
                metrics.update({f'consol_{k}': v for k, v in consol_metrics.items()})

        # Reset sleep pressure
        self.always_on.on_sleep()
        self.wake_steps_since_sleep = 0
        self._state = 'wake'

        return metrics

    def should_evaluate(self) -> bool:
        """Check if self-evaluation is due."""
        return self.global_step > 0 and self.global_step % self.config.eval_interval == 0

    @torch.no_grad()
    def self_evaluate(self, device: torch.device) -> Dict[str, float]:
        """
        Self-evaluation: test on held-out hippocampal memories.

        The model tests itself to know if it's improving or degrading.
        If degrading: increase sleep frequency, reduce learning rate.
        If improving: maintain current strategy.

        Returns: evaluation metrics.
        """
        self._state = 'evaluate'
        metrics = {}

        # Sample test memories from hippocampus
        test_mems = self.model.hippocampus.replay(
            n_samples=min(5, self.model.hippocampus.memory_size), device=device
        )
        if not test_mems:
            return {'eval_loss': float('nan'), 'trend': 'insufficient_data'}

        # Compute prediction error on test memories
        total_error = 0.0
        n_tested = 0
        for mem in test_mems:
            x = mem['x']
            if x.dim() < 3:
                continue
            h = x
            for col in self.model.columns:
                out = col(ff_input=h, td_context=None)
                h = out.output
            # Prediction error of last column
            error = (x - out.prediction).pow(2).mean().item()
            total_error += error
            n_tested += 1

        if n_tested == 0:
            return {'eval_loss': float('nan'), 'trend': 'no_testable_memories'}

        avg_error = total_error / n_tested
        self.performance_history.append(avg_error)
        metrics['eval_loss'] = avg_error

        # Trend detection: compare recent performance to older performance
        if len(self.performance_history) >= 3:
            recent = sum(self.performance_history[-3:]) / 3
            if len(self.performance_history) >= 6:
                older = sum(self.performance_history[-6:-3]) / 3
                if recent < older * 0.95:
                    metrics['trend'] = 'improving'
                    # Reward: advance developmental stage faster
                    dev = self.model.learning_manager.development
                    if hasattr(dev, '_step_counter'):
                        dev._step_counter += 50  # Accelerate advancement
                elif recent > older * 1.05:
                    metrics['trend'] = 'degrading'
                    # Corrective action 1: increase sleep frequency
                    self.config.sleep_interval = max(50, self.config.sleep_interval - 10)
                    # Corrective action 2: reduce Hebbian LR temporarily
                    self.model.learning_manager.hebbian_optimizer.lr *= 0.8
                    # Corrective action 3: severe degradation → emergency sleep
                    if recent > older * 1.2:
                        self.always_on.sleep_pressure = 1.0  # Force sleep next step
                        metrics['emergency_sleep'] = True
                else:
                    metrics['trend'] = 'stable'
            else:
                metrics['trend'] = 'warming_up'
        else:
            metrics['trend'] = 'warming_up'

        # Stagnation detection: if stable for 5+ evaluations, increase exploration
        if len(self.performance_history) >= 10:
            last_5 = self.performance_history[-5:]
            var = max(last_5) - min(last_5)
            mean = sum(last_5) / 5
            if mean > 0 and var / mean < 0.02:  # < 2% variation = stagnant
                metrics['stagnation_detected'] = True
                # Force exploration: increase Hebbian LR temporarily
                self.model.learning_manager.hebbian_optimizer.lr *= 1.5
                # Force sleep to consolidate and try new patterns
                self.always_on.sleep_pressure = 0.8

        self._state = 'wake'
        return metrics

    def step(self, input_ids: torch.Tensor, targets: Optional[torch.Tensor] = None,
             device: Optional[torch.device] = None) -> Dict:
        """
        ONE step of the autonomous lifecycle.

        Call this in a loop to run V11 autonomously:
          while True:
              data = get_next_input()
              result = loop.step(data, targets)

        The loop handles everything: learning, sleeping, dreaming,
        consolidating, evaluating — all automatically.
        """
        if device is None:
            device = next(self.model.parameters()).device

        all_metrics = {}

        # Aggressively free fragmented memory before main forward pass.
        # After sleep/EWC/eval phases, CUDA allocator can be fragmented enough
        # that the next forward pass OOMs despite having enough total free memory.
        import gc
        gc.collect()
        if torch.cuda.is_available():
            torch.cuda.empty_cache()

        # Wake: process input (with OOM retry — fragmentation can cause spurious OOMs)
        try:
            result = self.process(input_ids, targets)
        except (torch.cuda.OutOfMemoryError, torch.OutOfMemoryError):
            import gc
            gc.collect()
            if torch.cuda.is_available():
                torch.cuda.empty_cache()
            # Retry once after clearing cache
            result = self.process(input_ids, targets)
        all_metrics.update(result.get('autonomous_metrics', {}))

        # ── Auxiliary operations (all OOM-safe) ──────────────────────
        # Self-play, curiosity, sleep, EWC, eval can all trigger column forwards
        # that may OOM on memory-constrained GPUs. Wrap in try/except so the
        # main training loop survives — auxiliary operations are non-critical.
        try:
            # Self-play: learn from own output
            if self.self_play.should_play(self.global_step):
                prompt = input_ids[:, :min(16, input_ids.shape[1])]
                with torch.no_grad():
                    sp_metrics = self.self_play.play(self.model, prompt, device)
                all_metrics.update({f'sp_{k}': v for k, v in sp_metrics.items()})

            # Active curiosity: generate and learn from own prompts (every 5 steps)
            if (self.config.curiosity_enabled
                    and self.global_step > 10
                    and self.global_step % 5 == 0):
                with torch.no_grad():
                    curious_prompt = self.curiosity.generate_curious_prompt(
                        self.model, self.model.hippocampus, device
                    )
                if curious_prompt is not None:
                    with torch.no_grad():
                        curious_result = self.model.forward(curious_prompt)
                        self.always_on.on_experience(self.model, curious_result)
                    all_metrics['curiosity_generated'] = True

            # Sleep: if pressure is high enough
            if self.should_sleep():
                if torch.cuda.is_available():
                    torch.cuda.empty_cache()
                sleep_metrics = self.sleep_cycle(device)
                all_metrics.update(sleep_metrics)

            # EWC: periodically estimate parameter importance
            if (self.config.ewc_enabled
                    and self.global_step > 0
                    and self.global_step % self.config.ewc_estimation_interval == 0):
                if torch.cuda.is_available():
                    torch.cuda.empty_cache()
                ewc_metrics = self._estimate_ewc_importance(device)
                all_metrics.update(ewc_metrics)

            # Evaluate: periodically test self
            if self.should_evaluate():
                if torch.cuda.is_available():
                    torch.cuda.empty_cache()
                with torch.no_grad():
                    eval_metrics = self.self_evaluate(device)
                all_metrics.update(eval_metrics)

        except (torch.cuda.OutOfMemoryError, torch.OutOfMemoryError, RuntimeError) as e:
            if 'out of memory' in str(e).lower():
                if torch.cuda.is_available():
                    torch.cuda.empty_cache()
                all_metrics['aux_skipped_oom'] = True
            else:
                raise  # Re-raise non-OOM RuntimeErrors

        # Clean up after auxiliary operations to prevent fragmentation on next step
        import gc
        gc.collect()
        if torch.cuda.is_available():
            torch.cuda.empty_cache()

        result['autonomous_metrics'] = all_metrics
        return result

    def _estimate_ewc_importance(self, device: torch.device) -> Dict[str, float]:
        """
        Estimate EWC parameter importance from hippocampal memories.

        The brain knows which synapses are important by tracking how much
        they contributed to successful predictions. We approximate this
        via Fisher Information: F_i ≈ E[(∂L/∂θ_i)²].

        Uses hippocampal memories as the data source — these are the
        experiences the brain "remembers" and wants to protect.
        """
        memories = self.model.hippocampus.replay(
            n_samples=min(10, self.model.hippocampus.memory_size), device=device
        )
        if not memories or len(memories) < 3:
            return {'ewc_estimated': False, 'ewc_reason': 'insufficient_memories'}

        # Build a simple iterable from hippocampal memories for estimate_importance
        class MemoryLoader:
            def __init__(self, mems):
                self._mems = mems
            def __iter__(self):
                for mem in self._mems:
                    x = mem['x']  # [1, T, D] — batch-pooled at storage — but EWC needs token IDs
                    # We don't have token IDs in hippocampal memory (it stores activations).
                    # So we use the activation directly: run columns and compute PC loss.
                    yield mem

        # EWC on activations: compute gradient magnitude through PC loss
        # rather than NTP loss (we don't have token IDs stored).
        self._estimate_ewc_from_activations(memories, device)
        return {'ewc_estimated': True, 'ewc_step': self.global_step}

    @torch.no_grad()
    def _estimate_ewc_from_activations(self, memories: list, device: torch.device):
        """
        Estimate parameter importance from activations — ZERO autograd.

        Fisher approximation via activity-error correlation:
          F_i ≈ E[|activation_i|² × |prediction_error|²]

        This is a valid importance measure: parameters that carry large
        activations in the presence of large errors are critical for
        error correction. Biologically: synapses that fire during
        important predictions are tagged for protection (synaptic tagging,
        Frey & Morris 1997).
        """
        guard = self.continual_guard

        # Initialize or decay existing importance
        for name, param in self.model.named_parameters():
            if not param.requires_grad:
                continue
            if name in guard.importance:
                guard.importance[name] *= guard.importance_decay
            else:
                guard.importance[name] = torch.zeros_like(param)

        # Accumulate activity-error correlation from memories
        n_seen = 0
        for mem in memories:
            x = mem['x']
            if x.dim() < 3:
                continue

            # Run through columns (forward only, no autograd)
            h = x
            total_error_sq = 0.0
            prev_out = None
            for i, col in enumerate(self.model.columns):
                out = col(ff_input=h, td_context=None)
                target = x.detach() if i == 0 else prev_out.detach()
                error = target - out.prediction
                error_mag_sq = error.pow(2).mean().item()
                total_error_sq += error_mag_sq
                prev_out = out.output
                h = out.output

                # Activity-weighted importance for this column's parameters
                for name, param in col.named_parameters():
                    full_name = f'columns.{i}.{name}'
                    if full_name in guard.importance:
                        # Importance ∝ |param|² × error² (parameter magnitude × prediction error)
                        guard.importance[full_name] += param.pow(2) * error_mag_sq

            n_seen += 1

        # Normalize
        if n_seen > 0:
            for name in guard.importance:
                guard.importance[name] /= n_seen

        # Store current params as anchors
        for name, param in self.model.named_parameters():
            if param.requires_grad:
                guard.anchor_params[name] = param.data.clone()

        guard._initialized = True
        self.model.zero_grad()

    def get_status(self) -> Dict:
        """Return current autonomous system status."""
        return {
            'state': self._state,
            'global_step': self.global_step,
            'sleep_pressure': self.always_on.sleep_pressure,
            'total_experiences': self.always_on.total_experiences,
            'total_dreams': self.imagination.total_dreams,
            'total_consolidations': self.consolidation.total_consolidations,
            'mean_curiosity': self.curiosity.mean_curiosity,
            'memories': self.model.hippocampus.memory_size if hasattr(self.model, 'hippocampus') else 0,
            'semantic_knowledge': len(self.consolidation.semantic_knowledge),
            'performance_trend': self.performance_history[-5:] if self.performance_history else [],
            'ewc_initialized': self.continual_guard._initialized,
            'total_self_plays': self.self_play.total_self_plays,
            'mean_self_play_loss': self.self_play.mean_self_play_loss,
        }

    def save_autonomous_state(self, path: str):
        """
        Save the autonomous loop's non-model state.

        This captures everything the autonomous system tracks that is NOT
        in the model's state_dict:
          - EWC importance weights and anchor parameters
          - Performance history (for trend detection)
          - Consolidation semantic knowledge
          - Sleep pressure and counters
          - Self-play history
          - Global step counter

        Call alongside model.save_state() for complete persistence:
          model.save_state('brain.pt')
          loop.save_autonomous_state('autonomous.pt')
        """
        state = {
            # EWC state (the most critical non-model state)
            'ewc_importance': {
                name: tensor.cpu().clone()
                for name, tensor in self.continual_guard.importance.items()
            },
            'ewc_anchor_params': {
                name: tensor.cpu().clone()
                for name, tensor in self.continual_guard.anchor_params.items()
            },
            'ewc_initialized': self.continual_guard._initialized,

            # Performance tracking
            'performance_history': list(self.performance_history),
            'global_step': self.global_step,
            'wake_steps_since_sleep': self.wake_steps_since_sleep,

            # Sleep pressure
            'sleep_pressure': self.always_on.sleep_pressure,
            'total_experiences': self.always_on.total_experiences,

            # Consolidation knowledge
            'semantic_knowledge': [
                {k: v.cpu().clone() if isinstance(v, torch.Tensor) else v
                 for k, v in sk.items()}
                for sk in self.consolidation.semantic_knowledge
            ],
            'total_consolidations': self.consolidation.total_consolidations,

            # Self-play
            'total_self_plays': self.self_play.total_self_plays,
            'self_play_losses': list(self.self_play.self_play_losses),

            # Imagination
            'total_dreams': self.imagination.total_dreams,

            # Curiosity
            'mean_curiosity': self.curiosity.mean_curiosity,

            # Config
            'config_dict': {
                field.name: getattr(self.config, field.name)
                for field in self.config.__dataclass_fields__.values()
            },

            # Version marker
            'v11_autonomous_version': 1,
        }

        torch.save(state, path)

    def load_autonomous_state(self, path: str):
        """
        Restore autonomous loop state from disk.

        Call alongside model.load_state() for complete restoration:
          model.load_state('brain.pt')
          loop.load_autonomous_state('autonomous.pt')
        """
        state = torch.load(path, map_location='cpu', weights_only=False)

        # EWC
        if state.get('ewc_initialized', False):
            self.continual_guard.importance = {
                name: tensor.clone()
                for name, tensor in state['ewc_importance'].items()
            }
            self.continual_guard.anchor_params = {
                name: tensor.clone()
                for name, tensor in state['ewc_anchor_params'].items()
            }
            self.continual_guard._initialized = True

        # Performance
        self.performance_history = list(state.get('performance_history', []))
        self.global_step = state.get('global_step', 0)
        self.wake_steps_since_sleep = state.get('wake_steps_since_sleep', 0)

        # Sleep
        self.always_on.sleep_pressure = state.get('sleep_pressure', 0.0)
        self.always_on.total_experiences = state.get('total_experiences', 0)

        # Consolidation
        self.consolidation.semantic_knowledge = state.get('semantic_knowledge', [])
        self.consolidation.total_consolidations = state.get('total_consolidations', 0)

        # Self-play
        self.self_play.total_self_plays = state.get('total_self_plays', 0)
        self.self_play.self_play_losses = list(state.get('self_play_losses', []))

        # Imagination
        self.imagination.total_dreams = state.get('total_dreams', 0)

        # Curiosity
        if hasattr(self.curiosity, '_curiosity_history'):
            # Restore mean curiosity indirectly
            pass  # curiosity_history is transient — will rebuild from new data


# ═══════════════════════════════════════════════════════════════════════
# 7. Prenatal Self-Organization (Phase 0)
# ═══════════════════════════════════════════════════════════════════════

class PrenatalDevelopment:
    """
    Phase 0: Prenatal Self-Organization — Before Any External Data.

    The brain does NOT start from random weights and wait for training data.
    Before birth, extensive self-organization occurs through spontaneous activity:

      - Spontaneous retinal waves organize retinotopic maps (Meister et al. 1991)
      - Spontaneous cochlear bursts calibrate tonotopic maps (Tritsch et al. 2007)
      - Motor babbling calibrates sensorimotor maps (Doya & Sejnowski 1998)
      - Hebbian competition selects surviving synapses (Katz & Shatz 1996)
      - ~50% of synapses are pruned before birth (Huttenlocher 1979)
      - Oscillatory rhythms emerge from intrinsic dynamics (Khazipov & Luhmann 2006)
      - BCM thresholds calibrate from spontaneous statistics (Bear et al. 1987)

    After prenatal development, the network is NOT a blank slate — it has:
      1. Calibrated oscillatory rhythms (gamma/theta/alpha/delta phase-locked)
      2. Differentiated columns (each develops distinct selectivity)
      3. Pruned architecture (sparse, efficient, no dead weights)
      4. Calibrated BCM thresholds (from activity statistics)
      5. Working inhibitory balance (E/I ratio tuned)
      6. Functional prediction circuitry (PC can predict own activity)
      7. Initial hippocampal encoding patterns

    This is the "DNA" — the structured starting point from which rapid
    postnatal learning from real data can begin immediately.

    Disease mapping:
      Fetal alcohol syndrome → disrupted spontaneous waves → disorganized maps
      Congenital rubella → disrupted cochlear activity → deafness
      Preterm birth → insufficient prenatal organization → developmental delays
      Autism (some forms) → atypical prenatal pruning → over-connectivity

    Zero learnable params — uses existing model learning mechanisms.
    """

    def __init__(self, model, config=None):
        self.model = model
        self.cfg = model.cfg
        self.device = next(model.parameters()).device

        # Prenatal development phases
        self.phases = [
            ('spontaneous_waves', 0.30),   # 30% of steps: correlated wave patterns
            ('motor_babbling', 0.25),      # 25%: self-generated sequences
            ('competitive_diff', 0.25),    # 25%: column differentiation
            ('oscillatory_cal', 0.20),     # 20%: oscillatory stabilization
        ]

        # Tracking
        self.total_steps = 0
        self.phase_idx = 0
        self.metrics_history: List[Dict] = []
        self._weight_stats_history: List[Dict] = []

    # ── Spontaneous Activity Generators ─────────────────────────────

    def _generate_retinal_waves(self, batch_size: int, seq_len: int) -> torch.Tensor:
        """
        Generate temporally-correlated spontaneous activity (retinal wave analog).

        Retinal waves (Meister et al. 1991): spatially correlated traveling waves
        sweep across the retina before eye-opening. Neighboring neurons fire
        together, teaching the visual cortex about spatial relationships.

        For language (1D sequence): generate sequences where nearby tokens have
        correlated embeddings. This is a random walk in embedding space —
        each position's embedding is a noisy perturbation of the previous.

        This teaches L2/3 about LOCAL temporal structure: "nearby things are
        related" — the foundation for all sequential processing.

        Returns: [B, T, D_model] continuous activations (not token IDs)
        """
        D = self.cfg.d_model
        device = self.device

        # Random walk with momentum (smoother waves, like actual retinal waves)
        h = torch.randn(batch_size, 1, D, device=device) * 0.1
        velocity = torch.randn(batch_size, 1, D, device=device) * 0.02
        momentum = 0.9  # High momentum = smooth waves
        noise_scale = 0.05  # Small noise = highly correlated

        positions = [h]
        for t in range(1, seq_len):
            # Momentum-based random walk (models wave propagation)
            velocity = momentum * velocity + (1 - momentum) * torch.randn(batch_size, 1, D, device=device) * noise_scale
            h = h + velocity
            positions.append(h)

        wave = torch.cat(positions, dim=1)  # [B, T, D]

        # Normalize to reasonable activation scale
        wave = F.layer_norm(wave, [D])
        return wave

    def _generate_motor_babbling(self, batch_size: int, seq_len: int) -> torch.Tensor:
        """
        Generate self-produced sequences (motor babbling analog).

        Before language, infants babble — producing random phoneme sequences
        and hearing themselves. This calibrates the production-perception loop.
        (Doya & Sejnowski 1998, Oller 2000)

        For V11: the model generates auto-regressively from a random seed,
        then the generated sequence becomes the input for local learning.
        The model literally learns to predict its own output.

        Generation length capped at 16 tokens for speed (prenatal model barely
        knows anything, so long generation is wasted compute). The remainder is
        padded with random tokens — still provides diverse input for calibration.

        Returns: [B, T] token IDs (generated by the model itself)
        """
        # Random seed tokens
        seed_len = min(4, seq_len // 4)
        seed = torch.randint(0, self.cfg.vocab_size, (batch_size, seed_len), device=self.device)

        # Generate a SHORT sequence auto-regressively (16 tokens max for speed)
        # During prenatal, the model has near-random weights — long generation
        # is just expensive random sampling. Cap at 16 to keep prenatal fast.
        gen_len = min(16, seq_len - seed_len)
        self.model.eval()
        with torch.no_grad():
            generated = self.model.generate(seed, max_new_tokens=gen_len)
        self.model.train()

        # Pad remainder with random tokens (still diverse input)
        if generated.shape[1] < seq_len:
            pad = torch.randint(0, self.cfg.vocab_size,
                                (batch_size, seq_len - generated.shape[1]), device=self.device)
            generated = torch.cat([generated, pad], dim=1)
        elif generated.shape[1] > seq_len:
            generated = generated[:, :seq_len]

        return generated

    def _generate_structured_patterns(self, batch_size: int, seq_len: int) -> torch.Tensor:
        """
        Generate simple structured patterns for competitive differentiation.

        Different columns should develop different selectivities. To enable this,
        provide diverse structured inputs:
          - Repeated subsequences (periodicity detection)
          - Ascending/descending sequences (ordinal processing)
          - Alternating patterns (contrast detection)
          - Random segments (noise tolerance)

        This is the analog of prenatal sensory input from multiple modalities:
        visual patterns, auditory patterns, vestibular patterns — each with
        different statistical structure that drives different cortical areas.

        Returns: [B, T] token IDs with diverse statistical structure
        """
        V = self.cfg.vocab_size
        device = self.device
        patterns = []

        for b in range(batch_size):
            # Randomly select pattern type for this batch element
            pattern_type = torch.randint(0, 5, (1,)).item()

            if pattern_type == 0:
                # Repeated motif (periodicity): pick random motif, tile it
                motif_len = torch.randint(3, 12, (1,)).item()
                motif = torch.randint(0, V, (motif_len,), device=device)
                tiles = seq_len // motif_len + 1
                seq = motif.repeat(tiles)[:seq_len]
            elif pattern_type == 1:
                # Ascending with noise: base sequence + random perturbation
                base = torch.arange(seq_len, device=device) % V
                noise = torch.randint(0, max(1, V // 20), (seq_len,), device=device)
                seq = (base + noise) % V
            elif pattern_type == 2:
                # Alternating: two tokens alternating with random insertions
                a, b_tok = torch.randint(0, V, (2,), device=device)
                seq = torch.where(
                    torch.arange(seq_len, device=device) % 2 == 0,
                    a.expand(seq_len), b_tok.expand(seq_len)
                )
                # Random insertions at ~10% of positions
                mask = torch.rand(seq_len, device=device) < 0.1
                seq[mask] = torch.randint(0, V, (mask.sum(),), device=device)
            elif pattern_type == 3:
                # Segmented: 3-5 random segments, each from a different frequency band
                n_segments = torch.randint(3, 6, (1,)).item()
                parts = []
                remaining = seq_len
                for s in range(n_segments):
                    seg_len = remaining // (n_segments - s)
                    remaining -= seg_len
                    center = torch.randint(0, V, (1,), device=device)
                    spread = torch.randint(1, max(2, V // 10), (1,)).item()
                    part = (center + torch.randint(-spread, spread + 1, (seg_len,), device=device)) % V
                    parts.append(part)
                seq = torch.cat(parts)
            else:
                # Pure random (noise tolerance)
                seq = torch.randint(0, V, (seq_len,), device=device)

            patterns.append(seq)

        return torch.stack(patterns)  # [B, T]

    def _generate_oscillatory_input(self, batch_size: int, seq_len: int) -> torch.Tensor:
        """
        Generate oscillatory-structured activity for rhythm calibration.

        Prenatal EEG shows spontaneous oscillatory activity (Khazipov & Luhmann 2006).
        These intrinsic rhythms are NOT driven by external stimuli — they emerge
        from the network's own dynamics. We generate inputs whose statistics
        match the target oscillatory structure (gamma/theta/alpha/delta) so the
        network's oscillatory modules can lock onto them.

        Returns: [B, T, D_model] continuous activations with oscillatory structure
        """
        D = self.cfg.d_model
        device = self.device
        t = torch.arange(seq_len, device=device, dtype=torch.float32).unsqueeze(0).unsqueeze(-1)  # [1, T, 1]

        # Multi-frequency oscillatory pattern
        # Each frequency band modulates a different subset of dimensions
        gamma = torch.sin(2 * math.pi * t / self.cfg.gamma_period)   # Fast
        theta = torch.sin(2 * math.pi * t / self.cfg.theta_period)   # Medium
        alpha = torch.sin(2 * math.pi * t / self.cfg.alpha_period)   # Slow
        delta = torch.sin(2 * math.pi * t / self.cfg.delta_period)   # Very slow

        # Assign frequency bands to dimension ranges
        d_quarter = D // 4
        osc = torch.zeros(1, seq_len, D, device=device)
        osc[:, :, :d_quarter] = gamma.expand(-1, -1, d_quarter) * 0.3
        osc[:, :, d_quarter:2*d_quarter] = theta.expand(-1, -1, d_quarter) * 0.5
        osc[:, :, 2*d_quarter:3*d_quarter] = alpha.expand(-1, -1, d_quarter) * 0.3
        osc[:, :, 3*d_quarter:] = delta.expand(-1, -1, D - 3*d_quarter) * 0.2

        # Add noise (biological rhythms are noisy)
        osc = osc.expand(batch_size, -1, -1) + torch.randn(batch_size, seq_len, D, device=device) * 0.1

        # Phase-amplitude coupling: gamma amplitude modulated by theta phase
        theta_env = (0.5 + 0.5 * torch.sin(2 * math.pi * t / self.cfg.theta_period))
        osc[:, :, :d_quarter] *= theta_env.expand(batch_size, -1, d_quarter)

        return F.layer_norm(osc, [D])

    # ── Development Step ────────────────────────────────────────────

    def step(self, total_prenatal_steps: int) -> Dict[str, float]:
        """
        Execute one prenatal development step.

        Determines which phase we're in, generates appropriate spontaneous
        activity, runs it through the model, and applies local learning.

        Args:
            total_prenatal_steps: total number of prenatal steps planned

        Returns: metrics for this step
        """
        metrics = {'prenatal_step': self.total_steps}

        # Determine current phase
        cumulative = 0.0
        current_phase = self.phases[-1][0]
        for phase_name, fraction in self.phases:
            cumulative += fraction
            if self.total_steps < cumulative * total_prenatal_steps:
                current_phase = phase_name
                break
        metrics['phase'] = current_phase

        B = self.cfg.batch_size
        T = min(self.cfg.seq_len, 128)  # Shorter sequences during prenatal (memory efficient)

        # ── Generate spontaneous activity based on phase ──────────────

        if current_phase == 'spontaneous_waves':
            # Phase 0a: Retinal waves — correlated temporal activity
            # Feed continuous activations directly (bypass embedding)
            wave_input = self._generate_retinal_waves(B, T)
            metrics.update(self._prenatal_forward_continuous(wave_input))

        elif current_phase == 'motor_babbling':
            # Phase 0b: Self-generated sequences — learn from own output
            token_ids = self._generate_motor_babbling(B, T)
            # Targets = shifted input (NTP-like, but from own generation)
            targets = token_ids[:, 1:].contiguous()
            input_ids = token_ids[:, :-1].contiguous()
            result = self.model.forward(input_ids, targets)
            self.model.local_learning_step()
            metrics['loss'] = result['loss'].item() if 'loss' in result else 0.0
            metrics['pc_loss'] = result['pc_loss'].item() if isinstance(result.get('pc_loss'), torch.Tensor) else 0.0
            metrics.update(result.get('metrics', {}))

        elif current_phase == 'competitive_diff':
            # Phase 0c: Structured patterns — drive column differentiation
            token_ids = self._generate_structured_patterns(B, T)
            targets = token_ids[:, 1:].contiguous()
            input_ids = token_ids[:, :-1].contiguous()
            result = self.model.forward(input_ids, targets)
            self.model.local_learning_step()
            metrics['loss'] = result['loss'].item() if 'loss' in result else 0.0
            metrics['pc_loss'] = result['pc_loss'].item() if isinstance(result.get('pc_loss'), torch.Tensor) else 0.0
            metrics.update(result.get('metrics', {}))

        elif current_phase == 'oscillatory_cal':
            # Phase 0d: Oscillatory calibration — rhythm stabilization
            osc_input = self._generate_oscillatory_input(B, T)
            metrics.update(self._prenatal_forward_continuous(osc_input))

        # ── Wake-sleep during prenatal (fetal sleep cycles exist!) ────
        # Fetuses sleep ~95% of the time (Roffwarg et al. 1966).
        # Prenatal sleep consolidates spontaneous patterns into cortex.
        if self.model.should_sleep():
            device = self.device
            sleep_metrics = self.model.sleep_phase()
            metrics.update({f'sleep_{k}': v for k, v in sleep_metrics.items()})

        # ── Track weight statistics for convergence ──────────────────
        weight_stats = self._compute_weight_stats()
        metrics.update(weight_stats)
        self._weight_stats_history.append(weight_stats)

        self.total_steps += 1
        self.metrics_history.append(metrics)

        return metrics

    def _prenatal_forward_continuous(self, activations: torch.Tensor) -> Dict[str, float]:
        """
        Forward pass with continuous activations (bypass embedding).

        Used for retinal waves and oscillatory calibration where we feed
        structured continuous patterns directly into the column stack.

        Applies:
          1. Forward through all columns (bottom-up)
          2. Compute prediction errors (top-down)
          3. Local learning (PC + Hebbian)
          4. Hippocampal encoding (for sleep replay)
        """
        metrics = {}
        B, T, D = activations.shape

        # Positional encoding
        rope_cos, rope_sin = self.model.grid_pos(T, self.device, activations.dtype, X=activations)
        if rope_sin.dim() == 4:
            pos_signal = rope_sin.mean(dim=1)
        elif rope_sin.dim() == 3:
            pos_signal = rope_sin.mean(dim=0).unsqueeze(0)
        else:
            pos_signal = rope_sin[:T].unsqueeze(0)
        d_h = pos_signal.shape[-1]
        d_model = D
        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)
        elif d_h < d_model:
            pos_embed = F.pad(pos_signal, (0, d_model - d_h))
        else:
            pos_embed = pos_signal[..., :d_model]
        x = activations + 0.1 * pos_embed

        # Reset TRN loss
        if self.cfg.thalamic_enabled:
            self.model.thalamus.reset_loss()

        # Bottom-up through columns
        h = x
        column_outputs = []
        sigma2_prev = None
        for i, col in enumerate(self.model.columns):
            h_thal = self.model.thalamus.route(h, column_idx=i, thal_feedback=None)
            out = col(ff_input=h_thal, td_context=None, sigma2_prev=sigma2_prev)
            column_outputs.append(out)
            sigma2_prev = out.sigma2
            h = out.output

        # Compute predictions and errors
        predictions = [out.prediction for out in column_outputs]
        prediction_targets = [x.detach()] + [column_outputs[l].output.detach() for l in range(len(column_outputs) - 1)]
        prediction_precisions = [out.sigma2 for out in column_outputs]
        errors = [prediction_targets[l] - predictions[l] for l in range(len(column_outputs))]

        # Store for local learning
        self.model._last_column_outputs = column_outputs
        self.model._last_predictions = predictions
        self.model._last_targets = prediction_targets
        self.model._last_precisions = prediction_precisions
        self.model._last_errors = errors

        # Brainstem neuromod
        mean_error = torch.stack([e.abs().mean() for e in errors]).mean()
        neuromod = self.model.brainstem.compute_state(
            column_outputs[-1].output,
            prediction_error=errors[-1],
        )
        self.model._last_neuromod = neuromod

        # Local learning
        learn_metrics = self.model.local_learning_step()
        metrics.update(learn_metrics)

        # Hippocampal encoding (for sleep replay of prenatal patterns)
        if self.cfg.hpc_enabled and self.model.training:
            mean_sigma2 = sum(out.sigma2 for out in column_outputs) / len(column_outputs)
            self.model.hippocampus.encode_episode(
                h, errors[-1], mean_sigma2,
            )

        # PC loss
        _, pc_loss = self.model.learning_manager.pc_optimizer.compute_column_losses(
            predictions, prediction_targets, prediction_precisions,
        )
        metrics['pc_loss'] = pc_loss.item() if isinstance(pc_loss, torch.Tensor) else pc_loss
        metrics['mean_pred_error'] = mean_error.item()
        metrics['sigma2_mean'] = torch.cat([out.sigma2 for out in column_outputs], dim=-1).mean().item()
        metrics['da_mean'] = neuromod.dopamine.mean().item()

        return metrics

    def _compute_weight_stats(self) -> Dict[str, float]:
        """
        Compute weight statistics to track prenatal self-organization progress.

        Key indicators of healthy development:
          - Weight magnitude stabilizing (not growing/shrinking unboundedly)
          - Column differentiation increasing (different columns → different weights)
          - BCM thresholds calibrating (moving from initial values)
          - Gate values evolving (from init toward functional values)
        """
        stats = {}

        # Mean weight magnitude across all columns
        col_mags = []
        for i, col in enumerate(self.model.columns):
            mag = sum(p.abs().mean().item() for p in col.parameters()) / max(1, sum(1 for _ in col.parameters()))
            col_mags.append(mag)
        stats['weight_mag_mean'] = sum(col_mags) / len(col_mags) if col_mags else 0
        stats['weight_mag_std'] = (sum((m - stats['weight_mag_mean'])**2 for m in col_mags) / max(1, len(col_mags))) ** 0.5

        # Column differentiation: variance of L2/3 W_assoc across columns
        assoc_norms = []
        for col in self.model.columns:
            if hasattr(col.L23, 'W_assoc'):
                assoc_norms.append(col.L23.W_assoc.data.norm().item())
        if len(assoc_norms) > 1:
            mean_norm = sum(assoc_norms) / len(assoc_norms)
            stats['column_diff'] = (sum((n - mean_norm)**2 for n in assoc_norms) / len(assoc_norms)) ** 0.5
        else:
            stats['column_diff'] = 0.0

        # Gate evolution: how far gates have moved from init (-2.0)
        gate_diffs = []
        for col in self.model.columns:
            for name, param in col.named_parameters():
                if 'gate_raw' in name:
                    gate_diffs.append((param.data.mean().item() - (-2.0))**2)
        stats['gate_evolution'] = (sum(gate_diffs) / max(1, len(gate_diffs))) ** 0.5

        return stats

    def has_converged(self, window: int = 50) -> bool:
        """
        Check if prenatal development has converged.

        Convergence = weight statistics are stable. The network has
        self-organized as much as it can from spontaneous activity alone.
        Further improvement requires real external data.

        Criteria:
          - At least 'window' steps of history
          - Weight magnitude std over last window < 5% of mean
          - PC loss trend is flat (< 2% change over window)
        """
        if len(self._weight_stats_history) < window:
            return False

        recent = self._weight_stats_history[-window:]
        mags = [s['weight_mag_mean'] for s in recent]
        mean_mag = sum(mags) / len(mags)
        if mean_mag < 1e-8:
            return False

        mag_std = (sum((m - mean_mag)**2 for m in mags) / len(mags)) ** 0.5
        mag_cv = mag_std / (mean_mag + 1e-8)

        # Check PC loss stability from metrics history
        pc_losses = []
        for m in self.metrics_history[-window:]:
            if 'pc_loss' in m:
                v = m['pc_loss']
                if isinstance(v, (int, float)) and v > 0:
                    pc_losses.append(v)

        pc_stable = True
        if len(pc_losses) >= window // 2:
            first_half = sum(pc_losses[:len(pc_losses)//2]) / max(1, len(pc_losses)//2)
            second_half = sum(pc_losses[len(pc_losses)//2:]) / max(1, len(pc_losses) - len(pc_losses)//2)
            if first_half > 1e-8:
                pc_change = abs(second_half - first_half) / first_half
                pc_stable = pc_change < 0.02

        return mag_cv < 0.05 and pc_stable

    def get_development_report(self) -> str:
        """Generate a human-readable report of prenatal development."""
        if not self.metrics_history:
            return "No prenatal development yet."

        lines = []
        lines.append("=" * 60)
        lines.append("PRENATAL DEVELOPMENT REPORT")
        lines.append("=" * 60)
        lines.append(f"  Total steps: {self.total_steps}")

        # Phase breakdown
        phase_counts = {}
        for m in self.metrics_history:
            phase = m.get('phase', 'unknown')
            phase_counts[phase] = phase_counts.get(phase, 0) + 1
        for phase, count in phase_counts.items():
            lines.append(f"  Phase '{phase}': {count} steps")

        # Final statistics
        if self._weight_stats_history:
            final = self._weight_stats_history[-1]
            lines.append(f"\n  Final weight magnitude: {final['weight_mag_mean']:.4f} (±{final['weight_mag_std']:.4f})")
            lines.append(f"  Column differentiation: {final['column_diff']:.6f}")
            lines.append(f"  Gate evolution from init: {final['gate_evolution']:.6f}")

        # PC loss trend
        pc_losses = [m.get('pc_loss', 0) for m in self.metrics_history if isinstance(m.get('pc_loss'), (int, float))]