Training Script
Source: train_v11.py Lines: 1,078
Training Modes
NCT supports four training modes, each implementing a different level of biological fidelity:
| Mode | Learning Rule | NTP Backprop | Use Case |
|---|---|---|---|
hebbian | Hebbian + anti-Hebbian only | None | Purest biological, proof of concept |
predictive_coding | Local PC error signals per column | None (analytical LM head only) | Brain-like, zero global backprop |
hybrid | PC + Hebbian + analytical NTP on output pathway | LM head + final L5 only | Best performance, mostly local |
backprop | Standard backprop | Full global | Baseline comparison only |
Local Output Correction
In predictive_coding and hebbian modes, the only component receiving any form of gradient is the LM head, via an analytical delta rule. This is the critical mechanism that enables language modeling without any backpropagation through the column hierarchy:
The correction is computed analytically (not via autograd) using the chain rule applied only to the BrainLMHead’s parameters. Specifically, the error signal is projected back through the LM head’s low-rank production delta () and output bias () using simple matrix multiplications. No computational graph is built, no .backward() is called, and no gradients flow to any column parameter.
The learning rate multiplier compensates for the fact that this is the only supervised signal in the entire system, all column learning comes from local PC and Hebbian rules. Gradient clipping at prevents large corrections from destabilizing the LM head. Smoke test 11 verifies this property: column L2/3 weights, column L5 weights, and all hidden layer parameters show exactly zero change after a local output correction, while the LM head’s delta_A and output_bias show nonzero changes.
Data Loading
Training data is loaded from WikiText-2 via HuggingFace datasets library and tokenized with the NCT morphological tokenizer. The data loading pipeline:
Load the WikiText-2 raw text corpus (
wikitext-2-raw-v1split)Collect all non-empty text segments
Build or load the NCT morphological tokenizer vocabulary (from
nct_tokenizer/vocab/; if not found, builds on-the-fly from the training corpus withmax_roots=8000, max_whole_words=5000, min_word_freq=3, min_morpheme_freq=2)Encode all text segments to token IDs using the dual-route tokenizer
Concatenate all token IDs into a single long sequence
Chunk into sequences of length
seq_len(default 256)Create input/target pairs:
input = chunk[:-1],target = chunk[1:]
The HF_TOKEN environment variable is required for WikiText-2 download. If the datasets library is not available, the training script falls back to random data (for smoke testing).
Training Loop
For each step in the training loop:
Backprop mode: Standard forward loss.backward() optimizer.step().
PC/Hebbian/Hybrid modes:
Forward pass (computes logits, PC loss, cerebellar loss)
Local output correction (analytical, LM head only)
Local learning step (PC + Hebbian updates to column weights)
Wake-sleep check (every steps, run sleep phase)
Logging and checkpointing
Prenatal Phase
If --prenatal N is specified (recommended: ), prenatal self-organization runs before any data-driven training. This phase bootstraps the network from random weights through four types of spontaneous activity:
Spontaneous waves (30% of steps): Momentum random walk in embedding space simulating retinal waves. This teaches L2/3 about local temporal correlations: “nearby positions have related representations.”
Motor babbling (25%): Auto-regressive self-generation from random seed tokens (capped at 16 tokens for speed). The model learns to predict its own output, calibrating the production-perception loop.
Competitive differentiation (25%): Structured patterns (repeated motifs, ascending sequences, alternating tokens, segmented blocks, pure random) force different columns to develop different selectivities through competitive Hebbian learning.
Oscillatory calibration (20%): Multi-frequency sinusoidal input spanning theta/alpha/delta ranges. Calibrates the learnable oscillatory periods and PAC coupling strengths.
After prenatal development, the network is not a blank slate, it has calibrated oscillatory rhythms, differentiated columns, functional prediction circuitry, and tuned BCM thresholds. This is the “DNA”, the structured starting point from which rapid postnatal learning from real data can begin immediately. See Section 14 for the complete prenatal algorithm.
Smoke Test Suite (12 Tests)
The --smoke flag runs a comprehensive validation suite:
| # | Test | Validates |
|---|---|---|
| 1 | Forward pass | Correct output shapes, finite loss, finite PC loss |
| 2 | Local learning | PC + Hebbian updates run without error, metrics returned |
| 3 | Backprop step | Standard backprop produces finite gradients |
| 4 | Wake-sleep | Sleep triggers correctly, replay executes, downscaling applies |
| 5 | Generation | Auto-regressive generation produces valid token sequences |
| 6 | Numerical stability | All model parameters are finite (no NaN/Inf) |
| 7 | Gate values | All gates at init (identity-at-init verified) |
| 8 | Autonomous loop | AutonomousLoop processes steps, accumulates experiences, dreams |
| 9 | Always-on learning | Learning metrics computed after every forward pass |
| 10 | L2/3 complexity | Scaling ratio (linear, not quadratic) |
| 11 | Local output correction | Column weights unchanged (zero autograd), LM head weights changed |
| 12 | Prenatal | All 4 phases visited, weight stats tracked, report generated |
Checkpoint Format

CLI Reference
python3 nct_v11_standalone.py --smoke # 12 smoke tests
python3 nct_v11_standalone.py --mode predictive_coding \
--steps 5000 --prenatal 500 --bf16 --wake_sleep # PC training
python3 nct_v11_standalone.py --preset laptop \
--mode hybrid --steps 10000 --bf16 # Laptop preset
python3 nct_v11_standalone.py --mode hebbian \
--steps continuous --bf16 --wake_sleep # Never-ending
python3 nct_v11_standalone.py --resume_latest --bf16 # Resume
Source Code
Usage:
model = create_v11_model(cfg)
setup_v11_production(model)
result = model(input_ids)
if model.tools.should_use_tool(result):
# Use tool_use.py infrastructure
...
if model.retrieval.should_retrieve(result):
# Use retrieval.py infrastructure
...
"""
model.tools = V11ToolAdapter(model)
model.retrieval = V11RetrievalAdapter(model)
return model
# ===========================================================================
# Training Script
# Source: train_v11.py
# ===========================================================================
"""
NCT V11: Training Script — Cortical Column Network
====================================================
Training modes:
1. backprop: Standard backprop (baseline comparison)
2. hybrid: PC + Hebbian + backprop NTP loss (recommended for Phase 1)
3. predictive_coding: Pure local PC learning (Theorem A)
4. hebbian: Pure Hebbian learning (Theorem B — experimental)
Wake-Sleep cycle (Theorem D):
- Wake: process input + learn (PC/Hebbian/backprop)
- Sleep: replay from hippocampus + synaptic downscaling
- Cycle runs autonomously based on config.sleep_interval
Usage:
# Smoke test (quick validation)
python3 train_v11.py --steps 10 --smoke
# Backprop baseline (standard training for comparison)
python3 train_v11.py --mode backprop --steps 5000
# Hybrid mode (recommended — PC + Hebbian + NTP)
python3 train_v11.py --mode hybrid --steps 5000
# Pure predictive coding (Theorem A — no global backprop)
python3 train_v11.py --mode predictive_coding --steps 5000
# Full V11 with wake-sleep
python3 train_v11.py --mode hybrid --wake_sleep --steps 10000
"""
def _cuda_cleanup():
"""Release all CUDA memory on exit. Prevents driver memory leaks in containers."""
try:
import torch
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
# Reset device to ensure driver reclaims all memory
torch.cuda.reset_peak_memory_stats()
except Exception:
pass # Best effort — don't crash on cleanup
atexit.register(_cuda_cleanup)
# Add parent to path
sys.path.insert(0, str(Path(__file__).parent))
# [bundled] from nct_v2.v11_config import V11Config
# [bundled] from nct_v2.v11_model import CorticalColumnNetwork, create_v11_model
# ═══════════════════════════════════════════════════════════════════════
# Data Loading
# ═══════════════════════════════════════════════════════════════════════
def get_random_batch(vocab_size: int, batch_size: int, seq_len: int, device: torch.device):
"""Generate random batch for smoke testing."""
input_ids = torch.randint(0, vocab_size, (batch_size, seq_len), device=device)
targets = torch.randint(0, vocab_size, (batch_size, seq_len), device=device)
return input_ids, targets
def _get_or_build_nct_tokenizer(corpus_text: str = None):
"""Load NCT tokenizer from disk, or build from corpus if not available."""
# [bundled] from nct_tokenizer.tokenizer import NCTTokenizer
vocab_dir = os.path.join(os.path.dirname(__file__), 'nct_tokenizer', 'vocab')
if os.path.exists(os.path.join(vocab_dir, 'vocab.json')):
return NCTTokenizer.load(vocab_dir)
# Build vocab from provided corpus
if corpus_text is None:
raise RuntimeError(
"NCT tokenizer vocab not found. Build it first:\n"
" python3 -m nct_tokenizer.build_vocab\n"
"Or pass corpus_text to build on the fly."
)
print("[NCT Tokenizer] Building vocab from training corpus...")
tok = NCTTokenizer()
tok.build_vocab(corpus_text, max_roots=8000, max_whole_words=5000,
min_word_freq=3, min_morpheme_freq=2)
tok.save(vocab_dir)
return tok
def load_wikitext_data(seq_len: int, split: str = 'train', variant: str = 'auto'):
"""Load WikiText dataset, tokenized with NCT morphological tokenizer.
The brain processes morphemes, not BPE byte-pairs. V11 uses the NCT
dual-route tokenizer (Coltheart 2001 DRC model) as its ONLY tokenizer.
Args:
variant: 'auto' tries WikiText-103 first (100M tokens), falls back to
WikiText-2 (5.5M tokens). Use '103' or '2' to force.
"""
try:
from datasets import load_dataset
except ImportError:
print("WARNING: datasets not available, using random data")
return None, None
# Try WikiText-103 first (20x more data than WikiText-2)
dataset = None
if variant in ('auto', '103'):
try:
print(f"Loading WikiText-103 ({split})...")
dataset = load_dataset('wikitext', 'wikitext-103-raw-v1', split=split)
print(f" WikiText-103 loaded: {len(dataset)} examples")
except Exception as e:
if variant == '103':
raise
print(f" WikiText-103 unavailable ({e}), falling back to WikiText-2")
if dataset is None:
print(f"Loading WikiText-2 ({split})...")
dataset = load_dataset('wikitext', 'wikitext-2-raw-v1', split=split)
# Collect raw text for vocab building (if needed)
texts = [ex['text'].strip() for ex in dataset if ex['text'].strip()]
corpus = "\n".join(texts)
# NCT morphological tokenizer — the brain's tokenizer
tokenizer = _get_or_build_nct_tokenizer(corpus_text=corpus)
all_tokens = []
for text in texts:
enc = tokenizer.encode(text)
all_tokens.extend(enc.ids)
all_tokens = torch.tensor(all_tokens, dtype=torch.long)
print(f" Loaded {len(all_tokens):,} tokens (NCT morphological, V={tokenizer.vocab_size})")
return all_tokens, tokenizer
class TextEnvironment:
"""
Autonomous data acquisition for V11.
Reads text files from a directory, tokenizes them, and serves batches.
The model can point at a directory and learn forever.
Supports:
- Reading all .txt files from a directory
- Cycling through data infinitely
- Shuffling files between epochs
- Reporting what file is being processed (for logging)
"""
def __init__(self, data_dir: str, tokenizer, seq_len: int = 256,
batch_size: int = 2, device: torch.device = torch.device('cpu')):
import glob as _glob
self.tokenizer = tokenizer
self.seq_len = seq_len
self.batch_size = batch_size
self.device = device
self.files = sorted(_glob.glob(os.path.join(data_dir, '**/*.txt'), recursive=True))
if not self.files:
# Fallback: try any text-like files
for ext in ['*.md', '*.py', '*.json', '*.csv', '*.rst']:
self.files.extend(_glob.glob(os.path.join(data_dir, f'**/{ext}'), recursive=True))
self.files = sorted(self.files)
self._token_buffer = torch.tensor([], dtype=torch.long)
self._file_idx = 0
self._epoch = 0
self.current_file = None
print(f" TextEnvironment: {len(self.files)} files from {data_dir}")
def _load_next_file(self):
"""Load and tokenize the next file."""
if not self.files:
return
if self._file_idx >= len(self.files):
self._file_idx = 0
self._epoch += 1
import random
random.shuffle(self.files)
path = self.files[self._file_idx]
self._file_idx += 1
self.current_file = os.path.basename(path)
try:
with open(path, 'r', encoding='utf-8', errors='ignore') as f:
text = f.read()
if text.strip():
enc = self.tokenizer.encode(text)
new_tokens = torch.tensor(enc.ids, dtype=torch.long)
self._token_buffer = torch.cat([self._token_buffer, new_tokens])
except Exception:
pass # Skip unreadable files
def get_batch(self) -> tuple:
"""Get next batch of (input_ids, targets)."""
needed = (self.seq_len + 1) * self.batch_size
while len(self._token_buffer) < needed:
self._load_next_file()
if not self.files:
# No files — return random data as fallback
rand = torch.randint(0, 1000, (self.batch_size, self.seq_len + 1))
return rand[:, :-1].to(self.device), rand[:, 1:].to(self.device)
# Extract batch from buffer
chunks = []
for _ in range(self.batch_size):
chunk = self._token_buffer[:self.seq_len + 1]
chunks.append(chunk)
self._token_buffer = self._token_buffer[self.seq_len:]
batch = torch.stack(chunks) # [B, seq_len+1]
return batch[:, :-1].to(self.device), batch[:, 1:].to(self.device)
def get_batch_from_tokens(tokens: torch.Tensor, batch_size: int, seq_len: int,
device: torch.device, step: int):
"""Get a batch from pre-tokenized data."""
n = tokens.shape[0]
max_start = n - seq_len - 1
if max_start <= 0:
max_start = 1
# Deterministic batch selection based on step
starts = [(step * batch_size + i) * seq_len % max_start for i in range(batch_size)]
input_ids = torch.stack([tokens[s:s + seq_len] for s in starts]).to(device)
targets = torch.stack([tokens[s + 1:s + seq_len + 1] for s in starts]).to(device)
return input_ids, targets
# ═══════════════════════════════════════════════════════════════════════
# Local Output Correction (Zero Backprop)
# ═══════════════════════════════════════════════════════════════════════
_loc_diag_count = [0] # Mutable counter for one-time diagnostic
@torch.no_grad()
def _local_output_correction(model: CorticalColumnNetwork, result: dict, lr: float):
"""
Analytical local error feedback for the output pathway — NO autograd.
The cross-entropy gradient for a linear LM head is:
dL/dW = (softmax(logits) - one_hot(targets))^T @ hidden / N
This is the delta rule (Widrow-Hoff 1960), identical to what backprop
computes for a single linear layer, but calculated directly.
Biologically: auditory cortex computes speech error (heard vs intended)
and corrects motor-to-speech weights. Local computation — each output
neuron adjusts its own synaptic weights based on its own error signal.
"""
logits = result.get('logits')
targets = result.get('targets')
hidden = result.get('hidden_state') # [B, T, D] from lm_head_norm output
if logits is None or targets is None or hidden is None:
if _loc_diag_count[0] < 3:
print(f" [LOC] SKIPPED: logits={logits is not None}, targets={targets is not None}, hidden={hidden is not None}")
_loc_diag_count[0] += 1
return
B, T, V = logits.shape
D = hidden.shape[-1]
N = B * T
# ── Output error: softmax(logits) - one_hot(targets) ──────────
# This IS the analytical gradient of cross-entropy w.r.t. logits
probs = F.softmax(logits.float(), dim=-1) # [B, T, V], float32 for precision
targets_flat = targets.reshape(-1).clamp(0, V - 1) # Handle padding
one_hot = torch.zeros(N, V, device=logits.device, dtype=probs.dtype)
one_hot.scatter_(1, targets_flat.unsqueeze(1), 1.0)
error = probs.reshape(N, V) - one_hot # [N, V]
# Mask padding tokens (target == -1)
valid_mask = (targets.reshape(-1) >= 0).float().unsqueeze(1) # [N, 1]
error = error * valid_mask
n_valid = valid_mask.sum().clamp(min=1)
# ── LM head updates: BrainLMHead has delta_A, delta_B, output_bias ──
hidden_flat = hidden.reshape(N, D).float()
lm = model.lm_head
# Gradient clipping: prevents divergence when output bias concentrates
# probability mass and error signals grow for rare tokens.
MAX_GRAD_NORM = 1.0
# Output bias: dL/d(bias) = mean(error) per vocab entry
if hasattr(lm, 'output_bias'):
db = error.sum(dim=0) / n_valid # [V]
db_norm = db.norm()
if db_norm > MAX_GRAD_NORM:
db = db * (MAX_GRAD_NORM / db_norm)
lm.output_bias.data -= lr * db.to(lm.output_bias.dtype)
# Production delta (low-rank: delta_A @ delta_B approximates ΔW)
if hasattr(lm, 'delta_A') and hasattr(lm, 'delta_B'):
h_proj = hidden_flat @ lm.delta_B.t().float() # [N, r]
dA = (error.T @ h_proj) / n_valid # [V, r]
dA_norm = dA.norm()
if dA_norm > MAX_GRAD_NORM:
dA = dA * (MAX_GRAD_NORM / dA_norm)
lm.delta_A.data -= lr * dA.to(lm.delta_A.dtype)
error_proj = error @ lm.delta_A.float() # [N, r]
dB = (error_proj.T @ hidden_flat) / n_valid # [r, D]
dB_norm = dB.norm()
if dB_norm > MAX_GRAD_NORM:
dB = dB * (MAX_GRAD_NORM / dB_norm)
lm.delta_B.data -= lr * dB.to(lm.delta_B.dtype)
if _loc_diag_count[0] < 3:
print(f" [LOC] Applied: lr={lr}, |error|={error.abs().mean():.6f}, "
f"|dA|={dA.abs().mean() if hasattr(lm, 'delta_A') else 0:.8f}, "
f"|db|={db.abs().mean() if hasattr(lm, 'output_bias') else 0:.8f}")
_loc_diag_count[0] += 1
# ═══════════════════════════════════════════════════════════════════════
# Training Loop
# ═══════════════════════════════════════════════════════════════════════
def train(args):
"""Main training function."""
device = torch.device('cuda' if torch.cuda.is_available() else
'mps' if torch.backends.mps.is_available() else 'cpu')
print(f"Device: {device}")
# ── Config ───────────────────────────────────────────────────────
_preset_constructors = {
'1b': V11Config.v11_1b,
'laptop': V11Config.v11_laptop,
}
if args.preset in _preset_constructors:
cfg = _preset_constructors[args.preset](
learning_mode=args.mode,
wake_sleep_enabled=args.wake_sleep,
sleep_interval=args.sleep_interval,
base_lr=args.lr,
batch_size=args.batch_size,
seq_len=args.seq_len,
n_inference_steps=args.inference_steps,
pc_max_steps=args.inference_steps, # Wire --inference_steps to actual PC loop bound
pc_min_steps=min(2, args.inference_steps),
dropout=0.1 if not args.smoke else 0.0,
use_bf16=args.bf16 and device.type == 'cuda',
)
else:
cfg = V11Config(
d_model=args.d_model,
d_column=args.d_model, # Same as d_model for simplicity
n_columns=args.n_columns,
d_ff=args.d_model * 4,
vocab_size=args.vocab_size,
max_seq_len=args.seq_len * 2,
learning_mode=args.mode,
wake_sleep_enabled=args.wake_sleep,
sleep_interval=args.sleep_interval,
base_lr=args.lr,
batch_size=args.batch_size,
seq_len=args.seq_len,
n_inference_steps=args.inference_steps,
dropout=0.1 if not args.smoke else 0.0,
use_bf16=args.bf16 and device.type == 'cuda',
)
# ── Model ────────────────────────────────────────────────────────
model = create_v11_model(cfg).to(device)
if not args.smoke and device.type == 'cuda' and hasattr(torch, 'compile'):
try:
model = torch.compile(model, mode='reduce-overhead')
print(" torch.compile enabled (reduce-overhead)")
except Exception as e:
print(f" torch.compile failed ({e}), continuing without")
param_counts = model.count_parameters()
print(f"\n{'=' * 60}")
print(f"NCT V11: Cortical Column Network")
print(f"{'=' * 60}")
print(f" Mode: {args.mode}")
print(f" Columns: {cfg.n_columns}")
print(f" D_model: {cfg.d_model}")
print(f" D_ff: {cfg.d_ff}")
print(f" Assoc heads: {cfg.n_assoc_heads}")
print(f" Inference steps:{cfg.n_inference_steps}")
print(f" Wake-sleep: {cfg.wake_sleep_enabled}")
print(f" Vocab: {cfg.vocab_size}")
print(f" Parameters:")
for k, v in param_counts.items():
print(f" {k:20s}: {v:>12,}")
print(f"{'=' * 60}\n")
# ── Data (NCT morphological tokenizer — the brain's tokenizer) ──
train_tokens = None
tokenizer = None
text_env = None
if not args.smoke:
if args.data_file is not None and os.path.exists(args.data_file):
# Memory-mapped binary token file (from prepare_openwebtext.py)
# Zero RAM overhead — reads directly from disk via mmap
import struct as _struct
print(f"Loading mmap token file: {args.data_file}")
with open(args.data_file, 'rb') as _f:
magic = _f.read(4)
assert magic == b'NCT1', f"Bad magic: {magic} (expected NCT1)"
file_vocab = _struct.unpack('<I', _f.read(4))[0]
_f.read(4) # reserved
file_size = os.path.getsize(args.data_file)
n_file_tokens = (file_size - 12) // 4
import numpy as np
mmap_tokens = np.memmap(args.data_file, dtype=np.int32, mode='r',
offset=12, shape=(n_file_tokens,))
train_tokens = torch.from_numpy(mmap_tokens.astype(np.int64))
cfg.vocab_size = file_vocab
print(f" Loaded {n_file_tokens:,} tokens ({n_file_tokens/1e9:.2f}B) via mmap (V={file_vocab})")
print(f" Chinchilla ratio: {n_file_tokens/300e6:.1f} tokens/param")
model = create_v11_model(cfg).to(device)
# Load tokenizer for generation (lightweight, no corpus needed)
tokenizer = _get_or_build_nct_tokenizer()
else:
train_tokens, tokenizer = load_wikitext_data(args.seq_len, variant=args.wikitext)
if tokenizer is not None:
cfg.vocab_size = tokenizer.vocab_size
# Rebuild model with correct vocab size
print(f" NCT tokenizer: V={cfg.vocab_size} (morpheme dual-route)")
model = create_v11_model(cfg).to(device)
# Autonomous data environment (reads from directory)
if args.data_dir is not None and tokenizer is not None:
text_env = TextEnvironment(
args.data_dir, tokenizer, seq_len=args.seq_len,
batch_size=args.batch_size, device=device,
)
# ── Validation data (for generalization monitoring) ─────────────
val_tokens = None
if not args.smoke and tokenizer is not None:
val_data = load_wikitext_data(args.seq_len, split='validation',
variant=args.wikitext if hasattr(args, 'wikitext') else 'auto')
if val_data[0] is not None:
val_tokens = val_data[0]
print(f" Validation tokens: {len(val_tokens):,}")
# ── Optimizer (for backprop mode only — hybrid uses NTP-output-only) ──
optimizer = None
if args.mode == 'backprop':
param_groups = model.get_optimizer_groups(lr=args.lr)
optimizer = torch.optim.AdamW(param_groups, betas=(0.9, 0.95))
# ── AutonomousLoop (for hybrid/PC/hebbian modes) ──────────────
loop = None
if args.mode in ('hybrid', 'predictive_coding', 'hebbian'):
# [bundled] from nct_v2.v11_autonomous import AutonomousLoop, AutonomousConfig
auto_cfg = AutonomousConfig(
sleep_interval=cfg.sleep_interval if cfg.wake_sleep_enabled else 10000,
eval_interval=50,
consolidation_interval=200,
)
loop = AutonomousLoop(model, auto_cfg)
# ── Auto-resume: brain_best.pt, fallback to brain_latest.pt if corrupted
if args.resume_latest and args.save_dir and not args.resume:
best_path = os.path.join(args.save_dir, 'brain_best.pt')
latest_path = os.path.join(args.save_dir, 'brain_latest.pt')
if os.path.exists(best_path):
try:
torch.load(os.path.join(args.save_dir, 'meta_best.pt'), map_location='cpu', weights_only=False)
args.resume = best_path
print(f" [AUTO-RESUME] Found brain_best.pt")
except Exception:
print(f" [AUTO-RESUME] brain_best.pt corrupted, trying brain_latest.pt")
if os.path.exists(latest_path):
args.resume = latest_path
print(f" [AUTO-RESUME] Falling back to brain_latest.pt")
elif os.path.exists(latest_path):
args.resume = latest_path
print(f" [AUTO-RESUME] brain_best.pt not found, using brain_latest.pt")
else:
import glob as _glob_resume
brain_files = sorted(
_glob_resume.glob(os.path.join(args.save_dir, 'brain_step_*.pt')),
key=lambda p: int(os.path.basename(p).replace('brain_step_', '').replace('.pt', '')),
)
if brain_files:
args.resume = brain_files[-1]
print(f" [AUTO-RESUME] Found {len(brain_files)} checkpoints, resuming from: {args.resume}")
else:
print(f" [AUTO-RESUME] No checkpoints in {args.save_dir}, starting fresh.")
# ── Resume from checkpoint ─────────────────────────────────────
start_step = 0
best_loss = float('inf')
if args.resume:
print(f"\n Resuming from: {args.resume}")
model.load_state(args.resume, strict=True)
# Resolve companion files (brain_* → autonomous_*, meta_*)
base = args.resume.replace('brain_best', 'autonomous_best').replace('brain_latest', 'autonomous_latest').replace('brain_step_', 'autonomous_step_')
meta_base = args.resume.replace('brain_best', 'meta_best').replace('brain_latest', 'meta_latest').replace('brain_step_', 'meta_step_')
if loop is not None and os.path.exists(base):
loop.load_autonomous_state(base)
print(f" Restored autonomous state: {base}")
if os.path.exists(meta_base):
meta = torch.load(meta_base, map_location='cpu', weights_only=False)
start_step = meta.get('step', 0)
best_loss = meta.get('best_loss', float('inf'))
if optimizer is not None and meta.get('optimizer_state_dict') is not None:
optimizer.load_state_dict(meta['optimizer_state_dict'])
print(f" Resumed at step {start_step}, best_loss={best_loss:.4f}")
print(f" HPC memories: {model.hippocampus.memory_size}")
if loop is not None:
print(f" Autonomous global_step: {loop.global_step}")
# ── AMP ──────────────────────────────────────────────────────────
use_amp = cfg.use_bf16 and device.type == 'cuda'
scaler = torch.amp.GradScaler('cuda') if use_amp else None
autocast_ctx = torch.amp.autocast('cuda', dtype=torch.bfloat16) if use_amp else \
torch.amp.autocast('mps', dtype=torch.bfloat16) if (args.bf16 and device.type == 'mps') else \
torch.cuda.amp.autocast(enabled=False)
# ── Graceful shutdown handler (Ctrl+C saves brain state) ────────
_shutdown_requested = [False] # Mutable container for closure
def _handle_sigint(signum, frame):
if _shutdown_requested[0]:
print("\n [SIGINT] Force quit.")
sys.exit(1)
_shutdown_requested[0] = True
print("\n [SIGINT] Graceful shutdown — saving brain at end of current step...")
signal.signal(signal.SIGINT, _handle_sigint)
# ── Phase 0: Prenatal Self-Organization ────────────────────────
if args.prenatal > 0 and start_step == 0:
# [bundled] from nct_v2.v11_autonomous import PrenatalDevelopment
print(f"\n{'=' * 60}")
print(f"PHASE 0: PRENATAL SELF-ORGANIZATION")
print(f" Steps: {args.prenatal}")
print(f" The brain bootstraps itself before seeing any data.")
print(f"{'=' * 60}\n")
model.train()
prenatal = PrenatalDevelopment(model)
prenatal_start = time.time()
for ps in range(1, args.prenatal + 1):
with autocast_ctx:
p_metrics = prenatal.step(total_prenatal_steps=args.prenatal)
if ps % max(1, args.prenatal // 20) == 0 or ps == 1:
phase = p_metrics.get('phase', '?')
pc_loss = p_metrics.get('pc_loss', 0)
sigma2 = p_metrics.get('sigma2_mean', 0)
da = p_metrics.get('da_mean', 0)
w_mag = p_metrics.get('weight_mag_mean', 0)
col_diff = p_metrics.get('column_diff', 0)
gate_evo = p_metrics.get('gate_evolution', 0)
elapsed = time.time() - prenatal_start
print(f" prenatal {ps:>5d}/{args.prenatal} | {phase:17s} | "
f"pc {pc_loss:.4f} | σ² {sigma2:.3f} | DA {da:.3f} | "
f"w_mag {w_mag:.4f} | col_diff {col_diff:.6f} | gate_evo {gate_evo:.6f} | "
f"{elapsed:.0f}s", flush=True)
# Early convergence check
if ps >= 100 and prenatal.has_converged():
print(f"\n [CONVERGED] Prenatal development converged at step {ps}/{args.prenatal}")
break
if _shutdown_requested[0]:
print(f"\n [SIGINT] Prenatal interrupted at step {ps}")
break
# Print development report
report = prenatal.get_development_report()
print(f"\n{report}")
# Save post-prenatal state
if args.save_dir:
os.makedirs(args.save_dir, exist_ok=True)
prenatal_path = os.path.join(args.save_dir, 'brain_prenatal.pt')
model.save_state(prenatal_path)
print(f" Saved prenatal brain: {prenatal_path}")
if _shutdown_requested[0]:
_print_summary(args, model, cfg, loop, prenatal_start, 0, float('inf'), 0)
return model
print(f"\nPhase 0 complete. Transitioning to Phase 1: External Data Learning...\n")
# ── Training Loop ────────────────────────────────────────────────
print(f"Starting training: {'continuous' if args.continuous else f'{args.steps} steps'}, mode={args.mode}")
model.train()
total_tokens = 0
start_time = time.time()
step = start_step # Track for graceful shutdown summary
_overfit_strikes = 0 # Consecutive overfitting detections
_overfit_max = 3 # Auto-stop after N consecutive strikes
# Step iterator: finite or infinite (continuous mode)
if args.continuous:
# Unstoppable mode: run forever, self-improving
step_iter = iter(range(start_step + 1, sys.maxsize))
print(f" CONTINUOUS MODE: running indefinitely from step {start_step + 1}")
print(f" (Ctrl+C to stop — brain state auto-saved every {args.save_interval} steps)")
else:
step_iter = iter(range(start_step + 1, args.steps + 1))
for step in step_iter:
step_start = time.time()
# Get batch (priority: TextEnvironment > pre-tokenized > random)
if text_env is not None:
input_ids, targets = text_env.get_batch()
elif train_tokens is not None:
input_ids, targets = get_batch_from_tokens(
train_tokens, args.batch_size, args.seq_len, device, step
)
else:
input_ids, targets = get_random_batch(
cfg.vocab_size, args.batch_size, args.seq_len, device
)
total_tokens += input_ids.numel()
# ── Training step based on mode ──────────────────────────────
if args.mode == 'backprop':
# Standard backprop (baseline comparison — still a valid mode)
with autocast_ctx:
metrics = model.backprop_step(input_ids, targets, optimizer)
elif args.mode == 'hybrid':
# AutonomousLoop handles EVERYTHING:
# - forward pass
# - local learning (PC + Hebbian + neuromod)
# - sleep scheduling + dreams + consolidation
# - self-play (every N steps)
# - EWC estimation (every N steps)
# - self-evaluation
# ALL learning is analytical (.data manipulation) — same as PC mode.
# torch.no_grad() saves ~3 GiB by eliminating unused gradient graph.
with torch.no_grad(), autocast_ctx:
result = loop.step(input_ids, targets, device=device)
# NTP-output-only: analytical delta rule on LM head ONLY.
# Biological: auditory cortex corrects speech production pathway,
# does NOT propagate errors into cortical association areas.
# LR scaled 100x: error signal is O(1/V) per token, delta rule is stable.
# Grad clipping in _local_output_correction prevents divergence.
if result.get('loss') is not None:
_local_output_correction(model, result, lr=args.lr * 100)
metrics = {
'loss': result.get('loss', torch.tensor(0.0)).item() if isinstance(result.get('loss'), torch.Tensor) else result.get('loss', 0.0),
'pc_loss': result.get('pc_loss', torch.tensor(0.0)).item() if isinstance(result.get('pc_loss'), torch.Tensor) else result.get('pc_loss', 0.0),
'ppl': math.exp(min(result.get('loss', torch.tensor(20.0)).item() if isinstance(result.get('loss'), torch.Tensor) else 20.0, 20)),
**{k: v for k, v in result.items() if k not in ('loss', 'pc_loss', 'logits', 'metrics')},
**result.get('metrics', {}), # Flatten model metrics (sigma2, DA, etc.)
}
elif args.mode == 'predictive_coding':
# Pure local learning via AutonomousLoop — NO NTP backprop at all.
# ALL learning is analytical (.data manipulation): PC local_update,
# Hebbian update, and _local_output_correction (delta rule).
# torch.no_grad() eliminates the ~200-400 MB gradient graph that was
# previously built but never used, preventing CUDA OOM on 6 GB GPUs.
with torch.no_grad(), autocast_ctx:
result = loop.step(input_ids, targets, device=device)
# Local output correction: analytical delta rule on LM head ONLY.
# Biologically: auditory cortex computes heard-vs-intended error
# and corrects motor→speech weights. Local, no backprop through columns.
# Without this, PC updates columns but the LM head never learns the
# representation→vocabulary mapping, causing NTP loss to plateau.
# LR scaled 100x for output pathway: the error signal is O(1/V) per token
# so the base lr gives microscopic updates. The delta rule is inherently
# stable (bounded error), so high LR won't diverge. Matches gate_lr_mult=20.
if result.get('loss') is not None:
_local_output_correction(model, result, lr=args.lr * 100)
metrics = {
'loss': result.get('loss', torch.tensor(0.0)).item() if isinstance(result.get('loss'), torch.Tensor) else result.get('loss', 0.0),
'pc_loss': result.get('pc_loss', torch.tensor(0.0)).item() if isinstance(result.get('pc_loss'), torch.Tensor) else result.get('pc_loss', 0.0),
'ppl': math.exp(min(result.get('loss', torch.tensor(20.0)).item() if isinstance(result.get('loss'), torch.Tensor) else 20.0, 20)),
**{k: v for k, v in result.items() if k not in ('loss', 'pc_loss', 'logits', 'metrics')},
**result.get('metrics', {}), # Flatten model metrics (sigma2, DA, etc.)
}
elif args.mode == 'hebbian':
# Pure Hebbian via AutonomousLoop — no backprop, no PC loss backward
with torch.no_grad():
result = loop.step(input_ids, targets, device=device)
# Local output correction: analytical delta rule on LM head ONLY.
# Even pure Hebbian mode needs this — Hebbian updates L2/3 associations
# but never touches the representation→vocabulary mapping in the LM head.
# Without this, loss plateaus above random baseline (as seen in prior runs).
# LR scaled 100x: same rationale as PC mode (error O(1/V), delta rule stable).
if result.get('loss') is not None:
_local_output_correction(model, result, lr=args.lr * 100)
metrics = {
'loss': result.get('loss', torch.tensor(0.0)).item() if isinstance(result.get('loss'), torch.Tensor) else result.get('loss', 0.0),
'ppl': math.exp(min(result.get('loss', torch.tensor(20.0)).item() if isinstance(result.get('loss'), torch.Tensor) else 20.0, 20)),
**{k: v for k, v in result.items() if k not in ('loss', 'pc_loss', 'logits', 'metrics')},
**result.get('metrics', {}), # Flatten model metrics (sigma2, DA, etc.)
}
# ── Wake-Sleep (backprop mode still uses manual sleep) ───────
if args.mode == 'backprop' and model.should_sleep():
print(f"\n [SLEEP] Entering sleep phase (wake steps: {model.learning_manager.wake_sleep.wake_steps})")
sleep_metrics = model.sleep_phase()
print(f" [SLEEP] Replayed {sleep_metrics.get('replayed_memories', 0)} memories")
print(f" [SLEEP] Sleep phase #{sleep_metrics.get('sleep_phase', 0)} complete\n")
# ── Logging ──────────────────────────────────────────────────
step_time = time.time() - step_start
loss_val = metrics.get('loss', 0.0)
# Self-repair: checkpoint best + rollback if diverging
repair = model.checkpoint_best(loss_val)
if repair.get('rollback'):
print(f"\n [ROLLBACK] Loss diverged: {repair['from_loss']:.4f} → {repair['to_loss']:.4f}")
print(f" [ROLLBACK] Count: {repair['rollback_count']}, Sleep: {repair['sleep_interval']}\n")
if step % args.log_interval == 0 or step == 1:
elapsed = time.time() - start_time
tok_per_sec = total_tokens / elapsed if elapsed > 0 else 0
log_parts = [
f"step {step:>5d}/{'∞' if args.continuous else args.steps}",
f"loss {loss_val:.4f}",
f"ppl {metrics.get('ppl', 0):.1f}",
f"pc {metrics.get('pc_loss', 0):.4f}",
f"σ² {metrics.get('sigma2_mean', 0):.3f}",
f"DA {metrics.get('da_mean', 0):.3f}",
f"tok/s {tok_per_sec:.0f}",
f"{step_time*1000:.0f}ms",
]
if 'plasticity_mean' in metrics:
log_parts.append(f"plast {metrics['plasticity_mean']:.3f}")
if metrics.get('hpc_memory_size', 0) > 0:
log_parts.append(f"hpc {metrics['hpc_memory_size']}")
print(" | ".join(log_parts), flush=True)
# ── Generalization Monitor (σ² ratio — brain's overfitting detector) ──
# The model detects its own overfitting through its uncertainty system:
# σ² ratio (val/train) ≈ 1.0 → generalizing well
# σ² ratio > 2.0 → overconfident on train, surprised by new → overfitting
# Response: increase sleep frequency (more forgetting = more generalization)
if val_tokens is not None and step % 500 == 0 and step > 0:
# Save column outputs — monitoring forward passes would overwrite them,
# causing the next training step's Hebbian update to fire on stale data.
_saved_col_outputs = model._last_column_outputs
_saved_predictions = model._last_predictions
_saved_targets = model._last_targets
_saved_precisions = model._last_precisions
_saved_neuromod = model._last_neuromod
_saved_errors = model._last_errors
model_was_training = model.training
model.eval() # Prevent HPC encoding during monitoring
with torch.no_grad(), torch.amp.autocast('cuda', dtype=torch.bfloat16):
# Train σ²: mean precision on 5 training batches
train_sigma2_samples = []
for s in range(5):
t_input, _ = get_batch_from_tokens(
train_tokens, min(args.batch_size, 8), args.seq_len, device, step + s
)
model.forward(t_input)
if model._last_column_outputs:
t_s2 = sum(o.sigma2.mean().item() for o in model._last_column_outputs) / len(model._last_column_outputs)
train_sigma2_samples.append(t_s2)
# Val σ²: mean precision on 5 validation batches
val_sigma2_samples = []
for s in range(5):
v_input, _ = get_batch_from_tokens(
val_tokens, min(args.batch_size, 8), args.seq_len, device, step + s
)
model.forward(v_input)
if model._last_column_outputs:
v_s2 = sum(o.sigma2.mean().item() for o in model._last_column_outputs) / len(model._last_column_outputs)
val_sigma2_samples.append(v_s2)
if model_was_training:
model.train()
# Restore column outputs so next training step's learning is correct
model._last_column_outputs = _saved_col_outputs
model._last_predictions = _saved_predictions
model._last_targets = _saved_targets
model._last_precisions = _saved_precisions
model._last_neuromod = _saved_neuromod
model._last_errors = _saved_errors
if train_sigma2_samples and val_sigma2_samples:
train_s2 = sum(train_sigma2_samples) / len(train_sigma2_samples)
val_s2 = sum(val_sigma2_samples) / len(val_sigma2_samples)
s2_ratio = val_s2 / max(train_s2, 0.01)
status = "HEALTHY"
if s2_ratio > 2.0:
_overfit_strikes += 1
status = f"OVERFITTING (strike {_overfit_strikes}/{_overfit_max})"
# Brain response: increase sleep frequency (more consolidation)
if loop is not None:
old_interval = loop.config.sleep_interval
loop.config.sleep_interval = max(20, old_interval - 20)
status += f" sleep:{old_interval}→{loop.config.sleep_interval}"
else:
_overfit_strikes = max(0, _overfit_strikes - 1) # Recovery
# Restore sleep interval toward default when healthy
if loop is not None and _overfit_strikes == 0:
default_sleep = cfg.sleep_interval if hasattr(cfg, 'sleep_interval') else 100
if loop.config.sleep_interval < default_sleep:
loop.config.sleep_interval = min(default_sleep, loop.config.sleep_interval + 10)
if s2_ratio < 0.8:
status = "UNDERFITTING"
print(f" [GENERALIZATION] σ² train={train_s2:.3f} val={val_s2:.3f} "
f"ratio={s2_ratio:.2f} → {status}", flush=True)
# Auto-stop: 3 consecutive overfitting checks = stop training
if _overfit_strikes >= _overfit_max:
print(f"\n [AUTO-STOP] Sustained overfitting detected "
f"({_overfit_max} consecutive checks with σ² ratio > 2.0)")
print(f" Saving final checkpoint and stopping.")
if args.save_dir:
os.makedirs(args.save_dir, exist_ok=True)
model.save_state(os.path.join(args.save_dir, 'brain_latest.pt'))
if loop is not None:
loop.save_autonomous_state(os.path.join(args.save_dir, 'autonomous_latest.pt'))
torch.save({'step': step, 'best_loss': best_loss},
os.path.join(args.save_dir, 'meta_latest.pt'))
_shutdown_requested[0] = True
# ── Checkpointing ─────────────────────────────────────────
if args.save_dir:
os.makedirs(args.save_dir, exist_ok=True)
# 1. Best model: save when loss improves (min 100 steps apart to avoid thrashing early on)
if loss_val < best_loss and (step - getattr(model, '_best_save_step', 0)) >= 100:
best_loss = loss_val
model._best_save_step = step
best_brain = os.path.join(args.save_dir, 'brain_best.pt')
model.save_state(best_brain)
if loop is not None:
loop.save_autonomous_state(os.path.join(args.save_dir, 'autonomous_best.pt'))
torch.save({'step': step, 'best_loss': best_loss, 'metrics': metrics},
os.path.join(args.save_dir, 'meta_best.pt'))
print(f" NEW BEST {loss_val:.4f} (PPL {math.exp(min(loss_val, 20)):.1f}) → {best_brain}")
elif loss_val < best_loss:
best_loss = loss_val # Track best loss even if not saving yet
# 2. Rolling checkpoint: overwrite single file every save_interval
if step % args.save_interval == 0:
brain_path = os.path.join(args.save_dir, 'brain_latest.pt')
model.save_state(brain_path)
if loop is not None:
loop.save_autonomous_state(os.path.join(args.save_dir, 'autonomous_latest.pt'))
torch.save({
'step': step,
'optimizer_state_dict': optimizer.state_dict() if optimizer else None,
'best_loss': best_loss,
'metrics': metrics,
}, os.path.join(args.save_dir, 'meta_latest.pt'))
print(f" Saved checkpoint (step {step}) → {brain_path}")
# ── Graceful shutdown check ───────────────────────────────────
if _shutdown_requested[0]:
# Save final state to rolling checkpoint before exit
if args.save_dir:
os.makedirs(args.save_dir, exist_ok=True)
brain_path = os.path.join(args.save_dir, 'brain_latest.pt')
model.save_state(brain_path)
if loop is not None:
loop.save_autonomous_state(os.path.join(args.save_dir, 'autonomous_latest.pt'))
torch.save({
'step': step,
'optimizer_state_dict': optimizer.state_dict() if optimizer else None,
'best_loss': best_loss,
'metrics': metrics,
}, os.path.join(args.save_dir, 'meta_latest.pt'))
print(f" [SHUTDOWN] Brain saved at step {step} → {brain_path}")
break
# ── Final Summary ────────────────────────────────────────────────
_print_summary(args, model, cfg, loop, start_time, total_tokens, best_loss, step)
return model
def _print_summary(args, model, cfg, loop, start_time, total_tokens, best_loss, final_step):
"""Print training summary. Factored out so Ctrl+C handler can use it."""
elapsed = time.time() - start_time
print(f"\n{'=' * 60}")
print(f"Training {'interrupted' if args.continuous else 'complete'}!")
print(f" Steps: {final_step}")
print(f" Time: {elapsed:.1f}s ({elapsed/60:.1f}m)")
print(f" Best loss: {best_loss:.4f}")
print(f" Best PPL: {math.exp(min(best_loss, 20)):.1f}")
print(f" Tokens/s: {total_tokens / elapsed:.0f}" if elapsed > 0 else " Tokens/s: 0")
if loop is not None:
auto_status = loop.get_status()
print(f" Autonomous steps: {auto_status['global_step']}")
print(f" Dreams: {auto_status['total_dreams']}")
print(f" HPC memories: {model.hippocampus.memory_size if cfg.hpc_enabled else 0}")
elif cfg.wake_sleep_enabled:
status = model.learning_manager.get_status()
print(f" Sleep phases: {status['sleep_phases']}")
print(f" HPC memories: {model.hippocampus.memory_size if cfg.hpc_enabled else 0}")
print(f"{'=' * 60}")
# ═══════════════════════════════════════════════════════════════════════
# Smoke Test
# ═══════════════════════════════════════════════════════════════════════
def smoke_test():
"""Quick validation that the model works."""
print("=" * 60)
print("NCT V11 SMOKE TEST")
print("=" * 60)
device = torch.device('cuda' if torch.cuda.is_available() else
'mps' if torch.backends.mps.is_available() else 'cpu')
print(f"Device: {device}")
# Small config for testing
cfg = V11Config(
d_model=128,
d_column=128,
n_columns=4,
d_ff=512,
vocab_size=1000,
max_seq_len=64,
n_assoc_heads=4,
d_inhibitory=32,
nmda_slots=2,
nmda_d_slot=32,
silent_d_trace=32,
phono_capacity=4,
phono_d_slot=32,
d_relay=64,
d_trn=8,
hpc_d_sparse=256,
hpc_memory_size=32,
d_cerebellar=64,
d_bg=32,
n_inference_steps=2,
dropout=0.0,
learning_mode='hybrid',
wake_sleep_enabled=True,
sleep_interval=5,
sleep_replay_steps=3,
)
model = create_v11_model(cfg).to(device)
params = model.count_parameters()
print(f"\nModel parameters: {params['total']:,} ({params['trainable']:,} trainable)")
# Test 1: Forward pass
print("\n[TEST 1] Forward pass...")
B, T = 2, 32
input_ids = torch.randint(0, cfg.vocab_size, (B, T), device=device)
targets = torch.randint(0, cfg.vocab_size, (B, T), device=device)
result = model.forward(input_ids, targets)
assert result['logits'].shape == (B, T, cfg.vocab_size), f"Bad logits shape: {result['logits'].shape}"
assert 'loss' in result, "No loss in result"
assert 'pc_loss' in result, "No pc_loss in result"
assert torch.isfinite(result['loss']), f"Non-finite loss: {result['loss']}"
print(f" logits: {result['logits'].shape}")
print(f" loss: {result['loss'].item():.4f}")
print(f" pc_loss: {result['pc_loss'].item():.4f}")
print(f" cb_loss: {result['cb_loss'].item():.4f}")
print(f" PASS")
# Test 2: Local learning step
print("\n[TEST 2] Local learning step...")
learn_metrics = model.local_learning_step()
print(f" metrics: {learn_metrics}")
print(f" PASS")
# Test 3: Backprop step
print("\n[TEST 3] Backprop step...")
optimizer = torch.optim.AdamW(model.get_optimizer_groups(lr=1e-3))
bp_metrics = model.backprop_step(input_ids, targets, optimizer)
assert 'loss' in bp_metrics, "No loss in backprop metrics"
print(f" loss: {bp_metrics['loss']:.4f}")
print(f" ppl: {bp_metrics['ppl']:.1f}")
print(f" PASS")
# Test 4: Wake-sleep cycle
print("\n[TEST 4] Wake-sleep cycle...")
sleep_triggered = False
# Run enough steps to trigger sleep (dev program may increase interval)
effective_interval = model.learning_manager.development.get_sleep_interval()
for i in range(effective_interval + 5):
result = model.forward(input_ids, targets)
model.local_learning_step()
if model.should_sleep():
sleep_metrics = model.sleep_phase()
print(f" Sleep triggered at step {i+1} (interval={effective_interval})")
print(f" Replayed: {sleep_metrics.get('replayed_memories', 0)} memories")
sleep_triggered = True
break
assert sleep_triggered, f"Sleep never triggered in {effective_interval+5} steps!"
print(f" PASS")
# Test 5: Generation
print("\n[TEST 5] Generation...")
prompt = torch.randint(0, cfg.vocab_size, (1, 8), device=device)
generated = model.generate(prompt, max_new_tokens=16)
assert generated.shape == (1, 24), f"Bad generated shape: {generated.shape}"
print(f" Generated: {generated.shape}")
print(f" PASS")
# Test 6: No NaN/Inf
print("\n[TEST 6] Numerical stability...")
for name, param in model.named_parameters():
assert torch.isfinite(param).all(), f"Non-finite param: {name}"
print(f" All parameters finite")
print(f" PASS")
# Test 7: Gate values
print("\n[TEST 7] Gate values (identity at init check)...")
gates = {}
gates.update(model.columns[0].get_gate_values())
for name, val in gates.items():
print(f" {name}: {val:.4f}")
# All gates should be near sigmoid(-2) ≈ 0.1192 at init
# After a few steps, they may have moved
print(f" PASS")
# Test 8: Autonomous loop
print("\n[TEST 8] Autonomous loop...")
# [bundled] from nct_v2.v11_autonomous import AutonomousLoop, AutonomousConfig
auto_cfg = AutonomousConfig(sleep_interval=5, eval_interval=3, consolidation_interval=100)
loop = AutonomousLoop(model, auto_cfg)
for i in range(7):
input_batch = torch.randint(0, cfg.vocab_size, (2, 32), device=device)
target_batch = torch.randint(0, cfg.vocab_size, (2, 32), device=device)
result = loop.step(input_batch, target_batch, device=device)
status = loop.get_status()
assert status['global_step'] == 7, f"Expected 7 steps, got {status['global_step']}"
assert status['total_experiences'] >= 7, f"Expected >=7 experiences, got {status['total_experiences']}"
print(f" Steps: {status['global_step']}, Experiences: {status['total_experiences']}")
print(f" Dreams: {status['total_dreams']}, Sleep pressure: {status['sleep_pressure']:.3f}")
print(f" State: {status['state']}")
print(f" PASS")
# Test 9: learn_from_experience (always-on)
print("\n[TEST 9] Learn from experience (always-on)...")
result = model.learn_from_experience(input_ids, targets)
assert 'logits' in result, "No logits"
assert 'learning_metrics' in result, "No learning metrics"
print(f" Learning metrics: {list(result['learning_metrics'].keys())}")
print(f" PASS")