Skip to content
Part 16 of 20

Scaling Framework

Krrish Choudhary·March 23, 2026

Source: nct_v2/v11_scale.py Lines: 791 Functions: 12

The Fundamental Insight: Local Learning Enables Modular Scaling

In a standard transformer, global backpropagation couples all parameters: changing one layer’s weights affects gradients through every other layer. This means adding a layer, widening a layer, or restructuring the network requires full retraining from scratch. GPT-4 was not “grown” from GPT-3, it was retrained from random initialization at the target scale.

NCT’s local learning rules break this coupling. Each column learns independently via predictive coding and Hebbian plasticity. Adding a column does not invalidate existing columns’ learned representations, it only requires retraining the inter-column coordination mechanisms (thalamic routing, lateral connections, global workspace), which account for only 3.2% of total parameters.

Theorem 30 (Parameter Locality Enables Incremental Scaling). For a model with NN columns and dmodel=dd_{\text{model}} = d, the parameter distribution is: Plocal=N×(d2+2d⋅dff+d⋅di+d⋅dslot⋅K+…)⏟per-column: L4, L2/3, L5, interneurons, WM, osc≈84.3%Pglobal=G⋅(d⋅dr+dr⋅d)⏟thalamus+N⋅2⋅d⋅r⏟lateral+N⋅2⋅d⋅dws⏟workspace≈3.2%Pfixed=V⋅d⏟embedding+d⋅V+delta+comp⏟LM head≈8.6%Psubcortical=HPC+BG+CB+brainstem⏟d-dependent, N-independent≈3.9%\begin{aligned} P_{\text{local}} &= N \times \underbrace{(d^2 + 2d \cdot d_{\text{ff}} + d \cdot d_i + d \cdot d_{\text{slot}} \cdot K + \ldots)}_{\text{per-column: L4, L2/3, L5, interneurons, WM, osc}} \approx 84.3\% \\ P_{\text{global}} &= \underbrace{G \cdot (d \cdot d_r + d_r \cdot d)}_{\text{thalamus}} + \underbrace{N \cdot 2 \cdot d \cdot r}_{\text{lateral}} + \underbrace{N \cdot 2 \cdot d \cdot d_{\text{ws}}}_{\text{workspace}} \approx 3.2\% \\ P_{\text{fixed}} &= \underbrace{V \cdot d}_{\text{embedding}} + \underbrace{d \cdot V + \text{delta} + \text{comp}}_{\text{LM head}} \approx 8.6\% \\ P_{\text{subcortical}} &= \underbrace{\text{HPC} + \text{BG} + \text{CB} + \text{brainstem}}_{\text{d-dependent, N-independent}} \approx 3.9\% \end{aligned} Adding one column costs only Pone_col+0.2×Pglobal≈7.7%P_{\text{one\_col}} + 0.2 \times P_{\text{global}} \approx 7.7\% of full retraining.

Parameter distribution by component type. 84.3% of parameters are column-local (preserved during scaling). Only 3.2% (thalamic routing, lateral connections, workspace) need retraining when adding columns.
Figure 75. Parameter distribution by component type. 84.3% of parameters are column-local (preserved during scaling). Only 3.2% (thalamic routing, lateral connections, workspace) need retraining when adding columns.
(Illustrated) Parameter distribution by component type. 84.3% of parameters are column-local (preserved during scaling). Only 3.2% (thalamic routing, lateral connections, workspace) need retraining when adding...
Figure 76. (Illustrated) Parameter distribution by component type. 84.3% of parameters are column-local (preserved during scaling). Only 3.2% (thalamic routing, lateral connections, workspace) need retraining when adding...

Operation 1: Progressive Column Growth (grow_columns)

Theorem 31 (Progressive Column Growth). New columns can be added to a trained network with the following guarantees:

Preserved (∼\sim84% of params): All existing column internal weights (Hebbian associations WassocW_{\text{assoc}}, PC prediction weights WpredW_{\text{pred}}, L5 FFN, interneuron weights, working memory parameters, oscillatory coupling, BCM thresholds, metaplasticity EMAs).

Retrained (∼\sim3% of params): Thalamic routing matrix (expanded with new relay groups), lateral connections (new send/receive edges), workspace projections (new write/read weights). Existing inter-column weights between OLD columns are preserved.

Trained from scratch: New column internal weights (undergo prenatal self-organization before joining the trained network).

The growth algorithm proceeds in 10 steps:

Algorithm 2: Progressive Column Growth
Algorithm 2. Progressive Column Growth

Insertion modes: Three strategies for where new columns enter the hierarchy:

Column insertion strategies.
ModePositionWhen to Use
appendAfter all existing columnsDefault. New columns process the most abstract representations.
bottomBefore all existing columnsNew columns handle early (sensory) processing.
interleaveDistributed evenly among existingAdds processing depth throughout the hierarchy.
Progressive column growth: existing columns are frozen during bootstrap, new columns undergo prenatal self-organization. Thalamus, lateral, and workspace are expanded with identity-at-init weights. After bootstrap, all columns are unfrozen for coordinated learning.
Figure 77. Progressive column growth: existing columns are frozen during bootstrap, new columns undergo prenatal self-organization. Thalamus, lateral, and workspace are expanded with identity-at-init weights. After bootstrap, all columns are unfrozen for coordinated learning.
(Illustrated) Progressive column growth: existing columns are frozen during bootstrap, new columns undergo prenatal self-organization. Thalamus, lateral, and workspace are expanded with identity-at-init weights....
Figure 78. (Illustrated) Progressive column growth: existing columns are frozen during bootstrap, new columns undergo prenatal self-organization. Thalamus, lateral, and workspace are expanded with identity-at-init weights....
Net2Net column splitting: the parent column is deep-copied into two daughters with output weights scaled by 0.5 (preserving the sum). Symmetry-breaking noise (ε) is added to one copy. Subsequent competitive Hebbian learning drives divergence.
Figure 79. Net2Net column splitting: the parent column is deep-copied into two daughters with output weights scaled by 0.5 (preserving the sum). Symmetry-breaking noise (ε\varepsilon) is added to one copy. Subsequent competitive Hebbian learning drives divergence.
(Illustrated) Net2Net column splitting: the parent column is deep-copied into two daughters with output weights scaled by 0.5 (preserving the sum). Symmetry-breaking noise (ε) is added to one copy. S...
Figure 80. (Illustrated) Net2Net column splitting: the parent column is deep-copied into two daughters with output weights scaled by 0.5 (preserving the sum). Symmetry-breaking noise (ε\varepsilon) is added to one copy. S...

Thalamus expansion: New relay groups are created with random initialization. Existing relay weights are copied position-by-position. The TRN (thalamic reticular nucleus) operates on dmodeld_{\text{model}} (not column count), so its weights transfer directly without modification.

Lateral expansion: New columns get zero-initialized send weights (identity-at-init principle: no lateral signal initially). Old column positions are mapped to their new indices in the expanded arrangement.

Workspace expansion: New columns get zero-initialized write projections. Old write/read weights are copied to their new positions.

Operation 2: Net2Net Column Splitting (split_column)

Theorem 32 (Function-Preserving Column Split). A trained column kk with output weight WoutkW_{\text{out}}^k is split into two daughter columns (ka,kb)(k_a, k_b) such that: Woutka=0.5⋅Woutk,Woutkb=0.5⋅Woutk+N(0,ϵ)W_{\text{out}}^{k_a} = 0.5 \cdot W_{\text{out}}^k, \qquad W_{\text{out}}^{k_b} = 0.5 \cdot W_{\text{out}}^k + \mathcal{N}(0, \epsilon) At the moment of split: Woutka+Woutkb≈WoutkW_{\text{out}}^{k_a} + W_{\text{out}}^{k_b} \approx W_{\text{out}}^k, so network output is mathematically identical (up to noise ϵ\epsilon). The scaling applies to four output-facing weight matrices: WL5,outW_{\text{L5,out}}, WL5,predW_{\text{L5,pred}}, WL6,outW_{\text{L6,out}}, and WL2/3,outW_{\text{L2/3,out}}.

After split, competitive Hebbian learning drives the two copies to differentiate: child aa refines the parent’s original specialty, while child bb discovers a complementary sub-specialty.

Proposition 6 (Column Split is Analogous to Cell Division). Biological cell division produces two cells that together maintain the function of the parent. Subsequent gene expression differences drive specialization. In NCT, the 0.5×0.5\times weight scaling preserves function, and symmetry-breaking noise (ϵ=0.01\epsilon = 0.01) plus competitive Hebbian dynamics drive specialization. The lateral connection between the split pair inherits the parent’s weights, maintaining the neighborhood structure.

Operation 3: Overload Detection (find_overloaded_columns)

Before splitting, we need to identify which column is most overloaded, trying to represent too much with insufficient capacity.

Definition 8 (Column Overload Score). For each column ii, the overload score is computed over nn evaluation batches: overloadi=0.6×σˉi2−min⁡jσˉj2max⁡jσˉj2−min⁡jσˉj2+10−8⏟normalized prediction error+0.4×gˉi−min⁡jgˉjmax⁡jgˉj−min⁡jgˉj+10−8⏟normalized gate activation\text{overload}_i = 0.6 \times \underbrace{\frac{\bar{\sigma}^2_i - \min_j \bar{\sigma}^2_j}{\max_j \bar{\sigma}^2_j - \min_j \bar{\sigma}^2_j + 10^{-8}}}_{\text{normalized prediction error}} + 0.4 \times \underbrace{\frac{\bar{g}_i - \min_j \bar{g}_j}{\max_j \bar{g}_j - \min_j \bar{g}_j + 10^{-8}}}_{\text{normalized gate activation}} High σ2\sigma^2 (uncertain predictions) + high gate activation (all mechanisms maxed out) = overloaded column. The highest-scoring column is the best candidate for splitting.

The overload detection evaluates over n=50n = 50 batches, collecting mean σ2\sigma^2 and mean gate values per column. Results are returned sorted by overload score (highest first).

Operation 4: μ\muP Hyperparameter Transfer (extract_mu_p)

Theorem 33 (μ\muP Transfer for Local Learning (Yang & Hu, 2021)). Under Maximal Update Parameterization (μ\muP), hyperparameters found on a small model transfer to larger models without retuning. For NCT, 29 scale-invariant hyperparameters are extracted:

Learning rates (3): ηPC,ηH,ηbase\eta_{\text{PC}}, \eta_H, \eta_{\text{base}}, these control the magnitude of local updates and are independent of model width.

PC dynamics (5): Kmin⁡,Kmax⁡,τconv,σinit2,ηPCK_{\min}, K_{\max}, \tau_{\text{conv}}, \sigma^2_{\text{init}}, \eta_{\text{PC}}, the convergence behavior of predictive coding is a per-column dynamic, independent of the number of columns.

Hebbian parameters (3): kWTA,S,wk_{\text{WTA}}, S, w, sparsity ratio, settling steps, and window size are dimensionless or integer-valued.

Gate dynamics (2): g0,gate_LR_multg_0, \text{gate\_LR\_mult}, the sigmoid gate behavior is scale-independent.

BCM/Meta (2): τBCM,τmeta\tau_{\text{BCM}}, \tau_{\text{meta}}, homeostatic time constants.

Oscillatory (4): Pθ,Pα,Pδ,γP_\theta, P_\alpha, P_\delta, \gamma, oscillatory periods in tokens.

WM (2): KNMDA,KphonoK_{\text{NMDA}}, K_{\text{phono}}, slot counts.

Sleep (3): Is,R,δdownscaleI_s, R, \delta_{\text{downscale}}, wake-sleep timing.

Structural (3): θgrowth,θprune,Iprune\theta_{\text{growth}}, \theta_{\text{prune}}, I_{\text{prune}}.

Regularization (3): dropout, weight decay, grad norm.

NCT’s local learning rules make μ\muP transfer more reliable than for transformers: each column’s dynamics are independent of the total column count. Plasticity rates found on 12 columns should transfer directly to 64 columns, because the local Hebbian and PC update rules operate identically regardless of how many other columns exist.

Dimension-dependent parameters are scaled proportionally:

dparamlarge=max⁡(floor,⌊dparamsmall×dmodellargedmodelsmall⌋)d_{\text{param}}^{\text{large}} = \max\left(\text{floor}, \left\lfloor d_{\text{param}}^{\text{small}} \times \frac{d_{\text{model}}^{\text{large}}}{d_{\text{model}}^{\text{small}}} \right\rfloor\right)

This applies to: drelay,dinhibitory,dslot,dtrace,dsparse,dcerebellar,dbg,dtrn,nassoc_heads,nrelay_groups,hpc_memory_sized_{\text{relay}}, d_{\text{inhibitory}}, d_{\text{slot}}, d_{\text{trace}}, d_{\text{sparse}}, d_{\text{cerebellar}}, d_{\text{bg}}, d_{\text{trn}}, n_{\text{assoc\_heads}}, n_{\text{relay\_groups}}, hpc\_memory\_size.

μP hyperparameter transfer: train a small model (106M), extract 29 scale-invariant hyperparameters, transfer them to a large model (1B+) trained from scratch. Dimension-dependent parameters scale proportionally. NCT’s local learning makes this transfer more reliable than for transformers.
Figure 81. μ\muP hyperparameter transfer: train a small model (106M), extract 29 scale-invariant hyperparameters, transfer them to a large model (1B+) trained from scratch. Dimension-dependent parameters scale proportionally. NCT’s local learning makes this transfer more reliable than for transformers.
(Illustrated) μP hyperparameter transfer: train a small model (106M), extract 29 scale-invariant hyperparameters, transfer them to a large model (1B+) trained from scratch. Dimension-dependent parameters sca...
Figure 82. (Illustrated) μ\muP hyperparameter transfer: train a small model (106M), extract 29 scale-invariant hyperparameters, transfer them to a large model (1B+) trained from scratch. Dimension-dependent parameters sca...

Operation 5: Scaling Cost Report (scaling_report)

The scaling report provides a per-component parameter breakdown and estimates the cost of each scaling operation:

Table 11. Scaling cost analysis for the default 106M configuration.
OperationParams Affected% of TotalEst. Cost vs Retrain
Add 1 column7.5M (new) + 0.7M (routing)7.7%∼\sim8%
Split 1 column7.5M (divergence) + 0.3M (routing)7.3%∼\sim7%
Width ×2\times 2 (d:512→1024d: 512 \rightarrow 1024)All dd-dependent weights∼\sim75%∼\sim70%
Full retrainAll 106M100%100%

Small incremental scaling (12 →\rightarrow 16 →\rightarrow 20 columns): Use progressive column growth. Each step costs ∼\sim8% of full retraining. Existing column knowledge is fully preserved.

Targeted capacity increase (one column overloaded): Use column splitting on the highest-overload column. Function-preserving at split point, ∼\sim7% cost.

Large jump (>2×>2\times scale, e.g., 12 →\rightarrow 64 columns or d:512→2048d: 512 \rightarrow 2048): Use μ\muP hyperparameter transfer + train from scratch at target scale. The HPs from the small model transfer directly, saving the entire hyperparameter search cost.

Width expansion (dmodeld_{\text{model}} increase): Most expensive (∼\sim70%). Only use when column growth is insufficient. Old subspace is warm-started but new dimensions need full training.

Freeze / Unfreeze Utilities

Two helper functions manage parameter freezing during the column bootstrap phase, implementing the biological analog of “critical period protection”, ensuring that established cortical representations are not disrupted while new areas undergo initial self-organization:

unfreeze_columns(model, column_indices=None): Sets requires_grad = True for all parameters in specified columns. If column_indices is None, unfreezes all columns. Called after new columns complete their prenatal self-organization phase, signaling that they are ready to participate in coordinated learning with existing columns. Logs the number of unfrozen parameters and total trainable count.

freeze_columns(model, column_indices): Sets requires_grad = False for all parameters in specified columns. Used during progressive column growth: when new columns are added, existing columns are frozen to prevent their learned Hebbian associations, BCM thresholds, and metaplasticity EMAs from being disturbed by the chaotic, high-amplitude activity generated during prenatal self-organization of the new columns. Once the new columns have stabilized (completed prenatal phase), all columns are unfrozen and competitive Hebbian dynamics re-differentiates the full ensemble.

This freeze/unfreeze protocol is critical for knowledge preservation during scaling: without freezing, the prenatal activity of new columns can propagate through lateral connections and the global workspace, perturbing existing columns’ learned representations. With freezing, existing knowledge is locked in place during the bootstrap period.

Source Code

Python
793 lines
        if pc_losses:
            lines.append(f"\n  PC loss: {pc_losses[0]:.4f} → {pc_losses[-1]:.4f}")
            if pc_losses[0] > 1e-8:
                improvement = (pc_losses[0] - pc_losses[-1]) / pc_losses[0] * 100
                lines.append(f"  PC improvement: {improvement:.1f}%")

        # Sleep phases during prenatal
        sleep_count = sum(1 for m in self.metrics_history if 'sleep_replayed_memories' in m)
        lines.append(f"\n  Sleep phases: {sleep_count}")

        # Convergence
        lines.append(f"  Converged: {self.has_converged()}")

        lines.append("=" * 60)
        return "\n".join(lines)



# ===========================================================================
# Scaling (Column Growth, Splitting, µP Transfer)
# Source: nct_v2/v11_scale.py
# ===========================================================================

"""
NCT V11: Scaling — Progressive Column Growth & Column Splitting
================================================================

Brain-inspired scaling for the cortical column network.

Three scaling operations:
  1. Progressive Column Growth — add new columns to a trained network
  2. Net2Net Column Splitting — split overloaded columns into two
  3. µP Hyperparameter Transfer — extract hyperparameters for training at target scale

The key insight: V11 uses LOCAL learning (PC + Hebbian). ~90% of params are
intra-column weights that are preserved during scaling. Only inter-column
coordination (~10% — thalamus, lateral, workspace) needs retraining.

Usage:
  # Load trained checkpoint
  model, cfg = load_checkpoint('checkpoints/v11/best.pt')

  # Add 8 new columns (12 → 20)
  model, new_cfg = grow_columns(model, cfg, n_new=8)

  # Or split the most overloaded column
  model, new_cfg = split_column(model, cfg, column_idx=5)

  # Extract µP hyperparameters for training a larger model from scratch
  hp = extract_mu_p(model, cfg)
  large_cfg = V11Config(n_columns=64, d_model=2048, **hp)
"""



# [bundled] from .v11_config import V11Config
# [bundled] from .v11_column import CorticalColumn, LateralColumnConnection, RMSNorm
# [bundled] from .v11_systems import (

logger = logging.getLogger(__name__)


# ═══════════════════════════════════════════════════════════════════════
# 1. Progressive Column Growth
# ═══════════════════════════════════════════════════════════════════════

def grow_columns(
    model: nn.Module,
    cfg: V11Config,
    n_new: int,
    insertion: str = 'append',
    freeze_existing: bool = True,
    noise_scale: float = 0.01,
) -> Tuple[nn.Module, V11Config]:
    """
    Add new cortical columns to a trained network.

    Biological analog: postnatal cortical development. New functional areas
    come online alongside existing ones. Visual cortex doesn't retrain when
    language areas develop — they coordinate through thalamus.

    Args:
        model: trained CorticalColumnNetwork
        cfg: current config
        n_new: number of columns to add
        insertion: 'append' (add to top), 'interleave' (distribute evenly),
                   or 'bottom' (add before existing columns)
        freeze_existing: if True, freeze existing column params during bootstrap
        noise_scale: initialization noise for new columns

    Returns:
        (model, new_cfg) — model with added columns, updated config

    What's preserved (~90% of params):
        - All existing column internal weights (Hebbian, PC, FFN, WM, etc.)
        - Existing inter-column lateral weights (between OLD columns)
        - Embedding, LM head, position encoding

    What's retrained (~10% of params):
        - Thalamic routing (expanded for new columns)
        - Lateral connections (new cross-column edges)
        - Workspace (new read/write projections)
        - BG/Cerebellum/HPC interfaces are d_model-based, unchanged
    """
    old_n = cfg.n_columns
    new_n = old_n + n_new

    # ── 1. Create new config ──────────────────────────────────────────
    new_cfg = copy.deepcopy(cfg)
    new_cfg.n_columns = new_n
    # Adjust relay groups proportionally
    new_cfg.n_relay_groups = max(1, new_n // max(1, old_n // cfg.n_relay_groups))

    logger.info(f"Growing columns: {old_n} → {new_n} "
                f"(relay groups: {cfg.n_relay_groups} → {new_cfg.n_relay_groups})")

    # ── 2. Create new columns ─────────────────────────────────────────
    new_columns = []
    for i in range(n_new):
        col_idx = old_n + i  # default for 'append'
        col = CorticalColumn(new_cfg, column_idx=col_idx)

        # Add small noise to break symmetry between new columns
        with torch.no_grad():
            for p in col.parameters():
                if p.requires_grad:
                    p.add_(torch.randn_like(p) * noise_scale)

        new_columns.append(col)

    # ── 3. Insert columns at specified positions ──────────────────────
    old_columns = list(model.columns)

    if insertion == 'append':
        all_columns = old_columns + new_columns
    elif insertion == 'bottom':
        all_columns = new_columns + old_columns
    elif insertion == 'interleave':
        # Distribute new columns evenly among existing ones
        all_columns = []
        step = max(1, old_n // n_new)
        new_iter = iter(new_columns)
        for i, col in enumerate(old_columns):
            all_columns.append(col)
            if (i + 1) % step == 0:
                try:
                    all_columns.append(next(new_iter))
                except StopIteration:
                    pass
        # Append any remaining new columns
        for remaining in new_iter:
            all_columns.append(remaining)
    else:
        raise ValueError(f"Unknown insertion mode: {insertion}")

    # Reassign column indices
    for i, col in enumerate(all_columns):
        col.column_idx = i

    model.columns = nn.ModuleList(all_columns)

    # ── 4. Expand thalamic routing ────────────────────────────────────
    model.thalamus = _expand_thalamus(model.thalamus, cfg, new_cfg)

    # ── 5. Expand lateral connections ─────────────────────────────────
    model.lateral = _expand_lateral(model.lateral, cfg, new_cfg, old_columns, all_columns)

    # ── 6. Expand global workspace ────────────────────────────────────
    model.workspace = _expand_workspace(model.workspace, cfg, new_cfg)

    # ── 7. Expand self-assessment ─────────────────────────────────────
    model.self_assessment = SelfAssessment(new_cfg)

    # ── 8. Update config reference ────────────────────────────────────
    model.cfg = new_cfg

    # ── 9. Freeze existing columns if requested ───────────────────────
    if freeze_existing:
        frozen_count = 0
        for col in old_columns:
            for p in col.parameters():
                p.requires_grad = False
                frozen_count += 1
        logger.info(f"Froze {frozen_count} params in {len(old_columns)} existing columns. "
                    f"Call unfreeze_columns(model) after bootstrap.")

    # ── 10. Report parameter changes ──────────────────────────────────
    total_params = sum(p.numel() for p in model.parameters())
    trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
    logger.info(f"After growth: {total_params:,} total params, "
                f"{trainable_params:,} trainable ({trainable_params/total_params*100:.1f}%)")

    return model, new_cfg


def _expand_thalamus(old_thal: Thalamus, old_cfg: V11Config, new_cfg: V11Config) -> Thalamus:
    """Expand thalamus to accommodate more columns.

    Strategy: create new thalamus with more relay groups,
    copy existing relay weights into corresponding positions.
    TRN is dimension-based (d_model), so its weights transfer directly.
    """
    new_thal = Thalamus(new_cfg)

    if not old_thal.enabled or not new_thal.enabled:
        return new_thal

    # Copy existing relay group weights
    n_copy = min(old_cfg.n_relay_groups, new_cfg.n_relay_groups)
    with torch.no_grad():
        for i in range(n_copy):
            # Copy relay weights (W_in, W_out, gate, norm)
            new_thal.relays[i].load_state_dict(old_thal.relays[i].state_dict())

        # Copy TRN weights (operates on d_model, dimension unchanged)
        new_thal.trn.load_state_dict(old_thal.trn.state_dict())

    logger.info(f"Thalamus expanded: {old_cfg.n_relay_groups} → {new_cfg.n_relay_groups} relay groups "
                f"({n_copy} preserved)")
    return new_thal


def _expand_lateral(
    old_lat: LateralColumnConnection,
    old_cfg: V11Config,
    new_cfg: V11Config,
    old_columns: list,
    all_columns: list,
) -> LateralColumnConnection:
    """Expand lateral connections for new column count.

    Strategy: create new lateral system, copy weights for old column positions.
    New columns get zero-initialized send weights (identity-at-init principle).
    """
    new_lat = LateralColumnConnection(new_cfg)

    # Map old column positions in the new arrangement
    old_positions = []
    for i, col in enumerate(all_columns):
        if col in old_columns:
            old_positions.append(i)

    # Copy old lateral weights to their new positions
    with torch.no_grad():
        for old_idx, new_idx in enumerate(old_positions):
            if old_idx < len(old_lat.W_send) and new_idx < len(new_lat.W_send):
                new_lat.W_send[new_idx].load_state_dict(old_lat.W_send[old_idx].state_dict())
                new_lat.W_recv[new_idx].load_state_dict(old_lat.W_recv[old_idx].state_dict())
                new_lat.gate_raws[new_idx].data.copy_(old_lat.gate_raws[old_idx].data)

    logger.info(f"Lateral connections expanded: {old_cfg.n_columns} → {new_cfg.n_columns} "
                f"({len(old_positions)} preserved)")
    return new_lat


def _expand_workspace(
    old_ws: CorticalWorkspace,
    old_cfg: V11Config,
    new_cfg: V11Config,
) -> CorticalWorkspace:
    """Expand global workspace for new column count.

    Strategy: create new workspace, copy old read/write projections.
    New columns get zero-initialized write projections (identity-at-init).
    """
    new_ws = CorticalWorkspace(new_cfg)

    n_copy = min(old_cfg.n_columns, new_cfg.n_columns)
    with torch.no_grad():
        for i in range(n_copy):
            new_ws.W_write[i].load_state_dict(old_ws.W_write[i].state_dict())
            new_ws.W_read[i].load_state_dict(old_ws.W_read[i].state_dict())

    logger.info(f"Workspace expanded: {old_cfg.n_columns} → {new_cfg.n_columns} columns")
    return new_ws


# ═══════════════════════════════════════════════════════════════════════
# 2. Net2Net Column Splitting
# ═══════════════════════════════════════════════════════════════════════

def split_column(
    model: nn.Module,
    cfg: V11Config,
    column_idx: int,
    noise_scale: float = 0.01,
) -> Tuple[nn.Module, V11Config]:
    """
    Split a trained column into two — function-preserving at moment of split.

    Biological analog: cell division. The two daughter columns together compute
    the exact same function as the parent. Then competitive Hebbian learning
    drives them to differentiate (one keeps the original specialty, the other
    discovers a sub-specialty).

    Math: if Column_k has output weight W_out, we create:
        Column_k_a with W_out_a = 0.5 * W_out + noise
        Column_k_b with W_out_b = 0.5 * W_out + noise
    So: W_out_a + W_out_b ≈ W_out (function preserved)

    Args:
        model: trained CorticalColumnNetwork
        cfg: current config
        column_idx: which column to split (0-indexed)
        noise_scale: symmetry-breaking noise magnitude

    Returns:
        (model, new_cfg) — model with split column, updated config
    """
    old_n = cfg.n_columns
    new_n = old_n + 1

    if column_idx < 0 or column_idx >= old_n:
        raise ValueError(f"column_idx {column_idx} out of range [0, {old_n})")

    # ── 1. Deep-copy the column ───────────────────────────────────────
    parent = model.columns[column_idx]
    child_a = copy.deepcopy(parent)
    child_b = copy.deepcopy(parent)

    # ── 2. Scale output weights by 0.5 (function preservation) ────────
    # The key outputs are: L5 output (W_out), L6 feedback, prediction
    with torch.no_grad():
        _scale_output_weights(child_a, 0.5)
        _scale_output_weights(child_b, 0.5)

        # Add symmetry-breaking noise to child_b
        for pa, pb in zip(child_a.parameters(), child_b.parameters()):
            pb.add_(torch.randn_like(pb) * noise_scale)

    # ── 3. Insert child_b after child_a ───────────────────────────────
    columns = list(model.columns)
    columns[column_idx] = child_a
    columns.insert(column_idx + 1, child_b)

    # Reassign indices
    for i, col in enumerate(columns):
        col.column_idx = i

    model.columns = nn.ModuleList(columns)

    # ── 4. Update config and subsystems ───────────────────────────────
    new_cfg = copy.deepcopy(cfg)
    new_cfg.n_columns = new_n
    new_cfg.n_relay_groups = max(1, new_n // max(1, old_n // cfg.n_relay_groups))

    model.thalamus = _expand_thalamus(model.thalamus, cfg, new_cfg)
    model.lateral = _expand_lateral_for_split(model.lateral, cfg, new_cfg, column_idx)
    model.workspace = _expand_workspace(model.workspace, cfg, new_cfg)
    model.self_assessment = SelfAssessment(new_cfg)
    model.cfg = new_cfg

    total_params = sum(p.numel() for p in model.parameters())
    logger.info(f"Split column {column_idx}: {old_n} → {new_n} columns, "
                f"{total_params:,} total params. Function preserved at split point.")

    return model, new_cfg


def _scale_output_weights(column: CorticalColumn, scale: float):
    """Scale a column's output-facing weights to preserve function after split."""
    # L5 output (the main output pathway)
    if hasattr(column.L5, 'W_out'):
        column.L5.W_out.weight.mul_(scale)
    # L5 prediction head
    if hasattr(column.L5, 'W_pred'):
        column.L5.W_pred.weight.mul_(scale)
    # L6 thalamic feedback
    if hasattr(column.L6, 'W_out'):
        column.L6.W_out.weight.mul_(scale)
    # L2/3 output projection
    if hasattr(column.L23, 'W_out'):
        column.L23.W_out.weight.mul_(scale)


def _expand_lateral_for_split(
    old_lat: LateralColumnConnection,
    old_cfg: V11Config,
    new_cfg: V11Config,
    split_idx: int,
) -> LateralColumnConnection:
    """Expand lateral connections after a column split.

    The new column (at split_idx+1) gets a copy of the split column's
    lateral weights, maintaining the neighborhood structure.
    """
    new_lat = LateralColumnConnection(new_cfg)

    with torch.no_grad():
        for old_i in range(old_cfg.n_columns):
            # Map old index to new index (shift everything after split_idx by 1)
            new_i = old_i if old_i <= split_idx else old_i + 1

            if old_i < len(old_lat.W_send) and new_i < len(new_lat.W_send):
                new_lat.W_send[new_i].load_state_dict(old_lat.W_send[old_i].state_dict())
                new_lat.W_recv[new_i].load_state_dict(old_lat.W_recv[old_i].state_dict())
                new_lat.gate_raws[new_i].data.copy_(old_lat.gate_raws[old_i].data)

        # The new column (split_idx+1) gets a copy of the parent's lateral weights
        parent_i = split_idx
        child_i = split_idx + 1
        if parent_i < len(old_lat.W_send) and child_i < len(new_lat.W_send):
            new_lat.W_send[child_i].load_state_dict(old_lat.W_send[parent_i].state_dict())
            new_lat.W_recv[child_i].load_state_dict(old_lat.W_recv[parent_i].state_dict())
            new_lat.gate_raws[child_i].data.copy_(old_lat.gate_raws[parent_i].data)

    return new_lat


# ═══════════════════════════════════════════════════════════════════════
# 3. Identify Columns to Split (Overload Detection)
# ═══════════════════════════════════════════════════════════════════════

def find_overloaded_columns(
    model: nn.Module,
    dataloader,
    n_batches: int = 50,
    device: str = 'cuda',
) -> List[Dict]:
    """
    Identify which columns are overloaded and would benefit from splitting.

    Metrics for overload:
      1. High mean prediction error (σ² relative to others)
      2. Low sparsity (k-WTA near saturation — trying to represent too much)
      3. High gate activation (all mechanisms maxed out)
      4. Low column differentiation (not specialized enough)

    Returns:
        List of dicts sorted by overload score (highest first):
        [{'idx': 5, 'score': 0.87, 'pe': 2.1, 'sparsity': 0.45, 'gate_mean': 0.9}, ...]
    """
    model.eval()
    n_cols = model.cfg.n_columns

    # Accumulators
    pe_accum = torch.zeros(n_cols)
    sparsity_accum = torch.zeros(n_cols)
    gate_accum = torch.zeros(n_cols)
    count = 0

    with torch.no_grad():
        for batch_idx, batch in enumerate(dataloader):
            if batch_idx >= n_batches:
                break

            input_ids = batch['input_ids'].to(device) if isinstance(batch, dict) else batch[0].to(device)
            targets = batch.get('labels', None) if isinstance(batch, dict) else (batch[1].to(device) if len(batch) > 1 else None)

            result = model(input_ids, targets=targets)

            # Collect per-column metrics from the last forward pass
            if model._last_column_outputs is not None:
                for i, out in enumerate(model._last_column_outputs):
                    # Prediction error magnitude
                    pe_accum[i] += out.sigma2.mean().cpu()
                    # Gate values (proxy for mechanism utilization)
                    gates = model.columns[i].get_gate_values()
                    gate_mean = sum(gates.values()) / max(len(gates), 1)
                    gate_accum[i] += gate_mean

            count += 1

    if count == 0:
        logger.warning("No batches processed for overload detection")
        return []

    pe_accum /= count
    gate_accum /= count

    # Normalize to [0, 1] range
    pe_norm = (pe_accum - pe_accum.min()) / (pe_accum.max() - pe_accum.min() + 1e-8)
    gate_norm = (gate_accum - gate_accum.min()) / (gate_accum.max() - gate_accum.min() + 1e-8)

    # Overload score: high PE + high gate activation = overloaded
    overload_scores = 0.6 * pe_norm + 0.4 * gate_norm

    results = []
    for i in range(n_cols):
        results.append({
            'idx': i,
            'score': overload_scores[i].item(),
            'pe': pe_accum[i].item(),
            'gate_mean': gate_accum[i].item(),
        })

    results.sort(key=lambda x: x['score'], reverse=True)
    return results


# ═══════════════════════════════════════════════════════════════════════
# 4. µP Hyperparameter Transfer
# ═══════════════════════════════════════════════════════════════════════

def extract_mu_p(model: nn.Module, cfg: V11Config) -> Dict:
    """
    Extract µP-transferable hyperparameters from a trained small model.

    These hyperparameters are scale-invariant under Maximal Update
    Parameterization (Yang & Hu 2021) — they transfer from small to large
    models without retuning.

    For V11, local learning rules make µP transfer MORE reliable than for
    transformers: each column's dynamics are independent of the total
    column count, so plasticity rates found on 12 columns transfer to 64.

    Returns:
        Dict of hyperparameters suitable for constructing a larger V11Config
    """
    hp = {}

    # ── Learning rates (scale-invariant in µP) ────────────────────────
    hp['hebbian_lr'] = cfg.hebbian_lr
    hp['pc_learning_lr'] = cfg.pc_learning_lr
    hp['base_lr'] = cfg.base_lr

    # ── PC dynamics ───────────────────────────────────────────────────
    hp['pc_min_steps'] = cfg.pc_min_steps
    hp['pc_max_steps'] = cfg.pc_max_steps
    hp['pc_convergence_threshold'] = cfg.pc_convergence_threshold
    hp['sigma2_init'] = cfg.sigma2_init

    # ── Hebbian parameters ────────────────────────────────────────────
    hp['k_wta_ratio'] = cfg.k_wta_ratio
    hp['n_settle_steps'] = cfg.n_settle_steps
    hp['assoc_window_size'] = cfg.assoc_window_size

    # ── Neuromodulator scales (learned) ───────────────────────────────
    # Extract the effective neuromod scales from the trained brainstem
    if hasattr(model, 'brainstem'):
        bs = model.brainstem
        if hasattr(bs, 'da_scale'):
            hp['_da_scale_trained'] = bs.da_scale.item() if isinstance(bs.da_scale, torch.Tensor) else bs.da_scale
        if hasattr(bs, 'ne_scale'):
            hp['_ne_scale_trained'] = bs.ne_scale.item() if isinstance(bs.ne_scale, torch.Tensor) else bs.ne_scale

    # ── Gate dynamics ─────────────────────────────────────────────────
    hp['gate_init'] = cfg.gate_init
    hp['gate_lr_mult'] = cfg.gate_lr_mult

    # ── BCM / Metaplasticity ──────────────────────────────────────────
    hp['bcm_tau'] = cfg.bcm_tau

    # ── Oscillatory parameters ────────────────────────────────────────
    hp['gamma_period'] = cfg.gamma_period
    hp['theta_period'] = cfg.theta_period
    hp['alpha_period'] = cfg.alpha_period
    hp['delta_period'] = cfg.delta_period

    # ── WM parameters ─────────────────────────────────────────────────
    hp['nmda_slots'] = cfg.nmda_slots
    hp['phono_capacity'] = cfg.phono_capacity

    # ── Wake-sleep ────────────────────────────────────────────────────
    hp['sleep_interval'] = cfg.sleep_interval
    hp['sleep_replay_steps'] = cfg.sleep_replay_steps
    hp['synaptic_downscale'] = cfg.synaptic_downscale

    # ── Structural plasticity ─────────────────────────────────────────
    hp['growth_threshold'] = cfg.growth_threshold
    hp['prune_threshold'] = cfg.prune_threshold
    hp['prune_interval'] = cfg.prune_interval

    # ── Regularization ────────────────────────────────────────────────
    hp['dropout'] = cfg.dropout
    hp['weight_decay'] = cfg.weight_decay
    hp['max_grad_norm'] = cfg.max_grad_norm

    # ── Effective gate values (diagnostic, not directly transferred) ──
    hp['_gate_values'] = {}
    for i, col in enumerate(model.columns):
        hp['_gate_values'][f'col_{i}'] = col.get_gate_values()

    logger.info(f"Extracted {len(hp)} µP hyperparameters from {cfg.n_columns}-column model. "
                f"Transfer to any scale model.")

    return hp


def build_scaled_config(
    base_cfg: V11Config,
    mu_p: Dict,
    target_columns: int,
    target_d_model: int,
    target_d_ff: Optional[int] = None,
) -> V11Config:
    """
    Build a scaled-up V11Config using µP hyperparameters from a small model.

    Args:
        base_cfg: the small model's config (for structural reference)
        mu_p: hyperparameters from extract_mu_p()
        target_columns: number of columns in the large model
        target_d_model: d_model in the large model
        target_d_ff: d_ff in the large model (default: 4 * d_model)

    Returns:
        V11Config for the large model with transferred hyperparameters
    """
    if target_d_ff is None:
        target_d_ff = 4 * target_d_model

    # Scale dimension-dependent params proportionally
    d_ratio = target_d_model / base_cfg.d_model

    scaled = V11Config(
        # ── Target dimensions ──
        d_model=target_d_model,
        d_column=target_d_model,
        n_columns=target_columns,
        d_ff=target_d_ff,
        vocab_size=base_cfg.vocab_size,
        max_seq_len=base_cfg.max_seq_len,

        # ── Scaled proportionally to d_model ──
        n_assoc_heads=max(1, int(base_cfg.n_assoc_heads * d_ratio)),
        d_inhibitory=max(32, int(base_cfg.d_inhibitory * d_ratio)),
        nmda_d_slot=max(32, int(base_cfg.nmda_d_slot * d_ratio)),
        silent_d_trace=max(32, int(base_cfg.silent_d_trace * d_ratio)),
        phono_d_slot=max(32, int(base_cfg.phono_d_slot * d_ratio)),
        d_relay=max(64, int(base_cfg.d_relay * d_ratio)),
        d_trn=max(16, int(base_cfg.d_trn * d_ratio)),
        d_cerebellar=max(64, int(base_cfg.d_cerebellar * d_ratio)),
        d_bg=max(32, int(base_cfg.d_bg * d_ratio)),
        n_relay_groups=max(1, target_columns // max(1, base_cfg.n_columns // base_cfg.n_relay_groups)),
        hpc_d_sparse=max(512, int(base_cfg.hpc_d_sparse * d_ratio)),
        hpc_memory_size=int(base_cfg.hpc_memory_size * max(1.0, d_ratio)),

        # ── µP transferred (scale-invariant) ──
        hebbian_lr=mu_p.get('hebbian_lr', base_cfg.hebbian_lr),
        pc_learning_lr=mu_p.get('pc_learning_lr', base_cfg.pc_learning_lr),
        base_lr=mu_p.get('base_lr', base_cfg.base_lr),
        pc_min_steps=mu_p.get('pc_min_steps', base_cfg.pc_min_steps),
        pc_max_steps=mu_p.get('pc_max_steps', base_cfg.pc_max_steps),
        pc_convergence_threshold=mu_p.get('pc_convergence_threshold', base_cfg.pc_convergence_threshold),
        sigma2_init=mu_p.get('sigma2_init', base_cfg.sigma2_init),
        k_wta_ratio=mu_p.get('k_wta_ratio', base_cfg.k_wta_ratio),
        n_settle_steps=mu_p.get('n_settle_steps', base_cfg.n_settle_steps),
        assoc_window_size=mu_p.get('assoc_window_size', base_cfg.assoc_window_size),
        gate_init=mu_p.get('gate_init', base_cfg.gate_init),
        gate_lr_mult=mu_p.get('gate_lr_mult', base_cfg.gate_lr_mult),
        bcm_tau=mu_p.get('bcm_tau', base_cfg.bcm_tau),
        gamma_period=mu_p.get('gamma_period', base_cfg.gamma_period),
        theta_period=mu_p.get('theta_period', base_cfg.theta_period),
        alpha_period=mu_p.get('alpha_period', base_cfg.alpha_period),
        delta_period=mu_p.get('delta_period', base_cfg.delta_period),
        nmda_slots=mu_p.get('nmda_slots', base_cfg.nmda_slots),
        phono_capacity=mu_p.get('phono_capacity', base_cfg.phono_capacity),
        sleep_interval=mu_p.get('sleep_interval', base_cfg.sleep_interval),
        sleep_replay_steps=mu_p.get('sleep_replay_steps', base_cfg.sleep_replay_steps),
        synaptic_downscale=mu_p.get('synaptic_downscale', base_cfg.synaptic_downscale),
        growth_threshold=mu_p.get('growth_threshold', base_cfg.growth_threshold),
        prune_threshold=mu_p.get('prune_threshold', base_cfg.prune_threshold),
        prune_interval=mu_p.get('prune_interval', base_cfg.prune_interval),
        dropout=mu_p.get('dropout', base_cfg.dropout),
        weight_decay=mu_p.get('weight_decay', base_cfg.weight_decay),
        max_grad_norm=mu_p.get('max_grad_norm', base_cfg.max_grad_norm),

        # ── Structural settings (unchanged) ──
        learning_mode=base_cfg.learning_mode,
        error_hebbian_weight=base_cfg.error_hebbian_weight,
        ntp_output_only=base_cfg.ntp_output_only,
        autonomous_training=base_cfg.autonomous_training,
    )

    total_approx = (
        scaled.vocab_size * scaled.d_model  # embedding
        + scaled.n_columns * (
            scaled.d_model * scaled.d_column  # L4
            + scaled.d_column * scaled.d_column  # L2/3
            + scaled.d_column * scaled.d_ff * 2  # L5 FFN
            + scaled.d_column * scaled.d_model  # L5 output
            + scaled.d_column * scaled.d_model  # L6
        )
        + scaled.d_model * scaled.vocab_size  # LM head
    )
    logger.info(f"Built scaled config: {scaled.n_columns} columns, d={scaled.d_model}, "
                f"~{total_approx / 1e6:.0f}M params (approximate)")

    return scaled


# ═══════════════════════════════════════════════════════════════════════
# 5. Freeze / Unfreeze Utilities
# ═══════════════════════════════════════════════════════════════════════

def unfreeze_columns(model: nn.Module, column_indices: Optional[List[int]] = None):
    """Unfreeze column parameters after bootstrap phase.

    Args:
        model: CorticalColumnNetwork
        column_indices: specific columns to unfreeze, or None for all
    """
    unfrozen = 0
    for i, col in enumerate(model.columns):
        if column_indices is None or i in column_indices:
            for p in col.parameters():
                p.requires_grad = True
                unfrozen += 1

    total_trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
    logger.info(f"Unfroze {unfrozen} params. Total trainable: {total_trainable:,}")


def freeze_columns(model: nn.Module, column_indices: List[int]):
    """Freeze specific columns (e.g., during new column bootstrap)."""
    frozen = 0
    for i, col in enumerate(model.columns):
        if i in column_indices:
            for p in col.parameters():
                p.requires_grad = False
                frozen += 1

    logger.info(f"Froze {frozen} params in columns {column_indices}")


# ═══════════════════════════════════════════════════════════════════════
# 6. Scaling Report
# ═══════════════════════════════════════════════════════════════════════

def scaling_report(model: nn.Module, cfg: V11Config) -> Dict:
    """
    Generate a scaling analysis report for the current model.

    Reports:
      - Parameter distribution (local vs global)
      - Per-column parameter counts
      - Estimated cost of each scaling operation
      - Recommended scaling path
    """
    counts = model.count_parameters()

    # Per-column params
    col_params = []
    for i, col in enumerate(model.columns):
        n = sum(p.numel() for p in col.parameters())
        col_params.append(n)

    # Local vs global breakdown
    local_params = counts.get('columns', 0)
    global_params = (
        counts.get('thalamus', 0)
        + counts.get('lateral', 0)
        + counts.get('workspace', 0)
        + counts.get('self_assessment', 0)
    )
    fixed_params = (
        counts.get('embedding', 0)
        + counts.get('lm_head', 0)
        + counts.get('grid_pos', 0)
    )
    subcortical_params = (
        counts.get('hippocampus', 0)
        + counts.get('basal_ganglia', 0)
        + counts.get('cerebellum', 0)
        + counts.get('brainstem', 0)
    )

    total = counts.get('total', 1)

    report = {
        'total_params': total,
        'local_column_params': local_params,
        'local_pct': local_params / total * 100,
        'global_coordination_params': global_params,
        'global_pct': global_params / total * 100,
        'fixed_params': fixed_params,
        'fixed_pct': fixed_params / total * 100,
        'subcortical_params': subcortical_params,
        'subcortical_pct': subcortical_params / total * 100,
        'per_column_params': col_params,
        'mean_column_params': sum(col_params) / max(len(col_params), 1),
        'n_columns': cfg.n_columns,
        'd_model': cfg.d_model,
    }

    # Estimated costs
    one_col_params = report['mean_column_params']
    report['cost_add_1_column'] = one_col_params  # New column params
    report['cost_add_1_routing'] = global_params * 0.2  # ~20% of routing retrains
    report['cost_split_1_column'] = one_col_params + global_params * 0.1
    report['cost_full_retrain'] = total

    # Percentage costs
    report['pct_cost_grow_1'] = (one_col_params + global_params * 0.2) / total * 100
    report['pct_cost_split_1'] = (one_col_params + global_params * 0.1) / total * 100

    return report


def print_scaling_report(model: nn.Module, cfg: V11Config):
    """Pretty-print the scaling report."""
    r = scaling_report(model, cfg)