Skip to content
Part 9 of 20

Brain LM Head (Theorem 63)

Krrish Choudhary·March 23, 2026

Source: nct_v2/brain_lm_head.py Lines: 207

Neuroscience Foundation

Standard language models use a single linear projection (Wembed⊤h∈RVW_{\text{embed}}^\top \mathbf{h} \in \mathbb{R}^V) to produce logits. The brain’s lexical production system is far more complex, involving multiple stages modeled by Levelt’s WEAVER++ theory (1999):

Stage 1, Conceptual preparation: The intended meaning activates a concept node in the semantic network.

Stage 2, Lemma selection: Multiple word candidates are activated; the one with highest activation wins. This is a competitive process, similar words interfere (semantic interference effect).

Stage 3, Phonological encoding: The selected word’s sound form is retrieved and assembled.

Stage 4, Articulatory programming: Motor programs for speech production are prepared.

NCT models stages 1–2 computationally. The comprehension pathway (reading) shares lexical representations with the production pathway (speaking/writing), but production requires an additional “production delta”, the brain uses different access mechanisms for understanding vs. producing words.

Three-Component Architecture

Theorem 8 (Brain-Inspired Lexical Production (Theorem 63)). The BrainLMHead implements three biologically-motivated components:

1. Weight-tied base projection + low-rank production delta: logitsbase=Wembed⊤h∈RV(shared comprehension/production)logitsδ=WB(WAh)∈RV(production-specific deviation)\begin{aligned} \text{logits}_{\text{base}} &= W_{\text{embed}}^\top \mathbf{h} \in \mathbb{R}^V \qquad &\text{(shared comprehension/production)} \\ \text{logits}_\delta &= W_B(W_A \mathbf{h}) \in \mathbb{R}^V \qquad &\text{(production-specific deviation)} \end{aligned} where WA∈Rr×dW_A \in \mathbb{R}^{r \times d}, WB∈RV×rW_B \in \mathbb{R}^{V \times r}, r=32r = 32. The delta is low-rank because production deviations from comprehension are structured (e.g., “know” vs “now” differ in production difficulty but not meaning). WBW_B initialized N(0,0.01)\mathcal{N}(0, 0.01).

2. WEAVER++ competition gate: c=σ(WD(WCh))∈[0,1]V,logitscomp=c⊙logitsbase\mathbf{c} = \sigma(W_D(W_C \mathbf{h})) \in [0, 1]^V, \qquad \text{logits}_{\text{comp}} = \mathbf{c} \odot \text{logits}_{\text{base}} where WC∈Rrc×dW_C \in \mathbb{R}^{r_c \times d}, WD∈RV×rcW_D \in \mathbb{R}^{V \times r_c}, rc=64r_c = 64. This multiplicative gate models lexical selection competition: multiple candidate words are activated simultaneously (“cat,” “dog,” “animal” for a concept about pets), and the sigmoid gate selects the winner. Higher rcr_c than rr because competition involves more candidates than the production deviation.

3. Log-frequency bias: logitsfinal=logitscomp+logitsδ+bfreq\text{logits}_{\text{final}} = \text{logits}_{\text{comp}} + \text{logits}_\delta + \mathbf{b}_{\text{freq}} bfreq∈RV\mathbf{b}_{\text{freq}} \in \mathbb{R}^V initialized at 0\mathbf{0}, learns word frequency priors. The brain is exquisitely sensitive to word frequency, high-frequency words (“the,” “is”) have lower activation thresholds and are produced faster (word frequency effect). This bias captures that prior.

BrainLMHead architecture. Three parallel pathways: weight-tied base (comprehension), low-rank production delta (r = 32), and WEAVER++ competition gate (r_c = 64). The competition gate multiplicatively modulates the base logits before adding the production delta and frequency bias.
Figure 13. BrainLMHead architecture. Three parallel pathways: weight-tied base (comprehension), low-rank production delta (r=32r = 32), and WEAVER++ competition gate (rc=64r_c = 64). The competition gate multiplicatively modulates the base logits before adding the production delta and frequency bias.
(Illustrated) BrainLMHead architecture. Three parallel pathways: weight-tied base (comprehension), low-rank production delta (r = 32), and WEAVER++ competition gate (r_c = 64). The competition gate multiplic...
Figure 14. (Illustrated) BrainLMHead architecture. Three parallel pathways: weight-tied base (comprehension), low-rank production delta (r=32r = 32), and WEAVER++ competition gate (rc=64r_c = 64). The competition gate multiplic...

Weight Tying

The base projection shares WembedW_{\text{embed}} from the brain embedding pipeline’s Stage 1, following the standard practice of tying input and output embeddings (Press & Wolf, 2017). This is implemented via Python property assignment (lm_head.weight = embed.weight), not copying, both references point to the same underlying tensor. Changes to the embedding weights during training are immediately reflected in the LM head’s base projection, and vice versa.

This weight tying is biologically motivated: comprehension (reading a word) and production (writing a word) share the same lexical representations in the mental lexicon. The “production delta” (WA,WBW_A, W_B) captures the additional processing needed for production that goes beyond comprehension.

The implementation requires careful handling of PyTorch’s parameter system. The __setattr__ and __getattr__ methods are overridden in BrainLMHead to ensure that: (1) the tied weight is not double-counted in model.parameters(), (2) serialization (state_dict()) correctly saves/loads the tied weight, and (3) gradient computation flows correctly through both the embedding and LM head pathways.

Disease Mapping

Anomic aphasia results from damage to the left temporal or parietal cortex. Patients can understand words perfectly (comprehension intact) but cannot produce them, they experience “tip of the tongue” states where the concept is accessed but the phonological form cannot be retrieved. This is precisely the production delta: the base projection (comprehension) works, but the production-specific pathway (WA,WBW_A, W_B) is damaged.

In NCT, zeroing WAW_A and WBW_B while keeping Wembed⊤W_{\text{embed}}^\top intact would produce the computational analog of anomic aphasia: the model knows the meaning but cannot select the right word.

Initialization Protocol

BrainLMHead initialization values.
ParameterShapeInitRationale
WembedW_{\text{embed}} (tied)V×dV \times dN(0,0.02)\mathcal{N}(0, 0.02)From brain embedding Stage 1
WAW_A (delta down)r×dr \times dKaimingStandard projection
WBW_B (delta up)V×rV \times rN(0,0.01)\mathcal{N}(0, 0.01)Small: delta ≈0\approx 0 at init
WCW_C (comp down)rc×dr_c \times dKaimingStandard projection
WDW_D (comp up)V×rcV \times r_cN(0,0.01)\mathcal{N}(0, 0.01)Small: gate ≈0.5\approx 0.5 at init
bfreq\mathbf{b}_{\text{freq}}VV0\mathbf{0}No frequency prior initially

At initialization: logits≈Wembed⊤h⋅0.5+0+0≈0.5⋅Wembed⊤h\text{logits} \approx W_{\text{embed}}^\top \mathbf{h} \cdot 0.5 + 0 + 0 \approx 0.5 \cdot W_{\text{embed}}^\top \mathbf{h} (competition gate ≈0.5\approx 0.5, delta ≈0\approx 0, bias =0= 0). The model starts as a standard weight-tied LM head scaled by 0.5, then learns the production-specific components during training.

Source Code

Python
207 lines
# ===========================================================================
# Brain LM Head (Thm 63)
# Source: nct_v2/brain_lm_head.py
# ===========================================================================

"""
NCT Brain-Inspired Lexical Production Head — Theorem 63.

Replaces the standard linear projection LM head (logits = h @ W.T) with
biologically-grounded competitive lexical production, implementing three
principles from the WEAVER++ model of word production (Levelt et al. 1999;
Roelofs 1997):

  Theorem 63a (Competitive Lexical Selection):
    Lateral inhibition between semantically similar lemmas in a low-rank
    semantic competition space. Winner-take-all dynamics emerge:
    the highest-activated word receives LESS inhibition than its semantic
    competitors, sharpening the distribution (Roelofs 1997; Usher &
    McClelland 2001 Leaky Competing Accumulator).

  Theorem 63b (Production-Comprehension Weight Divergence):
    Low-rank delta separates production weights from recognition weights.
    W_produce = W_embed + A @ B (rank r << d). The brain uses DIFFERENT
    pathways for reading (temporal → Wernicke's) vs speaking (prefrontal →
    Broca's → motor). Weight tying captures shared semantics; the delta
    captures production-specific distinctions (Pickering & Garrod 2013).

  Theorem 63c (Frequency-Adaptive Selection Threshold):
    Per-word output bias models frequency-dependent selection thresholds.
    High-frequency words develop lower thresholds (easier to produce).
    The frequency effect is at the lexeme level (Jescheniak & Levelt 1994),
    separate from conceptual activation.

Disease mapping:
  Anomic aphasia (word-finding) → Weakened delta → concept active but can't
    select production form → circumlocutions ("the thing you sit on")
  Broca's aphasia (production) → Disrupted competition → multiple lemmas
    activate without resolution → reduced fluency
  Semantic paraphasia → Competition failure → semantic competitor wins
    ("cat" → "dog") instead of correct target
  Frequency anomia → Bias failure → high-frequency bias shifts to block
    rare words entirely

Integration with NCT V10.2:
  - Competition operates on final hidden states after ALL brain processing
    (hooks, WM, oscillations, precision gating)
  - Base weights are tied to BrainEmbedding.base_embed.weight (shared
    semantic space preserved)
  - Production delta captures output-specific features without disrupting
    the recognition pathway
  - α (competition strength) gates near-zero at init (σ(-5) ≈ 0.007)
  - Soft logit cap (Gemma 2 style) is applied AFTER competition externally

Identity at init: delta_A=0, delta_B=0, output_bias=0, α≈0.007 → output
    ≈ standard linear projection.

Computational cost:
  - Base logits: O(BTVd) — same as standard lm_head
  - Production delta (factored): O(BTdr) + O(BTrV) — ~5-8% overhead
  - Competition (low-rank): O(BTV r_s) × 2 — ~10-20% overhead at V=13K
  - Total: ~1.15-1.30× standard lm_head cost
"""



class BrainLMHead(nn.Module):
    """Theorem 63: Brain-Inspired Lexical Production.

    Three-stage output head:
      1. Lexical activation: logits = h @ W_embed.T + h @ B.T @ A.T + bias
      2. Competitive inhibition: logits -= α × ReLU(field_sim - self_sim)
      3. External soft-cap (applied by caller)

    Args:
        d_model: Hidden dimension (d=384 for small config)
        vocab_size: Vocabulary size (V=50257 for BPE, 13817 for NCT tok)
        rank: Rank of production delta A@B (default 32)
        competition_rank: Dimension of semantic competition space (default 64)
    """

    def __init__(self, d_model: int, vocab_size: int,
                 rank: int = 32, competition_rank: int = 64,
                 use_fused_kernels: bool = False):
        super().__init__()
        self._d = d_model
        self._V = vocab_size
        self._use_fused = use_fused_kernels
        # Use object.__setattr__ to bypass nn.Module parameter tracking.
        # _base_weight is set externally via weight property (tied to embedding).
        object.__setattr__(self, '_base_weight', None)

        # ── Theorem 63b: Production-comprehension weight divergence ──────
        # Low-rank delta: W_produce = W_embed + delta_A @ delta_B
        # Captures production-specific features without full V×d extra params.
        # Factored computation: h @ B.T → (B,T,r), then @ A.T → (B,T,V)
        #
        # LoRA-style init: delta_A=0 (up), delta_B=Gaussian (down).
        # Product = 0 → identity. Gradient flows through delta_B to delta_A
        # immediately; delta_B learns once delta_A becomes nonzero.
        self.delta_A = nn.Parameter(torch.zeros(vocab_size, rank))
        self.delta_B = nn.Parameter(torch.randn(rank, d_model) * (0.02 / rank**0.5))

        # ── Theorem 63c: Frequency-adaptive selection threshold ──────────
        # Per-word bias. High-freq words learn lower thresholds.
        # Jescheniak & Levelt 1994: frequency effect at lexeme level.
        self.output_bias = nn.Parameter(torch.zeros(vocab_size))

        # ── Theorem 63a: Competitive lateral inhibition ──────────────────
        # Gate: α = σ(gate_raw) ≈ 0.007 at init → competition OFF
        self.gate_raw_competition = nn.Parameter(torch.tensor(-5.0))
        # Semantic projection: maps V-dim embedding to r_s-dim competition space
        # Competition happens in this reduced space for efficiency
        self.sem_proj = nn.Linear(d_model, competition_rank, bias=False)

    def __setattr__(self, name, value):
        """Route 'weight' assignments to _base_weight, bypass nn.Module tracking."""
        if name == 'weight':
            object.__setattr__(self, '_base_weight', value)
        else:
            super().__setattr__(name, value)

    def __getattr__(self, name):
        """Return _base_weight for 'weight' access (compatible with lm_head.weight)."""
        if name == 'weight':
            return object.__getattribute__(self, '_base_weight')
        return super().__getattr__(name)

    def forward(self, h: torch.Tensor) -> torch.Tensor:
        """
        Compute brain-inspired lexical production logits.

        Args:
            h: Hidden states (B, T, d) — typically after final RMSNorm

        Returns:
            logits: (B, T, V) — lexical activations after competition

        Pipeline:
          1. Base activation: h @ W_embed.T
          2. Production delta: h @ B.T @ A.T (factored, no V×d intermediate)
          3. Add output bias
          4. Competitive lateral inhibition (gated by α)
        """
        W = self._base_weight  # (V, d) — tied to BrainEmbedding.base_embed.weight

        # ── Stage 1: Lexical activation ──────────────────────────────────
        # Base logits from tied embedding weights
        logits = F.linear(h, W)  # (B, T, V) = h @ W.T

        # Production-specific delta (factored: avoids V×d intermediate)
        # h → (B,T,r) → (B,T,V): two small matmuls instead of one big one
        h_proj = h @ self.delta_B.t()           # (B, T, r)
        logits = logits + h_proj @ self.delta_A.t()  # (B, T, V)

        # Frequency-adaptive bias
        logits = logits + self.output_bias       # (B, T, V)

        # ── Stage 2: Competitive lateral inhibition (Theorem 63a) ────────
        # WEAVER++ lemma selection: semantically similar words compete
        # through lateral inhibition. Winner-take-all emerges because the
        # highest-activated word receives LESS other-inhibition.

        # Semantic projection of vocabulary (detach W: competition gradients
        # should update sem_proj, not embedding weights — avoids conflict
        # with NTP gradient through base logit path)
        S = F.linear(W.detach(), self.sem_proj.weight)  # (V, r_s)

        if self._use_fused:
            # Top-K WEAVER++: O(V + K*r_s) instead of O(V*r_s)
            # For V=128K, K=256, r_s=64: 490× reduction in competition cost
            # [bundled] from nct_v2.kernels.weaver_topk import weaver_topk_inhibition
            logits = weaver_topk_inhibition(
                logits, S, self.gate_raw_competition, topk=256,
            )
        else:
            alpha = torch.sigmoid(self.gate_raw_competition)

            # Current probability distribution (detached: no gradient through softmax)
            p = F.softmax(logits.detach(), dim=-1)  # (B, T, V)

            # Centroid of active lemmas in semantic space
            centroid = p @ S  # (B, T, r_s)

            # Each word's similarity to the active field
            field_sim = F.linear(centroid, S)  # (B, T, V) = centroid @ S.T

            # Remove self-inhibition: word i's contribution to its own inhibition
            # = p_i × ||s_i||². Without removal, the winner gets MOST inhibited
            # (it's closest to the centroid IT dominates). With removal, the winner
            # gets LEAST inhibited → winner-take-all emerges.
            self_sim = (S * S).sum(-1)  # (V,) — ||s_i||² for each word
            inhibition = field_sim - p * self_sim  # (B, T, V) — other-inhibition only

            # ReLU truncation: only suppress competitors (positive inhibition).
            # Unrelated words (negative field similarity) are NOT affected.
            # This matches WEAVER++: competition is within semantic field only.
            inhibition = F.relu(inhibition)

            # Apply gated competition
            logits = logits - alpha * inhibition

        # Monitoring (tensor storage, no .item() — avoids CUDA sync + graph break)
        self._competition_alpha = torch.sigmoid(self.gate_raw_competition).detach()
        self._delta_norm = (self.delta_A.norm() * self.delta_B.norm()).detach()
        self._bias_std = self.output_bias.std().detach()

        return logits