import math import torch import torch.nn as nn import torch.nn.functional as F from .config import ModelConfig class RMSNorm(nn.Module): def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) self.eps = eps def forward(self, x): return ( x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight ) def rotate_half(x): x1 = x[..., ::2] x2 = x[..., 1::2] return torch.stack((-x2, x1), dim=-1).flatten(-2) def apply_rope(q, k, seq_len: int, base: float = 10000.0): d = q.shape[-1] device, dtype = q.device, q.dtype inv = 1.0 / ( base ** ( torch.arange( 0, d, 2, device=device, dtype=torch.float32, ) / d ) ) pos = torch.arange( seq_len, device=device, dtype=torch.float32, ) freqs = torch.outer(pos, inv) cos = freqs.cos().to(dtype)[None, None, :, :] sin = freqs.sin().to(dtype)[None, None, :, :] cos = cos.repeat_interleave(2, -1) sin = sin.repeat_interleave(2, -1) q = q * cos + rotate_half(q) * sin k = k * cos + rotate_half(k) * sin return q, k class CausalSelfAttention(nn.Module): def __init__(self, cfg: ModelConfig): super().__init__() d = cfg.d_model h = cfg.n_heads if d % h != 0: raise ValueError( f"d_model ({d}) must be divisible by n_heads ({h})" ) self.h = h self.head_dim = d // h self.qkv = nn.Linear( d, 3 * d, bias=False, ) self.proj = nn.Linear( d, d, bias=False, ) self.dropout = cfg.dropout def forward(self, x): B, T, C = x.shape q, k, v = self.qkv(x).chunk(3, dim=-1) q = q.view( B, T, self.h, self.head_dim, ).transpose(1, 2) k = k.view( B, T, self.h, self.head_dim, ).transpose(1, 2) v = v.view( B, T, self.h, self.head_dim, ).transpose(1, 2) q, k = apply_rope( q, k, T, ) y = F.scaled_dot_product_attention( q, k, v, attn_mask=None, dropout_p=self.dropout if self.training else 0.0, is_causal=True, ) y = ( y.transpose(1, 2) .contiguous() .view(B, T, C) ) return self.proj(y) class MLP(nn.Module): def __init__(self, cfg: ModelConfig): super().__init__() d = cfg.d_model h = cfg.ff_mult * d self.fc1 = nn.Linear( d, h, bias=False, ) self.fc2 = nn.Linear( h, d, bias=False, ) def forward(self, x): return self.fc2( F.silu( self.fc1(x) ) ) class TransformerBlock(nn.Module): def __init__(self, cfg: ModelConfig): super().__init__() self.n1 = RMSNorm( cfg.d_model ) self.attn = CausalSelfAttention( cfg ) self.n2 = RMSNorm( cfg.d_model ) self.mlp = MLP( cfg ) def forward(self, x): x = x + self.attn( self.n1(x) ) x = x + self.mlp( self.n2(x) ) return x class UltraSparseLM(nn.Module): """ CPU-first causal language model with adaptive depth. The first Transformer block is always executed. Its hidden state feeds: difficulty_head Current-token difficulty estimate. demand_head Predicted near-future compute demand. During adaptive inference, those signals can be combined with a persistent computation ledger to determine how much additional computation should be used. Training uses the full model so that the language model and controller heads can be optimized end-to-end. """ def __init__(self, cfg: ModelConfig): super().__init__() cfg.validate() self.cfg = cfg # --------------------------------------------------------- # Token embedding # --------------------------------------------------------- self.tok = nn.Embedding( cfg.vocab_size, cfg.d_model, ) # --------------------------------------------------------- # Transformer blocks # --------------------------------------------------------- self.blocks = nn.ModuleList( [ TransformerBlock(cfg) for _ in range(cfg.n_layers) ] ) # --------------------------------------------------------- # Final normalization # --------------------------------------------------------- self.norm = RMSNorm( cfg.d_model ) # --------------------------------------------------------- # Language-model head # # Weight tying is applied below. # --------------------------------------------------------- self.lm_head = nn.Linear( cfg.d_model, cfg.vocab_size, bias=False, ) self.lm_head.weight = self.tok.weight # --------------------------------------------------------- # Adaptive controller heads # --------------------------------------------------------- gate_h = max( 64, cfg.d_model // 2, ) self.difficulty_head = nn.Sequential( nn.Linear( cfg.d_model, gate_h, ), nn.SiLU(), nn.Linear( gate_h, 1, ), ) self.demand_head = nn.Sequential( nn.Linear( cfg.d_model, gate_h, ), nn.SiLU(), nn.Linear( gate_h, 1, ), ) # --------------------------------------------------------- # Initialization # --------------------------------------------------------- self.apply( self._init_weights ) self._tie_weights() def _init_weights(self, m): if isinstance(m, nn.Linear): nn.init.normal_( m.weight, mean=0.0, std=0.02, ) if m.bias is not None: nn.init.zeros_( m.bias ) elif isinstance(m, nn.Embedding): nn.init.normal_( m.weight, mean=0.0, std=0.02, ) def _tie_weights(self): self.lm_head.weight = self.tok.weight # ------------------------------------------------------------- # Context handling # ------------------------------------------------------------- def _context(self, idx): if idx.ndim != 2: raise ValueError( "idx must have shape [B,T]" ) if idx.shape[1] == 0: raise ValueError( "empty context" ) return idx[ :, -self.cfg.max_seq_len: ] # ------------------------------------------------------------- # Embedding # ------------------------------------------------------------- def embed(self, idx): return self.tok( self._context(idx) ) # ------------------------------------------------------------- # Full model forward # # Used during training. # ------------------------------------------------------------- def forward_full(self, idx): x = self.embed(idx) for block in self.blocks: x = block(x) h = self.norm(x) logits = F.linear( h, self.tok.weight, ) difficulty = torch.sigmoid( self.difficulty_head(h) ).squeeze(-1) demand = torch.sigmoid( self.demand_head(h) ).squeeze(-1) return ( logits, difficulty, demand, ) # ------------------------------------------------------------- # Standard PyTorch forward # # This was the missing method. # # m(x) now returns: # # [B, T, vocab_size] # ------------------------------------------------------------- def forward(self, idx): logits, _, _ = self.forward_full(idx) return logits # ------------------------------------------------------------- # Lightweight probe # # Executes block 0 and estimates difficulty/demand. # ------------------------------------------------------------- @torch.no_grad() def probe(self, idx): x = self.embed(idx) x = self.blocks[0](x) h = self.norm( x ) difficulty = torch.sigmoid( self.difficulty_head( h[:, -1] ) ).squeeze(-1) demand = torch.sigmoid( self.demand_head( h[:, -1] ) ).squeeze(-1) return ( difficulty, demand, x[:, -1], ) # ------------------------------------------------------------- # Legacy method # ------------------------------------------------------------- @torch.no_grad() def logits_from_probe( self, hidden_last, depth: int, ): depth = max( 1, min( self.cfg.n_layers, int(depth), ), ) # hidden_last contains only the last position. # # Later Transformer blocks require the complete causal # context, so this method intentionally does not attempt # to perform an approximate continuation. raise RuntimeError( "Use forward_depth() for exact causal inference." ) # ------------------------------------------------------------- # Exact fixed-depth inference # ------------------------------------------------------------- @torch.no_grad() def forward_depth( self, idx, depth: int, ): depth = max( 1, min( self.cfg.n_layers, int(depth), ), ) x = self.embed(idx) for block in self.blocks[:depth]: x = block(x) h = self.norm( x[:, -1:] ) logits = F.linear( h[:, -1], self.tok.weight, ) return logits # ------------------------------------------------------------- # Adaptive probe + exact logits # # Block 0 is executed once. # The controller reads the resulting state. # Additional blocks are then executed. # ------------------------------------------------------------- @torch.no_grad() def probe_and_logits( self, idx, depth: int, ): depth = max( 1, min( self.cfg.n_layers, int(depth), ), ) # --------------------------------------------------------- # Block 0 # --------------------------------------------------------- x = self.embed(idx) x = self.blocks[0](x) # --------------------------------------------------------- # Controller signals # --------------------------------------------------------- h1 = self.norm( x[:, -1] ) difficulty = torch.sigmoid( self.difficulty_head(h1) ).squeeze(-1) demand = torch.sigmoid( self.demand_head(h1) ).squeeze(-1) # --------------------------------------------------------- # Additional adaptive depth # --------------------------------------------------------- for block in self.blocks[1:depth]: x = block(x) # --------------------------------------------------------- # Final prediction # --------------------------------------------------------- h = self.norm( x[:, -1] ) logits = F.linear( h, self.tok.weight, ) return ( difficulty, demand, logits, ) # ------------------------------------------------------------- # Training loss # ------------------------------------------------------------- def training_loss( self, idx, compute_penalty=0.005, ): logits, difficulty, demand = self.forward_full( idx ) # --------------------------------------------------------- # Next-token prediction # --------------------------------------------------------- targets = idx[:, 1:] pred = logits[:, :-1] lm_loss = F.cross_entropy( pred.reshape( -1, pred.size(-1), ), targets.reshape(-1), ) # --------------------------------------------------------- # Teacher-forced controller targets # # These targets are detached from the language-model # computation so that the controller learns from the # measured token difficulty rather than changing the # language-model objective through this path. # --------------------------------------------------------- with torch.no_grad(): logp = F.log_softmax( pred, dim=-1, ) surprisal = ( -logp .gather( -1, targets.unsqueeze(-1), ) .squeeze(-1) ) # Smooth and normalize the surprisal target. diff_target = torch.sigmoid( (surprisal - 2.0) / 2.0 ) # ----------------------------------------------------- # Future demand target # ----------------------------------------------------- horizon = self.cfg.future_horizon demand_target = torch.zeros_like( diff_target ) for h in range( 1, horizon + 1, ): shifted = torch.cat( [ surprisal[:, h:], torch.zeros_like( surprisal[:, :h] ), ], dim=1, ) demand_target += shifted demand_target /= float( horizon ) demand_target = demand_target.clamp( 0.0, 1.0, ) # --------------------------------------------------------- # Controller losses # --------------------------------------------------------- diff_loss = F.smooth_l1_loss( difficulty[:, :-1], diff_target, ) demand_loss = F.smooth_l1_loss( demand[:, :-1], demand_target, ) # --------------------------------------------------------- # Soft compute target # --------------------------------------------------------- score = ( 0.5 * difficulty[:, :-1] + 0.5 * demand[:, :-1] ) expected_compute = ( 0.125 + score * (1.0 - 0.125) ) compute_loss = ( expected_compute.mean() * compute_penalty ) # --------------------------------------------------------- # Total objective # --------------------------------------------------------- total = ( lm_loss + 0.10 * diff_loss + 0.10 * demand_loss + compute_loss ) metrics = { "loss": float( total.detach() ), "lm_loss": float( lm_loss.detach() ), "difficulty_loss": float( diff_loss.detach() ), "demand_loss": float( demand_loss.detach() ), "compute_penalty": float( compute_loss.detach() ), } return total, metrics