Skip to content
Part 7 of 20

Brain Embeddings (Theorems 56–58)

Krrish Choudhary·March 23, 2026

Source: nct_v2/brain_embeddings.py Lines: 440 Classes: 4

Neuroscience Foundation

Standard neural network embeddings are flat lookup tables, each token maps to a single dd-dimensional vector with no internal structure. The brain’s lexical representations are far richer, organized through multiple processing stages that unfold over 0–300ms after word onset. Event-related potential (ERP) studies reveal distinct processing stages at well-characterized latencies: N170 at approximately 170ms reflects visual word form recognition in the fusiform gyrus; N250 at approximately 250ms reflects morphological decomposition in the left inferior frontal gyrus; N400 at approximately 400ms reflects semantic integration in temporal cortices; and P600 at approximately 600ms reflects syntactic reanalysis in frontal-parietal networks. Each of these stages adds structure to the lexical representation, transforming it from a simple visual pattern into a richly structured semantic-syntactic object.

NCT replaces the flat nn.Embedding with a 4-stage biologically-grounded pipeline that mirrors this temporal cascade. Each stage is gated and identity-at-init, ensuring that the embedding starts as a standard lookup and progressively acquires biological structure during training.

Stage 1: Base Embedding (0ms)

The base embedding provides the initial token representation via standard lookup. This corresponds to the earliest stage of visual word recognition, the visual word form area (VWFA) in the left fusiform gyrus, which maps orthographic patterns to abstract letter identities within approximately 100–170ms of fixation:

e=Wembed[token_id],Wembed∈RV×d,Wembed,init∼N(0,0.02)\mathbf{e} = W_{\text{embed}}[\text{token\_id}], \qquad W_{\text{embed}} \in \mathbb{R}^{V \times d}, \quad W_{\text{embed,init}} \sim \mathcal{N}(0, 0.02)

The embedding matrix WembedW_{\text{embed}} is shared with the LM head via weight tying (lm_head.weight = embed.weight), reflecting the brain’s shared lexical representations between comprehension and production pathways. The initialization standard deviation of 0.02 is chosen to match the scale of typical hidden representations, preventing exploding activations in early training.

Stage 2: Morphological Composition (170ms): Theorem 58

Theorem 4 (Dual-Route Morphological Composition (Theorem 58)). High-frequency tokens use direct lexical lookup; low-frequency tokens compose from learned subword morpheme representations. A 1D convolution captures sublexical patterns: s=Conv1D(e,kernel=3,padding=1),Wconv∈Rd×d×3\mathbf{s} = \text{Conv1D}(\mathbf{e}, \text{kernel}=3, \text{padding}=1), \qquad W_{\text{conv}} \in \mathbb{R}^{d \times d \times 3} A frequency-adaptive gate blends the two routes: gmorph=σ(Wge+bg),e′=gmorph⊙e+(1−gmorph)⊙sg_{\text{morph}} = \sigma(W_g \mathbf{e} + b_g), \qquad \mathbf{e}' = g_{\text{morph}} \odot \mathbf{e} + (1 - g_{\text{morph}}) \odot \mathbf{s} Gate bias bg,init=2.0b_{g,\text{init}} = 2.0 so g≈0.88g \approx 0.88 (lexical route dominates initially, matching the brain’s preference for direct access when available).

Disease mapping: surface dyslexia →\rightarrow lexical route damage →\rightarrow can’t read irregular high-frequency words. Phonological dyslexia →\rightarrow sublexical route damage →\rightarrow can’t read nonwords.

Stage 3: Hub-and-Spoke Semantic Integration (250ms): Theorem 56

Theorem 5 (Hub-and-Spoke Semantic Decomposition (Theorem 56)). Token embeddings decompose into S=6S = 6 modality-specific “spoke” subvectors integrated through a shared “hub” bottleneck, matching the brain’s anterior temporal lobe (ATL) semantic integration (Patterson et al., 2007): hs=Wse′+bs,s=1,…,S,hhub=Whub⋅1S∑s=1Shs\mathbf{h}_s = W_s \mathbf{e}' + b_s, \quad s = 1, \ldots, S, \qquad \mathbf{h}_{\text{hub}} = W_{\text{hub}} \cdot \frac{1}{S}\sum_{s=1}^S \mathbf{h}_s e′′=e′+σ(ghub)⋅hhub,ghub,init=−2.0\mathbf{e}'' = \mathbf{e}' + \sigma(g_{\text{hub}}) \cdot \mathbf{h}_{\text{hub}}, \qquad g_{\text{hub,init}} = -2.0 Each spoke Ws∈Rd×dW_s \in \mathbb{R}^{d \times d} represents a different semantic dimension (e.g., visual, auditory, motor, emotional, spatial, abstract). The hub integrates these into a unified amodal representation.

Disease mapping: semantic dementia (ATL atrophy) →\rightarrow hub failure →\rightarrow loss of cross-modal semantic integration. Patients can recognize objects visually but cannot name them or connect visual and verbal knowledge.

Brain embedding stages 2–4 in detail. Stage 2 (DRC): lexical and sublexical routes compete via a frequency-adaptive gate (bias 2.0 favors lexical). Stage 3 (Hub-Spoke): 6 modality spokes feed a central hub (ATL binding). Stage 4 (Sparse): 2times expansion then top-2% activation for exponential capacity.
Figure 8. Brain embedding stages 2–4 in detail. Stage 2 (DRC): lexical and sublexical routes compete via a frequency-adaptive gate (bias 2.0 favors lexical). Stage 3 (Hub-Spoke): 6 modality spokes feed a central hub (ATL binding). Stage 4 (Sparse): 2×\times expansion then top-2% activation for exponential capacity.
(Illustrated) Brain embedding stages 2–4 in detail. Stage 2 (DRC): lexical and sublexical routes compete via a frequency-adaptive gate (bias 2.0 favors lexical). Stage 3 (Hub-Spoke): 6 modality spokes feed a ce...
Figure 9. (Illustrated) Brain embedding stages 2–4 in detail. Stage 2 (DRC): lexical and sublexical routes compete via a frequency-adaptive gate (bias 2.0 favors lexical). Stage 3 (Hub-Spoke): 6 modality spokes feed a ce...

Stage 4: Sparse Distributed Activation (300ms): Theorem 57

Theorem 6 (Sparse Distributed Token Representations (Theorem 57)). After hub-spoke integration, embeddings project to an expanded space and enforce extreme sparsity matching neocortical firing statistics: a=Wupe′′∈R2d,a^=TopK(a,k=⌊0.02×2d⌋)\mathbf{a} = W_{\text{up}} \mathbf{e}'' \in \mathbb{R}^{2d}, \qquad \hat{\mathbf{a}} = \text{TopK}(\mathbf{a}, k = \lfloor 0.02 \times 2d \rfloor) e′′′=e′′+σ(gsparse)⋅Wdowna^,Wdown∈Rd×2d\mathbf{e}''' = \mathbf{e}'' + \sigma(g_{\text{sparse}}) \cdot W_{\text{down}} \hat{\mathbf{a}}, \qquad W_{\text{down}} \in \mathbb{R}^{d \times 2d} Only the top 2% of expanded activations survive. This matches biological neural firing rates (∼\sim1–5% of neurons active at any time) and provides exponential representational capacity: C(dsdr,k)=(2dk)≫1040C(d_{\text{sdr}}, k) = \binom{2d}{k} \gg 10^{40} unique patterns for d=512d = 512.

WdownW_{\text{down}} initialized at 0\mathbf{0}; gsparse,init=−2.0g_{\text{sparse,init}} = -2.0 (identity at init).

4-stage brain embedding pipeline matching the temporal cascade of neural word processing. Each stage is gated and identity-at-init.
Figure 10. 4-stage brain embedding pipeline matching the temporal cascade of neural word processing. Each stage is gated and identity-at-init.

Source Code

Python
440 lines
# ===========================================================================
# Brain Embeddings (Thm 56-58)
# Source: nct_v2/brain_embeddings.py
# ===========================================================================

"""
NCT Brain-Inspired Embedding System — Theorems 56-58.

Replaces flat nn.Embedding with a biologically-grounded distributed representation
that implements 8 neuroscience principles of lexical representation:

  Theorem 56 (Hub-and-Spoke Semantic Decomposition):
    Token embeddings decompose into S=6 modality-specific spoke subvectors integrated
    through a shared bottleneck hub, matching the brain's ATL semantic integration
    (Patterson et al. 2007; Lambon Ralph et al. 2017).

  Theorem 57 (Sparse Distributed Token Representations):
    After hub-spoke integration, embeddings project to an expanded space and enforce
    ~2% sparsity via exact-k activation, matching neocortical firing statistics
    (Kanerva 1988; Ahmad & Hawkins 2016). Capacity: C(d_sdr, k) >> 10^40 patterns.

  Theorem 58 (Morphological Composition with Dual-Route Access):
    High-frequency tokens use direct lexical lookup; low-frequency tokens compose
    from learned subword morpheme representations. A frequency-adaptive gate blends
    both routes (Coltheart et al. 2001 DRC model; Taft 2004; Rastle & Davis 2008).

Disease mapping:
  Semantic dementia (ATL atrophy) → Hub failure → loss of cross-modal integration
  Surface dyslexia → Lexical route damage → can't read irregular high-freq words
  Phonological dyslexia → Sublexical route damage → can't read nonwords
  Wernicke's aphasia → Spoke disconnection → modality-specific semantic loss

Integration with NCT V10.2:
  - PWPC σ² operates on structured embeddings → richer precision signal
  - CFC-UCAM binds structured features across theta-gamma cycles
  - PhonologicalLoop uses full embedding (phonological features embedded within)
  - DendriticFFN sparsity is compatible with sparse embedding input
  - Weight tying: lm_head ties to base embedding table (hub-spoke is residual)

Identity at init: gate_raw = -2.0 → σ(-2) ≈ 0.12. All modifications are gated
and initialized near-zero, so at init the output ≈ standard embedding.
"""


# [bundled] from .config import NCTv2Config


class HubAndSpokeProjection(nn.Module):
    """Theorem 56: Hub-and-Spoke Semantic Decomposition.

    Decomposes embedding into S modality-specific spoke subvectors, integrates
    through a shared bottleneck hub, and produces a structured correction.

    Neuroscience:
      - Spokes = modality-specific cortical regions (visual, auditory, motor,
        verbal, emotional, encyclopedic)
      - Hub = anterior temporal lobe (amodal semantic integration)
      - Semantic dementia (ATL atrophy) → hub failure → pan-modal degradation

    Architecture:
      e_spoke_i = W_spoke_i @ e_sub_i     (project each spoke subvector)
      h = GELU(W_hub_in(concat(e_spoke)))  (bottleneck: force cross-modal binding)
      correction = W_hub_out(h)             (back to d-dim)
      output = e + gate * correction        (identity at init)

    Parameters: S * (d_spoke * d_hub/S) + d_hub * d_hub/2 + d_hub/2 * d_hub + d_hub * d
    For d=384, S=6, d_hub=192: ~110K params
    """

    def __init__(self, d: int, S: int = 6):
        super().__init__()
        self.d = d
        self.S = S

        # Compute per-spoke input dims: last spoke gets remainder
        self.d_spoke = d // S  # 384//6=64, 512//6=85
        self._spoke_dims = [self.d_spoke] * S
        remainder = d - self.d_spoke * S
        if remainder > 0:
            self._spoke_dims[-1] += remainder  # last spoke absorbs remainder

        # Each spoke's output dimension (uniform)
        spoke_out_dim = d // (2 * S)  # 384//(2×6)=32, 512//(2×6)=42
        hub_in_dim = spoke_out_dim * S  # actual concatenated dimension

        # Each spoke projects its subvector into the hub
        self.spoke_projs = nn.ModuleList([
            nn.Linear(self._spoke_dims[i], spoke_out_dim, bias=False)
            for i in range(S)
        ])

        # Hub: nonlinear bottleneck that integrates all spokes
        hub_mid = max(hub_in_dim // 2, 1)  # guard against very small dims
        self.hub = nn.Sequential(
            nn.Linear(hub_in_dim, hub_mid, bias=True),
            nn.GELU(),
            nn.Linear(hub_mid, d, bias=True),
        )

        # Identity-at-init: gate starts near zero
        self.gate_raw = nn.Parameter(torch.tensor(-2.0))

        self._init_weights()

    def _init_weights(self):
        """Small-init hub output → tiny correction at init, but nonzero gradients."""
        # Small init ensures gradient flows from step 1, while gate_raw=-2 (σ≈0.12)
        # keeps total correction small: 0.12 × 0.01 ≈ 0.001 per dimension.
        nn.init.normal_(self.hub[-1].weight, std=0.01)
        nn.init.zeros_(self.hub[-1].bias)
        for proj in self.spoke_projs:
            nn.init.normal_(proj.weight, std=0.02)

    def forward(self, e: torch.Tensor) -> torch.Tensor:
        """
        e: (B, T, d) — base embedding

        Returns: (B, T, d) — embedding + gated hub-spoke correction
        """
        B, T, d = e.shape
        gate = torch.sigmoid(self.gate_raw)

        # Split embedding into S spoke subvectors (last spoke may be larger)
        spokes = e.split(self._spoke_dims, dim=-1)  # S tensors

        # Project each spoke
        spoke_outs = []
        for proj, spoke in zip(self.spoke_projs, spokes):
            spoke_outs.append(proj(spoke))

        # Concatenate and feed through hub bottleneck
        hub_input = torch.cat(spoke_outs, dim=-1)  # (B, T, d_hub)
        correction = self.hub(hub_input)  # (B, T, d)

        return e + gate * correction


class SparseDistributedProjection(nn.Module):
    """Theorem 57: Sparse Distributed Token Representations.

    Projects embeddings to an expanded space, enforces exact-k sparsity (2%),
    then projects back. This creates high-capacity, noise-robust representations
    where each token activates a unique small set of features.

    Neuroscience:
      - Neocortex: >90% of neurons silent at any time (Shoham et al. 2006)
      - Operating point: ~2% active neurons (Ahmad & Hawkins 2016)
      - Capacity: C(n, k) for n=2048, k=40 > 10^81 patterns
      - Superposition: OR of k SDRs preserves individual pattern identity
      - Noise robustness: random bit flips rarely hit the active set

    Architecture:
      h = W_up(e)                    (B, T, d) → (B, T, d_sdr)
      h_sparse = top_k(h, k)         exact k values kept, rest zeroed
      correction = W_down(h_sparse)   (B, T, d_sdr) → (B, T, d)
      output = e + gate * correction

    Gradient flow: straight-through estimator on top-k mask.

    Parameters: d * d_sdr + d_sdr * d = 2 * d * d_sdr
    For d=384, expansion=4 → d_sdr=1536: ~1.2M params (too many)
    For d=384, expansion=2 → d_sdr=768:  ~590K params (acceptable)

    Sparsity: k = max(1, int(0.02 * d_sdr)) = max(1, int(0.02 * 768)) = 15
    """

    def __init__(self, d: int, expansion: int = 2, sparsity: float = 0.02):
        super().__init__()
        self.d = d
        self.d_sdr = d * expansion
        self.k = max(1, int(self.d_sdr * sparsity))

        self.W_up = nn.Linear(d, self.d_sdr, bias=False)
        self.W_down = nn.Linear(self.d_sdr, d, bias=False)

        # Identity-at-init gate
        self.gate_raw = nn.Parameter(torch.tensor(-2.0))

        self._init_weights()

    def _init_weights(self):
        """Small-init W_down → tiny correction at init, but nonzero gradients."""
        nn.init.normal_(self.W_down.weight, std=0.01)
        nn.init.normal_(self.W_up.weight, std=0.02)

    def forward(self, e: torch.Tensor) -> torch.Tensor:
        """
        e: (B, T, d) — embedding from hub-spoke

        Returns: (B, T, d) — embedding + gated sparse correction
        """
        gate = torch.sigmoid(self.gate_raw)

        # Project up to expanded space
        h = self.W_up(e)  # (B, T, d_sdr)

        # Exact-k sparsity: keep top k activations per token
        # Use ReLU to ensure positive activations before top-k
        h_relu = F.relu(h)
        topk_vals, topk_idx = h_relu.topk(self.k, dim=-1)  # (B, T, k)

        # Scatter back to full dimension (sparse)
        h_sparse = torch.zeros_like(h)
        h_sparse.scatter_(-1, topk_idx, topk_vals)

        # Straight-through estimator: gradient flows through as if no sparsity
        # This preserves gradient flow while enforcing forward-pass sparsity
        h_sparse = h_relu + (h_sparse - h_relu).detach()

        # Project back to embedding dimension
        correction = self.W_down(h_sparse)  # (B, T, d)

        return e + gate * correction


class MorphemeCompositionGate(nn.Module):
    """Theorem 58: Morphological Composition with Dual-Route Access.

    Implements the brain's dual-route lexical access:
      Route 1 (Lexical): Direct embedding lookup for high-frequency tokens.
      Route 2 (Sublexical): Compose meaning from neighboring subword context.

    A learned per-token frequency gate blends the two routes:
      High-frequency tokens → mostly lexical route (fast, dedicated)
      Low-frequency tokens → mostly sublexical route (compositional, shared)

    Neuroscience:
      - DRC model (Coltheart et al. 2001): parallel lexical + sublexical routes
      - Surface dyslexia: lexical route damage → can't read irregular words
      - Phonological dyslexia: sublexical route damage → can't read nonwords
      - Morphological decomposition is obligatory at ~170ms (Rastle & Davis 2008)
      - Base frequency effect: RT correlates with stem frequency (Taft 2004)

    Architecture:
      BPE already provides partial morphological decomposition.
      For each token, we compose with its causal local context (2 past + current):
        sublexical = CausalConv1d(embed, kernel=3, groups=d)
      Route gate:
        g_lex = sigmoid(freq_gate_raw[token_id])
      Output:
        e_composed = g_lex * e_lexical + (1 - g_lex) * sublexical

    We initialize freq_gate_raw from log-frequency: high-freq tokens get
    positive bias (favor lexical route); low-freq get negative (favor sublexical).

    Parameters: d * d (conv kernel) + V (frequency gates) ≈ 148K + 50K ≈ 198K
    """

    def __init__(self, V: int, d: int, kernel_size: int = 3):
        super().__init__()
        self.V = V
        self.d = d
        self.kernel_size = kernel_size
        # Sublexical route: local context composition via depthwise-separable conv
        # Depthwise: each channel independently convolves over local context
        # Pointwise: mix channels
        # CAUSAL: no built-in padding — we manually pad left only in forward()
        self.sublexical_dw = nn.Conv1d(
            d, d, kernel_size=kernel_size, padding=0,
            groups=d, bias=False
        )
        self.sublexical_pw = nn.Linear(d, d, bias=False)

        # Per-token frequency bias: learned route preference per token
        # Higher values → more lexical; lower → more sublexical
        # Start neutral (0.0 → sigmoid(0) = 0.5 → equal blend)
        # Named 'freq_logit' (not 'gate_raw') to avoid 20x LR optimizer grouping
        self.freq_logit = nn.Parameter(torch.zeros(V))

        # Identity-at-init master gate
        self.gate_raw = nn.Parameter(torch.tensor(-2.0))

        self._init_weights()

    def _init_weights(self):
        """Initialize sublexical convolution near-identity with small noise.

        Pure identity init creates zero gradient to freq_logit and master gate
        (because e_sub = e_lex → blend is constant). Small noise in the side
        weights breaks this symmetry, enabling immediate gradient flow while
        keeping the sublexical output close to the lexical output.
        """
        # Depthwise conv: near-identity (rightmost = 1, left positions = small noise)
        # With causal padding (left-pad only), kernel position [-1] = current token
        nn.init.normal_(self.sublexical_dw.weight, std=0.01)
        with torch.no_grad():
            self.sublexical_dw.weight[:, :, -1] += 1.0

        # Pointwise: near-identity (I + small noise)
        nn.init.eye_(self.sublexical_pw.weight)
        with torch.no_grad():
            self.sublexical_pw.weight.add_(torch.randn_like(self.sublexical_pw.weight) * 0.01)

    def init_from_frequencies(self, token_frequencies: torch.Tensor):
        """Initialize frequency gates from corpus statistics.

        token_frequencies: (V,) tensor of token counts.
        High-frequency tokens get positive gate (favor lexical route).
        Low-frequency tokens get negative gate (favor sublexical route).

        Call this after model creation with corpus frequency counts.
        """
        with torch.no_grad():
            log_freq = torch.log1p(token_frequencies.float())
            # Normalize to [-2, 2] range
            log_freq_norm = log_freq / (log_freq.max() + 1e-8)
            # High freq → positive (lexical), low freq → negative (sublexical)
            self.freq_logit.copy_(4.0 * log_freq_norm - 2.0)

    def forward(self, e: torch.Tensor, token_ids: torch.Tensor) -> torch.Tensor:
        """
        e: (B, T, d) — base embedding (lexical route)
        token_ids: (B, T) — for frequency gate lookup

        Returns: (B, T, d) — dual-route composed embedding
        """
        B, T, d = e.shape
        master_gate = torch.sigmoid(self.gate_raw)

        # Sublexical route: compose from local context
        # Conv1d expects (B, d, T) — CAUSAL: pad left only (no future leakage)
        e_transposed = e.transpose(1, 2)  # (B, d, T)
        e_padded = F.pad(e_transposed, (self.kernel_size - 1, 0))  # left-pad only
        sub = self.sublexical_dw(e_padded)  # (B, d, T)
        sub = sub.transpose(1, 2)  # (B, T, d)
        sub = self.sublexical_pw(sub)  # (B, T, d)

        # Per-token frequency gate
        freq_gate = torch.sigmoid(self.freq_logit[token_ids])  # (B, T)
        freq_gate = freq_gate.unsqueeze(-1)  # (B, T, 1)

        # Dual-route blend
        composed = freq_gate * e + (1.0 - freq_gate) * sub

        # Master gate for identity-at-init
        # At init: master_gate ≈ 0.12, so output ≈ 0.88*e + 0.12*composed
        # composed ≈ e at init (because sublexical conv is identity-init)
        # So total output ≈ e (identity)
        return (1.0 - master_gate) * e + master_gate * composed


class BrainEmbedding(nn.Module):
    """Complete brain-inspired embedding system (Theorems 56-58).

    Replaces nn.Embedding with a biologically-grounded pipeline:
      1. Base lookup: nn.Embedding(V, d) — standard token embeddings
      2. Morphological composition (Thm 58): dual-route lexical/sublexical access
      3. Hub-and-spoke integration (Thm 56): S=6 modality-specific decomposition + hub
      4. Sparse activation (Thm 57): 2% sparsity in expanded space

    Each stage adds a gated correction to the embedding, all initialized near-zero,
    so at initialization the output equals the base embedding (identity property).

    Processing timeline (maps to brain):
      Stage 1 (0ms):   Token ID → base embedding lookup
      Stage 2 (170ms): Morphological composition (obligatory decomposition)
      Stage 3 (250ms): Hub-spoke cross-modal integration (ATL binding)
      Stage 4 (300ms): Sparse distributed activation (neocortical coding)

    Weight tying: lm_head.weight should be tied to self.base_embed.weight.
    All corrections are residual, so the base embedding space is preserved for
    the output projection.

    Disease mapping:
      Remove hub-spoke → semantic dementia (loss of cross-modal binding)
      Remove sublexical route → phonological dyslexia (can't compose new words)
      Remove lexical route → surface dyslexia (can't read irregular words)
      Remove sparse projection → increased interference (dense representations)

    Total new parameters (d=384, V=50257):
      MorphemeCompositionGate: ~199K (conv + freq gates)
      HubAndSpokeProjection:  ~68K (spoke projs + hub bottleneck)
      SparseDistributedProjection: ~590K (up/down projections)
      Total: ~857K new params (~0.81% of 105.5M model)
    """

    def __init__(self, cfg: NCTv2Config):
        super().__init__()
        self.cfg = cfg
        d = cfg.d
        V = cfg.V

        # Stage 1: Base embedding (same as before)
        self.base_embed = nn.Embedding(V, d)

        # Stage 2: Dual-route morphological composition (Theorem 58)
        self.morpheme_gate = MorphemeCompositionGate(V, d, kernel_size=3)

        # Stage 3: Hub-and-spoke semantic integration (Theorem 56)
        self.hub_spoke = HubAndSpokeProjection(d, S=6)

        # Stage 4: Sparse distributed activation (Theorem 57)
        self.sparse_proj = SparseDistributedProjection(d, expansion=2, sparsity=0.02)

        # Note: dropout is NOT applied here — the parent model applies self.drop_emb()
        # on the output of self.embed(tokens). This preserves the V8 forward pass structure.

        # Initialize base embedding
        nn.init.normal_(self.base_embed.weight, std=0.02)

    @property
    def weight(self):
        """For weight tying with lm_head: return base embedding weights.

        The lm_head projects from d → V using the same weight matrix.
        Hub-spoke and sparse corrections are residual, so the base embedding
        space is the correct projection space for logits.
        """
        return self.base_embed.weight

    def forward(self, token_ids: torch.Tensor) -> torch.Tensor:
        """
        token_ids: (B, T) integer token IDs

        Returns: (B, T, d) — brain-structured embedding

        Pipeline:
          base_embed(token_ids) → morpheme_gate → hub_spoke → sparse_proj → dropout
        """
        # Stage 1: Base lookup
        e = self.base_embed(token_ids)  # (B, T, d)

        # Stage 2: Dual-route morphological composition
        e = self.morpheme_gate(e, token_ids)  # (B, T, d)

        # Stage 3: Hub-and-spoke semantic integration
        e = self.hub_spoke(e)  # (B, T, d)

        # Stage 4: Sparse distributed activation
        e = self.sparse_proj(e)  # (B, T, d)

        return e

    def init_frequency_gates(self, token_frequencies: torch.Tensor):
        """Initialize dual-route frequency gates from corpus statistics.

        token_frequencies: (V,) tensor of token counts from training corpus.
        Call this after model creation, before training starts.
        """
        self.morpheme_gate.init_from_frequencies(token_frequencies)