Skip to content
In depthExperiments

Verace Neocortex: research model code

Brain-inspired language model code: precision-weighted predictive coding, gated modules and frozen-backbone adapters.

Verace Research
  1. V2 block: Eight-step block with a predictive-coding gate
  2. Gates initialised near zero: An extended model starts equal to its simpler one
  3. V10.2 model: Roughly 25 modules wired in through forward hooks
  4. V11 cortical columns: Six-layer columns trained by local rules and sleep
Figure 1. Model generations of Verace Neocortex, from V2 to V11. Schematic: the generations of Verace Neocortex, each built on the last. New brain-inspired modules enter behind gates set near zero, so each extended model starts equal to its simpler counterpart.
Open the simulator on its own pageWhat a line of versions keeps: an interactive toy model of the principle. You can also try it below

Overview

The research implementation of Verace Neocortex is one Python package, nct_v2, which holds the successive model generations of the line the lab's code calls NeuroCortex Transformer (NCT), from V2 through V11. It addresses one question: can mechanisms modelled on cortex, thalamus, hippocampus, basal ganglia and neuromodulators be added to a transformer language model as gated modules? In this design, a calibrated uncertainty signal σ2\sigma^2 drives attention, memory, retrieval, tool use and decoding.

The core of every generation is precision-weighted predictive coding (PWPC). Each block predicts its input. A bounded log-precision γ\gamma gives σ2=e−γ\sigma^2 = e^{-\gamma}, and a surprise gate blends the prediction with the raw input. New mechanisms enter as residual corrections behind sigmoid gates initialised near zero, so an extended model starts equal to its simpler counterpart. The V2 block runs an eight-step forward pass. In V10.2, roughly 25 brain-inspired modules are wired in through forward hooks. V11 replaces transformer blocks with six-layer cortical columns trained by analytical local rules and sleep phases.

NCT-Adapt places the modules after the layers of frozen third-party backbones: TinyLlama-1.1B in V1 and Qwen3.5-9B in V2. V3 sets module projections in closed form from SVDs of backbone activations. Around the models sit fused Triton kernels, quantization, LoRA, structured pruning, a cached inference engine, an agent loop and vision and audio encoders. The kernel benchmarks record the thalamic scan kernel as 26x faster and the fused oscillatory kernel as 0.83x. Gate priors taken from a 15K-step run of the lab's modules on Meta's frozen Llama 3.2 1B Instruct, the adapted model the lab calls Verace 1B, show that only 5 of 24 modules rose above their identity initialisation of −2.0.

Status: the model generations, adapters, kernels, quantization, pruning, inference and agent code are implemented, and test files cover kernels, quantization, grouped-query attention and the agent. The measurements recorded in this part are kernel speed benchmarks and the gate statistics of one 15K-step adapter run on a frozen 1B backbone. No language-modelling quality figures, benchmark scores or ablation results are recorded here. Several labels such as Thm 28g, Thm 72 or Thm 89 name results the code cites, but this part does not contain the proofs. Some code departs from its own docstrings, and those departures are listed among the findings.

Status

Experiments. The models and infrastructure are implemented with tests, and the only recorded measurements are kernel benchmarks used to set kernel flags and gate values from one adapter run on a frozen 1B backbone; no model-quality evaluation is recorded.

Simulator

A made-up line of thirteen versions of twelve parts. Each version replaces a few parts of the one before it and keeps the rest. Move along the line and change how much each version replaces.

  • versions, the baseline first
  • grey: a part of the baseline · colour: a part introduced later, brighter the newer
Baseline still in version 6
33%
Parts replaced since the baseline
8 of 12
Its oldest part is
6 versions old
Less than half baseline from
Version 5

Move along the line of versions, then replace more parts at each step and see how soon the baseline is gone.

This simulator is an illustration of the principle, with made-up numbers. It does not run the lab's code or show the lab's data, and nothing in it is a measurement.

Architecture

  1. NCT-V2 block and model

    An eight-step block (PCHP predictive-coding gate, LocalNeuromod, UCAM phase-biased attention, VCCE column ensemble, GLH Hebbian memory, mid residual, InhibitoryFFN, output gate) with tied embeddings and a shared GlobalNeuromod. It is trained with next-token cross-entropy plus 0.1 times a predictive-coding MSE.

  2. Matched GPT-2-style baseline

    A pre-RMSNorm transformer with RoPE, dense SwiGLU and tied embeddings, about 8.01M parameters. Its size is matched to V2-Nano for comparison.

  3. NCT V10.2 model

    NCTv102Model extends V10 with brain embeddings, BrainLMHead, V10.2 blocks and roughly 25 brain-inspired modules attached by forward hooks. It also provides optional fused kernels, ablation tools and brain decoding.

  4. V11 cortical column network

    A six-layer column (L4 input, L1 top-down, L2/3 windowed Hebbian association, interneurons, working memory, oscillations, L5 output, L6 feedback) replaces a transformer block. Subcortical systems sit alongside it: thalamus, hippocampus, basal ganglia, cerebellum, brainstem neuromodulators, global workspace and metacognition.

  5. NCT-Adapt adapters

    V1 post-processes each frozen TinyLlama-1.1B layer through NCT modules mixed in by a capped gated residual. V2 targets a frozen Qwen3.5-9B with layer-type-aware gates and calibrated abstention. V3 calibrates all projections without training.

  6. Fused Triton kernels

    Kernels for PWPC, the thalamic scan, TRN and tonic dopamine, pre-logits modulation, oscillations and element-wise hook chains. Every kernel has a PyTorch fallback and is enabled per kernel from benchmark results.

  7. Hippocampal episodic memory

    HippocampalGLH is one global, slowly decaying linear-attention memory per model. It reads before it writes and gates writes on σ2\sigma^2.

  8. Brain-inspired MoE feed-forward

    Eight dendritic SwiGLU experts behind a basal-ganglia D1/D2 router with dopamine modulation. The layer uses σ2\sigma^2-adaptive top-k and BCM load balancing, and starts gated nearly off.

  9. Deployment stack

    Mixed-precision quantization (group INT4/INT8, GPTQ, AWQ, FP8 emulation, INT8 KV cache, QAT), NCT-aware LoRA and a prefill/decode inference engine. The engine tracks 27 stateful components.

  10. Agent, retrieval and tool use

    An agentic loop chooses between generating, calling a tool, retrieving, replanning and stopping. The choice uses the model's σ2\sigma^2, tonic dopamine and ACC conflict signals, together with a learned retrieval gate and a D1/D2 tool selector.

  11. Multimodal encoders

    A V1, V2, V4 and IT convolutional vision hierarchy and an auditory hierarchy (learnable filterbank, A1, Belt, STS). Each also offers adapters over frozen ViT, SigLIP or Whisper features.

  12. Structured pruning

    Necessity scoring of the 28 registered gated V10.2 modules, homeostatic gate rescaling, a critical-period schedule, a gate sparsity loss and prune-then-finetune.

Implementation

Mechanisms as they are implemented in the source code, with the constants the code uses.

Surprise-gated precision blend
pwpc_fused.py computes γ=γmin+(γmax−γmin) sigmoid(W LN(X))\gamma = \gamma_{min} + (\gamma_{max} - \gamma_{min})\,\mathrm{sigmoid}(W\,\mathrm{LN}(X)) and σ2=e−γ\sigma^2 = e^{-\gamma}. Surprise is the mean squared prediction error divided by σ2+10−6\sigma^2 + 10^{-6}. The gate is g=sigmoid(β(s−τ))g = \mathrm{sigmoid}(\beta(s - \tau)) and the output is Xpc=(1−g) X^+gXX_{pc} = (1-g)\,\hat{X} + g X, with defaults γ∈[−3,3]\gamma \in [-3, 3] and β=5\beta = 5.
Sigmoid-bounded log-precision
In V4, γ=−1.609+3.912 sigmoid(WσXn)\gamma = -1.609 + 3.912\,\mathrm{sigmoid}(W_\sigma X_n), so σ2∈(0.1,5.0)\sigma^2 \in (0.1, 5.0) by construction (labelled Thm 28g). The bidirectional variant has separate up and down precisions. Its surprise is the larger of the two, with τ=softplus(τraw)\tau = \mathrm{softplus}(\tau_{raw}).
Gated Hebbian memory with LTD
Per step, S←at⊙S+ηwt(k⊗v)−δwt(k⊗k)S \leftarrow a_t \odot S + \eta w_t (k \otimes v) - \delta w_t (k \otimes k) and z←at⊙z+ηwtkz \leftarrow a_t \odot z + \eta w_t k, with output Sq/(z⋅q)Sq / (z \cdot q). Keys and queries use ELU+1 feature maps and a∈(0.2,0.98)a \in (0.2, 0.98). The LTD rate starts at δ=0.1 softplus(−2)≈0.013\delta = 0.1\,\mathrm{softplus}(-2) \approx 0.013, which erases stale traces for repeated keys.
Newton-refined smooth k-WTA
The threshold λ\lambda solves f(λ)=∑iσ(β(hi−λ))−k=0f(\lambda) = \sum_i \sigma(\beta(h_i - \lambda)) - k = 0 by λ←λ−f/f′\lambda \leftarrow \lambda - f/f' over 5 iterations, starting from the k-th largest value. The derivative f′f' is clamped at or below −10−8-10^{-8}. The mask σ(β(h−λ))\sigma(\beta(h - \lambda)) keeps about k units active, and k is set per token by neuromodulation.
Chunked linear recurrence scan
Recurrences ht=atht−1+bth_t = a_t h_{t-1} + b_t are solved with the associative operator (a,b)⊕(a′,b′)=(aa′,a′b+b′)(a,b) \oplus (a',b') = (aa', a'b + b'). The scan runs in chunks of 32 in float32 using cumulative products and sums, carrying the last state between chunks. It is stable for a≥0.2a \geq 0.2.
Capped gated adapter residual
In NCT-Adapt V1, each block outputs Xfrozen+α(Xnct−Xfrozen)X_{frozen} + \alpha (X_{nct} - X_{frozen}) with α=0.1 sigmoid(graw)\alpha = 0.1\,\mathrm{sigmoid}(g_{raw}) and grawg_{raw} initialised to −3, so α≈0.005\alpha \approx 0.005. The 0.1 cap stops NCT deltas compounding across 22 frozen layers. Trainable modules run in fp32 with autocast off.
SVD calibration without training
NCT-Adapt V3 sets WinW_{in} to the top-r right singular vectors of Φ(Xl)\Phi(X_l). Here Φ\Phi is the temporal difference, the residual difference or the identity, and Wout=0.1 Win⊤W_{out} = 0.1\,W_{in}^\top. The uncertainty projection is set to the negated covariance direction between normalised activations and per-position residual MSE, so σ2\sigma^2 rises with local error.
BCM-modulated Hebbian rule
V11 columns update ΔW=lr [(y⊙(y−θ))⊤x]/N\Delta W = \mathrm{lr}\,[(y \odot (y - \sqrt{\theta}))^\top x]/N with a zero diagonal and the norm clipped to 5. The threshold θ\theta is an EMA of mean squared activity with tau 1000. The update can be scaled by the per-token error ratio with weight 0.5.
Analytical predictive-coding update
Without autograd, ΔWpredict=−((ϵ/σ2)⊤h)/N\Delta W_{predict} = -((\epsilon/\sigma^2)^\top h)/N and ∂L/∂σ2=−ϵ2‾/(2σ4)+0.5/σ2\partial L/\partial \sigma^2 = -\overline{\epsilon^2}/(2\sigma^4) + 0.5/\sigma^2, the latter passed through a clamped sigmoid derivative. Gradient norms are clipped to 1.0 and lr is 3e-4 times a plasticity gate.
Three-phase sleep consolidation
Generative replay of hippocampal memories through the columns uses predictive-coding updates at 0.3 times lr and Hebbian updates at 0.5 times lr. A contrastive phase follows, with anti-Hebbian updates on noisy input and BCM updates on real input, then semantic centroid consolidation. The cycle ends with multiplicative synaptic downscaling by 0.99.
Sleep pressure model
Pressure grows by 0.001 (1+min⁡(PE,5))0.001\,(1 + \min(PE, 5)) per experience and scales wake learning by max⁡(0.1,1−p)\max(0.1, 1 - p). Sleep triggers at p≥0.7p \geq 0.7 or after 100 wake steps, and resets pp to 0.
Log-precision free energy loss
V8 uses F=eγ MSE−γF = e^{\gamma}\,\mathrm{MSE} - \gamma, whose equilibrium is σ2=MSE\sigma^2 = \mathrm{MSE}. The MSE is taken on RMS-normalised tensors so it stays within the σ2\sigma^2 bounds. The loss is weighted by dopamine and clamped at 50 per layer. An asymmetric penalty relu(0.3−σ2)2+relu(σ2−4)2\mathrm{relu}(0.3 - \sigma^2)^2 + \mathrm{relu}(\sigma^2 - 4)^2 with weight 0.001 replaces the earlier quadratic well.
Basal-ganglia D1/D2 router
Two GELU pathways produce GO and NOGO scores. The activations are d1=σ(8(DA−0.65))d_1 = \sigma(8(DA - 0.65)) and d2=σ(8(0.25−DA))d_2 = \sigma(8(0.25 - DA)), and the logits are d1⋅GO−d2⋅NOGOd_1 \cdot GO - d_2 \cdot NOGO. Zero-initialised outputs give uniform routing at the start, and BCM thresholds subtracted from the logits push expert usage toward 1/N1/N.
Drift-diffusion decoding
For the top 64 candidates, accumulators update as a←a+ℓ/max⁡(5σ,0.1)+σξa \leftarrow a + \ell / \max(5\sigma, 0.1) + \sigma \xi against a collapsing threshold θ(t)=θ0e−t/8\theta(t) = \theta_0 e^{-t/8}. Here θ0=3.0 (1+0.6(0.5−DA))\theta_0 = 3.0\,(1 + 0.6(0.5 - DA)) and σ=0.3σ2\sigma = 0.3\sqrt{\sigma^2}. The number of steps is 15 plus 10 times conflict, capped at 50, and the first crossing wins.
Uncertainty-gated retrieval
Retrieval value is modelled as V(σ2)=A(1−e−σ2/τ)V(\sigma^2) = A(1 - e^{-\sigma^2/\tau}), so retrieval fires when σ2>−τln⁡(1−Cr/A)\sigma^2 > -\tau \ln(1 - C_r/A) (labelled Thm 72). In practice, a learned gate over σ2\sigma^2, ACC conflict, dopamine and context fires above 0.5.
WEAVER++ lateral inhibition
With detached p=softmax(ℓ)p = \mathrm{softmax}(\ell), the head computes the centroid c=pSc = pS and the inhibition relu(c⋅Si−pi∥Si∥2)\mathrm{relu}(c \cdot S_i - p_i \lVert S_i \rVert^2). It then subtracts a gated amount from the logits. The top-K version applies this only to the 256 candidates.
Gate-based pruning necessity
The necessity of a module is Ni=sigmoid(gi) ∥Wout,i∥FN_i = \mathrm{sigmoid}(g_i)\,\lVert W_{out,i} \rVert_F, a first-order proxy for the loss increase if the module is removed. The prune threshold is 0.15. Pruning starts only after aux-loss annealing and once gates are stable (∣Δg∣<0.01|\Delta g| < 0.01 for 200 steps), with sensory modules pruned first and PFC modules last.
Uncertainty-guided quantization
Group saliency is the mean of activation squared times mean σ2\sigma^2 from PWPC blocks. Groups above the median get INT8 and the rest INT4. Group-wise asymmetric quantization over groups of 128 stores scale=(max⁡−min⁡)/(2n−1)\mathrm{scale} = (\max - \min)/(2^n - 1) and packs INT4 two per byte.
Uncertainty-frozen fine-tuning
LoRA excludes WσW_\sigma, gates, neuromodulators, decay biases, norms and positional calibration parameters from adaptation, so σ2\sigma^2 calibration is preserved (labelled Thm 83). Dopamine-gated LoRA scales the adapter by σ(β(DA−θ))\sigma(\beta(DA - \theta)) with β=5\beta = 5 and θ=0.5\theta = 0.5 at init.
Triton forward, recompute backward
Custom autograd functions run the fused Triton kernel in the forward pass. The backward pass recomputes the PyTorch reference under enable_grad to obtain input gradients. Fusing element-wise hook chains reduces memory traffic from 2Nd2Nd to 2d2d.

Results

From the lab's own experiments and records. They have not been independently replicated.

  1. Thalamic scan kernel recorded 26x faster

    The lab's L4 benchmarks recorded the fused thalamic scan kernel as 26x faster than its reference, and it is enabled by default.

  2. Several fused kernels were slower and disabled

    The benchmark-derived flags disable the kwta, nmda, oscillatory, trn_tonic and pre_logits kernels. The fused oscillatory kernel is recorded at 0.83x.

  3. Most modules stayed near identity in training

    In a 15K-step run of the lab's modules on Meta's frozen Llama 3.2 1B Instruct, the adapted model the lab calls Verace 1B, only 5 of 24 modules rose above the identity gate initialisation of −2.0. NCT-Adapt V3 therefore sets the inactive modules to −4.0.

  4. Quadratic well forced uncertainty toward one

    The V8 code records that the quadratic σ2\sigma^2 penalty forced σ2\sigma^2 toward 1. It was replaced by an asymmetric boundary penalty that is zero inside [0.3, 4], so the ELBO can calibrate σ2\sigma^2.

  5. Gaussian ELBO loss detaches its log term

    The V7 loss is meant to reach σ2=MSE\sigma^2 = \mathrm{MSE} at equilibrium. The code detaches the log⁡σ2\log \sigma^2 term, so that calibration gradient is absent.

  6. Code departs from several docstrings

    The SlowReplay consolidation loss applies to all positions despite its docstring, and the Triton kernel for cross-frequency attention is an empty stub behind a PyTorch tiled path. The package init lists agent, LoRA, quantization, scan and pruning names in its exports without importing them, and the watermark's theta-phase framing is nominal.

  7. Synaptic importance guard disabled by default

    The EWC penalty with λ=100\lambda = 100 is disabled by default because it ran out of memory on 6GB GPUs.

Concepts

Precision-weighted predictive coding
Each layer predicts its input and weights the prediction error by a precision 1/σ21/\sigma^2. The code follows Friston's precision weighting, so confident predictions dominate and surprising inputs pass through.
Log-precision
The model parameterises uncertainty as γ=log⁡(1/σ2)\gamma = \log(1/\sigma^2) and bounds γ\gamma with a sigmoid. This keeps σ2\sigma^2 inside a fixed interval such as (0.1, 5) without clamping.
Identity at initialisation
Every added module starts behind a sigmoid gate set to values such as σ(−2)≈0.12\sigma(-2) \approx 0.12 or σ(−5)\sigma(-5), often with a zero-initialised output projection. The extended model therefore initially reproduces the base model.
Multi-scale uncertainty
In V11, mean σ2\sigma^2 per column is grouped by depth quartile into token, phrase, sentence and discourse uncertainty. These four values drive fine-tuning, retrieval and tool decisions.
Gated linear Hebbian memory
A linear-attention memory that accumulates key-value outer products with learned decay. Reads are normalised by an accumulated key sum, and it serves as a fast associative store inside blocks and in the hippocampus module.
Long-term depression term
An anti-Hebbian subtraction proportional to k⊗kk \otimes k in the memory write. It removes stale associations when the same key recurs.
k-winner-take-all sparsity
Only about k units stay active per token. The model computes a smooth mask whose threshold is solved so that the expected active count equals k.
Neuromodulatory signals
Dopamine, acetylcholine and noradrenaline analogues are computed from surprise and novelty. They scale learning, attention temperature, routing, write gates and decoding thresholds.
Tonic dopamine
A slow EMA of the sigmoid of mean running surprise. It sets the D1 or D2 regime of the basal-ganglia selector, the MoE router and an inverted-U modulation.
BCM plasticity
The Bienenstock-Cooper-Munro rule uses a sliding threshold that rises with recent activity. The code uses it both in Hebbian column learning and as parameter-free expert load balancing.
Global workspace
A per-sequence vector or attention over layer summaries, read into every layer or added before the output head. It gives communication across layers beyond the residual stream.
Theta-gamma coupling
Oscillatory phase assignments, with theta for slow grouping and gamma for fast items, are turned into a log attention bias. A cross-modal version binds vision, audio and text tokens.
Frozen-backbone adaptation
NCT-Adapt keeps a pretrained third-party model frozen and feeds it unmodified inputs. Trainable NCT modules act only on layer outputs through a capped residual.
Wake-sleep lifecycle
V11 runs states for wake, sleep replay, dream replay with noise, consolidation from episodic to semantic memory, and evaluation. All of these use analytic updates under no_grad.
Developmental critical periods
V11 training is staged into sensory, association, integration and refinement phases. Each phase changes learning rate, inhibition, the Hebbian-versus-error balance, growth threshold and sleep interval.
Cortical inhibitory triad
SST tonic suppression, VIP disinhibition and a chandelier veto gate act on top-down corrections. Apical amplification scales the result by a product of basal and apical activity.
Benchmark-gated kernel dispatch
Each fused kernel is turned on only if measured speedups favour it. Every kernel keeps a PyTorch fallback for CPU, MPS or disabled cases.
Brain mixed-precision policy
Large backbone weights use INT4, mechanism weights use INT8 or FP8, and timing-critical parameters such as σ2\sigma^2, decay, phase and position stay in FP16.

About this page

Written from the lab's own documents and source code. Figures and results are the lab's measurements as it recorded them at the time, and have not been independently replicated.

Published under the PolyForm Noncommercial License 1.0.0: free for noncommercial use.