Skip to content
Part 8 of 20

Grid Cell Position Encoding (Theorems 59, 61, 62)

Krrish Choudhary·March 23, 2026

Source: nct_v2/brain_position.py Lines: 269

Neuroscience Foundation

In the entorhinal cortex, grid cells fire at regularly-spaced locations as an animal moves through space, creating a multi-scale spatial coordinate system (Hafting et al., 2005; Nobel Prize in Physiology or Medicine 2014). Each grid cell has a characteristic spatial frequency, and different cells tile the environment at different scales, from fine-grained (small spacing ∼\sim30cm) to coarse (large spacing ∼\sim3m). The population activity of grid cells at multiple scales provides a unique, high-capacity position code for any location.

Critically, grid cell representations are allocentric (world-centered, not self-centered) and metric (encode actual distances, not just ordinal position). This differs from standard sinusoidal position encodings, which use fixed frequencies. NCT’s grid cell encoding uses learnable frequencies that adapt during training to the statistical structure of the data.

Why Not RoPE?

RoPE (Rotary Position Embedding) applies position-dependent rotations to query and key vectors:

qt=Rtq,kt=Rtk,⇒qt⊤ks=q⊤Rt−sk\mathbf{q}_t = R_t \mathbf{q}, \quad \mathbf{k}_t = R_t \mathbf{k}, \quad \Rightarrow \quad \mathbf{q}_t^\top \mathbf{k}_s = \mathbf{q}^\top R_{t-s} \mathbf{k}

This makes dot-product attention (q⊤k\mathbf{q}^\top \mathbf{k}) depend on relative position t−st - s. However, NCT has no dot-product attention, L2/3 uses windowed Hebbian association with distance-weighted context. Rotary transformations have no effect without a dot product to modulate. Instead, NCT uses additive position encoding.

Mathematical Formulation

Theorem 7 (Grid Cell Position Encoding (Theorems 59, 61, 62)). For each association head h∈{1,…,H}h \in \{1, \ldots, H\} and position dimension j∈{1,…,dh/2}j \in \{1, \ldots, d_h/2\}:

1. Learnable frequencies via softplus (bare, no clamp): fh,j=softplus(ωh,jraw),ωh,j,initraw=log⁡(eθj−1),θj=1100002j/dhf_{h,j} = \text{softplus}(\omega_{h,j}^{\text{raw}}), \qquad \omega_{h,j,\text{init}}^{\text{raw}} = \log(e^{\theta_j} - 1), \quad \theta_j = \frac{1}{10000^{2j/d_h}} The softplus initialization is chosen so that softplus(ωinit)=θj\text{softplus}(\omega_{\text{init}}) = \theta_j, matching the standard sinusoidal frequency schedule at initialization. During training, frequencies adapt to the data.

2. Phase computation: ϕh,j(t)=2π⋅fh,j⋅t\phi_{h,j}(t) = 2\pi \cdot f_{h,j} \cdot t

3. Sinusoidal encoding: ph,t=sh⋅[cos⁡ϕh,1(t),sin⁡ϕh,1(t),cos⁡ϕh,2(t),sin⁡ϕh,2(t),…]+bh\mathbf{p}_{h,t} = s_h \cdot [\cos\phi_{h,1}(t), \sin\phi_{h,1}(t), \cos\phi_{h,2}(t), \sin\phi_{h,2}(t), \ldots] + \mathbf{b}_h where shs_h (per-head scale, init 1.0) and bh\mathbf{b}_h (per-head boundary offset, init 0\mathbf{0}) are learnable. The scale allows the model to learn how much position information each head should receive. The boundary offset implements grid cell boundary remapping (Theorem 62).

4. Additive encoding (not rotary): x←x+0.1⋅p‾t,p‾t=1H∑h=1Hph,t\mathbf{x} \leftarrow \mathbf{x} + 0.1 \cdot \overline{\mathbf{p}}_t, \qquad \overline{\mathbf{p}}_t = \frac{1}{H}\sum_{h=1}^H \mathbf{p}_{h,t} The 0.1 scale factor prevents position from dominating content at initialization.

Grid cell position encoding uses learnable multi-scale frequencies. Like biological grid cells in the entorhinal cortex, different heads operate at different spatial scales, and the population activity uniquely identifies each position. Frequencies are learnable via softplus(ω^raw), no hard clamps (parameter bounding principle).
Figure 11. Grid cell position encoding uses learnable multi-scale frequencies. Like biological grid cells in the entorhinal cortex, different heads operate at different spatial scales, and the population activity uniquely identifies each position. Frequencies are learnable via softplus(ωraw)\text{softplus}(\omega^{\text{raw}}), no hard clamps (parameter bounding principle).
(Illustrated) Grid cell position encoding uses learnable multi-scale frequencies. Like biological grid cells in the entorhinal cortex, different heads operate at different spatial scales, and the population acti...
Figure 12. (Illustrated) Grid cell position encoding uses learnable multi-scale frequencies. Like biological grid cells in the entorhinal cortex, different heads operate at different spatial scales, and the population acti...

Proposition 1 (Capacity of Multi-Scale Grid Code). With HH heads and dh/2d_h/2 frequency dimensions per head, the grid cell code can uniquely represent: C=∏h=1H∏j=1dh/2⌈T⋅fh,j⌉C = \prod_{h=1}^H \prod_{j=1}^{d_h/2} \lceil T \cdot f_{h,j} \rceil positions. For H=8H = 8, dh=64d_h = 64, this capacity far exceeds any practical sequence length, ensuring that every position has a unique encoding.

Implementation Details

The grid cell encoding is content-dependent: frequencies are applied to the input-derived position signal, not a fixed position index. The forward pass:

  1. Compute learnable frequencies: fh,j=softplus(ωh,jraw)f_{h,j} = \text{softplus}(\omega_{h,j}^{\text{raw}})

  2. Compute phases: ϕh,j(t)=2πfh,jt\phi_{h,j}(t) = 2\pi f_{h,j} t for t=0,…,T−1t = 0, \ldots, T-1

  3. Build sinusoidal features: [cos⁡ϕ,sin⁡ϕ][\cos\phi, \sin\phi] concatenated per head

  4. Apply per-head scale and boundary: sh⋅[cos⁡;sin⁡]+bhs_h \cdot [\cos; \sin] + \mathbf{b}_h

  5. Average over heads, tile to dmodeld_{\text{model}}, add with 0.1 scale

If the head dimension dhd_h doesn’t evenly tile into dmodeld_{\text{model}}, the position signal is padded with zeros (not repeated). This prevents artificial periodicity in the position embedding.

Disease Mapping

Alzheimer’s disease begins with atrophy of the entorhinal cortex, where grid cells reside. Early symptoms include spatial disorientation and difficulty navigating familiar environments. In the language domain, this maps to difficulty tracking sequential position, forgetting where in a sentence or paragraph the model is, leading to repetition and incoherence. NCT’s grid cell encoding explicitly models this faculty, and its removal (by zeroing the position encoding) produces the expected deficit.

Source Code

Python
269 lines
# ===========================================================================
# Grid Cell Position Encoding (Thm 59/61/62)
# Source: nct_v2/brain_position.py
# ===========================================================================

"""
NCT V10.2 Brain-Inspired Position Encoding — Theorems 59, 61, 62.

Replaces Rotary Position Embeddings (RoPE) with a biologically-grounded
grid-cell-inspired position encoding with three innovations:

  1. Grid cells (entorhinal cortex): learnable periodic multi-scale modules
     → Thm 59: GridCellPositionEncoding with learnable periods and phase offsets

  2. Boundary/border cells (entorhinal cortex): phase reset at boundaries
     → Thm 61: Cumulative phase shifts at detected boundaries (grid cell remapping)

  3. Conjunctive coding (head direction × grid cells): head-specific scales
     → Thm 62: Per-head period scale factors for multi-resolution attention

Design decisions:
  - Same interface as RoPE: produces (cos, sin) tensors for Q/K rotation
  - Identity at init: all three innovations have zero effect at step 0
    - Thm 59: frequencies = RoPE frequencies, offsets = 0
    - Thm 61: boundary_phase = 0 → zero cumulative shift regardless of gate
    - Thm 62: head_scale = 1.0 → all heads identical to shared RoPE
  - apply_rope extended to handle 3D (n_heads, T, d_h) and 4D (B, H, T, d_h)
  - Boundary detection uses raw embeddings (analogous to border cells)
  - Phase remapping is additive (cumulative), not positional reset — matches
    grid cell remapping in neuroscience (Fyhn et al. 2007)

Neuroscience references:
  - Hafting et al. 2005: Grid cells in entorhinal cortex
  - Stensola et al. 2012: Grid cell module organization (4-5 modules, ratio ~1.4)
  - Fiete et al. 2008: Residue number system theory of grid coding
  - Fyhn et al. 2007: Grid cell remapping (phase shift) at environment boundaries
  - Solstad et al. 2008: Border cells in entorhinal cortex

Disease mapping:
  - Alzheimer's (entorhinal atrophy): grid cell disintegration → spatial disorientation
    → NCT: grid module degradation → position confusion → PPL rise
  - Epilepsy (temporal lobe): grid cell phase corruption → remapping failure
    → NCT: learned period distortion → position encoding noise
  - Williams syndrome (boundary cell deficit): impaired spatial segmentation
    → NCT: boundary detection failure → no position reset → long-range confusion

Mathematical properties:
  - RoPE is a special case: M=d_h/2 modules, freq_i = 1/10000^(2i/d_h), offset_i = 0
  - Grid-cell encoding: same M modules but with learnable periods and offsets
  - Unique encoding range: LCM(τ₁, ..., τ_M) >> max_seq_len (preserved)
  - Learnable τ_m preserves rotation property: Q·K^T depends on relative position
  - At init: max deviation from RoPE < 2e-6 (from softplus inversion precision)
  - Boundary phase shifts are additive → do not affect relative position encoding
    within a segment (only across boundaries)

Params at d_h=48, n_heads=8, d_model=384:
  - Thm 59: d_h/2 periods + d_h/2 offsets = 48
  - Thm 62: n_heads scale factors = 8
  - Thm 61: d_model+1 detector + d_h/2 phase + 1 gate = 410
  Total: 466 params (negligible vs 92.4M model)
"""



class GridCellPositionEncoding(nn.Module):
    """
    Grid-Cell-Inspired Position Encoding (Theorems 59, 61, 62).

    Replaces RoPE's fixed sinusoidal frequencies with learnable grid-cell modules,
    per-head scale factors, and boundary-aware phase remapping.

    Mathematical formulation:
      RoPE:      angle_i(t) = t / 10000^(2i/d_h)
      GridCell:  angle_{h,i}(t) = 2π × t / (τ_i × s_h) + φ₀_i
                                  + gate × Σ_{u≤t} p_boundary(u) × φ_boundary_i

    Where:
      τ_i = softplus(raw_i) — learnable period for module i (Thm 59)
      φ₀_i — learnable global phase offset (Thm 59, environment remapping)
      s_h = softplus(scale_raw_h) — per-head scale factor (Thm 62)
      p_boundary(u) = σ(W_b · x(u) + b_b) — boundary probability at position u (Thm 61)
      φ_boundary_i — learnable phase shift per boundary event (Thm 61)
      gate = σ(gate_raw) — controls boundary influence (Thm 61)

    At init: τ_i = RoPE periods, φ₀_i = 0, s_h = 1, φ_boundary = 0 → exact RoPE.

    Properties:
    - Rotation property preserved: Q_rot · K_rot^T depends on relative position
    - Head specialization: different heads attend at different temporal scales
    - Boundary awareness: position encoding adapts at document/paragraph boundaries
    - Infinite context: phases cycle naturally, no extrapolation problem

    Output shapes:
    - With X (boundary-aware): (B, n_heads, T, d_h)
    - Without X:               (n_heads, T, d_h)
    """

    def __init__(self, max_seq_len: int, d_h: int, n_heads: int, d_model: int = None):
        super().__init__()
        self.max_seq_len = max_seq_len
        self.d_h = d_h
        self.half = d_h // 2
        self.n_heads = n_heads

        # ── Theorem 59: Grid cell module periods ─────────────────────────
        # RoPE frequencies: freq_i = 1 / 10000^(2i/d_h)
        # RoPE angles: angle_i(t) = t × freq_i = t / 10000^(2i/d_h)
        # Grid cell angles: angle_i(t) = 2π × t / τ_i
        # Equivalence: τ_i = 2π / freq_i = 2π × 10000^(2i/d_h)
        #
        # We parameterize as: τ_i = softplus(log_period_raw_i)
        # Init: log_period_raw_i = inverse_softplus(τ_rope_i)
        rope_freqs = 1.0 / (10000.0 ** (torch.arange(0, self.half).float() / self.half))
        rope_periods = 2.0 * math.pi / rope_freqs  # angular periods T_i

        # Inverse softplus: raw = log(exp(x) - 1)
        # For large x (>20), softplus(x) ≈ x, so raw ≈ x.
        # For small x, use exact formula: raw = x + log(1 - exp(-x))
        log_period_raw = rope_periods + torch.log(1.0 - torch.exp(-rope_periods))
        self.log_period_raw = nn.Parameter(log_period_raw)  # (half,)

        # ── Theorem 59: Grid cell phase offsets (environment remapping) ──
        # Init at 0 → no offset at start (exact RoPE recovery)
        # During training: learns optimal phase biases for each frequency module
        # Biologically: grid cells remap (shift phases) in new environments
        self.phase_offset = nn.Parameter(torch.zeros(self.half))  # (half,)

        # ── Theorem 62: Head-specific grid module scales ─────────────────
        # Each attention head multiplies the base periods by a learnable
        # positive scale factor, allowing heads to specialize in different
        # temporal resolutions.
        # Init: softplus(inv_sp_1) = 1.0 → all heads identical (RoPE recovery).
        # After training: some heads become "local" (small scale → short periods),
        # others become "global" (large scale → long periods).
        # Brain basis: grid cell modules have 4-5 discrete scales with ratio ~1.4
        # (Stensola 2012). Different cortical areas attend at different scales.
        inv_softplus_1 = math.log(math.e - 1.0)  # ≈ 0.5414
        self.head_scale_raw = nn.Parameter(
            torch.full((n_heads,), inv_softplus_1)
        )  # (n_heads,)

        # ── Theorem 61: Boundary-aware phase remapping ───────────────────
        # Grid cells remap (shift phases) when an animal enters a new
        # environment (Fyhn et al. 2007). In language, boundaries are:
        # document ends, paragraph breaks, topic shifts, sentence boundaries.
        #
        # Architecture: lightweight boundary detector on raw embeddings
        # (analogous to border cells in medial entorhinal cortex) produces
        # boundary probability p(t) ∈ [0,1]. At each boundary, a learned
        # phase shift φ_boundary accumulates additively.
        #
        # Effect on angles:
        #   Δφ(t) = gate × Σ_{u≤t} p_boundary(u) × φ_boundary
        # This is additive: does NOT affect relative position within segments,
        # only adds cross-boundary phase offsets.
        #
        # Identity at init: φ_boundary = 0 → Δφ = 0 regardless of gate value.
        if d_model is not None:
            self.boundary_detector = nn.Linear(d_model, 1, bias=True)
            nn.init.zeros_(self.boundary_detector.weight)
            nn.init.constant_(self.boundary_detector.bias, -3.0)  # mostly OFF at init

            # Phase shift applied per boundary event: learnable (half,)
            # Init at 0 → zero contribution at step 0 (exact identity)
            self.boundary_phase = nn.Parameter(torch.zeros(self.half))

            # Gate controlling boundary influence (identity-init)
            # Named with 'gate_raw' suffix so optimizer puts it in gate group (20x LR)
            self.boundary_gate_raw = nn.Parameter(torch.tensor(-2.0))
        else:
            self.boundary_detector = None

        # Precompute position indices (static buffer)
        pos = torch.arange(max_seq_len).float()
        self.register_buffer('pos', pos)

    def forward(
        self,
        T: int,
        device: torch.device,
        dtype: torch.dtype = torch.float32,
        X: torch.Tensor = None,
    ) -> tuple:
        """
        Compute position-dependent (cos, sin) tables for attention rotation.

        Args:
            T: sequence length
            device: target device
            dtype: target dtype
            X: (B, T, d) embeddings — if provided and boundary_detector exists,
               enables boundary-aware phase remapping (Thm 61), producing
               batch-specific cos/sin with per-head scales.

        Returns:
            If X provided with boundary_detector:
                cos, sin: (B, n_heads, T, d_h) — batch+head-specific
            Else:
                cos, sin: (n_heads, T, d_h) — head-specific only
        """
        # ── Base periods (Thm 59) ────────────────────────────────────────
        periods = F.softplus(self.log_period_raw)  # (half,)

        # ── Per-head scale (Thm 62) ──────────────────────────────────────
        head_scale = F.softplus(self.head_scale_raw)  # (n_heads,)
        # Each head's periods = base_periods × head_scale_h
        periods_h = periods.unsqueeze(0) * head_scale.unsqueeze(1)  # (n_heads, half)

        # Phase offsets (shared across heads)
        offsets = self.phase_offset  # (half,)

        # Position indices — always use torch.arange for compile compatibility.
        # The registered buffer self.pos is only used for legacy/non-compiled path.
        # torch.arange is lightweight and avoids a shape-dependent branch that
        # causes graph breaks in torch.compile.
        pos = torch.arange(T, device=device, dtype=torch.float32)

        # ── Base angles: (n_heads, T, half) ──────────────────────────────
        # angle_{h,i}(t) = 2π × t / (τ_i × s_h) + φ₀_i
        base_angles = (
            2.0 * math.pi
            * pos.unsqueeze(0).unsqueeze(-1)     # (1, T, 1)
            / periods_h.unsqueeze(1)              # (n_heads, 1, half)
            + offsets.unsqueeze(0).unsqueeze(0)   # (1, 1, half)
        )  # → (n_heads, T, half)

        if X is not None and self.boundary_detector is not None:
            # ── Boundary phase remapping (Thm 61) ────────────────────────
            B = X.shape[0]
            boundary_gate = torch.sigmoid(self.boundary_gate_raw)

            # Detect boundaries from raw embeddings (detach: don't backprop
            # loss gradient through boundary detection into embedding layer)
            boundary_prob = torch.sigmoid(
                self.boundary_detector(X.detach())
            ).squeeze(-1)  # (B, T)

            # Cumulative boundary phase: Σ_{u≤t} p(u) × φ_boundary
            # boundary_prob: (B, T) → (B, T, 1)
            # boundary_phase: (half,) → (1, 1, half)
            weighted = (
                boundary_prob.unsqueeze(-1)                    # (B, T, 1)
                * self.boundary_phase.unsqueeze(0).unsqueeze(0)  # (1, 1, half)
            )  # → (B, T, half)
            cum_boundary = torch.cumsum(weighted, dim=1)  # (B, T, half)

            # Add boundary phase to base angles:
            # base_angles: (n_heads, T, half) → (1, n_heads, T, half)
            # cum_boundary: (B, T, half) → (B, 1, T, half)
            angles = (
                base_angles.unsqueeze(0)        # (1, n_heads, T, half)
                + boundary_gate
                * cum_boundary.unsqueeze(1)     # (B, 1, T, half)
            )  # → (B, n_heads, T, half)

            # Store for monitoring (tensor, no .item() — avoids CUDA sync + graph break)
            self._boundary_mean = boundary_prob.mean().detach()

            # RoPE format: duplicate for both halves of each dimension pair
            cos_a = torch.cat([torch.cos(angles), torch.cos(angles)], dim=-1)
            sin_a = torch.cat([torch.sin(angles), torch.sin(angles)], dim=-1)
            return cos_a.to(dtype), sin_a.to(dtype)  # (B, n_heads, T, d_h)

        else:
            # ── No boundary info: head-specific only (Thm 62) ────────────
            # RoPE format: duplicate for both halves
            cos_a = torch.cat([torch.cos(base_angles), torch.cos(base_angles)], dim=-1)
            sin_a = torch.cat([torch.sin(base_angles), torch.sin(base_angles)], dim=-1)
            return cos_a.to(dtype), sin_a.to(dtype)  # (n_heads, T, d_h)