Verace Neocortex: research model code
Brain-inspired language model code: precision-weighted predictive coding, gated modules and frozen-backbone adapters.
- V2 block: Eight-step block with a predictive-coding gate
- Gates initialised near zero: An extended model starts equal to its simpler one
- V10.2 model: Roughly 25 modules wired in through forward hooks
- V11 cortical columns: Six-layer columns trained by local rules and sleep
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 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 gives , 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
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.
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.
NCT V10.2 model
NCTv102Modelextends 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.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.
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.
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.
Hippocampal episodic memory
HippocampalGLHis one global, slowly decaying linear-attention memory per model. It reads before it writes and gates writes on .Brain-inspired MoE feed-forward
Eight dendritic SwiGLU experts behind a basal-ganglia D1/D2 router with dopamine modulation. The layer uses -adaptive top-k and BCM load balancing, and starts gated nearly off.
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.
Agent, retrieval and tool use
An agentic loop chooses between generating, calling a tool, retrieving, replanning and stopping. The choice uses the model's , tonic dopamine and ACC conflict signals, together with a learned retrieval gate and a D1/D2 tool selector.
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.
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.pycomputes and . Surprise is the mean squared prediction error divided by . The gate is and the output is , with defaults and .- Sigmoid-bounded log-precision
- In V4, , so by construction (labelled Thm 28g). The bidirectional variant has separate up and down precisions. Its surprise is the larger of the two, with .
- Gated Hebbian memory with LTD
- Per step, and , with output . Keys and queries use ELU+1 feature maps and . The LTD rate starts at , which erases stale traces for repeated keys.
- Newton-refined smooth k-WTA
- The threshold solves by over 5 iterations, starting from the k-th largest value. The derivative is clamped at or below . The mask keeps about k units active, and k is set per token by neuromodulation.
- Chunked linear recurrence scan
- Recurrences are solved with the associative operator . The scan runs in chunks of 32 in float32 using cumulative products and sums, carrying the last state between chunks. It is stable for .
- Capped gated adapter residual
- In NCT-Adapt V1, each block outputs with and initialised to −3, so . 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 to the top-r right singular vectors of . Here is the temporal difference, the residual difference or the identity, and . The uncertainty projection is set to the negated covariance direction between normalised activations and per-position residual MSE, so rises with local error.
- BCM-modulated Hebbian rule
- V11 columns update with a zero diagonal and the norm clipped to 5. The threshold 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, and , 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 per experience and scales wake learning by . Sleep triggers at or after 100 wake steps, and resets to 0.
- Log-precision free energy loss
- V8 uses , whose equilibrium is . The MSE is taken on RMS-normalised tensors so it stays within the bounds. The loss is weighted by dopamine and clamped at 50 per layer. An asymmetric penalty 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 and , and the logits are . Zero-initialised outputs give uniform routing at the start, and BCM thresholds subtracted from the logits push expert usage toward .
- Drift-diffusion decoding
- For the top 64 candidates, accumulators update as against a collapsing threshold . Here and . 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 , so retrieval fires when (labelled Thm 72). In practice, a learned gate over , ACC conflict, dopamine and context fires above 0.5.
- WEAVER++ lateral inhibition
- With detached , the head computes the centroid and the inhibition . 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 , 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 ( 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 from PWPC blocks. Groups above the median get INT8 and the rest INT4. Group-wise asymmetric quantization over groups of 128 stores and packs INT4 two per byte.
- Uncertainty-frozen fine-tuning
- LoRA excludes , gates, neuromodulators, decay biases, norms and positional calibration parameters from adaptation, so calibration is preserved (labelled Thm 83). Dopamine-gated LoRA scales the adapter by with and 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 to .
Results
From the lab's own experiments and records. They have not been independently replicated.
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.
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.
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.
Quadratic well forced uncertainty toward one
The V8 code records that the quadratic penalty forced toward 1. It was replaced by an asymmetric boundary penalty that is zero inside [0.3, 4], so the ELBO can calibrate .
Gaussian ELBO loss detaches its log term
The V7 loss is meant to reach at equilibrium. The code detaches the term, so that calibration gradient is absent.
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.
Synaptic importance guard disabled by default
The EWC penalty with 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 . The code follows Friston's precision weighting, so confident predictions dominate and surprising inputs pass through.
- Log-precision
- The model parameterises uncertainty as and bounds with a sigmoid. This keeps 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 or , often with a zero-initialised output projection. The extended model therefore initially reproduces the base model.
- Multi-scale uncertainty
- In V11, mean 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 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 , 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.