NCT-Adapt: Wrapper Modules for Pre-Trained Language Models
Abstract
A computing system and method for augmenting pre-trained neural network language models with calibrated hallucination detection capability through thirty (30) brain-inspired wrapper modules. Distinguished from LoRA (Hu 2021) and Adapters (Houlsby 2019) by: (1) a capped gated residual (alpha = alpha_max * sigmoid(gate_raw), alpha_max = 0.1 FIXED, NON-LEARNABLE) structurally guaranteeing at most 10% influence per layer, preventing compounding degradation bounded by (1.1)^L; (2) post-block-only architecture where ALL modules operate exclusively on frozen layer outputs; (3) identity-at-initialization verified by logit comparison (max diff < 1e-3). Distinguished from MC-Dropout (Gal 2016) and Ensembles (Lakshminarayanan 2017) by: (4) single-forward-pass uncertainty using sigmoid-bounded sigma-squared trained via free energy loss with analytical equilibrium at sigma-squared = MSE; (5) AUROC 0.917 hallucination detection with less than 2% compute overhead. The wrapper includes an inhibitory triad (SST, VIP, Apical in mandated non-commutative order on correction signal), seven working memory modules via removable forward hooks, neuromodulatory gates (D1D2, TonicDA, TripartiteACh, SurpriseWeighting), and self-regulating training (BCM homeostasis, astrocyte modulation, synaptic scaling, sleep consolidation, five differentiated learning rate groups). Demonstrated on TinyLlama-1.1B: NTP accuracy +3.5% (0.512 vs 0.477), PCC 0.459, val PPL improved 10.4 to 9.8, 77M trainable parameters (7% overhead), converged gate alpha = 0.01, zero degradation.
Status
Open research. This document was first drafted in the form of a patent specification, which is why it speaks of an invention and of claims. No patent application was filed and the lab does not intend to file one. It is an earlier draft than the seven specifications of the cortical column network, kept here for the detail it holds. The work is published as open research.
1. Field
The present invention relates to augmenting pre-trained neural network language models with external trainable modules for uncertainty quantification and hallucination detection. More particularly, the invention relates to a computing system employing a capped gated residual wrapper architecture comprising thirty (30) distinct brain-inspired computational modules, wherein:
trainable wrapper modules operate exclusively on frozen layer outputs (post-block architecture) and are connected through a hard-capped gate limiting maximum influence to a fixed non-learnable constant alpha_max per layer;
a per-position uncertainty head produces sigmoid-bounded sigma-squared estimates trained via a free energy loss with analytical equilibrium, enabling single-forward-pass calibrated hallucination detection;
global working memory modules are applied through removable forward hooks on the pre-trained model’s final normalization layer, providing multi-timescale episodic, phonological, temporal, and phase-coded memory without permanently modifying the base model’s computation graph;
a biologically-derived self-regulation training system comprising per-parameter BCM homeostasis, per-layer astrocyte modulation, periodic synaptic scaling, sleep consolidation with GradScaler state preservation, dopamine-weighted per-token learning, and five differentiated learning rate groups maintains training stability without manual hyperparameter intervention;
a non-commutative inhibitory triad (SST Martinotti suppression, then VIP disinhibition, then Apical amplification) operates on a correction signal rather than the representation itself, implementing the complete PV/SST/VIP interneuron circuit of biological cortex;
without modifying any parameter of the pre-trained model, adding less than 10% parameter overhead, and achieving hallucination detection AUROC exceeding 0.90 in a single forward pass.
2. Background
Prior Art Analysis
Category 1: Parameter-Efficient Fine-Tuning (PEFT)
LoRA (Hu et al., 2021, “Low-Rank Adaptation of Large Language Models”): Adds low-rank weight matrices (W = W_0 + BA) to the frozen model’s attention projections. The adaptation MODIFIES the weight matrices during the forward pass (additively). LoRA does NOT:
Provide uncertainty quantification or hallucination detection
Implement any gating mechanism that limits the magnitude of adaptation per layer
Operate exclusively post-block (LoRA modifies within the attention computation itself, altering Q, K, V projections)
Implement any self-regulation, homeostatic feedback, or neuromodulatory signals
Produce per-position confidence signals correlated with prediction error
Contain any working memory, temporal coding, phase-amplitude coupling, or inhibitory circuit mechanism
Provide any structural guarantee against compounding degradation across layers
Adapter Layers (Houlsby et al., 2019, “Parameter-Efficient Transfer Learning for NLP”): Inserts small bottleneck layers (down-project, nonlinearity, up-project) BETWEEN existing transformer layers. Adapters do NOT:
Limit their influence via a hard cap (the adapter’s contribution is unbounded in magnitude)
Implement biologically-derived processing modules of any kind
Produce uncertainty estimates or hallucination confidence scores
Apply post-block wrapping with a gated residual that blends frozen and adapted outputs
Preserve the frozen computation chain (adapters modify the inter-layer data flow)
Guarantee identity-at-initialization (adapter residual connections approximate but do not structurally guarantee identity)
Prefix Tuning (Li & Liang, 2021): Prepends learnable “virtual tokens” to the input sequence, modifying the attention computation indirectly. QLoRA (Dettmers et al., 2023): Quantized variant of LoRA with 4-bit backbone and paged optimizers. BitFit (Ben Zaken et al., 2021): Trains only bias terms of the frozen model. ALL PEFT methods share a fundamental limitation: they are purely engineering solutions that adapt the model’s outputs without providing any uncertainty quantification, self-regulation, homeostatic feedback, working memory, inhibitory gating, temporal coding, or hallucination detection capability. None of them implement any biologically-motivated computational mechanism. None of them provide a structural guarantee limiting per-layer influence.
Category 2: Uncertainty Estimation in Pre-Trained LLMs
MC-Dropout (Gal & Ghahramani, 2016, “Dropout as a Bayesian Approximation: Representing Model Uncertainty in Deep Learning”): Applies dropout at inference time and performs 10-50 forward passes to estimate predictive variance. MC-Dropout does NOT:
Train uncertainty end-to-end with a dedicated loss function
Have an analytical equilibrium where uncertainty converges to actual prediction error
Produce uncertainty in a single forward pass (requires N forward passes, where N is typically 10-50)
Add any trainable modules to the model
Provide per-position (per-token) uncertainty with calibration guarantees
Use biologically-motivated free energy minimization for calibration
Deep Ensembles (Lakshminarayanan, Pritzel & Blundell, 2017, “Simple and Scalable Predictive Uncertainty Estimation using Deep Ensembles”): Trains N independent copies of the model (typically N=3-5) and uses variance of predictions. Deep Ensembles do NOT:
Have analytical equilibrium properties for uncertainty calibration
Add less than 200% parameter overhead (minimum 2x, typically 3-5x)
Use a single model for uncertainty estimation
Employ biologically-motivated calibration mechanisms
Verbalized Confidence (Kadavath et al., 2022, “Language Models (Mostly) Know What They Know”): Prompts the model to self-assess confidence using natural language. Verbalized Confidence does NOT:
Provide calibrated numerical uncertainty estimates
Train any module specifically for uncertainty estimation
Guarantee correlation between stated confidence and actual accuracy
Work reliably for all input types (known to be inconsistent and overconfident on hallucinations)
Token Probability Thresholding: Uses the softmax probability of the most-likely token as a confidence signal. This approach does NOT:
Account for the known miscalibration of neural network softmax outputs
Provide post-hoc calibration without additional temperature scaling
Distinguish between inherently uncertain inputs and model ignorance
Correlate reliably with factual accuracy (overconfident on hallucinations)
Conformal Prediction (Angelopoulos et al., 2022): Provides prediction sets with coverage guarantees. Conformal Prediction does NOT:
Produce per-token uncertainty estimates during generation
Add trainable modules to improve model capabilities alongside uncertainty
Use biologically-motivated mechanisms for calibration
NONE of the above uncertainty methods:
Add trainable modules that LEARN to estimate uncertainty end-to-end through backpropagation
Use a biologically-motivated free energy loss for calibrating uncertainty with analytical equilibrium
Produce calibrated uncertainty in a single forward pass at minimal computational overhead
Limit their impact on the base model via a structurally hard-capped gate
Implement neuromodulatory learning signals (dopamine, acetylcholine, sigma-squared) that self-regulate the training process
Provide working memory, temporal coding, or inhibitory circuits alongside uncertainty estimation
Category 3: Brain-Inspired Computing and Neuromorphic Approaches
Spiking Neural Networks (Maass, 1997): Implement temporal dynamics using discrete spikes. SNNs do NOT:
Wrap pre-trained transformer models
Provide uncertainty quantification
Operate as a post-hoc augmentation to existing LLMs
Implement the specific combination of mechanisms described herein (capped gating, inhibitory triad, neuromodulatory learning rates)
Predictive Coding Networks (Rao & Ballard, 1999; Millidge et al., 2022): Implement hierarchical prediction and error correction. Existing PC implementations do NOT:
Wrap frozen pre-trained models with capped influence gates
Implement per-position uncertainty with free energy calibration loss
Combine PC with 30 additional brain-inspired mechanisms in a unified wrapper
Provide hallucination detection AUROC > 0.85
Neuromorphic hardware (Intel Loihi, IBM TrueNorth): Implements brain-inspired computation in hardware. These do NOT:
Operate as software wrappers on existing GPU-trained LLMs
Provide parameter-efficient adaptation of pre-trained models
Implement the specific module combination and training system described herein
Category 4: Wrapper and Augmentation Methods for LLMs
Retrieval-Augmented Generation (RAG) (Lewis et al., 2020): Augments LLM output with retrieved documents. RAG does NOT:
Add trainable brain-inspired modules to the model’s computation graph
Provide per-token uncertainty estimates
Implement working memory, inhibitory circuits, or neuromodulatory signals
Chain-of-Thought Verification (Wei et al., 2022): Uses reasoning chains to improve accuracy. This does NOT:
Modify the model’s internal representations
Provide calibrated uncertainty
Implement biologically-motivated computational mechanisms
Guardrails and Safety Layers (e.g., NeMo Guardrails): Add rule-based filters to LLM output. These do NOT:
Add trainable neural modules with end-to-end gradient flow
Provide per-position uncertainty estimates
Implement biological self-regulation mechanisms
Technical Problem
There exists a need for a system that:
adds calibrated uncertainty quantification to ANY pre-trained LLM without modifying its parameters, producing per-position sigma-squared estimates in a single forward pass;
prevents catastrophic degradation through a mathematically guaranteed influence cap (alpha_max), providing a structural upper bound on per-layer and cumulative deviation from the base model;
achieves hallucination detection AUROC exceeding 0.85 in a single forward pass, without requiring multiple forward passes, model ensembles, or prompted self-assessment;
uses biologically-motivated self-regulation (BCM homeostasis, astrocyte gradient modulation, synaptic scaling, sleep consolidation, dopamine-weighted learning) that requires minimal hyperparameter tuning and maintains training stability autonomously;
adds less than 10% parameter overhead while providing 30 distinct brain-inspired computational mechanisms including working memory, temporal coding, phase-amplitude coupling, inhibitory gating, neuromodulatory signals, and event boundary detection;
guarantees identity-at-initialization, meaning the augmented model produces outputs identical to the base model before any training, verified by logit comparison;
provides a removable hook-based architecture for global working memory, such that all augmentations can be instantly disabled without model reload.
3. Summary
The present invention provides NCT-Adapt, a wrapper system that augments a frozen pre-trained language model with thirty (30) trainable brain-inspired modules organized into per-block modules (applied at each frozen layer), shared modules (shared across all layers), and global modules (applied once via forward hook). The invention is distinguished from ALL prior art by the following specific novelties:
Novelty 1, Capped Gated Residual (Distinguished from LoRA, Adapters, all PEFT)
The wrapper output at each layer is computed as:
alpha = alpha_max * sigmoid(gate_raw) X_output = X_frozen + alpha * (X_nct - X_frozen)
where alpha_max = 0.1 is a FIXED, NON-LEARNABLE structural constant. This means:
At ANY point during training, the wrapper’s contribution is at most 10% per layer
This is NOT a regularization trick or loss penalty, it is a STRUCTURAL constraint in the computation graph that cannot be circumvented by any gradient update
The maximum compounding across L layers is bounded by (1 + alpha_max)^L, which for L=22 and alpha_max=0.1 gives (1.1)^22 = 7.4x, within a provably stable regime
WITHOUT this cap: (1 + alpha)^L for uncapped alpha=0.5 gives (1.5)^22 = 31,382x, destroying the base model
The gate_raw parameter is initialized to -3.0, giving alpha_init = 0.1 * sigmoid(-3.0) = 0.1 * 0.047 = 0.0047, meaning the system starts with only 0.47% NCT contribution
In practice, the gate converges to approximately alpha = 0.01 (1% influence), demonstrating that the system self-regulates to use the MINIMUM necessary NCT intervention
Measured maximum gate opening after 5000 steps of training: alpha = 0.0102 (1.02%)
No prior PEFT method has this structural guarantee. LoRA’s contribution is unbounded (the rank-decomposed weight update BA has no magnitude limit). Adapters have no influence cap. Prefix tuning has no per-layer influence bound. This structural difference prevents the compounding degradation failure mode that ALL prior wrapper methods suffer from.
Novelty 2, Post-Block Only Architecture (Distinguished from LoRA, Adapters)
ALL NCT modules operate on the frozen layer’s OUTPUT, never its input:
X_frozen = frozen_layer(X_input) # frozen forward pass, no gradient X_nct = NCT_chain(X_frozen) # trainable modules process the OUTPUT X_output = blend(X_frozen, X_nct) # capped blend
LoRA modifies the INTERNAL computation of the layer (changing Q, K, V weight matrices). Adapters are inserted BETWEEN layers, modifying the input to the next layer. NCT-Adapt processes the OUTPUT only, preserving the frozen computation chain exactly. The frozen layer receives its original input unchanged and produces its original output unchanged.
This post-block architecture prevents “input corruption”, the catastrophic failure mode where modified inputs cause the frozen layer to produce garbage output because it receives out-of-distribution input it was never trained on. Experimentally verified: pre-block corruption causes immediate NTP degradation, while post-block processing maintains or improves NTP accuracy.
Novelty 3, Single-Pass Uncertainty Head with Free Energy Loss (Distinguished from MC-Dropout, Ensembles, Verbalized Confidence)
Each wrapper block contains an Uncertainty Head that computes per-position sigma-squared estimates:
raw = W_gamma(LayerNorm(X_nct)) # learnable projection, shape (B, T, 1) gamma = gamma_min + (gamma_max - gamma_min) * sigmoid(raw) # bounded log-precision sigma_squared = exp(-gamma) # sigma^2 from log-precision
The uncertainty is trained using a free energy loss:
L_unc = mean(exp(gamma) * MSE - gamma)
This loss has an ANALYTICAL EQUILIBRIUM: setting dL_unc/d(gamma) = 0 gives exp(gamma) * MSE - 1 = 0, therefore exp(gamma) = 1/MSE, therefore sigma_squared = MSE. The trained uncertainty converges exactly to the actual prediction error magnitude. No prior uncertainty method has this property:
MC-Dropout has no loss function for uncertainty, it is a stochastic byproduct of random dropout masks
Deep Ensembles use variance of predictions across independent models, no analytical equilibrium, no single-model operation
Verbalized confidence is not trained, it is prompted, with no calibration guarantee
Additionally, the sigma-squared parameterization uses a sigmoid bound:
sigma_squared in [exp(-gamma_max), exp(-gamma_min)]
which prevents sigma-squared from reaching zero (avoiding division-by-zero in precision computations) or infinity (avoiding numerical overflow), while leaving full freedom within the bounded range. An asymmetric boundary loss adds quadratic penalty only outside a free zone [0.3, 4.0]:
L_bound = mean(relu(0.3 - sigma_squared)^2 + relu(sigma_squared - 4.0)^2)
Novelty 4, Thirty Brain-Inspired Computational Modules (Distinguished from all PEFT and all LLM augmentation methods)
Each wrapper block and the global module chain contains modules derived from specific neuroscience mechanisms, each mapping to a specific brain region, cell type, or neuromodulatory system. No prior method implements ANY of these modules, let alone their specific combination and interaction:
Per-block modules (12 distinct modules instantiated at each of L layers):
StochasticResonance, learnable noise injection at BOTH train and inference (NOT dropout)
RepetitionSuppression, anti-Hebbian novelty amplification
LCEventBoundary, norepinephrine context-shift detection and reset pulse
PrefrontalContextGate, top-down contextual modulation
ChandelierVetoGate (shared), axo-axonic output veto (PV+ interneuron)
EndocannabinoidGate, retrograde suppression of over-active positions
ACCConflictMonitor, anterior cingulate conflict detection and control
SSTMartinotti, dendritic suppression of top-down correction (SST+ interneuron)
VIPDisinhibitoryGate, release of SST suppression (VIP+ interneuron)
ApicalAmplification, BAC firing coincidence detection
StriatalConfidenceGate (shared), confidence-based routing
UncertaintyHead, per-position sigma-squared estimation
Global modules (applied once via forward hook on final LayerNorm, 7 modules):
CerebellarTiming, temporal prediction error correction
NMDAAttractorSlots, persistent attractor-based working memory
ThetaPhasePrecession, phase-coded temporal position
ThetaGammaPAC, phase-amplitude coupling for binding
ActivitySilentTrace, synaptic facilitation trace memory
PhonologicalLoop, cyclic rehearsal buffer (K=8 slots)
TimeCellBank, multi-timescale temporal receptive fields (32 cells)
Additional global modules (applied during loss computation / neuromodulation):
D1D2InvertedU, dopamine D1/D2 receptor inverted-U response
TonicDATemperature, slow EMA-based exploration/exploitation
TripartiteAChGate, DA + ACh + sigma-squared combination gate
SurpriseWeightingGate, per-token gradient importance modulation
ThalamicRelay, frequency-group-specific relay with reticular gating
ThalamicReticularFilter, top-down relevance filtering of thalamic relay
BasalGangliaSelector (shared), D1/D2 pathway column selection bias
DAComputer, dopamine-like prediction error signal computation
Training system modules (applied during optimization):
BCMHomeostasis, per-parameter Bienenstock-Cooper-Munro gradient stability
AstrocyteHomeostasis, two-timescale per-layer gradient modulation
SleepConsolidation, periodic replay of high-surprise batches
None of these modules exist in any prior PEFT method. None exist in any prior LLM uncertainty method. None exist in any prior LLM wrapper or augmentation system.
Novelty 5, Global Working Memory via Non-Invasive Forward Hook (Distinguished from all LLM modifications)
Working memory modules are applied using a PyTorch forward hook registered on the pre-trained model’s final LayerNorm:
hook_handle = base_model.model.norm.register_forward_hook(wm_hook)
The hook is registered BEFORE each forward pass and removed AFTER (in a try/finally block), leaving ZERO permanent modification to the base model’s computation graph. The working memory modules (CerebellarTiming, NMDAAttractorSlots, ThetaPhasePrecession, ThetaGammaPAC, ActivitySilentTrace, PhonologicalLoop, TimeCellBank) provide multi-timescale memory that the base model lacks, but can be removed instantly by simply not registering the hook.
This architecture has a critical property: the seven working memory modules operate on the hidden states AFTER all frozen transformer layers have processed them but BEFORE the language model head projects to vocabulary logits. This placement means:
Working memory can inject temporal, phase-coded, and episodic information into the representation that the LM head uses for prediction
The frozen transformer layers are completely unaffected (they have already completed their computation)
The hook can be registered or not registered on a per-forward-pass basis, enabling instant A/B comparison
No prior method adds persistent working memory to a frozen LLM via a removable hook architecture.
Novelty 6, Biologically-Derived Self-Regulating Training System (Distinguished from uniform cross-entropy training and all PEFT training)
The training loss weights each token’s contribution by a dopamine-like surprise signal:
ntp_errors = cross_entropy(logits, labels, reduction='none') cumulative_mean = cumulative_sum(ntp_errors) / position_counts da_t = ntp_errors / (cumulative_mean + epsilon) da_t = 3.0 * da_t / (1.0 + da_t) # Michaelis-Menten saturation da_weights = 1.0 + da_scale * tanh(da_t - 1.0) # centered modulation da_signal = sigmoid(ntp_errors - cumulative_mean) # [0,1] surprise signal
Tokens that the model predicts INCORRECTLY (high cross-entropy) receive HIGHER gradient weight. Tokens it already predicts well receive LOWER weight. This implements biological prediction-error-driven learning: “learn more from mistakes, less from what is already known.”
Combined with four homeostatic mechanisms:
BCM Homeostasis: Per-parameter gradient modulation using running EMA of gradient magnitude
Astrocyte Homeostasis: Per-layer two-timescale (tau_fast=50, tau_slow=500) gradient scaling
Synaptic Scaling: Every 100 steps, normalize working memory weight row norms toward their mean
Sleep Consolidation: Every 1000 steps, replay top-20 highest-DA batches at 0.3x learning rate, with GradScaler state preservation
And five differentiated learning rate groups:
gates: 5x base LR (gate parameters need fast discovery to find optimal opening)
working_memory: 5x base LR (WM modules need fast adaptation to learn temporal patterns)
sigma2: 0.05x base LR (precision calibration must be slow to avoid oscillation)
neuromod: 0.3x base LR (neuromodulatory signals represent slow biological timescales)
other: 1x base LR (standard neocortical learning rate)
This creates a self-regulating training system that automatically focuses learning on the model’s weak points, prevents gradient explosion/vanishing via homeostatic feedback, consolidates difficult patterns through sleep replay, and maintains stability across widely different module types through differentiated learning rates. No prior PEFT or fine-tuning method implements any homeostatic training feedback, any dopamine-weighted per-token learning, or any differentiated multi-group learning rates for biologically-motivated module types.
4. Description of the Figures
FIG. 1 is a system architecture diagram illustrating the overall NCT-Adapt wrapper system, showing the frozen backbone model, per-layer NCTAdaptBlock wrapping with capped gated residual, global working memory hook, neuromodulatory gate chain, frozen LM head, and hallucination detection output, with parameter budget annotations (frozen ~1.1B, trainable ~77M, 7% overhead).
FIG. 2 is a flowchart illustrating the nine-step per-block processing chain within each NCTAdaptBlock, showing: (1) frozen layer forward pass, (2) float32 cast, (3) signal conditioning chain (StochasticResonance, RepetitionSuppression, LCEventBoundary, PrefrontalContextGate), (4) shared module pass (ChandelierVetoGate, EndocannabinoidGate, ACCConflictMonitor), (5) inhibitory triad, (6) StriatalConfidenceGate, (7) UncertaintyHead, (8) capped gated residual, (9) dtype cast back, with X_frozen bypass path.
FIG. 3 is a diagram illustrating the capped gated residual mechanism, showing the alpha_max = 0.1 fixed non-learnable structural constant, the gate computation alpha = alpha_max * sigmoid(gate_raw), the blend formula X_output = X_frozen + alpha * (X_nct - X_frozen), and a compounding analysis table comparing NCT-Adapt (safe: 1.12x to 7.4x) against uncapped LoRA (catastrophic: 31,382x) and Adapters (catastrophic: 4.2Mx) across L=22 layers.
FIG. 4 is a flowchart illustrating the inhibitory triad operating on the correction signal in mandated non-commutative order: Step 1 SST Martinotti suppression (dendritic inhibition, Theorem 46), Step 2 VIP Disinhibitory release (disinhibition of SST, Theorem 38), Step 3 Apical Amplification (BAC firing coincidence detection, Theorem 40), with biological annotations and non-commutativity proof reference (Claim 17).
FIG. 5 is a diagram illustrating the global working memory hook architecture, showing the register_forward_hook / try-finally mechanism on the frozen final LayerNorm, the seven working memory modules in order (CerebellarTiming, NMDAAttractorSlots, ThetaPhasePrecession, ThetaGammaPAC, ActivitySilentTrace, PhonologicalLoop, TimeCellBank), with temporal hierarchy annotations and key properties (zero permanent modification, removable).
FIG. 6 is a dual-panel diagram illustrating: (left) the UncertaintyHead forward path from input through LayerNorm, linear projection (zero-initialized), sigmoid-bounded gamma parameterization, to sigma-squared output; (right) the training losses including free energy loss with analytical equilibrium proof (sigma-squared = MSE), asymmetric boundary loss with free zone [0.3, 4.0], and total loss formula; with prior art comparison.
FIG. 7 is a flowchart illustrating the end-to-end hallucination detection pipeline during inference: Step 1 single forward pass, Step 2 aggregate uncertainty across L layers, Step 3 per-position thresholding with conservative/balanced/aggressive options, Step 4 span-level hallucination alert aggregation, with an example output visualization showing token-level sigma-squared values and flagged hallucination span.
FIG. 8 is a diagram illustrating the self-regulating training system, showing: the three-component loss function (DA-weighted NTP, free energy, boundary), the mandated gradient processing order (global clip FIRST, BCM SECOND, astrocyte THIRD), five differentiated learning rate groups with 100x ratio between gates and sigma-squared, and post-step maintenance (EMA update, synaptic scaling, sleep buffer, sleep replay with GradScaler state preservation).
FIG. 9 is a taxonomy diagram organizing all thirty (30) brain-inspired modules into four categories: twelve per-block modules (instantiated at each of L layers), seven global working memory modules (applied via forward hook), eight neuromodulatory modules (applied during loss/neuromod computation), and three training system modules (applied during optimization), with processing order, temporal hierarchy, hook properties, and parameter summary annotations.
FIG. 10 is a results table and bar chart presenting experimental results comparing base TinyLlama-1.1B against NCT-Adapt after 5000 training steps: NTP accuracy +3.5% (0.477 to 0.512), hallucination AUROC from 0.500 random to 0.917, Val PPL improved 10.4 to 9.8, novel capabilities (PCC=0.459, Trust Alignment=0.433, Uncertainty Gap=1.878), gate self-regulation to 1.02%, and stability guarantees (zero NaN, zero degradation, identity test passed).
5. Figures
6. Detailed Description
Section A: Overall System Architecture
A.1 System Overview
NCT-Adapt wraps a pre-trained Transformer-based Large Language Model (LLM) with the following structure. The system is demonstrated on TinyLlama-1.1B (22 transformer layers, hidden dimension 2048, 32 attention heads, intermediate size 5632, vocabulary size 32000) but is designed to be applied to any Transformer-based LLM including but not limited to LLaMA, Mistral, GPT, Falcon, Phi, Qwen, and Gemma families.
A.2 Frozen Backbone
The base model is loaded with all parameters frozen:
base_model = AutoModelForCausalLM.from_pretrained(model_name, dtype=backbone_dtype)
for p in base_model.parameters():
p.requires_grad = FalseThe backbone dtype is typically float16 for GPU deployment or float32 for CPU/MPS. ALL trainable NCT parameters are maintained in float32 for numerical stability, with explicit dtype casting at the boundary between frozen and trainable computations.
A.3 Configuration Derivation
The NCT configuration is automatically derived from the base model’s architecture:
d = llama_config.hidden_size # 2048 for TinyLlama L = llama_config.num_hidden_layers # 22 for TinyLlama H = llama_config.num_attention_heads # 32 for TinyLlama d_ff = llama_config.intermediate_size # 5632 for TinyLlama V = llama_config.vocab_size # 32000 for TinyLlama
This automatic configuration enables the system to be applied to ANY Transformer-based LLM without architecture-specific code changes. The wrapper modules dynamically size their internal projections based on the hidden dimension d.
A.4 Shared Module Instantiation
Three module types are instantiated ONCE and shared across all L layers to reduce parameter count while maintaining per-layer specificity:
ChandelierVetoGate: Contains a single set of veto detection weights (W_veto_in: d -> 64, W_veto_out: 64 -> 1) shared across all layers, with a per-layer block_bias parameter (shape: (L), initialized to 5.0) that provides layer-specific veto thresholds.
StriatalConfidenceGate: Contains a single confidence probe (W_probe: d -> 1) shared across all layers, with a per-layer bias parameter (shape: (L), initialized to 3.0) that provides layer-specific confidence thresholds.
BasalGangliaSelector: Contains shared D1 and D2 pathway projections (W_D1_in: d -> 256, W_D1_out: 256 -> K, W_D2_in: d -> 256, W_D2_out: 256 -> K) with per-layer gate_raw parameters (shape: (L), initialized to -2.0).
A.5 Per-Layer Wrapping
Each of the L frozen transformer layers is wrapped with an NCTAdaptBlock:
for i in range(L):
wrapped = NCTAdaptBlock(
frozen_layer=base_model.model.layers[i],
layer_idx=i,
cfg=cfg,
chandelier=shared_chandelier,
striatal=shared_striatal,
bg_selector=shared_bg_selector,
)
base_model.model.layers[i] = wrappedEach NCTAdaptBlock contains its OWN instances of: StochasticResonance, RepetitionSuppression, LCEventBoundary, PrefrontalContextGate, ACCConflictMonitor, EndocannabinoidGate, UncertaintyHead, SSTMartinotti, VIPDisinhibitoryGate, ApicalAmplification. Plus references to the three shared modules.
A.6 Global Module Instantiation
Global modules are instantiated once on the NCTAdaptModel:
CerebellarTiming, NMDAAttractorSlots, ThetaPhasePrecession, ThetaGammaPAC, ActivitySilentTrace, PhonologicalLoop, TimeCellBank (working memory, applied via forward hook)
D1D2InvertedU, TonicDATemperature, TripartiteAChGate, SurpriseWeightingGate (neuromodulatory, applied during loss computation)
ThalamicRelay (n_groups = max(1, L//4) frequency groups), ThalamicReticularFilter (top-down attention filter)
A.7 Identity-at-Initialization Guarantee
At training step zero, the system is designed to produce outputs IDENTICAL to the base model:
nct_gate_raw is initialized to -3.0: alpha = 0.1 * sigmoid(-3.0) = 0.1 * 0.047 = 0.0047
ALL output projection weights (W_timing_out, W_error, W_out, W_pulse, W_rs_out, W_sst_out, W_vip_out, W_gain, W_project, W_read, W_retrieve, W_pac, W_suppress, W_mod_out, W_ctx_out, W_control, W_temp, W_tri_combine) are initialized to ZERO
All gate_raw parameters are initialized to -2.0: sigmoid(-2.0) = 0.12, but multiplied by zero-init output weights = zero contribution
ChandelierVetoGate block_bias initialized to 5.0: sigmoid(5.0) = 0.993, meaning pass_prob starts near 1.0 (pass-through)
StriatalConfidenceGate bias initialized to 3.0: gate starts near identity
Therefore: X_output = X_frozen + 0.0047 * (approximately_zero) = X_frozen within floating-point precision.
This identity property is VERIFIED by running an explicit identity test:
# Test 1: Fully disabled (gate_raw = -100) base_logits = base_model(input_ids) adapt.set_all_gates(-100.0) adapt_logits = adapt(input_ids) assert max_diff(base_logits, adapt_logits) < 1e-3 # PASS # Test 2: Default init (gate_raw = -2.0 for modules, -3.0 for blend) adapt.restore_gates() adapt_logits = adapt(input_ids) assert mean_diff(base_logits, adapt_logits) < 5.0 # PASS
Measured results: Test 1 max diff < 1e-3 (PASS), Test 2 mean diff < 5.0 (PASS).
A.8 Parameter Budget
For TinyLlama-1.1B backbone:
Frozen parameters: ~1,100,000,000 (1.1B)
Trainable NCT parameters: ~77,000,000 (77M)
Overhead: 77M / 1100M = 7.0% (less than 10%)
Gate convergence: alpha = 0.0102 (1.02% actual influence per layer after 5000 steps)
Section B: NCTAdaptBlock: Per-Block Processing Chain
B.1 Forward Pass Overview
The forward pass of each NCTAdaptBlock follows this EXACT sequence. The ordering is mandated and non-commutative, reordering modules changes the computation:
Input: hidden_states (from previous layer or embedding)
# STEP 1: FROZEN PASS -- no gradient, preserves base model exactly
with torch.no_grad():
X_frozen = frozen_layer(
hidden_states.to(frozen_dtype),
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
position_embeddings=position_embeddings,
)
if isinstance(X_frozen, tuple): X_frozen = X_frozen[0]
# STEP 2: CAST TO FLOAT32 for numerical stability of NCT modules
X = X_frozen.float()
X_in = hidden_states.float() # save input for correction signal
# STEP 3: SIGNAL CONDITIONING CHAIN
X = stochastic_resonance(X) # Thm 48: learnable noise injection
X = rep_suppression(X) # Thm 45: anti-Hebbian novelty amp
X = lc_boundary(X) # Thm 43: context shift detection
X = pfc_gate(X) # Prefrontal context modulation
# STEP 4: SHARED MODULE PASS
X = chandelier(X_in, X, layer_idx) # Thm 41: output veto
X = ecb_gate(X) # Thm 49: retrograde suppression
X = acc_conflict(X) # Thm 39: conflict detection
# STEP 5: INHIBITORY TRIAD (NON-COMMUTATIVE ORDER)
correction = X - X_in # compute correction signal
correction = sst_martinotti(X_in, correction) # Thm 46: SST suppress
correction = vip_disinhibit(X_in, correction) # Thm 38: VIP release
correction = apical_amp(X_in, correction) # Thm 40: amplify
X_nct = X_in + correction
# STEP 6: STRIATAL CONFIDENCE GATE
X_nct = striatal(X_in, X_nct, layer_idx) # Thm 30: confidence routing
# STEP 7: UNCERTAINTY ESTIMATION
sigma2, log_gamma = uncertainty_head(X_nct)
store sigma2 and log_gamma for loss computation
# STEP 8: CAPPED GATED RESIDUAL (KEY STRUCTURAL INNOVATION)
alpha = 0.1 * sigmoid(nct_gate_raw) # alpha_max = 0.1 FIXED
nct_delta = X_nct - X_frozen
X_output = X_frozen + alpha * nct_delta
# STEP 9: CAST BACK to frozen dtype
Output: X_output.to(frozen_dtype)
B.2 Step 3 Module Details: Signal Conditioning Chain
B.2.1 StochasticResonance (Theorem 48)
Biological basis: Stochastic resonance is the phenomenon where weak subthreshold signals in neurons are amplified by the addition of an optimal level of noise. Unlike dropout (which sets activations to zero and is disabled at test time), stochastic resonance ADDS noise at a learned amplitude that is maintained at BOTH training AND inference. The noise amplitude converges to a non-zero equilibrium that enhances weak signal detection.
Architecture:
log_sigma: learnable parameter, shape (d,), initialized to -0.730
gate_raw: learnable parameter, scalar, initialized to -2.0
forward(X):
gate = sigmoid(gate_raw)
sigma = exp(-7.0 + 12.3 * sigmoid(log_sigma)) # bounded noise amplitude
noise = randn_like(X) * sigma # Gaussian noise
return X + gate * noise
The parameterization exp(-7.0 + 12.3 * sigmoid(log_sigma)) bounds the noise amplitude to the range [exp(-7.0), exp(5.3)] = [9.1e-4, 200.3], with initialization at exp(-7.0 + 12.3 * sigmoid(-0.730)) = exp(-7.0 + 12.3 * 0.325) = exp(-3.0) = 0.050. The gate further scales this by sigmoid(-2.0) = 0.12, giving initial effective noise amplitude of approximately 0.006.
The key distinction from dropout: dropout is multiplicative (sets activations to zero), is disabled at inference, and has fixed probability. Stochastic resonance is additive (adds noise), is ACTIVE at inference, has learned amplitude, and converges to a beneficial non-zero level. The noise amplitude is a diagnostic: _noise_amp tracks gate * sigma for monitoring.
B.2.2 RepetitionSuppression (Theorem 45)
Biological basis: Neurons in visual and temporal cortex show decreased response to repeated stimuli and increased response to novel stimuli. This anti-Hebbian mechanism ensures that the network allocates representational capacity to new information rather than redundantly encoding repeated patterns.
Architecture:
W_rs_in: Linear(d, 16, bias=False)
W_rs_out: Linear(16, d, bias=False) # initialized to ZERO
rs_norm: LayerNorm(d)
gate_raw: scalar, initialized to -2.0
forward(X):
X_n = rs_norm(X)
X_prev = concat([X_n[:, :1, :], X_n[:, :-1, :]], dim=1) # shift right
delta = X_n - X_prev # change signal
novelty = gelu(W_rs_in(delta))
correction = W_rs_out(novelty) # zero at init
gate = sigmoid(gate_raw)
return X + gate * correctionThe shift-right operation creates X_prev by duplicating the first position and shifting all others one step right. The delta = X_n - X_prev captures position-to-position change: large delta = novel content, small delta = repeated content. The GELU nonlinearity passes through large changes while suppressing near-zero changes. W_rs_out is zero-initialized, ensuring identity at initialization.
B.2.3 LCEventBoundary (Theorem 43)
Biological basis: The locus coeruleus (LC) releases norepinephrine (NE) at context boundaries, moments when the statistical structure of the input changes significantly. This NE pulse acts as a “reset signal” that updates working memory representations and prepares the system for a new context. Disease mapping: damage to LC produces confabulation (inability to segment experience into episodes).
Architecture:
W_detect: Linear(d, 32, bias=False)
W_boundary: Linear(32, 1, bias=True)
W_pulse: Linear(32, d, bias=False) # initialized to ZERO
lc_norm: LayerNorm(d)
gate_raw: scalar, initialized to -2.0
forward(X):
X_n = lc_norm(X)
X_prev = concat([X_n[:, :1, :], X_n[:, :-1, :]], dim=1)
cos_sim = cosine_similarity(X_n, X_prev, dim=-1, eps=1e-6)
change = (1.0 - cos_sim).unsqueeze(-1) # 0 = same, 1 = orthogonal
features = gelu(W_detect(X_n))
boundary_logit = W_boundary(features) + 3.0 * change
boundary_prob = sigmoid(boundary_logit) # probability of boundary
pulse = W_pulse(features * boundary_prob) # NE reset pulse
gate = sigmoid(gate_raw)
_boundary_signal = boundary_prob.detach().mean() # diagnostic
return X + gate * pulse
The cosine similarity between consecutive positions detects content shifts. The 3.0 * change term biases the boundary detector toward positions with large representational change. The boundary_prob modulates the feature extraction, and the resulting pulse is projected back to the full hidden dimension. Diagnostics track mean boundary probability across positions.
B.2.4 PrefrontalContextGate (Prefrontal Cortex Top-Down Modulation)
Biological basis: The prefrontal cortex (PFC) maintains task-relevant context and modulates downstream processing via top-down signals. This module computes a sequence-level context vector and uses it to multiplicatively modulate each position’s representation.
Architecture:
W_ctx_in: Linear(d, 128, bias=False)
W_ctx_out: Linear(128, d, bias=False) # initialized to ZERO
W_mod_in: Linear(d, 128, bias=False)
W_mod_out: Linear(128, d, bias=False) # initialized to ZERO
pfc_norm: LayerNorm(d)
gate_raw: scalar, initialized to -2.0
forward(X):
X_n = pfc_norm(X)
context = X_n.mean(dim=1) # sequence-level context, shape (B, d)
ctx = W_ctx_out(gelu(W_ctx_in(context)))
modulation = tanh(W_mod_out(gelu(W_mod_in(ctx))))
gate = sigmoid(gate_raw)
return X * (1.0 + gate * modulation.unsqueeze(1)) # multiplicativeThe mean-pooled context vector captures the global content of the sequence. The modulation signal is bounded by tanh to [-1, 1] and scaled by the gate, then applied multiplicatively. At initialization, both W_ctx_out and W_mod_out are zero, so modulation = 0 and the output is exactly X.
B.3 Step 4 Module Details: Shared Module Pass
B.3.1 ChandelierVetoGate (Theorem 41, Shared)
Biological basis: Chandelier cells (a type of PV+ inhibitory interneuron) form synapses on the axon initial segment of pyramidal neurons, the point where action potentials are initiated. A single chandelier cell can completely VETO the output of a pyramidal neuron. This provides the most powerful inhibitory mechanism in cortex: complete output suppression. Disease mapping: chandelier cell deficit causes epilepsy (runaway excitation).
Architecture:
W_veto_in: Linear(d, 64, bias=False) # shared across layers
W_veto_out: Linear(64, 1, bias=True) # shared, initialized to ZERO
veto_norm: LayerNorm(d) # shared
block_bias: Parameter, shape (L,), init=5.0 # per-layer
forward(X_in, X_out, layer_idx):
X_n = veto_norm(X_out)
veto_logit = W_veto_out(gelu(W_veto_in(X_n)))
veto_logit = veto_logit + block_bias[layer_idx] # per-layer bias
pass_prob = sigmoid(veto_logit) # high = pass, low = veto
return X_in + pass_prob * (X_out - X_in)The block_bias initialization of 5.0 means sigmoid(5.0) = 0.993, so at initialization pass_prob is near 1.0 (nearly all signal passes through). The chandelier can learn to veto specific layers’ outputs by driving pass_prob toward 0, in which case the output reverts to X_in (the layer’s input). This is shared across all layers with per-layer bias, reducing parameter count by L-fold.
B.3.2 EndocannabinoidGate (Theorem 49)
Biological basis: Endocannabinoids are retrograde neurotransmitters released by postsynaptic neurons when their activity exceeds a threshold. They travel backward to presynaptic terminals and suppress further excitation. This provides a local, activity-dependent brake on runaway activation. Disease mapping: cannabis disrupts this system causing altered perception; MS involves endocannabinoid dysregulation.
Architecture:
threshold: Parameter, scalar, initialized to 1.0
W_suppress: Linear(1, d, bias=False) # initialized to ZERO
ecb_norm: LayerNorm(d)
gate_raw: scalar, initialized to -2.0
forward(X):
X_n = ecb_norm(X)
act_mag = X_n.detach().norm(dim=-1, keepdim=True) # .detach() = retrograde
excess = relu(act_mag - softplus(threshold)) # only above threshold
suppression = sigmoid(W_suppress(excess))
gate = sigmoid(gate_raw)
return X * (1.0 - gate * suppression)The .detach() on act_mag is critical: it implements the retrograde nature of endocannabinoid signaling. The activity magnitude is measured but does NOT propagate gradients back through the representation, the suppression acts on the forward signal based on a non-differentiable measurement of activity. The softplus(threshold) ensures the threshold is always positive. At initialization, W_suppress is zero, so suppression = sigmoid(0) = 0.5, but gate = sigmoid(-2.0) = 0.12, giving minimal suppression.
B.3.3 ACCConflictMonitor (Theorem 39)
Biological basis: The anterior cingulate cortex (ACC) monitors for response conflict, situations where multiple incompatible responses are simultaneously active. High conflict triggers increased cognitive control. Disease mapping: ACC damage causes OCD (perseveration) or abulia (decision paralysis).
Architecture:
n_channels = 8
W_probe: Linear(d, n_channels * 5, bias=False)
W_control: Linear(n_channels * 5 + 1, d, bias=False) # initialized to ZERO
acc_norm: LayerNorm(d)
gate_raw: scalar, initialized to -2.0
forward(X):
X_n = acc_norm(X)
probed = W_probe(X_n) # shape (B, T, 40)
channels = probed.reshape(B, T, 8, 5) # 8 channels of 5 dims
energy = channels.pow(2).sum(dim=-1) # per-channel energy
probs = softmax(energy, dim=-1) # normalized distribution
herfindahl = probs.pow(2).sum(dim=-1, keepdim=True) # concentration index
conflict = 1.0 - herfindahl # high = many active = conflict
combined = concat([probed, conflict], dim=-1)
control = tanh(W_control(combined))
gate = sigmoid(gate_raw)
return X * (1.0 + gate * control)
The Herfindahl index (sum of squared probabilities) measures concentration: if one channel dominates, herfindahl = 1.0 and conflict = 0.0. If energy is equally distributed across all 8 channels, herfindahl = 1/8 = 0.125 and conflict = 0.875. The conflict signal is concatenated with the probed features and projected to produce a multiplicative control signal bounded by tanh.
B.4 Step 5: Inhibitory Triad (NON-COMMUTATIVE ORDER)
The inhibitory triad implements the complete PV+/SST+/VIP+ interneuron circuit of biological cortex. The ordering is biologically mandated and mathematically non-commutative:
SST Martinotti FIRST: Suppresses the correction signal at the dendritic level (prevents overwriting of existing representations)
VIP Disinhibitory SECOND: Releases the SST suppression where top-down signals indicate relevance (enables selective updating)
Apical Amplification THIRD: Amplifies the surviving correction via BAC (backpropagation-activated calcium) firing coincidence detection
Applying these in a different order produces DIFFERENT outputs. The biological order is: suppression -> selective release -> amplification. This is the only correct computational order.
B.4.1 SSTMartinotti (Theorem 46)
Biological basis: SST+ (somatostatin-positive) Martinotti cells are inhibitory interneurons that form synapses on the apical dendrites of pyramidal neurons. They suppress TOP-DOWN input (correction signals) rather than bottom-up signals. Disease mapping: SST deficit causes generalized anxiety disorder (GAD), inability to suppress irrelevant corrections.
Architecture:
W_sst_in: Linear(d, 32, bias=False)
W_sst_out: Linear(32, d, bias=False) # initialized to ZERO
sst_norm: LayerNorm(d)
gate_raw: scalar, initialized to -2.0
forward(X_bu, correction):
X_n = sst_norm(X_bu) # normalize BOTTOM-UP input
sst_activity = sigmoid(W_sst_out(gelu(W_sst_in(X_n))))
gate = sigmoid(gate_raw)
_suppression = (gate * sst_activity).detach().mean() # diagnostic
return correction * (1.0 - gate * sst_activity)CRITICAL SEMANTICS: high sst_activity = MORE suppression (not less). The output is correction * (1.0 - suppression_amount), so when sst_activity is high, the correction is reduced. The SST module looks at the bottom-up input X_bu to decide how much to suppress the correction, it does NOT look at the correction itself, matching the biological circuit where SST cells respond to feedforward drive, not feedback.
B.4.2 VIPDisinhibitoryGate (Theorem 38)
Biological basis: VIP+ (vasoactive intestinal peptide) interneurons inhibit SST cells, thereby disinhibiting pyramidal neurons. When VIP is active, it “releases” the SST suppression, allowing top-down corrections to pass through. This is the mechanism by which attention and expectation can selectively enable learning. Disease mapping: VIP dysfunction contributes to autism spectrum disorder (impaired top-down modulation).
Architecture:
W_vip_in: Linear(d, 64, bias=False)
W_vip_out: Linear(64, d, bias=False) # initialized to ZERO
vip_norm: LayerNorm(d)
gate_raw: scalar, initialized to -2.0
forward(X_bu, correction):
X_n = vip_norm(X_bu) # normalize BOTTOM-UP input
vip_response = sigmoid(W_vip_out(gelu(W_vip_in(X_n))))
gate = sigmoid(gate_raw)
return correction * (1.0 + gate * vip_response)VIP AMPLIFIES the correction (1.0 + …), counteracting SST’s suppression (1.0 - …). The net effect of SST followed by VIP is selective gating: positions where SST suppresses AND VIP does not release remain suppressed; positions where VIP releases allow the correction through. This implements biological selective attention at the circuit level.
B.4.3 ApicalAmplification (Theorem 40)
Biological basis: BAC (Backpropagation-Activated Calcium) firing occurs when bottom-up (basal) and top-down (apical) signals are simultaneously active at a pyramidal neuron. This coincidence detection amplifies corrections that are consistent with both bottom-up evidence and top-down expectations. Disease mapping: loss of BAC firing corresponds to loss of consciousness under anesthesia.
Architecture:
W_basal: Linear(d, 128, bias=False)
W_apical: Linear(d, 128, bias=False)
W_gain: Linear(128, d, bias=False) # initialized to ZERO
ap_norm: LayerNorm(d)
gate_raw: scalar, initialized to -2.0
forward(X_bu, correction):
X_n = ap_norm(X_bu) # bottom-up evidence
basal = sigmoid(W_basal(X_n)) # basal compartment response
apical = sigmoid(W_apical(correction)) # apical compartment response
coincidence = basal * apical # element-wise AND operation
gain = sigmoid(W_gain(coincidence)) # amplification factor
gate = sigmoid(gate_raw)
return correction * (1.0 + gate * gain)
The coincidence = basal * apical implements a soft AND: both basal AND apical must be active for coincidence to be large. This gain is applied multiplicatively to the correction. At initialization, W_gain is zero, so gain = sigmoid(0) = 0.5, but gate = sigmoid(-2.0) = 0.12, giving minimal amplification.
B.5 Step 6: StriatalConfidenceGate (Theorem 30, Shared)
Biological basis: The striatum (basal ganglia) implements automaticity, actions that have been well-practiced are executed via the “direct pathway” (D1) without cortical deliberation, while novel actions require cortical involvement. This gate routes information based on confidence: high-confidence representations pass through with minimal NCT modification; low-confidence representations receive more NCT processing.
Architecture:
probe: Linear(d_model, 1, bias=False) # initialized to ZERO
bias: Parameter, shape (n_layers,), init=3.0
forward(X_in, X_out, layer_idx):
conf = probe(X_in.detach()) # .detach() = no grad through probe input
gate = sigmoid(bias[layer_idx] - conf) # high conf -> low gate -> more X_in
return gate * X_out + (1.0 - gate) * X_in
With bias initialized to 3.0 and probe weights at zero, the initial gate = sigmoid(3.0) = 0.953, so the output is approximately X_out (passes NCT processing through). As training progresses, the probe learns to identify confident representations, and the gate routes them toward X_in (bypass NCT), while uncertain representations continue to receive NCT processing.
B.6 Step 7: UncertaintyHead
Architecture:
norm: LayerNorm(d_model)
proj: Linear(d_model, 1) # weight and bias initialized to ZERO
gamma_min = -3.0 # sigma_max = exp(3.0) = 20.09
gamma_max = 3.0 # sigma_min = exp(-3.0) = 0.050
forward(X):
raw = proj(norm(X))
gamma = gamma_min + (gamma_max - gamma_min) * sigmoid(raw)
sigma2 = exp(-gamma)
return sigma2, gammaThe sigmoid-bounded parameterization ensures:
gamma is always in [gamma_min, gamma_max] = [-3.0, 3.0]
sigma_squared is always in [exp(-3.0), exp(3.0)] = [0.050, 20.09]
No division by zero is possible (sigma_squared >= 0.050)
No overflow is possible (sigma_squared <= 20.09)
The initial output (with zero weights) is gamma = gamma_min + (gamma_max - gamma_min) * 0.5 = 0.0, giving sigma_squared = exp(0) = 1.0
B.7 Step 8: Capped Gated Residual
alpha = alpha_max * sigmoid(nct_gate_raw) nct_delta = X_nct - X_frozen X_output = X_frozen + alpha * nct_delta
Where alpha_max = 0.1 is a FIXED, NON-LEARNABLE constant (not a parameter, not a buffer, a Python float literal in the code). The gate_raw is a learnable scalar parameter initialized to -3.0.
Compounding analysis for L = 22 layers:
Maximum per-layer deviation factor: (1 + alpha_max) = 1.1
Maximum cumulative deviation: (1.1)^22 = 7.40
At converged gate (alpha = 0.01): (1.01)^22 = 1.24
For comparison, uncapped alpha = 0.5: (1.5)^22 = 31,382 (catastrophic)
The capped gate provides a mathematical certificate that the wrapped model’s output is within a bounded multiplicative factor of the frozen model’s output, regardless of training duration or gradient magnitudes.
Section C: Global Modules (Applied Once, Not Per-Block)
C.1 Working Memory Hook Architecture
Seven working memory modules are applied via a single forward hook on the base model’s final LayerNorm:
def wm_hook(module, input, output):
orig_dtype = output.dtype
h = output.float() # cast to float32 for numerical stability
h = cerebellar(h) # temporal prediction
h = nmda_slots(h) # persistent attractor WM
h = theta_precession(h) # phase coding
h = theta_gamma_pac(h) # phase-amplitude coupling
h = silent_trace(h) # synaptic facilitation
h = phono_loop(h) # cyclic rehearsal
h = time_cells(h) # temporal receptive fields
wm_hidden_ref[0] = h # save for neuromodulation
return h.to(orig_dtype) # cast back to frozen dtype
hook_handle = base_model.model.norm.register_forward_hook(wm_hook)
try:
output = base_model(input_ids)
finally:
hook_handle.remove() # ALWAYS remove, even on exception
The try/finally ensures the hook is removed even if the forward pass raises an exception. This guarantees that the base model is never permanently modified.
C.2 CerebellarTiming (Theorem 24)
Biological basis: The cerebellum generates precise temporal predictions by computing the expected next state and correcting based on prediction error. Cerebellar damage (spinocerebellar ataxia) causes speech timing errors and motor coordination failure. In language, the cerebellum contributes to prosody, syntactic prediction, and temporal coherence.
Architecture:
W_timing_in: Linear(d, d, bias=False)
W_timing_out: Linear(d, d, bias=False) # initialized to ZERO
W_error: Linear(d, d, bias=False) # initialized to ZERO
timing_norm: LayerNorm(d)
gate_raw: scalar, initialized to -2.0
forward(X): # X shape: (B, T, d)
X_n = timing_norm(X)
X_cb = W_timing_in(X_n) # project to cerebellar space
X_pred = X_cb[:, :-1, :] # predicted: positions 0..T-2
X_actual = X_cb[:, 1:, :].detach() # actual: positions 1..T-1 (no grad)
error = X_pred - X_actual # prediction error
padded_error = pad(error, (0, 0, 1, 0)) # pad first position with zero
correction = W_timing_out(X_cb) + W_error(padded_error)
gate = sigmoid(gate_raw)
return X + gate * correction
compute_loss(X, sigma2_top):
# Precision-weighted temporal prediction loss
X_n = timing_norm(X)
X_cb = W_timing_in(X_n)
error = (X_cb[:, :-1, :] - X_cb[:, 1:, :].detach()).pow(2).sum(dim=-1, keepdim=True)
weights = 1.0 / sigma2_top[:, 1:, :].float().detach()
weights = weights / weights.mean().clamp(min=1e-6)
return (weights * error).mean()
The .detach() on X_actual prevents the gradient from flowing backward through the “future” representation, the cerebellum learns to predict the future from the past, not to modify the future to match predictions. The precision weighting by 1/sigma_squared means the cerebellar loss focuses on positions where the model is confident (low sigma_squared = high precision = high weight).
C.3 NMDAAttractorSlots (Theorem 31)
Biological basis: NMDA receptors in prefrontal cortex support persistent neural activity through recurrent excitation, creating “attractor states” that maintain information in working memory without external input. The NMDA receptor’s slow kinetics (decay time constant ~100ms vs ~10ms for AMPA) enable sustained activity. Disease mapping: NMDA receptor hypofunction (as in schizophrenia) causes working memory failure.
Architecture:
d_attn = 128
W_k: Linear(d, 128, bias=False) # key projection
W_v: Linear(d, 128, bias=False) # value projection
W_q: Linear(d, 128, bias=False) # query projection
W_out: Linear(128, d, bias=False) # initialized to ZERO
W_gate: Linear(d, 1, bias=True) # write gate, bias=-2.0
nmda_norm: LayerNorm(d)
decay_bias: Parameter, scalar, init=6.0 # sigmoid(6.0) = 0.997 = slow decay
gate_raw: scalar, init=-2.0
forward(X): # X shape: (B, T, d)
X_n = nmda_norm(X)
K = elu(W_k(X_n)) + 1.0 # positive keys (ELU+1 = positive-definite)
V = W_v(X_n) # values
Q = elu(W_q(X_n)) + 1.0 # positive queries
g_w = sigmoid(W_gate(X_n)) # per-position write gate
a = sigmoid(decay_bias) # decay rate, initially 0.997
# Sequential scan (linear attention with decay)
S = zeros(B, 128, 128) # state matrix
z = zeros(B, 128) # normalizer
for t in range(T):
# READ: query current state
num = S @ q_t # (B, 128)
den = (z * q_t).sum(-1).clamp(min=1e-8)
out_t = num / den
# WRITE: update state with gated outer product
write = g_w_t * (k_t outer v_t)
S = a * S + write # decay old + add new
z = a * z + g_w_t * k_t # update normalizer
correction = W_out(outputs) # zero at init
gate = sigmoid(gate_raw)
return X + gate * correction
The sequential scan implements linear attention with exponential decay (NMDA-like slow kinetics). The state matrix S accumulates key-value associations over time, with each new association gated by g_w (allowing selective writing). The decay rate a = sigmoid(6.0) = 0.997 means information persists for approximately 1/(-ln(0.997)) = 333 time steps, matching the NMDA receptor’s sustained activity timescale.
C.4 TimeCellBank (Theorem 32)
Biological basis: Time cells in the hippocampus and medial prefrontal cortex fire at specific temporal intervals after a triggering event. Different cells tile the temporal interval, creating a “temporal basis set” that encodes elapsed time. Disease mapping: temporal lobe epilepsy disrupts time cells, causing flat temporal gradients (inability to judge temporal distances).
Architecture:
n_cells = 32
decay_rates: buffer, shape (32,)
# Geometric spacing: tau_i = 2^(i/4), decay_i = exp(-1/tau_i)
# Covers range from tau=1.0 (fast) to tau=256.0 (slow)
W_trigger: Linear(d, 1, bias=True) # trigger detection, init ZERO
W_project: Linear(32, d, bias=False) # initialized to ZERO
tc_norm: LayerNorm(d)
gate_raw: scalar, init=-2.0
forward(X):
X_n = tc_norm(X)
trigger = sigmoid(W_trigger(X_n)) # per-position trigger probability
h = zeros(B, 32) # time cell bank state
for t in range(T):
h = decay_rates * h + trigger[:, t] # decay + trigger
basis_list.append(h)
basis = stack(basis_list, dim=1) # shape (B, T, 32)
temporal_ctx = W_project(basis) # project to hidden dim
gate = sigmoid(gate_raw)
return X + gate * temporal_ctx
The 32 time cells with geometrically spaced decay rates create a temporal basis set spanning from single-token to 256-token timescales. After a trigger event, each cell decays at its own rate, and the collection of cell activations encodes how much time has passed since the trigger. The trigger itself is learned end-to-end.
C.5 ThetaPhasePrecession (Theorem 33)
Biological basis: Hippocampal place cells fire at progressively earlier phases of the theta oscillation as an animal traverses a place field. This phase precession encodes position within a sequence relative to the theta cycle. In language, this translates to encoding position within a syntactic or semantic “field” relative to a learned oscillatory period.
Architecture:
r = 32 # projection rank
W_content: Linear(d, 32, bias=False)
W_phase: Linear(2, 32, bias=False)
W_out: Linear(32, d, bias=False) # initialized to ZERO
theta_norm: LayerNorm(d)
period_raw: Parameter, scalar, init=5.3 # softplus(5.3) = 5.3 tokens
gate_raw: scalar, init=-2.0
forward(X):
X_n = theta_norm(X)
period = softplus(period_raw) # always positive
pos = arange(T) # 0, 1, ..., T-1
phase = 2*pi * pos / period # phase within theta cycle
phase_emb = stack([sin(phase), cos(phase)], dim=-1) # (T, 2)
content_proj = W_content(X_n) # (B, T, 32)
phase_proj = W_phase(phase_emb) # (T, 32) -> broadcast to (B, T, 32)
interaction = content_proj * phase_proj # element-wise: content * phase
modulation = tanh(W_out(interaction)) # bounded [-1, 1]
gate = sigmoid(gate_raw)
return X * (1.0 + gate * modulation) # multiplicative phase modulation
The period parameter is learnable (via softplus for positivity), allowing the system to discover the optimal oscillatory period for the task. The content * phase interaction creates position-dependent modulation that is also content-dependent, different content receives different phase modulation.
C.6 ThetaGammaPAC (Theorem 34)
Biological basis: Phase-amplitude coupling (PAC) between theta (4-8 Hz) and gamma (30-100 Hz) oscillations is a fundamental mechanism for organizing information in working memory. Gamma bursts carry content, and their amplitude is modulated by theta phase, creating temporally organized “packets” of information. Disease mapping: PAC deficit in schizophrenia causes disordered binding and loose associations.
Architecture:
W_gamma: Linear(d, 1, bias=False) # gamma amplitude detector
W_theta: Linear(d, 1, bias=False) # theta phase detector
W_pac: Linear(2, d, bias=False) # initialized to ZERO
pac_norm: LayerNorm(d)
gate_raw: scalar, init=-2.0
forward(X):
X_n = pac_norm(X)
gamma_amp = sigmoid(W_gamma(X_n)) # gamma amplitude [0, 1]
theta_phase = sigmoid(W_theta(X_n)) # theta phase [0, 1]
pac_signal = gamma_amp * cos(2*pi * theta_phase) # PAC interaction
pac_features = concat([pac_signal, gamma_amp], dim=-1) # (B, T, 2)
modulation = tanh(W_pac(pac_features)) # zero at init
gate = sigmoid(gate_raw)
return X * (1.0 + gate * modulation)
The pac_signal = gamma_amp * cos(2pi theta_phase) implements the core PAC computation: gamma amplitude is modulated by the cosine of theta phase. The result is maximized when theta_phase is at 0 or 1 (peak of theta) and minimized at theta_phase = 0.5 (trough). This creates the characteristic “nested oscillation” pattern observed in biological hippocampal recordings.
C.7 ActivitySilentTrace (Theorem 35)
Biological basis: Working memory can persist in a “silent” state through short-term synaptic facilitation, even when no neurons are actively firing. This allows information to be maintained without the metabolic cost of sustained neural activity. Disease mapping: age-related working memory decline correlates with reduced synaptic facilitation.
Architecture:
d_trace = 64
W_store: Linear(d, 64, bias=False)
W_retrieve: Linear(64, d, bias=False) # initialized to ZERO
W_gate: Linear(d, 1, bias=True) # bias=-1.0 (conservative write)
trace_norm: LayerNorm(d)
decay_bias: Parameter, scalar, init=3.0 # sigmoid(3.0) = 0.953
gate_raw: scalar, init=-2.0
forward(X):
X_n = trace_norm(X)
store_val = W_store(X_n) # what to store
g_w = sigmoid(W_gate(X_n)) # write gate
a = sigmoid(decay_bias) # decay rate
trace = zeros(B, 64) # silent trace state
for t in range(T):
trace = a * trace + g_w[:, t, :] * store_val[:, t, :]
outputs.append(trace)
retrieval = W_retrieve(stack(outputs)) # zero at init
gate = sigmoid(gate_raw)
return X + gate * retrieval
The trace variable represents synaptic facilitation, a “memory” that persists at the synapse level without active neural firing. The decay rate a = sigmoid(3.0) = 0.953 gives a half-life of approximately 14 time steps: ln(0.5)/ln(0.953) = -14.3. This is faster than NMDA (~333 steps) but slower than direct activation, filling an intermediate timescale.
C.8 PhonologicalLoop (Theorem 36)
Biological basis: Baddeley’s phonological loop is a cyclic rehearsal buffer with K slots (typically 7 +/- 2 for humans) that maintains information through continuous refreshing. Items are written to the current slot position and read by attention over all slots. Disease mapping: phonological dyslexia involves impaired phonological loop function, causing poor nonword repetition.
Architecture:
K = 8 # number of rehearsal slots
d_slot = 64 # slot dimension
W_write: Linear(d, 64, bias=False)
W_query: Linear(d, 64, bias=False)
W_read: Linear(64, d, bias=False) # initialized to ZERO
W_gate: Linear(d, 1, bias=True) # bias=-1.0
loop_norm: LayerNorm(d)
gate_raw: scalar, init=-2.0
forward(X):
X_n = loop_norm(X)
write_vals = W_write(X_n)
queries = W_query(X_n)
g_w = sigmoid(W_gate(X_n))
slots = zeros(B, 8, 64) # K=8 rehearsal slots
for t in range(T):
# READ: attention over all slots
scores = bmm(slots, q_t.unsqueeze(-1)).squeeze(-1) # (B, 8)
weights = softmax(scores, dim=-1)
read_out = (weights.unsqueeze(-1) * slots).sum(dim=1)
# WRITE: cyclic addressing (t mod K)
ptr = t % K # cyclic pointer
new_val = (1.0 - g_w_t) * slots[:, ptr, :] + g_w_t * w_t
slots[:, ptr, :] = new_val # overwrite slot at pointer
retrieval = W_read(stack(outputs)) # zero at init
gate = sigmoid(gate_raw)
return X + gate * retrieval
The cyclic pointer ptr = t % K implements the rehearsal mechanism: every K positions, the pointer wraps around and starts overwriting old content. The gated write (1 - g_w) * old + g_w * new allows partial updates, blending old and new content at each slot. The attention-based read allows any position to query any slot, enabling non-sequential retrieval.
C.9 D1D2InvertedU (Theorem 37)
Biological basis: Dopamine has opposing effects via D1 and D2 receptors, creating an inverted-U dose-response curve. Moderate dopamine levels optimize prefrontal function; too little (Parkinson’s) or too much (psychosis) impairs it. The D1 pathway supports maintenance (direct pathway), while D2 supports flexibility (indirect pathway).
Architecture:
d_proj = 64
W_proj: Linear(d, 64, bias=False)
W_da: Linear(3, 64) # 3 input features
W_out: Linear(64, d, bias=False) # initialized to ZERO
da_norm: LayerNorm(d)
gate_raw: scalar, init=-2.0
forward(X, da_signal):
X_n = da_norm(X)
X_proj = W_proj(X_n)
inverted_u = 4.0 * da * (1.0 - da) # peak at da=0.5, zero at 0 and 1
d1_signal = da # direct pathway
d2_signal = 1.0 - da # indirect pathway
da_features = concat([inverted_u, d1_signal, d2_signal], dim=-1)
da_proj = gelu(W_da(da_features))
interaction = X_proj * da_proj # content * DA interaction
modulation = tanh(W_out(interaction)) # zero at init
gate = sigmoid(gate_raw)
return X * (1.0 + gate * modulation)
The inverted_u = 4da(1-da) formula creates a parabola peaking at da=0.5 with value 1.0, and zero at da=0 and da=1. This implements the Yerkes-Dodson/inverted-U relationship where moderate arousal is optimal. The da_signal is passed as sigmoid(surprise), mapping the raw surprise signal to (0, 1) before computing D1/D2 pathways.
C.10 TonicDATemperature (Theorem 47)
Biological basis: Tonic (sustained baseline) dopamine levels in prefrontal cortex control the balance between exploration (high tonic DA = high noise tolerance) and exploitation (low tonic DA = precise execution). This is computed as a slow EMA of phasic DA signals. Disease mapping: depression corresponds to chronically low tonic DA (over-exploitation), mania to chronically high tonic DA (over-exploration).
Architecture:
W_temp: Linear(1, d, bias=False) # initialized to ZERO
gate_raw: scalar, init=-2.0
ema_da: buffer, scalar, init=0.5 # running average of DA
ema_alpha = 0.999 # very slow update
forward(X, current_da=None):
if current_da is not None:
with no_grad():
ema_da = 0.999 * ema_da + 0.001 * current_da.mean()
deviation = (ema_da - 0.5).unsqueeze(0) # deviation from baseline
temp_modulation = tanh(W_temp(deviation))
gate = sigmoid(gate_raw)
return X * (1.0 + gate * temp_modulation)The ema_alpha = 0.999 gives a time constant of 1000 steps, meaning the tonic DA signal represents the average surprise level over the last ~1000 training steps. This is the slowest-adapting module in the system, capturing long-term trends in model performance.
C.11 TripartiteAChGate (Acetylcholine + DA + sigma-squared)
Biological basis: In biological cortex, the tripartite synapse integrates signals from three sources: (1) dopamine (DA), reward prediction error / surprise, (2) acetylcholine (ACh), attentional engagement / novelty, (3) precision (1/sigma-squared), confidence in current predictions. These three orthogonal signals combine to gate plasticity and information routing.
Architecture:
d_proj = 64
W_tri_proj: Linear(d, 64, bias=False)
W_tri_in: Linear(3, 64) # 3 neuromodulatory inputs
W_tri_combine: Linear(128, d, bias=False) # initialized to ZERO (both weight and bias)
tri_norm: LayerNorm(d)
gate_raw: scalar, init=-2.0
forward(X, da, ach, sigma2):
X_n = tri_norm(X)
X_proj = W_tri_proj(X_n)
neuro = concat([da, ach, sigma2], dim=-1) # 3 signals
neuro_proj = gelu(W_tri_in(neuro))
combined = concat([X_proj, neuro_proj], dim=-1) # (B, T, 128)
modulation = tanh(W_tri_combine(combined)) # zero at init
gate = sigmoid(gate_raw)
return X * (1.0 + gate * modulation)
C.12 SurpriseWeightingGate (Per-Token Gradient Modulation)
Architecture:
d_proj = 64, d_hidden = 128
W_proj: Linear(d, 64, bias=False)
W_combine: Linear(67, 128) # 64 + 3 neuro signals
W_out: Linear(128, 1) # initialized to ZERO
swg_norm: LayerNorm(d)
gate_raw: scalar, init=-2.0
forward(X, da, ach, sigma2):
X_proj = W_proj(swg_norm(X))
combined = concat([X_proj, da, ach, sigma2], dim=-1)
hidden = gelu(W_combine(combined))
raw = W_out(hidden)
gate = sigmoid(gate_raw)
importance = 0.5 + 1.5 * sigmoid(raw) # range [0.5, 2.0]
return (1.0 - gate) * 1.0 + gate * importance
The output is a per-token importance weight in [0.5, 2.0] that modulates gradient flow. At initialization (gate = 0.12, raw = 0), the output is approximately 1.0 (uniform weighting). As training progresses, the module learns to up-weight surprising/uncertain/attention-worthy tokens and down-weight well-predicted ones.
C.13 ThalamicRelay (Frequency-Group Routing)
Biological basis: The thalamus routes information between cortical areas, with different thalamic nuclei handling different modalities and frequency bands. The reticular nucleus provides inhibitory gating that filters irrelevant relay signals. Disease mapping: thalamic infarct causes modality-specific sensory loss.
Architecture:
n_groups = max(1, L // 4) # e.g., 5 groups for 22 layers
For each group i in [0, n_groups):
relay_in[i]: Linear(d, 128, bias=False)
relay_out[i]: Linear(128, d, bias=False) # initialized to ZERO
ret_gate[i]: Linear(d, 1, bias=False)
relay_norm[i]: LayerNorm(d)
gate_raw[i]: Parameter, scalar, init=-2.0
forward(X, group_idx):
X_n = relay_norm[group_idx](X)
relay = relay_out[group_idx](gelu(relay_in[group_idx](X_n)))
ret = sigmoid(ret_gate[group_idx](X_n)) # reticular gating
gate = sigmoid(gate_raw[group_idx])
return X + gate * ret * relayC.14 ThalamicReticularFilter (Top-Down Attention Filter)
Architecture:
d_trn = 24
W_q: Linear(d, 24, bias=False) # cortical query (top-down)
W_k: Linear(d, 24, bias=False) # relay key (bottom-up delta)
trn_norm: LayerNorm(d)
gate_raw: scalar, init=-2.0
scale = 24^(-0.5)
forward(X_pre, X_post):
relay_delta = X_post - X_pre # what the relay changed
X_n = trn_norm(X_pre)
cortical_q = W_q(X_n) # what cortex is looking for
relay_k = W_k(relay_delta) # what relay provides
relevance = sigmoid((cortical_q * relay_k).sum(-1, keepdim=True) * scale)
gate = sigmoid(gate_raw)
return X_pre + (1.0 - gate + gate * relevance) * relay_delta
When gate = 0 (initialization), the output is X_pre + 1.0 * relay_delta = X_post (pass-through). As the gate opens, relevance modulates which relay changes are passed: high relevance allows the change, low relevance suppresses it.
C.15 BasalGangliaSelector (Shared, D1/D2 Column Selection)
Architecture:
d_bg = 256, K = 4 (number of columns)
W_D1_in: Linear(d, 256, bias=False)
W_D1_out: Linear(256, K, bias=False) # initialized to ZERO
W_D2_in: Linear(d, 256, bias=False)
W_D2_out: Linear(256, K, bias=False) # initialized to ZERO
bg_norm: LayerNorm(d)
gate_raw: Parameter, shape (L,), init=-2.0
forward(X, layer_idx):
X_n = bg_norm(X)
X_pool = X_n.mean(dim=1) # sequence-level representation
D1 = W_D1_out(gelu(W_D1_in(X_pool))) # direct pathway, shape (B, K)
D2 = W_D2_out(gelu(W_D2_in(X_pool))) # indirect pathway, shape (B, K)
gate = sigmoid(gate_raw[layer_idx])
bg_bias = gate * (D1 - D2) # D1 - D2 = net go/no-go per column
return bg_bias.unsqueeze(1) # shape (B, 1, K), broadcast over T
The D1 - D2 computation implements the basal ganglia’s go/no-go mechanism: D1 > D2 for a column means “activate this column” (go), D1 < D2 means “suppress this column” (no-go). This per-layer column selection bias allows different layers to specialize in different columns.
C.16 DAComputer (Dopamine-Like Prediction Error Signal)
The DAComputer is a stateless utility that computes two signals from the model’s logits and targets:
class DAComputer:
@staticmethod
def compute(logits, targets, da_scale=1.0):
# Per-token cross-entropy (prediction error)
ntp_errors = cross_entropy(logits, targets, reduction='none') # (B, T)
# Cumulative EMA of prediction error (running baseline)
cumsum = ntp_errors.cumsum(dim=1)
counts = arange(1, T+1)
ema_t = cumsum / counts # running mean at each position
# Phasic DA: prediction error relative to baseline
da_t = ntp_errors / (ema_t + 1e-6)
da_t = 3.0 * da_t / (1.0 + da_t) # Michaelis-Menten saturation
# DA weights for loss: up-weight surprising tokens
da_weights = (1.0 + da_scale * tanh(da_t - 1.0)).unsqueeze(-1)
# DA signal for neuromodulation: sigmoid surprise
da_signal = sigmoid(ntp_errors - ema_t).unsqueeze(-1)
return da_weights, da_signal # both shape (B, T, 1)
The Michaelis-Menten saturation (3.0 * x / (1 + x)) prevents extreme DA values while preserving the relative ordering. The da_weights center around 1.0: tokens with above-baseline error get weight > 1.0 (learn more), below-baseline get weight < 1.0 (learn less). The da_signal maps raw surprise to (0, 1) via sigmoid for use by neuromodulatory modules.
All computations are performed under torch.no_grad(), the DA signal modulates gradients but does not itself require gradients.
Section D: Uncertainty Head and Hallucination Detection Pipeline
D.1 Per-Block Uncertainty Estimation
Each NCTAdaptBlock contains an UncertaintyHead that produces per-position (per-token) uncertainty estimates. The architecture is:
UncertaintyHead:
norm: LayerNorm(d_model)
proj: Linear(d_model, 1) # weight=0, bias=0 at init
gamma_min = -3.0 # corresponding sigma_max = exp(3.0) = 20.09
gamma_max = 3.0 # corresponding sigma_min = exp(-3.0) = 0.050
forward(X):
raw = proj(norm(X)) # (B, T, 1)
gamma = gamma_min + (gamma_max - gamma_min) * sigmoid(raw) # bounded [-3, 3]
sigma2 = exp(-gamma) # bounded [0.050, 20.09]
return sigma2, gammaD.2 Sigmoid-Bounded Parameterization
The parameterization gamma = gamma_min + (gamma_max - gamma_min) * sigmoid(raw) ensures:
sigma_squared is ALWAYS in [exp(-gamma_max), exp(-gamma_min)] = [0.050, 20.09]
No division by zero: sigma_squared >= 0.050 always
No numerical overflow: sigma_squared <= 20.09 always
Smooth gradients: sigmoid is differentiable everywhere
At initialization (raw=0): gamma = (-3 + 3) * 0.5 = 0.0, so sigma_squared = exp(0) = 1.0
This is distinguished from:
Unconstrained parameterization (sigma_squared = softplus(raw)): can reach zero or infinity
Hard clamping (sigma_squared = clamp(raw, 0.1, 10)): zero gradient at boundaries
Log-space parameterization without bounds: requires additional clamping for numerical safety
D.3 Free Energy Loss for Uncertainty Calibration
The uncertainty is trained using a free energy loss derived from variational free energy minimization:
# Per-layer computation gamma = -log(mean_sigma2 + 1e-8) # log-precision precision = exp(gamma).clamp(max=100.0) # numerical safety clamp error_sq = (per_token_ce.detach() ** 2).unsqueeze(-1) # squared prediction error L_unc = mean(precision * error_sq - gamma) L_unc = L_unc.clamp(max=50.0) # prevent loss explosion
D.3.1 Analytical Equilibrium Proof
Setting the gradient to zero:
dL_unc/d(gamma) = precision * error_sq - 1 = 0 precision * error_sq = 1 exp(gamma) * MSE = 1 gamma = -log(MSE) sigma_squared = exp(-gamma) = MSE
Therefore, at equilibrium, the learned uncertainty sigma_squared converges EXACTLY to the mean squared prediction error MSE. This provides automatic calibration without requiring post-hoc calibration procedures (temperature scaling, Platt scaling, isotonic regression).
D.3.2 Free Energy Interpretation
The loss L_unc = precision * MSE - gamma is the variational free energy:
precision * MSE = accuracy term (penalizes high precision when error is high)
-gamma = complexity term (penalizes high precision in general, Occam’s razor)
The balance between accuracy and complexity drives sigma_squared to MSE: the model is as confident as its actual prediction accuracy warrants, no more and no less.
D.4 Asymmetric Boundary Loss
L_bound = mean(relu(0.3 - sigma2).pow(2) + relu(sigma2 - 4.0).pow(2))
This creates a FREE ZONE [0.3, 4.0] where NO penalty is applied:
sigma_squared in [0.3, 4.0]: L_bound = 0 (full freedom)
sigma_squared < 0.3: quadratic penalty (relu(0.3 - sigma2)^2)
sigma_squared > 4.0: quadratic penalty (relu(sigma2 - 4.0)^2)
The quadratic form (not linear) ensures smooth gradients near the boundary. The asymmetric boundaries reflect the different costs: too-low sigma_squared (overconfidence) is dangerous for hallucination detection, while too-high sigma_squared (underconfidence) wastes the model’s knowledge.
D.5 Per-Position Uncertainty Aggregation
During inference, uncertainty estimates from all L layers are aggregated:
sigma2_list = [layer._sigma2 for layer in model.base_model.model.layers
if hasattr(layer, '_sigma2') and layer._sigma2 is not None]
mean_sigma2 = torch.stack(sigma2_list).mean(dim=0) # average across layers
# mean_sigma2 shape: (B, T, 1)Each position t in each batch element b has a scalar uncertainty estimate mean_sigma2[b, t, 0] that represents the model’s confidence in its prediction at that position.
D.6 Hallucination Detection via Uncertainty
D.6.1 AUROC Computation
The hallucination detection AUROC is computed by treating the uncertainty as a binary classifier:
Positive class: incorrect predictions (logits.argmax(-1) != labels)
Negative class: correct predictions (logits.argmax(-1) == labels)
Score: mean_sigma2 (higher sigma_squared = more uncertain = predicts “incorrect”)
# Evaluation preds = logits.argmax(dim=-1) correct = (preds == labels).float() # 1.0 = correct, 0.0 = wrong s2 = mean_sigma2.squeeze(-1) # per-position uncertainty # AUROC: how well does sigma2 separate correct from incorrect? # Measured: AUROC = 0.917
An AUROC of 0.917 means that if we randomly pick one correct prediction and one incorrect prediction, the incorrect prediction has higher sigma_squared 91.7% of the time. This enables reliable hallucination flagging: positions with sigma_squared above a threshold are flagged as potential hallucinations.
D.6.2 Confidence-Accuracy Alignment (CAA)
median_s2 = s2.median() high_conf = (s2 < median_s2) # lower sigma2 = higher confidence low_conf = (s2 >= median_s2) high_conf_acc = correct[high_conf].mean() # accuracy when model is confident low_conf_acc = correct[low_conf].mean() # accuracy when model is uncertain CAA = high_conf_acc - low_conf_acc # positive = well-calibrated
A positive CAA means the model is more accurate when it claims to be confident, the uncertainty is genuinely informative. Measured: CAA is positive, confirming calibration.
D.6.3 Precision-Confidence Correlation (PCC)
s2_centered = s2 - s2.mean() ce_centered = per_token_ce - per_token_ce.mean() PCC = (s2_centered * ce_centered).mean() / (s2_centered.std() * ce_centered.std())
PCC measures the Pearson correlation between sigma_squared and actual cross-entropy loss. A positive PCC means higher uncertainty corresponds to higher actual error. Measured: PCC = 0.459 (strong positive correlation).
D.6.4 Trust Alignment Score
The trust alignment score measures how well sigma_squared tracks the actual prediction error distribution across the full range of uncertainty values, not just at the median split. It is computed by binning positions by sigma_squared decile and checking that error increases monotonically with uncertainty.
D.6.5 Uncertainty Gap
The uncertainty gap measures the separation between sigma_squared distributions for correct vs. incorrect predictions:
s2_correct = s2[correct == 1.0] s2_incorrect = s2[correct == 0.0] uncertainty_gap = s2_incorrect.mean() - s2_correct.mean()
Measured: uncertainty_gap = 1.878, meaning incorrect predictions have substantially higher sigma_squared on average.
D.7 Base PPL Comparison via Gate Disabling
The system provides a principled method to measure the base model’s performance by temporarily disabling all NCT gates:
def compute_base_ppl(model, val_loader):
# Save all gate_raw values
saved_gates = {}
for name, p in model.named_parameters():
if "gate_raw" in name:
saved_gates[name] = p.data.clone()
p.data.fill_(-100.0) # sigmoid(-100) = 0 for all practical purposes
# Evaluate with gates disabled (= pure base model)
base_ppl = evaluate_ppl(model, val_loader)
# Restore gates
for name, p in model.named_parameters():
if name in saved_gates:
p.data.copy_(saved_gates[name])
return base_ppl
This allows measuring the exact contribution of the NCT wrapper without requiring a separate base model instance. Setting gate_raw = -100 makes sigmoid(-100) = 3.7e-44, effectively zero, disabling all NCT contributions.
Section E: Training System
E.1 Loss Function
The total training loss combines three components:
L_total = L_NTP_weighted + lambda_unc * L_unc + lambda_bound * L_bound
where:
lambda_unc = 0.01 (uncertainty loss weight)
lambda_bound = 0.1 (boundary loss weight)E.1.1 Dopamine-Weighted Next-Token Prediction Loss
per_token_ce = cross_entropy(logits, labels, ignore_index=-1, reduction='none') # per_token_ce shape: (B, T) L_NTP = (per_token_ce * da_weights.squeeze(-1)).mean()
The da_weights (computed by DAComputer) up-weight surprising tokens and down-weight well-predicted tokens, implementing prediction-error-driven learning.
E.1.2 Free Energy Uncertainty Loss
sigma2_stack = torch.stack(sigma2_list) # (L, B, T, 1) mean_sigma2 = sigma2_stack.mean(dim=0) # (B, T, 1) error_sq = (per_token_ce.detach() ** 2).unsqueeze(-1) gamma = -log(mean_sigma2 + 1e-8) precision = exp(gamma).clamp(max=100.0) L_unc = (precision * error_sq - gamma).mean().clamp(max=50.0)
E.1.3 Asymmetric Boundary Loss
L_bound = relu(0.3 - mean_sigma2).pow(2).mean()
+ relu(mean_sigma2 - 4.0).pow(2).mean()E.2 Five-Group Differentiated Learning Rates
base_lr = 3e-4 (default, configurable)
Group 1 - gates: LR = base_lr * 5 = 1.5e-3, weight_decay=0
Parameters: all gate_raw, all log_sigma (StochasticResonance)
Group 2 - sigma2: LR = base_lr * 0.05 = 1.5e-5, weight_decay=0
Parameters: all uncertainty_head parameters
Group 3 - wm: LR = base_lr * 5 = 1.5e-3, weight_decay=0.01
Parameters: all NMDA, phono, silent, theta, time_cell parameters
Group 4 - neuromod: LR = base_lr * 0.3 = 9.0e-5, weight_decay=0
Parameters: tonic_da, acc_conflict, tripartite, surprise_gate, d1d2
Group 5 - other: LR = base_lr * 1 = 3.0e-4, weight_decay=0.1
Parameters: all remaining trainable parameters
Group 6 - frozen: LR = 0 (no gradient computed)
Parameters: all base model parameters (1.1B)
The 100x ratio between gates (5x) and sigma2 (0.05x) ensures that gates discover their optimal opening BEFORE sigma_squared calibrates, preventing the failure mode where premature sigma_squared calibration locks the system into a suboptimal operating point.
E.3 BCMHomeostasis
Biological basis: The Bienenstock-Cooper-Munro (BCM) theory describes how synaptic plasticity is modulated by the neuron’s recent activity history. High recent activity raises the plasticity threshold, preventing further potentiation. This creates a per-synapse homeostatic mechanism.
class BCMHomeostasis:
tau = 100.0
alpha = 1.0 / tau = 0.01
For each trainable parameter p:
ema[p] = None (initialized on first update)
update_and_scale(params):
with no_grad():
for each p with grad:
grad_mag = p.grad.abs().mean()
if ema[p] is None:
ema[p] = grad_mag
else:
ema[p] = lerp(ema[p], grad_mag, alpha)
ratio = grad_mag / (ema[p] + 1e-8)
scale = 1.0 / (1.0 + 0.5 * relu(ratio - 2.0))
p.grad *= scale
The BCM mechanism: when a parameter’s current gradient magnitude exceeds 2x its recent average (ratio > 2.0), the gradient is scaled down. The scaling factor 1/(1 + 0.5*excess) provides gradual damping: at ratio=3 (1.5x over threshold), scale = 1/(1+0.25) = 0.8; at ratio=5 (2.5x over threshold), scale = 1/(1+0.75) = 0.57. This prevents sudden gradient spikes from destabilizing training.
E.4 AstrocyteHomeostasis
Biological basis: Astrocytes are glial cells that surround and modulate groups of synapses. They operate on a SLOWER timescale than neurons, providing a layer-level homeostatic signal. The two-timescale design (fast and slow EMA) implements the astrocyte’s ability to detect both rapid changes and slow drifts in neural activity.
class AstrocyteHomeostasis:
alpha_fast = 1.0 / 50 = 0.02 # tau_fast = 50 steps
alpha_slow = 1.0 / 500 = 0.002 # tau_slow = 500 steps
For each of L layers:
ema_fast[i] = None
ema_slow[i] = None
update_and_scale(model):
with no_grad():
for each layer i:
mean_grad_norm = average of all parameter grad norms in layer i
if ema_fast[i] is None:
ema_fast[i] = ema_slow[i] = mean_grad_norm
else:
ema_fast[i] += alpha_fast * (mean_grad_norm - ema_fast[i])
ema_slow[i] += alpha_slow * (mean_grad_norm - ema_slow[i])
ratio = ema_fast[i] / (ema_slow[i] + 1e-8)
mod = clamp(1.0 / ratio, 0.8, 1.2)
for each parameter in layer i:
p.grad *= mod
The ratio ema_fast/ema_slow detects whether gradient norms are currently above (ratio > 1) or below (ratio < 1) their long-term average. If above: mod < 1 (suppress gradients). If below: mod > 1 (boost gradients). The clamp [0.8, 1.2] limits modulation to +/- 20%.
E.5 SleepConsolidation
class SleepConsolidation:
capacity = 20 # buffer stores top-20 batches
interval = 1000 # replay every 1000 steps
n_replay = 10 # replay 10 batches per sleep episode
buffer: deque(maxlen=20) of (da_mean, input_ids, labels)
maybe_store(batch, da_mean):
if not isnan(da_mean):
buffer.append((da_mean, input_ids.cpu(), labels.cpu()))
should_replay(step):
return step > 0 and step % 1000 == 0 and len(buffer) >= 10
get_replay_batches():
sorted by da_mean descending (highest surprise first)
return top 10 batches
Sleep consolidation replays the highest-surprise batches at reduced learning rate:
if sleep.should_replay(step):
scaler_state = scaler.state_dict() # SAVE GradScaler state
for each replay batch:
loss = compute_loss(...) * 0.3 # 0.3x learning rate
backward + step
scaler.load_state_dict(scaler_state) # RESTORE GradScaler stateThe GradScaler state save/restore is CRITICAL: without it, the sleep replay steps would update the GradScaler’s loss_scale estimate based on the replay batches (which may have different gradient statistics than the main training), causing loss_scale drift that leads to training instability. This was a bug discovered and fixed during development.
NOTE: Sleep consolidation is available but DISABLED by default in NCT-Adapt’s recommended configuration, because empirical testing showed that sleep replay can cause regression spikes in the adaptation setting (where the frozen backbone provides a strong prior that sleep replay can disrupt). The module is retained for use in settings where the backbone is weaker or the adaptation target is more distant from the pretraining distribution.
E.6 SynapticScaling
def synaptic_scaling(model, step, interval=100):
if step == 0 or step % interval != 0:
return
with no_grad():
for each module in [nmda, phono, silent, theta, time_cell]:
for each Linear layer with requires_grad:
norms = weight.norm(dim=1, keepdim=True) # per-row norms
mean_norm = norms.mean()
if mean_norm > 1e-6:
scale = (mean_norm / (norms + 1e-8)).clamp(0.9, 1.1)
weight *= scale
Every 100 steps, each working memory module’s weight row norms are normalized toward their mean. The clamp [0.9, 1.1] limits the adjustment to 10% per step. This prevents individual neurons from dying (norms -> 0) or saturating (norms -> infinity) while preserving the angular structure (learned selectivity patterns) of the weight matrix.
E.7 GradientAlignment Monitor
class GradientAlignment:
window = 50
ntp_norms: deque(maxlen=50)
unc_norms: deque(maxlen=50)
record(ntp_grad_norm, unc_grad_norm):
append to respective deques
get_damping():
if len < 10: return 1.0 (warmup)
if unc_mean > 2.0 * ntp_mean:
return max(0.1, ntp_mean / unc_mean) # damp uncertainty
return 1.0
The gradient alignment monitor detects when the uncertainty loss gradient dominates the NTP gradient (ratio > 2x) and returns a damping factor to scale down the uncertainty loss. This prevents the failure mode where uncertainty calibration “steals” gradient capacity from the primary NTP objective.
E.8 Optimizer and Scheduler
optimizer = AdamW(param_groups, lr=base_lr, betas=(0.9, 0.999))
lr_lambda(step):
if step < warmup_steps:
return step / warmup_steps # linear warmup
progress = (step - warmup_steps) / (total_steps - warmup_steps)
return 0.5 * (1 + cos(pi * progress)) # cosine decay to 0
scheduler = LambdaLR(optimizer, lr_lambda)
scaler = GradScaler("cuda", enabled=use_amp)
The 100-step warmup prevents early training instability when all modules are near their identity initialization and gradients are small and noisy. The cosine decay reduces the learning rate smoothly to zero at the end of training, allowing fine convergence.
E.9 EMA Model for Evaluation
if use_ema:
ema_model = deepcopy(model)
for p in ema_model.parameters():
p.requires_grad = False
ema_alpha = 0.999
# After each training step:
for ema_p, model_p in zip(ema_model.parameters(), model.parameters()):
if model_p.requires_grad:
ema_p.data.lerp_(model_p.data, 1.0 - ema_alpha)The EMA model provides a smoother, more stable version of the trained parameters for evaluation and checkpointing. With alpha=0.999, the EMA averages over approximately 1000 steps, removing high-frequency training noise.
E.10 Training Loop Overview
for step in range(total_steps):
input_ids, labels = next(data_iter)
# Forward pass with AMP
with autocast(enabled=use_amp):
logits, sigma2_list, info = model(input_ids, labels=labels)
loss, loss_dict = compute_adapt_loss(logits, labels, sigma2_list, ...)
# Backward pass
optimizer.zero_grad()
scaler.scale(loss).backward()
scaler.unscale_(optimizer)
# Gradient processing (ORDER MATTERS)
grad_norm = clip_grad_norm_(trainable_params, max_norm=1.0) # FIRST
bcm.update_and_scale(trainable_params) # SECOND
astrocyte.update_and_scale(model) # THIRD
# Optimizer step
scaler.step(optimizer)
scaler.update()
scheduler.step()
# Post-step maintenance
ema_update()
synaptic_scaling(model, step)
sleep.maybe_store(batch, da_mean)
if sleep.should_replay(step): do_sleep_replay()
The ordering of gradient processing is mandated: (1) global gradient clipping prevents exploding gradients, (2) BCM per-parameter modulation adjusts relative gradient magnitudes, (3) astrocyte per-layer modulation adjusts layer-level gradient balance. Reversing the order (e.g., BCM before clip) would allow BCM to be “washed out” by the subsequent clip operation.
Section F: Hallucination Detection Pipeline
F.1 End-to-End Pipeline
The complete hallucination detection pipeline during inference:
Step 1: Forward pass through wrapped model
logits, sigma2_list, info = model(input_ids)
Step 2: Aggregate uncertainty across layers
mean_sigma2 = stack(sigma2_list).mean(dim=0) # (B, T, 1)
Step 3: For each position t in generated text:
if mean_sigma2[b, t, 0] > threshold:
flag position t as potential hallucination
Step 4: Aggregate per-position flags into span-level alerts:
if consecutive_flagged_positions > min_span:
flag span as hallucinated contentF.2 Threshold Selection
The threshold can be selected based on the desired precision-recall trade-off:
Conservative (high precision): threshold = sigma_squared at 90th percentile
Balanced: threshold = median sigma_squared
Aggressive (high recall): threshold = sigma_squared at 25th percentile
The AUROC of 0.917 is threshold-independent and measures the overall discriminative power.
F.3 Runtime Overhead
The hallucination detection adds:
Per-block overhead: one LayerNorm + one Linear projection per layer = negligible
Aggregation overhead: one stack + one mean operation = negligible
Total overhead: less than 2% of the base model’s forward pass time
Memory overhead: L * B * T * 1 = L * B * T floats for sigma_squared storage
This is in contrast to:
MC-Dropout: 10-50x compute overhead (10-50 forward passes)
Deep Ensembles: 3-5x compute and 3-5x memory overhead
Verbalized confidence: additional generation time for confidence questions
Section G: Identity Test Protocol
G.1 Test 1: Full Disable Test
Purpose: Verify that when all NCT gates are set to extreme negative values, the wrapped model produces EXACTLY the same output as the base model.
# Set all gate_raw = -100 (sigmoid(-100) = effectively zero) # Set all block_bias = +100 (ChandelierVeto pass_prob = effectively 1.0) # Set all striatal bias = +100 (StriatalGate = effectively pass-through) base_logits = base_model(input_ids) adapt_logits = adapt_model(input_ids) max_diff = (base_logits - adapt_logits).abs().max().item() # PASS criterion: max_diff < 1e-3
This test verifies the POST-BLOCK ONLY architecture: when NCT modules contribute zero to the output, the wrapped model is mathematically identical to the base model. Any failure indicates that NCT modules are modifying the input to the frozen layer (a bug).
G.2 Test 2: Default Init Test
Purpose: Verify that at default initialization (before any training), the wrapped model produces output CLOSE to the base model.
# Use default initialization (gate_raw = -2.0, nct_gate_raw = -3.0) base_logits = base_model(input_ids) adapt_logits = adapt_model(input_ids) mean_diff = (base_logits - adapt_logits).abs().mean().item() # PASS criterion: mean_diff < 5.0
This test verifies the IDENTITY-AT-INITIALIZATION property: the small non-zero gate values (alpha = 0.005) and non-zero but small module outputs produce only minimal deviation from the base model. This ensures that training starts from a known-good starting point.
G.3 Test 3: Sigma-Squared Initialization Test
Purpose: Verify that sigma_squared starts at approximately 1.0 (the neutral value).
sigma2_mean = stack(sigma2_list).mean().item() # PASS criterion: sigma2_mean approximately 1.0
G.4 Test 4: Parameter Count Verification
Purpose: Verify that trainable parameters are less than 10% of frozen parameters.
trainable = model.count_trainable() # ~77M frozen = model.count_frozen() # ~1,100M ratio = trainable / frozen # ~7% # PASS criterion: ratio < 0.10
7. Claims
CAPPED GATED RESIDUAL CLAIMS (Distinguished from LoRA, Adapters, all PEFT)
Claim 1 (Independent System, Capped Gated Residual Wrapper):
A computing system for augmenting a pre-trained neural network language model with uncertainty quantification and hallucination detection, the system comprising: a processor; a memory storing a pre-trained neural network language model with frozen parameters comprising L transformer layers; and instructions that cause the processor to:
for each of the L layers of the pre-trained model, instantiate a wrapper module comprising a plurality of trainable brain-inspired modules that receive the frozen layer’s output and process it through a chain of transformations to produce a modified output, wherein the wrapper module operates exclusively on the frozen layer’s output and does not modify the frozen layer’s input (post-block architecture);
combine the frozen layer’s output with the modified output using a capped gated residual: alpha = alpha_max * sigmoid(gate_raw) X_output = X_frozen + alpha * (X_nct - X_frozen) where alpha_max is a FIXED, NON-LEARNABLE structural constant less than or equal to 0.15, structurally guaranteeing that the wrapper’s contribution at each layer cannot exceed alpha_max regardless of training duration, gate parameter values, or gradient magnitudes;
compute per-position uncertainty estimates (sigma_squared) within each wrapper module using a sigmoid-bounded parameterization: gamma = gamma_min + (gamma_max - gamma_min) * sigmoid(W * X) sigma_squared = exp(-gamma) trained with a free energy loss: L_unc = mean(exp(gamma) * MSE - gamma) having an analytical equilibrium at sigma_squared equals the mean squared prediction error;
during inference, produce both output token probabilities and calibrated per-position uncertainty estimates in a single forward pass, wherein positions with uncertainty exceeding a threshold are identified as potential hallucinations;
wherein the maximum cumulative deviation from the frozen model’s output across all L layers is bounded by (1 + alpha_max)^L.
Claim 2 (Dependent, Identity at Initialization):
The computing system of claim 1, wherein at training step zero:
all output projection weights in the wrapper modules are initialized to zero, ensuring each module produces zero correction;
the gate_raw parameter for the capped gated residual is initialized to a value (specifically -3.0) such that alpha = alpha_max * sigmoid(gate_raw) is less than 0.005;
all internal gate_raw parameters for individual modules are initialized to -2.0, giving sigmoid(-2.0) = 0.12, which when multiplied by zero-initialized output weights produces zero contribution;
the system produces outputs that are identical to the base pre-trained model’s outputs within floating-point precision (maximum difference less than 1e-3); and this identity is verified by running the same input through both the base model and the augmented model and comparing logits.
Claim 3 (Dependent, Compounding Guarantee):
The computing system of claim 1, wherein the capped gated residual provides a mathematical guarantee that the maximum deviation from the frozen model’s output after L layers is bounded by (1 + alpha_max)^L, which for alpha_max = 0.1 and L = 22 yields at most a factor of 7.4x of the frozen model’s output magnitude, and wherein the converged gate opening (alpha approximately 0.01) after training gives a cumulative factor of approximately (1.01)^22 = 1.24x, preventing the catastrophic degradation that occurs when uncapped modifications compound across layers.
Claim 4 (Dependent, Gate Self-Regulation):
The computing system of claim 1, wherein the gate_raw parameter is trained via standard backpropagation with a learning rate multiplier of 5x the base learning rate, and wherein the gate self-regulates to a converged value of alpha approximately 0.01 (1% influence per layer), demonstrating that the system discovers the minimum necessary NCT intervention without external constraint beyond the structural cap.
UNCERTAINTY AND HALLUCINATION CLAIMS (Distinguished from MC-Dropout, Ensembles, Verbalized Confidence)
Claim 5 (Independent Method, Single-Pass Hallucination Detection):
A method for detecting hallucinations in a pre-trained neural network language model, implemented by a digital processor, the method comprising:
freezing all parameters of the pre-trained model;
for each of L layers of the pre-trained model, adding a trainable wrapper module comprising an uncertainty head that computes per-position uncertainty estimates using a sigmoid-bounded parameterization: gamma = gamma_min + (gamma_max - gamma_min) * sigmoid(W_gamma * X) sigma_squared = exp(-gamma) where gamma_min and gamma_max are fixed constants defining the range of log-precision;
training the uncertainty estimates using a free energy loss: L_unc = mean(precision * MSE - gamma) where precision = exp(gamma) and MSE is the mean squared prediction error, and wherein this loss has an analytical equilibrium at sigma_squared = MSE providing automatic calibration;
additionally training with an asymmetric boundary loss: L_bound = mean(relu(sigma_low - sigma_squared)^2 + relu(sigma_squared - sigma_high)^2) creating a free zone [sigma_low, sigma_high] with zero penalty within the zone;
limiting the wrapper’s influence on the base model’s output using a capped gate: alpha = alpha_max * sigmoid(gate_raw), where alpha_max is a fixed constant less than or equal to 0.15;
aggregating uncertainty estimates across L layers to produce per-position confidence scores;
during inference, flagging output positions where the aggregated uncertainty exceeds a threshold as potential hallucinations;
wherein the method achieves hallucination detection AUROC greater than 0.85 in a single forward pass without requiring multiple forward passes, model ensembles, or prompted self-assessment, with computational overhead less than 10% of the base model’s forward pass cost.
Claim 6 (Dependent, Free Energy Equilibrium):
The method of claim 5, wherein the free energy loss in step (c) has an analytical equilibrium derived by setting dL_unc/d(gamma) = 0, yielding precision * MSE = 1, therefore sigma_squared = MSE, meaning the trained uncertainty converges to the actual prediction error magnitude, providing automatic calibration without requiring post-hoc calibration procedures including temperature scaling, Platt scaling, or isotonic regression.
Claim 7 (Dependent, Single Pass vs Multi-Pass):
The method of claim 5, wherein the uncertainty estimates are computed during the SAME forward pass that produces the output token probabilities, with zero additional forward passes required, the per-block uncertainty computation comprising one LayerNorm operation and one linear projection, and the total computational overhead of uncertainty estimation being less than 2% of the base model’s forward pass cost.
Claim 8 (Dependent, AUROC via Gate Disabling):
The method of claim 5, further comprising computing a base model performance metric by temporarily setting all gate_raw parameters to an extreme negative value (gate_raw = -100, making sigmoid(-100) effectively zero), evaluating the model to obtain a base perplexity measurement, and restoring the original gate_raw values, thereby measuring the NCT wrapper’s contribution without requiring a separate base model instance.
BRAIN-INSPIRED MODULE CLAIMS (Distinguished from all PEFT and fine-tuning methods)
Claim 9 (Independent System, Brain-Inspired Wrapper):
A computing system for augmenting a pre-trained language model, comprising a processor executing instructions that wrap each of L layers of a frozen pre-trained model with a trainable wrapper module, the wrapper module comprising at least:
a stochastic resonance module that injects learnable Gaussian noise with per-dimension amplitude during BOTH training AND inference, with the noise amplitude trained end-to-end via backpropagation to a non-zero equilibrium value, distinguished from dropout which is multiplicative, uses fixed probability, and is disabled at inference;
a repetition suppression module that computes the difference between each position’s representation and the preceding position’s representation, passes the difference through a learned nonlinear projection, and adds the result as a correction, thereby amplifying novel inputs and suppressing repeated inputs via an anti-Hebbian mechanism;
an event boundary detection module that computes cosine similarity between consecutive positions, detects positions with low similarity as context boundaries, and emits a learned pulse signal at boundary positions, implementing locus coeruleus norepinephrine reset;
an inhibitory triad comprising three modules applied in the mandated non-commutative order on a CORRECTION signal (not the representation itself):
SST Martinotti suppression: correction = correction * (1 - gate * sst_activity), where sst_activity is computed from the bottom-up input, then
VIP disinhibitory release: correction = correction * (1 + gate * vip_response), then
Apical amplification: correction = correction * (1 + gate * gain), where gain is computed as a coincidence of basal (bottom-up) and apical (correction) signals;
an endocannabinoid gate that measures activity magnitude with detached gradients (implementing retrograde signaling), computes excess above a learnable threshold, and applies multiplicative suppression;
an anterior cingulate conflict monitor that projects the representation into multiple channels, computes a Herfindahl concentration index across channels, and applies multiplicative control proportional to detected conflict;
an uncertainty estimation module producing per-position sigma_squared estimates via sigmoid-bounded parameterization;
wherein the wrapper module’s influence on the base model is limited by a hard-capped gate with a fixed non-learnable maximum influence per layer.
Claim 10 (Dependent, Shared Modules):
The computing system of claim 9, further comprising at least one module shared across all L layers, the shared module receiving a layer index parameter and producing layer-specific behavior through per-layer learnable parameters, comprising at least:
a chandelier veto gate that computes a pass probability using shared veto detection weights and per-layer block_bias parameters initialized to 5.0 (near pass-through), capable of completely suppressing any layer’s NCT output independently;
a striatal confidence gate that routes information based on a shared confidence probe with per-layer bias parameters initialized to 3.0, wherein high-confidence representations bypass NCT processing while low-confidence representations receive full NCT processing;
a basal ganglia selector that computes D1 and D2 pathway responses using shared projection weights and per-layer gate_raw parameters, producing a per-column go/no-go selection bias; wherein sharing reduces total parameter count by a factor of approximately L compared to per-layer instantiation.
Claim 11 (Dependent, Forward Hook Working Memory):
The computing system of claim 9, further comprising seven global working memory modules applied via a single forward hook registered on the pre-trained model’s final normalization layer, the hook being registered before each forward pass and removed after (in a try/finally construct), such that:
the base model’s computation graph is not permanently modified and no persistent state is added to the base model object;
the working memory modules can be removed instantly by not registering the hook;
the working memory modules are applied in the following order: CerebellarTiming, NMDAAttractorSlots, ThetaPhasePrecession, ThetaGammaPAC, ActivitySilentTrace, PhonologicalLoop, TimeCellBank;
the working memory modules operate on the hidden states AFTER all frozen transformer layers have completed their computation but BEFORE the language model head projects to vocabulary logits.
Claim 12 (Dependent, NMDA Attractor Working Memory):
The computing system of claim 11, wherein the NMDAAttractorSlots module implements persistent attractor-based working memory using:
positive-definite key and query projections via ELU(x) + 1.0 activation;
a sequential scan computing linear attention with exponential decay: S = a * S + g_w * (k outer v), where a = sigmoid(decay_bias) with decay_bias initialized to 6.0 giving a = 0.997 (persistence for approximately 333 time steps);
a gated write mechanism where g_w = sigmoid(W_gate(X)) with W_gate bias initialized to -2.0 (conservative write);
output projection W_out initialized to zero (identity at initialization).
Claim 13 (Dependent, PhonologicalLoop Cyclic Rehearsal):
The computing system of claim 11, wherein the PhonologicalLoop module implements cyclic rehearsal using:
K=8 slots of dimension d_slot=64 representing the rehearsal buffer;
a cyclic write pointer: ptr = t mod K, implementing the rehearsal mechanism where every K positions the pointer wraps around and begins overwriting old content;
gated write: new_val = (1 - g_w) * old_slot + g_w * new_content, enabling partial updates;
attention-based read: scores = bmm(slots, query), weights = softmax(scores), output = weighted_sum(slots, weights), enabling non-sequential retrieval from any slot.
Claim 14 (Dependent, TimeCellBank Multi-Timescale):
The computing system of claim 11, wherein the TimeCellBank module implements multi-timescale temporal receptive fields using:
n_cells=32 time cells with geometrically spaced decay rates: tau_i = 2^(i/4) for i = 0..31, covering time constants from 1 to 256 positions;
decay rates computed as exp(-1/tau_i) and stored as non-learnable buffers;
a learnable trigger detector: trigger = sigmoid(W_trigger(X)) that learns to identify positions that should initiate temporal tracking;
sequential scan: h = decay_rates * h + trigger_t, where the 32-dimensional h vector creates a temporal basis set encoding elapsed time since each trigger.
Claim 15 (Dependent, Phase Coding):
The computing system of claim 11, further comprising:
a ThetaPhasePrecession module that creates multiplicative phase modulation using: interaction = W_content(X) * W_phase([sin(2pipos/period), cos(2pipos/period)]), where period is a learnable parameter via softplus, and the modulation output = tanh(W_out(interaction));
a ThetaGammaPAC module that computes phase-amplitude coupling: pac_signal = gamma_amp * cos(2pi theta_phase), where gamma_amp = sigmoid(W_gamma(X)) and theta_phase = sigmoid(W_theta(X)), implementing the nested oscillation pattern observed in biological hippocampal recordings.
Claim 16 (Dependent, Working Memory Hierarchy):
The computing system of claim 11, wherein the seven working memory modules collectively implement a multi-timescale working memory hierarchy:
NMDAAttractorSlots: persistent active memory with decay time constant approximately 333 positions;
ActivitySilentTrace: synaptic facilitation memory with decay time constant approximately 14 positions;
PhonologicalLoop: cyclic rehearsal with K=8 slots, capacity limited by slot count;
CerebellarTiming: next-step prediction with single-step lookahead;
TimeCellBank: temporal basis set spanning 1 to 256 positions;
ThetaPhasePrecession: phase-coded position within learned oscillatory period;
ThetaGammaPAC: phase-amplitude coupling for temporal binding; providing coverage across temporal scales from single-token to multi-hundred-token.
Inhibitory Triad Claims
Claim 17 (Dependent, Inhibitory Triad Non-Commutative Order):
The computing system of claim 9, wherein the inhibitory triad in clause (d) operates on a CORRECTION signal defined as correction = X_processed - X_input, and the three modules are applied in the mandated non-commutative order:
SSTMartinotti: correction = correction * (1 - gate * sst_activity), where sst_activity = sigmoid(W_sst_out(gelu(W_sst_in(LayerNorm(X_input))))) is computed from the BOTTOM-UP input only;
VIPDisinhibitoryGate: correction = correction * (1 + gate * vip_response), where vip_response = sigmoid(W_vip_out(gelu(W_vip_in(LayerNorm(X_input)))));
ApicalAmplification: correction = correction * (1 + gate * gain), where gain = sigmoid(W_gain(basal * apical)), basal = sigmoid(W_basal(LayerNorm(X_input))), and apical = sigmoid(W_apical(correction)); and the final output is X_output = X_input + correction; wherein applying the three modules in any other order produces mathematically different outputs.
Claim 18 (Dependent, SST Semantics):
The computing system of claim 17, wherein the SSTMartinotti module computes sst_activity from the bottom-up input X_input (not from the correction signal), implementing the biological constraint that SST+ interneurons respond to feedforward drive and suppress top-down corrections, and wherein high sst_activity produces MORE suppression (correction approaches zero), not less.
Claim 19 (Dependent, Apical Coincidence):
The computing system of claim 17, wherein the ApicalAmplification module computes gain as a coincidence (element-wise multiplication) of basal response (from bottom-up input) and apical response (from the correction signal), amplifying only corrections that are consistent with both bottom-up evidence and top-down expectations, implementing the BAC (backpropagation-activated calcium) firing mechanism.
Neuromodulatory Gate Claims
Claim 20 (Dependent, D1D2 Inverted-U):
The computing system of claim 9, further comprising a D1D2InvertedU module that computes three dopamine features from a surprise signal da in (0, 1): inverted_u = 4.0 * da * (1.0 - da) (parabola peaking at da=0.5) d1_signal = da (direct pathway) d2_signal = 1.0 - da (indirect pathway) and combines them with content projections to produce a multiplicative modulation bounded by tanh, implementing the Yerkes-Dodson inverted-U relationship where moderate dopamine is optimal and both too-little and too-much impair function.
Claim 21 (Dependent, TonicDA Slow Modulation):
The computing system of claim 9, further comprising a TonicDATemperature module that maintains an exponential moving average of dopamine signals with alpha=0.999 (time constant approximately 1000 steps), computing deviation from a baseline of 0.5, and applying a learned multiplicative temperature modulation, implementing the exploration/exploitation balance where high tonic DA promotes exploration and low tonic DA promotes exploitation.
Claim 22 (Dependent, Tripartite ACh Gate):
The computing system of claim 9, further comprising a TripartiteAChGate module that combines three orthogonal neuromodulatory signals:
dopamine (DA): prediction error / surprise signal;
acetylcholine (ACh): attentional engagement / novelty signal;
sigma_squared: precision / confidence signal; into a single multiplicative modulation via learned projections: X * (1 + gate * tanh(W_combine(concat(X_proj, gelu(W_in(concat(da, ach, sigma2))))))), implementing the biological tripartite synapse where astrocytes integrate multiple neuromodulatory signals.
Claim 23 (Dependent, Surprise Weighting):
The computing system of claim 9, further comprising a SurpriseWeightingGate module that produces per-token importance weights in the range [0.5, 2.0] based on learned combination of content projections, dopamine, acetylcholine, and sigma_squared signals, implementing: importance = 0.5 + 1.5 * sigmoid(W_out(gelu(W_combine(concat(X_proj, da, ach, sigma2))))), and applying these weights as gradient modulation during training.
Event Processing and Signal Conditioning Claims
Claim 24 (Dependent, LC Event Boundary):
The computing system of claim 9, wherein the event boundary detection module in clause (c) specifically computes:
cosine similarity between consecutive positions: cos_sim = cosine_similarity(X_n, X_prev, dim=-1);
change signal: change = (1.0 - cos_sim), where high change indicates a context boundary;
boundary probability: boundary_prob = sigmoid(W_boundary(features) + 3.0 * change), where the 3.0 multiplicative bias emphasizes representational change;
NE reset pulse: pulse = W_pulse(features * boundary_prob), modulated by boundary probability; implementing the biological locus coeruleus NE burst at context transitions, with tracked diagnostic _boundary_signal for monitoring.
Claim 25 (Dependent, Stochastic Resonance at Inference):
The computing system of claim 9, wherein the stochastic resonance module in clause (a) specifically:
parameterizes noise amplitude as: sigma = exp(-7.0 + 12.3 * sigmoid(log_sigma)), bounding amplitude to [9.1e-4, 200.3] with initialization at approximately 0.050;
injects Gaussian noise: X_out = X + gate * randn_like(X) * sigma;
maintains non-zero noise amplitude at inference convergence (noise is NOT disabled during evaluation);
tracks diagnostic _noise_amp = (gate * sigma).mean() for monitoring; distinguished from dropout which is multiplicative, uses fixed probability, and is always disabled at inference.
Claim 26 (Dependent, Endocannabinoid Retrograde):
The computing system of claim 9, wherein the endocannabinoid gate in clause (e) specifically:
computes activity magnitude with DETACHED gradients: act_mag = X.detach().norm(dim=-1), implementing the retrograde nature of endocannabinoid signaling where the postsynaptic measurement does not propagate gradients to the representation;
computes excess above a learnable threshold: excess = relu(act_mag - softplus(threshold));
applies suppression proportional to excess: X_out = X * (1 - gate * sigmoid(W_suppress(excess))); providing activity-dependent homeostatic braking without gradient interference.
TRAINING SYSTEM CLAIMS (Distinguished from standard fine-tuning)
Claim 27 (Dependent, Dopamine-Weighted Learning):
The computing system of claim 1, wherein the training loss weights each token’s contribution by a dopamine-like surprise signal computed as:
per-token cross-entropy: ntp_errors = cross_entropy(logits, labels, reduction=‘none’);
running baseline: ema_t = cumulative_sum(ntp_errors) / position_counts;
phasic DA with Michaelis-Menten saturation: da_t = 3.0 * (ntp_errors / (ema_t + epsilon)) / (1.0 + ntp_errors / (ema_t + epsilon));
modulated weights: da_weights = 1.0 + da_scale * tanh(da_t - 1.0); such that tokens with above-baseline prediction error (surprising) receive proportionally more gradient weight and below-baseline tokens receive less.
Claim 28 (Dependent, Five-Group Learning Rates):
The computing system of claim 1, wherein training employs at least five parameter groups with differentiated learning rates:
gate parameters (gate_raw, log_sigma) at 5x base learning rate with zero weight decay;
uncertainty head parameters at 0.05x base learning rate with zero weight decay;
working memory parameters (NMDA, phonological, silent, theta, time_cell) at 5x base learning rate with 0.01 weight decay;
neuromodulatory parameters (tonic_da, acc_conflict, tripartite, surprise_gate, d1d2) at 0.3x base learning rate with zero weight decay;
all other trainable parameters at 1x base learning rate with 0.1 weight decay; wherein gate parameters and uncertainty parameters differ by at least a 100x learning rate ratio (5x / 0.05x = 100x), ensuring gate discovery precedes precision calibration.
Claim 29 (Dependent, Four-Part Homeostasis):
The computing system of claim 1, further comprising a homeostatic training system including:
per-parameter BCM (Bienenstock-Cooper-Munro) gradient modulation: maintaining a running EMA (tau=100) of each parameter’s gradient magnitude, computing ratio of current gradient to EMA, and scaling gradients down when ratio exceeds 2.0 via scale = 1.0 / (1.0 + 0.5 * relu(ratio - 2.0));
per-layer astrocyte modulation using fast (tau=50 steps) and slow (tau=500 steps) exponential moving averages of gradient norms, computing ratio of fast to slow EMA, and scaling all gradients in each layer by clamp(1.0/ratio, 0.8, 1.2);
periodic synaptic scaling every 100 steps: normalizing working memory module weight row norms toward their mean with scale factor clamped to [0.9, 1.1], preserving angular structure while preventing dead or saturated neurons;
periodic sleep consolidation (available but optionally disabled): every 1000 steps, replaying top-10 highest-DA batches from a 20-batch buffer at 0.3x learning rate, with GradScaler state saved before and restored after sleep to prevent loss_scale drift.
Claim 30 (Dependent, Gradient Processing Order):
The computing system of claim 29, wherein the gradient processing is applied in the mandated order:
FIRST: global gradient clipping (max_norm=1.0) to prevent exploding gradients;
SECOND: per-parameter BCM modulation to adjust relative gradient magnitudes;
THIRD: per-layer astrocyte modulation to adjust layer-level gradient balance; and this ordering is mandated because: BCM before clip would allow BCM modulation to be washed out by subsequent clipping; astrocyte before BCM would adjust layer-level balance before parameter-level stability is established.
Claim 31 (Dependent, EMA for Evaluation):
The computing system of claim 1, further comprising an exponential moving average (EMA) model maintained during training, wherein:
the EMA model is a deep copy of the full model with all parameters set to requires_grad=False;
after each training step, only trainable parameters are updated: ema_p = lerp(ema_p, model_p, 1 - alpha), where alpha = 0.999;
the EMA model is used for ALL evaluation and checkpointing instead of the training model;
the EMA provides noise-reduced parameter estimates by averaging over approximately 1000 training steps.
Claim 32 (Dependent, Warmup and Scheduler):
The computing system of claim 1, wherein the training employs a learning rate schedule comprising:
linear warmup for 100 steps: lr_multiplier = step / 100;
cosine decay from step 100 to the final step: lr_multiplier = 0.5 * (1 + cos(pi * progress)); wherein the warmup prevents early training instability when all modules are near their identity initialization and gradients are small and noisy.
Identity-at-initialization Claims
Claim 33 (Dependent, Zero-Init Output Weights):
The computing system of claim 2, wherein the zero-initialization of output weights specifically comprises: all of the following projection matrices initialized to zero weights: W_timing_out (CerebellarTiming), W_error (CerebellarTiming), W_out (NMDAAttractorSlots), W_pulse (LCEventBoundary), W_rs_out (RepetitionSuppression), W_sst_out (SSTMartinotti), W_vip_out (VIPDisinhibitoryGate), W_gain (ApicalAmplification), W_project (TimeCellBank), W_read (PhonologicalLoop), W_retrieve (ActivitySilentTrace), W_pac (ThetaGammaPAC), W_suppress (EndocannabinoidGate), W_mod_out (PrefrontalContextGate), W_ctx_out (PrefrontalContextGate), W_control (ACCConflictMonitor), W_temp (TonicDATemperature), W_tri_combine (TripartiteAChGate), W_out (SurpriseWeightingGate), W_D1_out (BasalGangliaSelector), W_D2_out (BasalGangliaSelector), W_veto_out (ChandelierVetoGate), and all ThalamicRelay relay_out projections; ensuring that EVERY module produces zero correction at initialization regardless of input.
Claim 34 (Dependent, Gate Initialization Convention):
The computing system of claim 2, wherein:
the per-block blend gate nct_gate_raw is initialized to -3.0 (sigmoid(-3.0) = 0.047, alpha = 0.0047);
all per-module gate_raw parameters are initialized to -2.0 (sigmoid(-2.0) = 0.12);
the ChandelierVetoGate block_bias is initialized to 5.0 (sigmoid(5.0) = 0.993, near pass-through);
the StriatalConfidenceGate bias is initialized to 3.0 (sigmoid(3.0) = 0.953, near pass-through);
gate parameters receive 5x the base learning rate to accelerate discovery;
the combination of near-zero blend gate and near-zero module output gives effective NCT contribution of approximately 0.0047 * 0.12 * 0 = 0 at step zero.
Claim 35 (Dependent, Verifiable Identity):
The computing system of claim 2, further comprising an identity test protocol that:
sets all gate_raw parameters to -100.0 (sigmoid(-100) = effectively zero) and all block_bias/striatal_bias to +100.0 (pass-through);
computes logits from both the base model and the augmented model on the same input;
verifies maximum absolute difference is less than 1e-3;
restores original parameter values;
at default initialization, verifies mean absolute difference is less than 5.0;
verifies sigma_squared mean is approximately 1.0;
verifies trainable parameter count is less than 10% of frozen parameter count.
Computer-readable Medium and Model-agnostic Claims
Claim 36:
A non-transitory computer-readable storage medium storing instructions that, when executed by a processor, cause the processor to implement the computing system of claim 1.
Claim 37:
A non-transitory computer-readable storage medium storing instructions that, when executed by a processor, cause the processor to perform the method of claim 5.
Claim 38 (Dependent, Model-Agnostic):
The computing system of claim 1, wherein the wrapper modules are automatically configured from the base model’s architecture parameters:
hidden dimension d from the base model’s hidden_size;
number of layers L from the base model’s num_hidden_layers;
feed-forward dimension d_ff from the base model’s intermediate_size;
vocabulary size V from the base model’s vocab_size;
thalamic relay groups n_groups = max(1, L // 4); allowing the system to be applied to any Transformer-based pre-trained language model including LLaMA, Mistral, GPT, Falcon, Phi, Qwen, and Gemma families without architecture-specific code modifications.
Claim 39 (Dependent, Minimal Overhead):
The computing system of claim 1, wherein the trainable wrapper modules collectively comprise less than 10% of the total parameter count of the pre-trained model, and the maximum gate opening after training convergence is less than 2% (alpha < 0.02), and the hallucination detection AUROC exceeds 0.85, demonstrating that calibrated uncertainty and hallucination detection require minimal model modification.
Claim 40 (Dependent, CerebellarTiming Precision-Weighted Loss):
The computing system of claim 11, wherein the CerebellarTiming module further provides a precision-weighted temporal prediction loss:
computing prediction error between consecutive positions: error = (W_timing_in(X_t) - W_timing_in(X_{t+1}).detach())^2;
weighting the error by precision (1/sigma_squared) from the uncertainty head, normalized to mean 1.0;
such that the cerebellar learning focuses on positions where the model is confident (low sigma_squared = high precision = high weight), implementing the biological principle that motor learning is faster when sensory feedback is reliable.
8. Comparison with Prior Work
| Concept | Prior Art | NCT-Adapt SPECIFIC Novelty | How it differs |
|---|---|---|---|
| Weight adaptation | LoRA (Hu 2021): Low-rank W = W_0 + BA, modifies Q/K/V internally | Post-block wrapper with HARD CAP (alpha_max=0.1 fixed), operates on OUTPUT only, never touches internal computation, compounding bounded by (1.1)^L | The structural guarantee from a non-learnable cap was never suggested; post-block-only is architecturally opposite of LoRA’s within-layer approach |
| Inserted modules | Adapters (Houlsby 2019): Bottleneck between layers | Wraps around layers with capped blend to frozen output, NOT inserted between them. Identity-at-init verifiable by logit comparison. 30 biologically-derived modules vs. 1 generic bottleneck | Capped blending to frozen output instead of inserting modules is architecturally different; biological module specificity has no adapter analogue |
| Uncertainty | MC-Dropout: 10-50 passes, no training | SINGLE PASS, TRAINABLE sigmoid-bounded sigma^2 with free energy loss, analytical equilibrium sigma^2=MSE, AUROC 0.917 | Training uncertainty end-to-end with guaranteed equilibrium is fundamentally different from stochastic sampling |
| Uncertainty | Deep Ensembles: N models | SINGLE model, 7% overhead, free energy calibration, PCC=0.459, asymmetric boundary loss | 7% overhead vs 300-1000% for ensembles; free energy loss has no ensemble analogue |
| Self-regulation | None in any PEFT | 4-part homeostasis: BCM + astrocyte + synaptic scaling + sleep + mandated gradient processing order | No prior adaptation method has any homeostatic feedback of any kind |
| Learning modulation | Uniform CE everywhere | Dopamine-weighted per-token loss with Michaelis-Menten saturation and cumulative EMA baseline | Per-token weighting by DA surprise with analytical saturation has no PEFT analogue |
| Working memory | None in any PEFT | Hook-based WM: 7 modules (NMDA, phono, silent, theta, PAC, cerebellar, time cells), registered/removed per pass | No prior method adds multi-timescale working memory to frozen models via removable hooks |
| Inhibitory gating | None in any PEFT | SST -> VIP -> Apical triad on correction signal with mandated non-commutative ordering, proven mathematically different from any reordering | Biologically-derived inhibitory circuit with proven non-commutativity has no ML analogue |
| Gate dynamics | LoRA rank: fixed throughout | Gate starts at 0.47%, converges to 1.0%, hard-capped at 10%. Self-regulating with 5x LR | Self-regulating gate with structural cap and documented convergence dynamics is novel |
| Noise at inference | Dropout: OFF at test | Stochastic resonance: ON at test, learned amplitude per-dimension, beneficial for weak signal detection | Intentional beneficial test-time noise with learned amplitude has no PEFT or ML analogue |
| Retrograde signaling | None in any ML | EndocannabinoidGate: .detach() on activity measurement implements retrograde non-differentiable suppression | Activity-dependent suppression with detached gradient measurement has no prior art |
| Conflict detection | None in any PEFT | ACCConflictMonitor: Herfindahl index across 8 channels as conflict measure, multiplicative control | Statistical conflict detection via concentration index has no PEFT analogue |
| Phase coding | None in any PEFT | ThetaPhasePrecession + ThetaGammaPAC: content * phase interaction, PAC = gamma_amp * cos(2pitheta_phase) | Oscillatory phase coding mechanisms have no transformer or PEFT analogue |
9. Experimental Results
| Metric | Base TinyLlama | NCT-Adapt | Improvement |
|---|---|---|---|
| NTP Accuracy | 0.477 | 0.512 | +3.5% |
| Hallucination AUROC | 0.500 (random) | 0.917 | +41.7 points |
| PCC | N/A | 0.459 | Novel capability |
| Trust Alignment | N/A | 0.433 | Novel capability |
| Uncertainty Gap | N/A | 1.878 | Novel capability |
| Val PPL | 10.4 | 9.8 | -5.8% |
| Trainable Params | N/A | 77M | 7% of backbone |
| Gate Max Alpha | N/A | 0.0102 | Within 0.1 cap |
| NaN Events | N/A | 0 | Stable |
| Degradation | N/A | 0 | Non-destructive |
Training configuration: 5000 steps, MPS device, 2.7 hours, batch_size=4, seq_len=512, base_lr=3e-4, 100-step warmup, cosine decay, EMA alpha=0.999.
License
PolyForm Noncommercial License 1.0.0This work is open research. Free for any noncommercial use: research, education, personal projects, evaluation, and nonprofit or public-sector use. Commercial use requires a separate license, available by contacting krrish@verace.in.