Cortex-System-One / Model.py
siddiVinayaka's picture
Release Cortex-System-One Architecture, Model Card, and Inference Suite
b92a420 verified
Raw History Blame Contribute Delete
60.9 kB
""" Nexus β€” Simplified Transformer Architecture ============================================= Clean 20-layer transformer with integrated neural memory. Architecture (brain-inspired): Embed β†’ Memory β†’ [Layers 0-6] β†’ Memory β†’ [Layers 7-13] β†’ Memory β†’ [Layers 14-19] β†’ Output ↑ input sensory ↑ bridge processing ↑ bridge output context update update Components: - GQA Attention (heads=16, kv_heads=4) + Flash Attention 2 - SwiGLU FFN (2.67Γ— expansion) - GlobalNeuralMemory at 3 strategic bridge points - YaRN RoPE for context extension - MTP head for multi-token prediction training """ import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Optional, List, Tuple, Dict, Any, Union from v3_modules import YaRNRotaryEmbedding, MTPHead, HyperConnection, RMSNorm # ───────────────────────────────────────────────────────────────────────────── # BASIC BUILDING BLOCKS # ───────────────────────────────────────────────────────────────────────────── def apply_rotary_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: """Apply rotary position embeddings. x: [B, H, S, D]""" d = x.shape[-1] x1, x2 = x[..., : d // 2], x[..., d // 2 :] cos = cos.unsqueeze(0).unsqueeze(0) sin = sin.unsqueeze(0).unsqueeze(0) return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1) class SwiGLU(nn.Module): """SwiGLU FFN β€” the standard modern FFN choice.""" def __init__(self, dim: int, hidden_dim: Optional[int] = None, num_layers: int = 1, layer_id: int = 0): super().__init__() if hidden_dim is None: hidden_dim = int(2.67 * dim) self.w1 = nn.Linear(dim, hidden_dim, bias=False) self.w2 = nn.Linear(dim, hidden_dim, bias=False) self.w3 = nn.Linear(hidden_dim, dim, bias=False) self.layer_id = layer_id self.inner_norm = RMSNorm(hidden_dim) # Standard init for w1, w2 nn.init.normal_(self.w1.weight, std=0.02) nn.init.normal_(self.w2.weight, std=0.02) # Scale down the output projection to stabilize deep residuals std_proj = 0.02 / math.sqrt(2 * num_layers) nn.init.normal_(self.w3.weight, std=std_proj) def forward(self, x: torch.Tensor) -> torch.Tensor: hidden = F.silu(self.w1(x)) * self.w2(x) hidden_normed = self.inner_norm(hidden) return self.w3(hidden_normed) # ───────────────────────────────────────────────────────────────────────────── # GQA ATTENTION β€” Grouped Query Attention with Flash Attention 2 # ───────────────────────────────────────────────────────────────────────────── class Attention(nn.Module): """Grouped Query Attention with KV cache and Flash Attention 2 support.""" def __init__(self, dim: int, num_heads: int = 16, num_kv_heads: int = 4, num_layers: int = 20, layer_id: int = 0, attn_scale: float = 1.0): super().__init__() self.num_heads = num_heads self.num_kv_heads = num_kv_heads self.head_dim = dim // num_heads self.n_rep = num_heads // num_kv_heads self.q = nn.Linear(dim, num_heads * self.head_dim, bias=False) self.k = nn.Linear(dim, num_kv_heads * self.head_dim, bias=False) self.v = nn.Linear(dim, num_kv_heads * self.head_dim, bias=False) self.out = nn.Linear(num_heads * self.head_dim, dim, bias=False) self.layer_id = layer_id self.attn_scale = attn_scale self.inner_norm = RMSNorm(num_heads * self.head_dim) self.q_norm = RMSNorm(self.head_dim) self.k_norm = RMSNorm(self.head_dim) # Standard init for q, k, v for layer in (self.q, self.k, self.v): nn.init.normal_(layer.weight, std=0.02) # Scale down output projection std_proj = 0.02 / math.sqrt(2 * num_layers) nn.init.normal_(self.out.weight, std=std_proj) self._flash_available = False try: import flash_attn self._flash_available = True except ImportError: pass def forward( self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, past_kv=None, use_flash: bool = False, is_causal: Optional[bool] = None, ) -> Tuple[torch.Tensor, Any]: B, S, D = x.shape q = self.q(x).view(B, S, self.num_heads, self.head_dim) k = self.k(x).view(B, S, self.num_kv_heads, self.head_dim) v = self.v(x).view(B, S, self.num_kv_heads, self.head_dim).transpose(1, 2) q = self.q_norm(q).transpose(1, 2) k = self.k_norm(k).transpose(1, 2) q = apply_rotary_emb(q, cos, sin) k = apply_rotary_emb(k, cos, sin) # KV cache if past_kv is not None: if hasattr(past_kv, 'update'): k, v = past_kv.update(k, v) else: past_k, past_v = past_kv k = torch.cat([past_k, k], dim=2) v = torch.cat([past_v, v], dim=2) new_past_kv = past_kv if hasattr(past_kv, 'update') else (k, v) if is_causal is None: is_causal = (past_kv is None) # Flash Attention 2 if use_flash and self._flash_available: from flash_attn import flash_attn_func q_fa = q.transpose(1, 2) if self.n_rep > 1: k_fa = k.repeat_interleave(self.n_rep, dim=1).transpose(1, 2) v_fa = v.repeat_interleave(self.n_rep, dim=1).transpose(1, 2) else: k_fa, v_fa = k.transpose(1, 2), v.transpose(1, 2) orig_dtype = q_fa.dtype scale = self.attn_scale / math.sqrt(self.head_dim) attn = flash_attn_func( q_fa.to(torch.bfloat16), k_fa.to(torch.bfloat16), v_fa.to(torch.bfloat16), causal=is_causal, softmax_scale=scale, ).to(orig_dtype).reshape(B, S, -1) else: # PyTorch SDPA (also very fast) if self.n_rep > 1: k_s = k.repeat_interleave(self.n_rep, dim=1) v_s = v.repeat_interleave(self.n_rep, dim=1) else: k_s, v_s = k, v scale = self.attn_scale / math.sqrt(self.head_dim) attn = F.scaled_dot_product_attention(q, k_s, v_s, is_causal=is_causal, scale=scale) attn = attn.transpose(1, 2).reshape(B, S, -1) attn_normed = self.inner_norm(attn) return self.out(attn_normed), new_past_kv # ───────────────────────────────────────────────────────────────────────────── # TRANSFORMER BLOCK β€” Attention + FFN with pre-norm residuals & HyperConnections # ───────────────────────────────────────────────────────────────────────────── class TransformerBlock(nn.Module): """Single transformer layer: RMSNorm β†’ Attention β†’ RMSNorm β†’ SwiGLU.""" def __init__(self, dim: int, num_heads: int = 16, num_kv_heads: int = 4, num_layers: int = 20, layer_id: int = 0, use_flash: bool = False, attn_scale: float = 1.0): super().__init__() self.attn_norm = RMSNorm(dim) self.attn = Attention(dim, num_heads, num_kv_heads, num_layers, layer_id, attn_scale=attn_scale) self.ffn_norm = RMSNorm(dim) self.ffn = SwiGLU(dim, num_layers=num_layers, layer_id=layer_id) # Hyper connections self.hyper_attn = HyperConnection(dim, n_streams=2) self.hyper_ffn = HyperConnection(dim, n_streams=2) self.use_flash = use_flash def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, past_kv=None, is_causal: Optional[bool] = None) -> Tuple[torch.Tensor, Any]: # Attention with residual attn_out, new_kv = self.attn( self.attn_norm(x), cos, sin, past_kv, use_flash=self.use_flash, is_causal=is_causal) h = self.hyper_attn(x, attn_out) # learnable residual # FFN with residual ffn_out = self.ffn(self.ffn_norm(h)) h = self.hyper_ffn(h, ffn_out) # second learnable residual return h, new_kv # ───────────────────────────────────────────────────────────────────────────── # CROSS ATTENTION β€” For Neural Memory read/write # ───────────────────────────────────────────────────────────────────────────── class CrossAttention(nn.Module): """Cross-attention for memory read/write operations.""" def __init__(self, dim: int, num_heads: int = 16, num_kv_heads: int = 4): super().__init__() self.num_heads = num_heads self.num_kv_heads = num_kv_heads self.head_dim = dim // num_heads self.n_rep = num_heads // num_kv_heads self.q = nn.Linear(dim, num_heads * self.head_dim, bias=False) self.k = nn.Linear(dim, num_kv_heads * self.head_dim, bias=False) self.v = nn.Linear(dim, num_kv_heads * self.head_dim, bias=False) self.out = nn.Linear(num_heads * self.head_dim, dim, bias=False) # Standard init for q, k, v for layer in (self.q, self.k, self.v): nn.init.normal_(layer.weight, std=0.02) # Standard scale for out projection nn.init.normal_(self.out.weight, std=0.02) def forward(self, x: torch.Tensor, context: torch.Tensor) -> torch.Tensor: B, S, _ = x.shape _, S_ctx, _ = context.shape q = self.q(x).view(B, S, self.num_heads, self.head_dim).transpose(1, 2) k = self.k(context).view(B, S_ctx, self.num_kv_heads, self.head_dim).transpose(1, 2) v = self.v(context).view(B, S_ctx, self.num_kv_heads, self.head_dim).transpose(1, 2) if self.n_rep > 1: k = k.repeat_interleave(self.n_rep, dim=1) v = v.repeat_interleave(self.n_rep, dim=1) attn = F.scaled_dot_product_attention(q, k, v) return self.out(attn.transpose(1, 2).reshape(B, S, -1)) # ───────────────────────────────────────────────────────────────────────────── # GLOBAL NEURAL MEMORY β€” Persistent memory that learns across the sequence # ───────────────────────────────────────────────────────────────────────────── class GlobalNeuralMemory(nn.Module): """Persistent cognitive memory with task-driven read/write routing. Loss v2 does not impose a generic "memory must be used" or diversity target. Instead, the downstream decision objective supplies utility signals for the read intervention, the memory write, and final reflection. """ def __init__(self, dim: int, num_slots: int = 128, heads: int = 16, retain_floor: float = 0.5, write_scale: float = 0.3, role: str = "generic"): super().__init__() self.num_slots = num_slots self.dim = dim self.role = role self.memory_init = nn.Parameter(torch.randn(num_slots, dim) * 0.02) self.norm_x = RMSNorm(dim) self.norm_mem = RMSNorm(dim) self.mem_norm = RMSNorm(dim) self.read_attn = CrossAttention(dim, heads, max(1, heads // 4)) self.write_attn = CrossAttention(dim, heads, max(1, heads // 4)) # Read router: its gate is supervised by downstream task utility. self.read_gate = nn.Sequential( nn.Linear(dim * 2, dim), nn.Sigmoid(), ) nn.init.zeros_(self.read_gate[0].weight) nn.init.constant_(self.read_gate[0].bias, 0.0) self.write_scale = write_scale self.retain_floor = retain_floor # Write admission router: its gate is supervised by future-example # utility. Slot contents are trained directly through downstream loss. self.affinity_gate = nn.Sequential( nn.Linear(dim * 2, dim), nn.Sigmoid(), ) nn.init.zeros_(self.affinity_gate[0].weight) nn.init.constant_(self.affinity_gate[0].bias, 0.0) # Retention is learned through the task gradient through new_memory. self.gate = nn.Sequential( nn.Linear(dim, dim), nn.Sigmoid(), ) nn.init.zeros_(self.gate[0].weight) target_retention = min(retain_floor + 0.3, 0.9) if retain_floor == 0.3: target_retention = 0.6 elif retain_floor == 0.5: target_retention = 0.7 elif retain_floor == 0.7: target_retention = 0.8 bias_val = math.log(target_retention / (1.0 - target_retention)) nn.init.constant_(self.gate[0].bias, bias_val) self.last_read_gate: Optional[torch.Tensor] = None self.last_write_mask: Optional[torch.Tensor] = None def init_memory(self, batch_size: int, device: torch.device) -> torch.Tensor: return self.memory_init.unsqueeze(0).expand(batch_size, -1, -1).clone() def forward( self, x: torch.Tensor, memory_state: torch.Tensor, domain_id: Optional[int] = None, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: x_norm = self.norm_x(x) memory_state = memory_state + (self.memory_init * 0.0).unsqueeze(0) mem_norm = self.norm_mem(memory_state) # Read intervention: gated additive residual injection from memory. read_out = self.read_attn(x_norm, mem_norm) gate = self.read_gate(torch.cat([x, read_out], dim=-1)) read_delta = gate * read_out x_new = x + read_delta if not (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling()): self.last_read_gate = gate.detach() # Write intervention. mem_query = mem_norm + self.memory_init.unsqueeze(0) mem_update = self.write_attn(mem_query, x_norm) affinity = self.affinity_gate(torch.cat([mem_norm, mem_update], dim=-1)) # Unified Cognitive Memory: # Full capacity across all slots without artificial domain quadrant walls, # exactly as trained during pretraining (30B tokens / 153k steps). forget = self.gate(memory_state).clamp(self.retain_floor, 0.95) candidate = forget * memory_state + (1.0 - forget) * (self.write_scale * mem_update) new_memory = affinity * candidate + (1.0 - affinity) * memory_state new_memory = self.mem_norm(new_memory) if not (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling()): self.last_write_mask = affinity.detach() lb_loss = torch.zeros((), device=x.device, dtype=x.dtype) return x_new, new_memory, lb_loss, gate, affinity, read_delta, forget # ───────────────────────────────────────────────────────────────────────────── # KV CACHE β€” Simple flat KV cache for inference # ───────────────────────────────────────────────────────────────────────────── class KVCache: """Simple KV cache for autoregressive inference.""" def __init__(self, num_layers: int): self.num_layers = num_layers self.kvs: List[Any] = [None] * num_layers def get_past_len(self) -> int: """Get the sequence length of cached keys.""" for kv in self.kvs: if kv is not None: if hasattr(kv, 'seq_len'): return kv.seq_len return kv[0].shape[2] return 0 def update(self, layer_idx: int, new_kv): self.kvs[layer_idx] = new_kv def reset(self): self.kvs = [None] * self.num_layers # ───────────────────────────────────────────────────────────────────────────── # DYNAMIC SYSTEM 1 DECISION HEAD # ───────────────────────────────────────────────────────────────────────────── # --------------------------------------------------------------------------- # Dynamic Decision Head # --------------------------------------------------------------------------- class DynamicDecisionHead(nn.Module): """ Laya-Aligned Non-Causal Transformer Decision Head with GELU Non-Linear Scorer. Clean, minimal, high-capacity, zero artificial heuristics: 1. Task & Domain Conditioning: type_emb(3, D) + domain_emb(16, D) 2. Non-Causal Bidirectional Comparator: [Q_cond, C_1, ..., C_K] -> TransformerEncoderLayer 3. Exact Laya Non-Linear Scorer: LayerNorm -> Linear(D, D) -> GELU -> Linear(D, 1) Zero memory cross-attention, zero artificial scaling, zero distractor subtraction heuristics. """ def __init__( self, dim: int = 1280, num_layers: int = 2, heads: int = 16, dropout: float = 0.10, **kwargs, ): super().__init__() self.dim = dim self.num_layers = num_layers if num_layers is not None else 2 # 1. Task & Domain Conditioning self.type_emb = nn.Embedding(3, dim) nn.init.normal_(self.type_emb.weight, std=0.02) self.domain_emb = nn.Embedding(16, dim) nn.init.normal_(self.domain_emb.weight, std=0.02) # 2. 2-Layer Non-Causal Bidirectional Transformer Comparator (Exact Laya head_layers=2) if self.num_layers > 0: encoder_layer = nn.TransformerEncoderLayer( d_model=dim, nhead=heads, dim_feedforward=4 * dim, dropout=dropout, batch_first=True, norm_first=True, # Pre-LN ) self.transformer = nn.TransformerEncoder( encoder_layer, num_layers=self.num_layers, enable_nested_tensor=False, ) for layer in self.transformer.layers: nn.init.orthogonal_(layer.self_attn.out_proj.weight, gain=1.0) nn.init.orthogonal_(layer.linear1.weight, gain=1.0) nn.init.orthogonal_(layer.linear2.weight, gain=1.0) else: self.transformer = None # 3. Causal Context Fusion (Solves Causal Option Blindness) # Pre-LN normalizations and projection to inject global sequence summary Q # into candidate vectors before entering comparator and scoring. self.query_proj = nn.Linear(dim, dim) nn.init.orthogonal_(self.query_proj.weight, gain=1.0) nn.init.zeros_(self.query_proj.bias) self.cand_norm = nn.LayerNorm(dim) self.query_norm = nn.LayerNorm(dim) self.fusion_norm = nn.LayerNorm(dim) # 4. Exact Laya Non-Linear Scorer (LayerNorm -> Linear(D, D) -> GELU -> Linear(D, 1), NO DROPOUT) self.scorer = nn.Sequential( nn.LayerNorm(dim), nn.Linear(dim, dim), nn.GELU(), nn.Linear(dim, 1), ) for m in self.scorer.modules(): if isinstance(m, nn.Linear): nn.init.orthogonal_(m.weight, gain=1.0) if m.bias is not None: nn.init.zeros_(m.bias) def forward( self, global_context: Optional[torch.Tensor] = None, candidate_hidden: Optional[torch.Tensor] = None, candidate_mask: Optional[torch.Tensor] = None, primitive_id: Optional[Any] = None, domain_id: Optional[Any] = None, sequence_context: Optional[torch.Tensor] = None, candidate_positions: Optional[torch.Tensor] = None, return_ablated: bool = False, **kwargs, ) -> Any: device = candidate_hidden.device if candidate_hidden is not None else sequence_context.device B = candidate_hidden.size(0) if candidate_hidden is not None else sequence_context.size(0) target_dtype = sequence_context.dtype if sequence_context is not None else (candidate_hidden.dtype if candidate_hidden is not None else torch.float32) if primitive_id is not None: p_idx = primitive_id if isinstance(primitive_id, torch.Tensor) else torch.tensor([primitive_id] * B, device=device) p_idx = p_idx.to(device=device, dtype=torch.long).view(-1).clamp(0, 2) if p_idx.numel() == 1 and B > 1: p_idx = p_idx.expand(B) t_emb = self.type_emb(p_idx) else: t_emb = torch.zeros((B, self.dim), device=device, dtype=target_dtype) if domain_id is not None: d_idx = domain_id if isinstance(domain_id, torch.Tensor) else torch.tensor([domain_id] * B, device=device) d_idx = d_idx.to(device=device, dtype=torch.long).view(-1).clamp(0, 15) if d_idx.numel() == 1 and B > 1: d_idx = d_idx.expand(B) d_emb = self.domain_emb(d_idx) else: d_emb = torch.zeros((B, self.dim), device=device, dtype=target_dtype) cond = t_emb + d_emb # [B, D] # 2. Extract Candidate representations via vectorized mean-pooling if not provided if candidate_hidden is None: if sequence_context is not None and candidate_positions is not None: if candidate_positions.ndim == 3 and candidate_positions.shape[-1] == 2: prefix = torch.cat( [ torch.zeros(B, 1, sequence_context.size(-1), device=device, dtype=sequence_context.dtype), torch.cumsum(sequence_context, dim=1), ], dim=1, ) s = candidate_positions[:, :, 0].clamp(0, sequence_context.size(1) - 1) e = candidate_positions[:, :, 1].clamp(0, sequence_context.size(1) - 1) e = torch.maximum(s, e) s_idx = s.unsqueeze(-1).expand(-1, -1, sequence_context.size(-1)) e_idx = (e + 1).unsqueeze(-1).expand(-1, -1, sequence_context.size(-1)) sum_s = torch.gather(prefix, dim=1, index=s_idx) sum_e = torch.gather(prefix, dim=1, index=e_idx) counts = (e - s + 1).unsqueeze(-1).float().clamp_min(1.0) candidate_hidden = ((sum_e - sum_s) / counts).to(sequence_context.dtype) else: pos_idx = candidate_positions[:, :, -1] if candidate_positions.ndim == 3 else candidate_positions pos_idx = pos_idx.clamp(0, sequence_context.size(1) - 1) idx = pos_idx.unsqueeze(-1).expand(-1, -1, sequence_context.size(-1)) candidate_hidden = torch.gather(sequence_context, dim=1, index=idx) else: raise ValueError("candidate_hidden or (sequence_context and candidate_positions) must be provided.") B, K, D = candidate_hidden.shape if global_context is None: global_context = sequence_context[:, -1, :] if sequence_context is not None else candidate_hidden.mean(dim=1) # 3. Solves Causal Option Blindness: # Candidate k was extracted from option k's token span in the causal autoregressive backbone. # Early options (e.g. Option A) never attended to later options (B, C, D) in the backbone. # Here, we inject the contextualized query Q (the final sequence token which HAS causally # attended to the entire state, instructions, and all options) into each candidate vector: Q_norm = self.query_norm(global_context + cond) # [B, D] Q_proj = self.query_proj(Q_norm).unsqueeze(1) # [B, 1, D] cand_injected = self.cand_norm(candidate_hidden + Q_proj + cond.unsqueeze(1)) # [B, K, D] # 4. Form interaction sequence [Q_cond, C_1_cond, C_2_cond, ..., C_K_cond] tokens = torch.cat([Q_norm.unsqueeze(1), cand_injected], dim=1) # [B, 1 + K, D] # 5. Bidirectional Non-Causal Transformer Comparator (Exact Laya head_layers=2) if self.transformer is not None: if candidate_mask is not None: q_mask = torch.zeros((B, 1), dtype=torch.bool, device=device) pad_mask = torch.cat([q_mask, ~candidate_mask.bool().to(device)], dim=1) else: pad_mask = None tokens_out = self.transformer(tokens, src_key_padding_mask=pad_mask) Q_out = tokens_out[:, 0:1, :] # [B, 1, D] cand_out = tokens_out[:, 1:, :] # [B, K, D] else: Q_out = Q_norm.unsqueeze(1) cand_out = cand_injected # 6. Contrastive Query-Candidate Scorer (Contextual Query Fused with Candidate) # Evaluates the interaction between the contextualized query Q_out and each candidate cand_out fused_cand = self.fusion_norm(cand_out + Q_out) # [B, K, D] logits = self.scorer(fused_cand).squeeze(-1).float() # [B, K] if candidate_mask is not None: logits = logits.masked_fill(~candidate_mask.bool().to(device), -1e4) if return_ablated: return logits, logits return logits # Alias for backwards compatibility StreamlinedDynamicDecisionHead = DynamicDecisionHead # ───────────────────────────────────────────────────────────────────────────── # NEXUS β€” The Main Model # ───────────────────────────────────────────────────────────────────────────── class Nexus(nn.Module): """Nexus β€” Clean transformer with neural memory. Architecture: Embed β†’ Memory₁ β†’ [Layer 0-6] β†’ Memoryβ‚‚ β†’ [Layer 7-13] β†’ Memory₃ β†’ [Layer 14-19] β†’ Head Brain analogy: Memory₁ = "What do I already know about this input?" (hippocampal retrieval) Layers 0-6 = Sensory cortex (perception, pattern recognition) Memoryβ‚‚ = "Update what I've learned from perception" (hippocampal encoding) Layers 7-13 = Association cortex (reasoning, integration) Memory₃ = "Consolidate reasoning into memory" (hippocampal consolidation) Layers 14-19 = Motor cortex (output generation) """ def __init__( self, vocab_size: int = 100_277, dim: int = 1280, heads: int = 16, kv_heads: int = 4, num_layers: int = 20, memory_slots: int = 128, use_flash: bool = False, mtp_depths: int = 1, decision_layers: int = 2, decision_dropout: float = 0.10, ): super().__init__() self.dim = dim self.heads = heads self.num_layers = num_layers # ── Embedding ──────────────────────────────────────────────────────── self.embed = nn.Embedding(vocab_size, dim) nn.init.normal_(self.embed.weight, std=0.01) # Domain Conditioning for Core Model & Neural Memory self.domain_emb = nn.Embedding(16, dim) nn.init.normal_(self.domain_emb.weight, std=0.02) head_dim = dim // heads self.rope = YaRNRotaryEmbedding( head_dim, max_seq_len=8192, original_max_len=2048, yarn_scale=8.0) # ── Transformer Layers ─────────────────────────────────────────────── self.layers = nn.ModuleList([ TransformerBlock(dim, heads, kv_heads, num_layers, i, use_flash, attn_scale=self.rope.attn_scale) for i in range(num_layers) ]) # ── Neural Memory (called at 3 strategic bridge points) ────────────── # Step 9: Hierarchical Memory Specialization memory_configs = [ {"slots": 32, "retain_floor": 0.3, "write_scale": 0.5, "role": "lexical"}, {"slots": 64, "retain_floor": 0.5, "write_scale": 0.3, "role": "semantic"}, {"slots": 128, "retain_floor": 0.7, "write_scale": 0.35, "role": "reasoning"}, ] self.memory = nn.ModuleList([ GlobalNeuralMemory( dim, num_slots=cfg["slots"], heads=heads, retain_floor=cfg["retain_floor"], write_scale=cfg["write_scale"], role=cfg["role"] ) for cfg in memory_configs ]) # Legacy module retained only for pure-checkpoint compatibility. # It is frozen and unused by Nexus Loss v2. self.memory_predictor = nn.Linear(dim, dim, bias=False) nn.init.normal_(self.memory_predictor.weight, std=0.01) # Memory bridge schedule: after which layers to call memory # Bridges shifted slightly deeper: [3, 10, 17] self.memory_bridges = [3, 10, 17] # ── MTP Head ──────────────────────────────────────────────────────── self.mtp_heads = nn.ModuleList([MTPHead(dim) for _ in range(mtp_depths)]) # ── Output ────────────────────────────────────────────────────────── self.norm = RMSNorm(dim) # Output Reflection: lets the final layers read the newly written memory # This ties the memory writing mechanism to the LM loss. self.final_memory_read = CrossAttention(dim, heads, max(1, heads // 4)) self.final_memory_scale = nn.Parameter(torch.tensor(0.50)) self.final_memory_gate = nn.Linear(dim, 1) nn.init.zeros_(self.final_memory_gate.weight) nn.init.constant_(self.final_memory_gate.bias, 0.0) # Starts at gate=0.5 self.head = nn.Linear(dim, vocab_size, bias=False) self.head.weight = self.embed.weight # Weight tying # --- Dynamic System 1 Decision Head --- # Candidate-count agnostic. It scores an arbitrary number K of # candidate representations, rather than hard-coding 5 classes. self.system1_head = DynamicDecisionHead(dim, num_layers=decision_layers, dropout=decision_dropout) # Attention-weighted candidate span pooling: zero-initialized for exact mean-pooling equivalence at step 0 self.span_attn = nn.Linear(dim, 1, bias=False) nn.init.zeros_(self.span_attn.weight) self.use_system1_head = False # Gradient checkpointing toggle (reduces activation VRAM by 85-90% during training) self.gradient_checkpointing = True # ── Print summary ─────────────────────────────────────────────────── total_params = sum(p.numel() for p in self.parameters()) print(f"[OK] Nexus initialized: {total_params:,} parameters ({total_params/1e9:.3f}B)") print(f" Architecture: {num_layers} layers (dim={dim}, heads={heads}, kv_heads={kv_heads})") print(f" Memory: {[c['slots'] for c in memory_configs]} slots Γ— {dim}d at bridges {self.memory_bridges}") print(f" FFN: SwiGLU ({int(2.67 * dim)}d hidden)") print(f" MTP Heads: {mtp_depths}") attn_desc = "FlashAttention-2 (Tri Dao)" if use_flash else "PyTorch Fused SDPA (Mem-Efficient Kernel for T4/SM75)" print(f" Attention: {attn_desc}") def project_logits(self, hidden: torch.Tensor) -> torch.Tensor: return self.head(self.norm(hidden)) def forward( self, x: torch.Tensor, memory_state: Optional[List[torch.Tensor]] = None, kv_cache: Optional[KVCache] = None, targets: Optional[torch.Tensor] = None, return_intermediates: bool = False, last_token_only: bool = False, candidate_positions: Optional[torch.Tensor] = None, candidate_mask: Optional[torch.Tensor] = None, seq_lens: Optional[torch.Tensor] = None, domain_id: Optional[int] = None, primitive_id: Optional[Any] = None, task_id: Optional[Any] = None, disable_memory: Optional[bool] = None, is_causal: Optional[bool] = None, memory_only: bool = False, **kwargs: Any, ) -> Any: B, S = x.shape h = self.embed(x) # ── Domain Conditioning for Core Model & Neural Memory ─────────────── if domain_id is not None: if isinstance(domain_id, int): d_idx = torch.tensor([domain_id] * B, device=x.device, dtype=torch.long) elif isinstance(domain_id, torch.Tensor): d_idx = domain_id.to(x.device, dtype=torch.long).view(-1) if d_idx.numel() == 1 and B > 1: d_idx = d_idx.expand(B) else: d_idx = torch.zeros(B, device=x.device, dtype=torch.long) d_emb = self.domain_emb(d_idx.clamp(0, 15)).unsqueeze(1) # [B, 1, D] h = h + d_emb # ── Memory Bypass Configuration ───────────────────────────────────── disable_mem = disable_memory if disable_memory is not None else getattr(self, "disable_memory", False) # ── Attention Causal Mode ─────────────────────────────────────────── # Native causal masking matching 30B-token pretraining inductive bias. if is_causal is not None: causal_mode = is_causal else: causal_mode = (kv_cache is None) # ── RoPE ──────────────────────────────────────────────────────────── past_len = kv_cache.get_past_len() if kv_cache else 0 total_len = past_len + S cos_full, sin_full = self.rope(h, total_len) cos = cos_full[past_len:total_len] sin = sin_full[past_len:total_len] # ── Initialize memory ────────────────────────────────────────────── if not disable_mem and memory_state is None: memory_state = [mem.init_memory(B, h.device) for mem in self.memory] # ── Forward through layers with memory bridges ───────────────────── bridge_idx = 0 new_memory_state = [] read_gates = [] read_deltas = [] write_masks = [] forget_gates = [] memory_deltas = [] for i, layer in enumerate(self.layers): # Memory bridge BEFORE this layer group starts. if not disable_mem and i in self.memory_bridges: old_mem = memory_state[bridge_idx] h, m_state, lb_loss, r_gate, affinity, read_delta, f_gate = self.memory[bridge_idx]( h, old_mem, domain_id=domain_id ) new_memory_state.append(m_state) read_gates.append(r_gate) read_deltas.append(read_delta) write_masks.append(affinity) forget_gates.append(f_gate) memory_deltas.append(m_state - old_mem) bridge_idx += 1 # Transformer layer (with activation checkpointing during training to reduce VRAM by 85-90%) pkv = kv_cache.kvs[i] if kv_cache else None if self.training and kv_cache is None and getattr(self, "gradient_checkpointing", True): from torch.utils.checkpoint import checkpoint def _create_layer_forward(layer_module, causal_flag): def _layer_forward(*inputs): out_hidden, _ = layer_module(*inputs, is_causal=causal_flag) return out_hidden return _layer_forward h = checkpoint(_create_layer_forward(layer, causal_mode), h, cos, sin, None, use_reentrant=False) new_kv = None else: h, new_kv = layer(h, cos, sin, pkv, is_causal=causal_mode) if kv_cache: kv_cache.update(i, new_kv) # ── Output / Reflection ─────────────────────────────────────────── h_normed = self.norm(h) candidate_hidden = None candidate_hidden_pre_reflection = None reflection = None reflection_gate = None reflection_delta = None memory_context = None reflection_cand = None mem_logits = None refl_logits = None global_context = None ablated_logits = None pre_reflection_h_normed = h_normed if not disable_mem and new_memory_state: # Reflection reads the CURRENT example's freshly written memory. all_mem = torch.cat(new_memory_state, dim=1) reflection = self.final_memory_read(h_normed, all_mem) reflection_gate = 0.20 + 0.80 * torch.sigmoid(self.final_memory_gate(h_normed)) reflection_delta = reflection_gate * self.final_memory_scale * reflection h = h + reflection_delta h_normed = self.norm(h) if (getattr(self, "use_system1_head", False) and not memory_only) or candidate_positions is not None: if candidate_positions is None: raise ValueError( "Dynamic System 1 head requires candidate_positions " "with shape [B,K]. Pass one position per option." ) if candidate_positions.ndim not in (2, 3): raise ValueError( "candidate_positions must have shape [B,K] (single token) or [B,K,2] (spans), " f"got {tuple(candidate_positions.shape)}" ) if candidate_positions.shape[0] != B: raise ValueError( "candidate_positions batch dimension must match input batch: " f"{candidate_positions.shape[0]} vs {B}" ) if candidate_positions.dtype != torch.long: candidate_positions = candidate_positions.long() if candidate_positions.device != h_normed.device: candidate_positions = candidate_positions.to(h_normed.device) # Vectorized candidate extraction on GPU: # When candidate_positions is [B, K, 2] (spans), compute exact span mean-pooling via prefix sum. # When candidate_positions is [B, K] (single tokens), gather directly. if candidate_positions.ndim == 3 and candidate_positions.shape[-1] == 2: # Attention-Weighted Candidate Span Extraction: # Weights individual tokens in each option span via learned attention. # Zero-initialized at step 0 to produce uniform 1/L weights (exact zero-drift match to mean pooling). # During training, concentrates candidate representations onto decisive action verbs and condition clauses. s = candidate_positions[:, :, 0].clamp(0, h_normed.size(1) - 1) e = candidate_positions[:, :, 1].clamp(0, h_normed.size(1) - 1) e = torch.maximum(s, e) s_idx = s.unsqueeze(-1).expand(-1, -1, h_normed.size(-1)) e_idx = (e + 1).unsqueeze(-1).expand(-1, -1, h_normed.size(-1)) counts = (e - s + 1).unsqueeze(-1).float().clamp_min(1.0) if hasattr(self, "span_attn"): # Vectorized prefix-sum attention weighting over candidate spans: # w_t = exp(span_attn(h_t)) # cand_k = sum_{t=s}^e (w_t * h_t) / sum_{t=s}^e w_t # At step 0, span_attn.weight is 0 => w_t=1 => cand_k is exact mean pooling. w = torch.exp(self.span_attn(h_normed).clamp(-10.0, 10.0)) wh = w * h_normed w_prefix = torch.cat( [torch.zeros(B, 1, 1, device=h_normed.device, dtype=h_normed.dtype), torch.cumsum(w, dim=1)], dim=1 ) wh_prefix = torch.cat( [torch.zeros(B, 1, h_normed.size(-1), device=h_normed.device, dtype=h_normed.dtype), torch.cumsum(wh, dim=1)], dim=1 ) s_idx_1 = s.unsqueeze(-1) e_idx_1 = (e + 1).unsqueeze(-1) w_sum = torch.gather(w_prefix, dim=1, index=e_idx_1) - torch.gather(w_prefix, dim=1, index=s_idx_1) wh_sum = torch.gather(wh_prefix, dim=1, index=e_idx) - torch.gather(wh_prefix, dim=1, index=s_idx) candidate_hidden = (wh_sum / w_sum.clamp_min(1e-6)).to(h_normed.dtype) else: prefix = torch.cat( [torch.zeros(B, 1, h_normed.size(-1), device=h_normed.device, dtype=h_normed.dtype), torch.cumsum(h_normed, dim=1)], dim=1 ) sum_s = torch.gather(prefix, dim=1, index=s_idx) sum_e = torch.gather(prefix, dim=1, index=e_idx) candidate_hidden = ((sum_e - sum_s) / counts).to(h_normed.dtype) else: pos_idx = candidate_positions[:, :, -1] if candidate_positions.ndim == 3 else candidate_positions pos_idx = pos_idx.clamp(0, h_normed.size(1) - 1) gather_idx = pos_idx.unsqueeze(-1).expand(-1, -1, h_normed.size(-1)) candidate_hidden = torch.gather(h_normed, dim=1, index=gather_idx) # Preserve the unreflected candidate representation for the # contrastive reflection objective. Passing the post-reflection # candidate here would count reflection twice in its own target. if candidate_positions.ndim == 3 and candidate_positions.shape[-1] == 2: pre_prefix = torch.cat( [torch.zeros(B, 1, pre_reflection_h_normed.size(-1), device=pre_reflection_h_normed.device, dtype=pre_reflection_h_normed.dtype), torch.cumsum(pre_reflection_h_normed, dim=1)], dim=1 ) pre_s_sum = torch.gather(pre_prefix, dim=1, index=s_idx) pre_e_sum = torch.gather(pre_prefix, dim=1, index=e_idx) candidate_hidden_pre_reflection = ((pre_e_sum - pre_s_sum) / counts).to(pre_reflection_h_normed.dtype) else: candidate_hidden_pre_reflection = torch.gather( pre_reflection_h_normed, dim=1, index=gather_idx ) # Multi-Module Cognitive Context Extraction: # 1. Consolidated memory reasoning context (from Bridge 2 reasoning memory across all slots) if new_memory_state and len(new_memory_state) > 0: last_mem = new_memory_state[-1] if last_mem.dim() == 3 and last_mem.size(1) > 0: memory_context = last_mem.mean(dim=1) # Vectorized Candidate-Level Reflection Extraction from reflection_delta: # Enables true reflection telemetry and contrastive reflection verification without zero-placeholders. if reflection_delta is not None and candidate_positions is not None: if candidate_positions.ndim == 3 and candidate_positions.shape[-1] == 2: refl_prefix = torch.cat( [torch.zeros(B, 1, reflection_delta.size(-1), device=reflection_delta.device, dtype=reflection_delta.dtype), torch.cumsum(reflection_delta, dim=1)], dim=1 ) sum_s_r = torch.gather(refl_prefix, dim=1, index=s_idx) sum_e_r = torch.gather(refl_prefix, dim=1, index=e_idx) reflection_cand = ((sum_e_r - sum_s_r) / counts).to(reflection_delta.dtype) else: reflection_cand = torch.gather(reflection_delta, dim=1, index=gather_idx) else: reflection_cand = None if seq_lens is not None: batch_indices = torch.arange(B, device=h_normed.device) last_indices = (seq_lens - 1).clamp_min(0) global_context = h_normed[batch_indices, last_indices] else: global_context = h_normed[:, -1, :] # [B,D] # Direct 3rd Neural Memory Block (Bridge 2, Layer 17: 128 slots) for Decision Head mem3_slots = new_memory_state[-1] if (new_memory_state and len(new_memory_state) >= 3) else (torch.cat(new_memory_state, dim=1) if new_memory_state else None) seq_mask = (torch.arange(S, device=h_normed.device).unsqueeze(0) < seq_lens.unsqueeze(1)) if seq_lens is not None else None ablated_logits = None if hasattr(self.system1_head, "forward"): res = self.system1_head( global_context, candidate_hidden, candidate_mask=candidate_mask, primitive_id=primitive_id, domain_id=domain_id, memory_context=memory_context, reflection_cand=reflection_cand, memory_slots=mem3_slots, sequence_context=h_normed, sequence_mask=seq_mask, candidate_positions=candidate_positions, return_ablated=self.training, ) if self.training: logits, ablated_logits = res else: logits = res else: logits = self.system1_head( global_context, candidate_hidden, candidate_mask=candidate_mask, primitive_id=primitive_id, memory_slots=all_memory_slots, ) if last_token_only: # Preserve the existing [B,1,K] interface expected by the # training wrapper while keeping K dynamic. logits = logits.unsqueeze(1) if ablated_logits is not None: ablated_logits = ablated_logits.unsqueeze(1) else: if last_token_only: logits = self.head(h_normed[:, -1:, :]) else: logits = self.head(h_normed) # ── MTP loss (multi-token prediction, training only) ──────────────── mtp_loss = torch.tensor(0.0, device=h.device) if targets is not None and self.training and len(self.mtp_heads) > 0: mtp_losses = [] h_prev = h_normed for d, mtp_head in enumerate(self.mtp_heads): offset = d + 2 # predict token at position +2, +3, ... if S <= offset: break tgt_ids = targets[:, d : -1] tgt_embed = self.embed(tgt_ids) h_prev_trunc = h_prev[:, : -1] h_mtp = mtp_head(h_prev_trunc, tgt_embed) labels = targets[:, d + 1 :] if labels.shape[1] == 0: break # Memory-efficient chunked MTP logit & loss computation loss_sum = torch.tensor(0.0, device=h_mtp.device) h_mtp_flat = h_mtp.reshape(-1, h_mtp.size(-1)) labels_flat = labels.reshape(-1) valid_tokens = (labels_flat != -1).sum() chunk_size = 512 # Small chunk to prevent 100K vocab OOM from torch.utils.checkpoint import checkpoint # We use a static loop that torch.compile can unroll or trace for start_idx in range(0, h_mtp_flat.size(0), chunk_size): end_idx = min(start_idx + chunk_size, h_mtp_flat.size(0)) chunk_h = h_mtp_flat[start_idx:end_idx] chunk_labels = labels_flat[start_idx:end_idx] if self.training: def _compute_chunk_loss(h, y): return F.cross_entropy(self.head(h), y, ignore_index=-1, reduction='sum') chunk_loss = checkpoint(_compute_chunk_loss, chunk_h, chunk_labels, use_reentrant=False) else: chunk_loss = F.cross_entropy(self.head(chunk_h), chunk_labels, ignore_index=-1, reduction='sum') loss_sum = loss_sum + chunk_loss loss_flat = loss_sum / valid_tokens.clamp(min=1) mtp_losses.append(loss_flat) h_prev = h_mtp if mtp_losses: mtp_loss = sum(mtp_losses) / len(mtp_losses) # ── Loss-v2 intervention telemetry ───────────────────────────────── # The trainer converts these interventions into task-derived utility # targets. No generic memory/predictor/diversity/coherence objective is # computed inside the model. if global_context is None: global_context = h_normed[:, -1, :] aux_dict = { "read_gates": read_gates, "read_deltas": read_deltas, "write_masks": write_masks, "forget_gates": forget_gates, "memory_deltas": memory_deltas, "reflection_gate": reflection_gate, "reflection_delta": reflection_delta, "candidate_hidden": candidate_hidden, "candidate_hidden_pre_reflection": candidate_hidden_pre_reflection, "memory_context": memory_context, "reflection_cand": reflection_cand, "global_context": global_context, "fused_logits": logits, "ablated_logits": ablated_logits, # Backward compatibility for existing benchmark readers. "refl_decision_logits": None, "refl_sim": torch.zeros((), device=h.device, dtype=h.dtype), "refl_ctx": torch.zeros((), device=h.device, dtype=h.dtype), } # ── Return ────────────────────────────────────────────────────────── ponder = torch.tensor(1.0, device=h.device) if targets is not None: return logits, ponder, aux_dict, new_memory_state, mtp_loss, h_normed elif return_intermediates: return logits, ponder, aux_dict, new_memory_state, h_normed return logits, ponder, aux_dict, new_memory_state # Legacy memory-loss helpers intentionally removed from the active # specialist objective. Routing supervision lives in the trainer. def configure_optimizers( self, learning_rate: float, weight_decay: float, betas: Tuple[float, float] = (0.9, 0.95), ) -> torch.optim.AdamW: decay, no_decay, hyper_decay = set(), set(), set() for mn, m in self.named_modules(): for pn, _ in m.named_parameters(recurse=False): fpn = f"{mn}.{pn}" if mn else pn # HyperConnection alpha/beta get their own mild decay group if isinstance(m, HyperConnection) and pn in ("alpha", "beta"): hyper_decay.add(fpn) elif pn.endswith("bias"): no_decay.add(fpn) elif pn.endswith("weight") and isinstance(m, (nn.Linear, nn.Embedding)): decay.add(fpn) else: no_decay.add(fpn) param_dict = dict(self.named_parameters()) optim_groups = [ {"params": [param_dict[p] for p in sorted(decay) if p in param_dict], "weight_decay": weight_decay}, {"params": [param_dict[p] for p in sorted(no_decay) if p in param_dict], "weight_decay": 0.0}, {"params": [param_dict[p] for p in sorted(hyper_decay) if p in param_dict], "weight_decay": 0.01}, # mild decay to anchor alpha/beta near init ] return torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, fused=torch.cuda.is_available()) # Backward-compatible alias so old checkpoint loading code still works Cortex = Nexus CortexV7 = Nexus # ───────────────────────────────────────────────────────────────────────────── # SANITY CHECK # ───────────────────────────────────────────────────────────────────────────── if __name__ == "__main__": print("Running Nexus sanity check …\n") device = "cuda" if torch.cuda.is_available() else "cpu" model = Nexus( vocab_size = 100_277, dim = 1280, heads = 16, kv_heads = 4, num_layers = 20, memory_slots = 128, use_flash = True, mtp_depths = 1, ).to(device) # ── Training forward pass ────────────────────────────────────────────── print("\n[1] Training pass (batch=2, seq=64) …") x = torch.randint(0, 100_277, (2, 64), device=device) targets = torch.randint(0, 100_277, (2, 64), device=device) model.train() with torch.no_grad(): logits, ponder, aux, new_mem, mtp_loss, h_normed = model(x, targets=targets) print(f" logits: {logits.shape} ponder: {ponder:.3f} mtp_loss: {mtp_loss:.4f}") assert logits.shape == (2, 64, 100_277), f"Shape mismatch: {logits.shape}" print(" [OK] Training pass OK") # ── Inference with KV cache ──────────────────────────────────────────── print("\n[2] Inference with KV cache (prefill 16 + generate 8) …") model.eval() cache = KVCache(num_layers=20) prompt = torch.randint(0, 100_277, (1, 16), device=device) with torch.no_grad(): logits_pre, _, _, mem, *_ = model(prompt, kv_cache=cache) print(f" Prefill: {logits_pre.shape}, cache len: {cache.get_past_len()}") next_token = logits_pre[:, -1, :].argmax(-1, keepdim=True) for step in range(8): with torch.no_grad(): logits_step, _, _, mem, *_ = model(next_token, memory_state=mem, kv_cache=cache) next_token = logits_step[:, -1, :].argmax(-1, keepdim=True) print(f" Generated 8 tokens. Cache len: {cache.get_past_len()}") print(" [OK] KV Cache inference OK") print(f"\n[OK] Nexus sanity check passed!") print(f" {sum(p.numel() for p in model.parameters()):,} parameters") print(f" Memory bridges at layers: {model.memory_bridges}")
"""
Nexus β€” Simplified Transformer Architecture
=============================================
Clean 20-layer transformer with integrated neural memory.
Architecture (brain-inspired):
Embed β†’ Memory β†’ [Layers 0-6] β†’ Memory β†’ [Layers 7-13] β†’ Memory β†’ [Layers 14-19] β†’ Output
↑ input sensory ↑ bridge processing ↑ bridge output
context update update
Components:
- GQA Attention (heads=16, kv_heads=4) + Flash Attention 2
- SwiGLU FFN (2.67Γ— expansion)
- GlobalNeuralMemory at 3 strategic bridge points
- YaRN RoPE for context extension
- MTP head for multi-token prediction training
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from typing import Optional, List, Tuple, Dict, Any, Union
from v3_modules import YaRNRotaryEmbedding, MTPHead, HyperConnection, RMSNorm
# ─────────────────────────────────────────────────────────────────────────────
# BASIC BUILDING BLOCKS
# ─────────────────────────────────────────────────────────────────────────────
def apply_rotary_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
"""Apply rotary position embeddings. x: [B, H, S, D]"""
d = x.shape[-1]
x1, x2 = x[..., : d // 2], x[..., d // 2 :]
cos = cos.unsqueeze(0).unsqueeze(0)
sin = sin.unsqueeze(0).unsqueeze(0)
return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1)
class SwiGLU(nn.Module):
"""SwiGLU FFN β€” the standard modern FFN choice."""
def __init__(self, dim: int, hidden_dim: Optional[int] = None,
num_layers: int = 1, layer_id: int = 0):
super().__init__()
if hidden_dim is None:
hidden_dim = int(2.67 * dim)
self.w1 = nn.Linear(dim, hidden_dim, bias=False)