import json import math import os from dataclasses import dataclass from typing import Optional, Tuple, Dict, Any, Union, List import torch import torch.nn as nn import torch.nn.functional as F try: import triton import triton.language as tl _TRITON_AVAILABLE = torch.cuda.is_available() except ImportError: triton = None tl = None _TRITON_AVAILABLE = False try: from safetensors import safe_open from safetensors.torch import load_file _SAFETENSORS_AVAILABLE = True except ImportError: _SAFETENSORS_AVAILABLE = False try: from transformers import AutoTokenizer, PreTrainedTokenizerFast _TRANSFORMERS_AVAILABLE = True except ImportError: _TRANSFORMERS_AVAILABLE = False __all__ = [ "UnifiedLMConfig", "TrainConfig", "RMSNorm", "MultiScaleCausalStateMixer", "SRVQ", "CausalContextInjector", "ResidualPyramidAttention", "HarmonicDifferentialStarCarrierFFN", "UnifiedTransformerBlock", "UnifiedLM", "load_tokenizer", ] # ============================================================================= # 0. Model Configuration # ============================================================================= @dataclass class UnifiedLMConfig: vocab_size: int = 2048 d_model: int = 192 n_heads: int = 4 n_layers: int = 3 softcap: float = 30.0 max_seq_len: int = 8192 ffn_dropout: float = 0.0 # Alias for backward-compatible unpickling of training .pt checkpoints TrainConfig = UnifiedLMConfig # ============================================================================= # 1. Multi-Octave Precomputed RoPE # ============================================================================= def precompute_multi_octave_rope( head_dim: int, n_heads: int, max_seq_len: int, base_min: float = 64.0, base_max: float = 262144.0, device: Union[str, torch.device] = "cpu", dtype: torch.dtype = torch.float32, ) -> Tuple[torch.Tensor, torch.Tensor]: half_d = head_dim // 2 dim_idx = torch.arange(0, half_d, device=device, dtype=dtype) / half_d if n_heads > 1: exponents = torch.linspace(0.0, 1.0, n_heads, device=device, dtype=dtype) bases = base_min * ((base_max / base_min) ** exponents) else: bases = torch.tensor([base_min], device=device, dtype=dtype) inv_freq = 1.0 / (bases.unsqueeze(-1) ** dim_idx.unsqueeze(0)) # [H, half_D] t = torch.arange(max_seq_len, device=device, dtype=dtype) # [N] freqs = torch.einsum("n,hd->hnd", t, inv_freq) # [H, N, half_D] cos = freqs.cos().unsqueeze(0) # [1, H, N, half_D] sin = freqs.sin().unsqueeze(0) # [1, H, N, half_D] return cos, sin def apply_multi_octave_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: """x: [B, H, N, D], cos/sin: [1, H, N, D/2].""" half_D = x.shape[-1] // 2 N = x.shape[2] x1 = x[..., :half_D] x2 = x[..., half_D:] c = cos[:, :, :N, :half_D].to(dtype=x.dtype) s = sin[:, :, :N, :half_D].to(dtype=x.dtype) return torch.cat([x1 * c - x2 * s, x1 * s + x2 * c], dim=-1) # ============================================================================= # 2. Coalesced Triton Causal Inverted Index Kernel (+ CPU Fallback) # ============================================================================= if triton is not None: @triton.jit def build_causal_index_fast_kernel( q_b1_ptr, q_b2_ptr, k_buckets_ptr, indices_ptr, stride_qb, stride_qh, stride_qn, stride_ib, stride_ih, stride_in, stride_ibmax, N: tl.constexpr, B_max: tl.constexpr, B_top1: tl.constexpr, B_top2: tl.constexpr, NUM_BUCKETS: tl.constexpr, H: tl.constexpr, W: tl.constexpr ): pid = tl.program_id(0) bucket_id = pid % NUM_BUCKETS h = (pid // NUM_BUCKETS) % H b = pid // (NUM_BUCKETS * H) offs_bmax = tl.arange(0, B_max) buf = tl.full([B_max], -1, dtype=tl.int32) ring_idx = 0 for n in range(N): if n >= W: n_insert = n - W k_val = tl.load(k_buckets_ptr + b * stride_qb + h * stride_qh + n_insert * stride_qn) if k_val == bucket_id: buf = tl.where(offs_bmax == ring_idx, n_insert, buf) ring_idx = (ring_idx + 1) % B_max q_offset = b * stride_qb + h * stride_qh + n * stride_qn q_val1 = tl.load(q_b1_ptr + q_offset) if q_val1 == bucket_id: rank = (ring_idx + B_max - 1 - offs_bmax) % B_max idx_ptrs = ( indices_ptr + b * stride_ib + h * stride_ih + n * stride_in + rank * stride_ibmax ) tl.store(idx_ptrs, buf, mask=(rank < B_top1)) if B_top2 > 0: q_val2 = tl.load(q_b2_ptr + q_offset) if q_val2 == bucket_id: rank = (ring_idx + B_max - 1 - offs_bmax) % B_max idx_ptrs = ( indices_ptr + b * stride_ib + h * stride_ih + n * stride_in + (B_top1 + rank) * stride_ibmax ) tl.store(idx_ptrs, buf, mask=(rank < B_top2)) def _build_causal_inverted_index_reference( q_buckets_1: torch.Tensor, q_buckets_2: torch.Tensor, k_buckets: torch.Tensor, B_max: int = 16, B_top1: int = 10, num_buckets: int = 16, W: int = 0, ) -> torch.Tensor: """Pure-PyTorch fallback when running on CPU or without Triton.""" B, H, N = q_buckets_1.shape B_top2 = B_max - B_top1 indices = torch.full((B, H, N, B_max), -1, device=q_buckets_1.device, dtype=torch.int32) q_b1_cpu = q_buckets_1.tolist() q_b2_cpu = q_buckets_2.tolist() k_b_cpu = k_buckets.tolist() out_cpu = indices.tolist() for b in range(B): for h in range(H): ring_bufs = [[-1] * B_max for _ in range(num_buckets)] ring_ptrs = [0] * num_buckets for n in range(N): if n >= W: n_ins = n - W kb = k_b_cpu[b][h][n_ins] ptr = ring_ptrs[kb] ring_bufs[kb][ptr] = n_ins ring_ptrs[kb] = (ptr + 1) % B_max qb1 = q_b1_cpu[b][h][n] ptr1 = ring_ptrs[qb1] buf1 = ring_bufs[qb1] for r in range(B_top1): out_cpu[b][h][n][r] = buf1[(ptr1 - 1 - r) % B_max] if B_top2 > 0: qb2 = q_b2_cpu[b][h][n] ptr2 = ring_ptrs[qb2] buf2 = ring_bufs[qb2] for r in range(B_top2): out_cpu[b][h][n][B_top1 + r] = buf2[(ptr2 - 1 - r) % B_max] return torch.tensor(out_cpu, device=q_buckets_1.device, dtype=torch.int32) def build_causal_inverted_index( q_buckets_1: torch.Tensor, q_buckets_2: torch.Tensor, k_buckets: torch.Tensor, B_max: int = 16, B_top1: int = 10, num_buckets: int = 16, W: int = 0, ) -> torch.Tensor: if not (q_buckets_1.is_cuda and _TRITON_AVAILABLE): return _build_causal_inverted_index_reference( q_buckets_1, q_buckets_2, k_buckets, B_max=B_max, B_top1=B_top1, num_buckets=num_buckets, W=W ) B, H, N = q_buckets_1.shape q_b1 = q_buckets_1.contiguous() q_b2 = q_buckets_2.contiguous() k_b = k_buckets.contiguous() B_top2 = B_max - B_top1 indices = torch.full((B, H, N, B_max), -1, device=q_buckets_1.device, dtype=torch.int32) build_causal_index_fast_kernel[(B * H * num_buckets,)]( q_b1, q_b2, k_b, indices, q_b1.stride(0), q_b1.stride(1), q_b1.stride(2), indices.stride(0), indices.stride(1), indices.stride(2), indices.stride(3), N=N, B_max=B_max, B_top1=B_top1, B_top2=B_top2, NUM_BUCKETS=num_buckets, H=H, W=W ) return indices # ============================================================================= # 3. Single-Pass RMSNorm # ============================================================================= class RMSNorm(nn.Module): def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim)) def forward(self, x: torch.Tensor) -> torch.Tensor: input_dtype = x.dtype x_f32 = x.float() variance = x_f32.pow(2).mean(-1, keepdim=True) normed = x_f32 * torch.rsqrt(variance + self.eps) return (normed * self.weight.float()).to(input_dtype) # ============================================================================= # 4. Neural Modules: MSCSM, SRVQ, RPA, & StarCarrier FFN # ============================================================================= class MultiScaleCausalStateMixer(nn.Module): def __init__(self, d_model: int): super().__init__() self.d_model = d_model self.in_proj = nn.Linear(d_model, 2 * d_model, bias=False) self.out_proj = nn.Linear(d_model, d_model, bias=False) self.conv1 = nn.Conv1d(d_model, d_model, kernel_size=3, groups=d_model, bias=False) self.conv2 = nn.Conv1d(d_model, d_model, kernel_size=5, dilation=2, groups=d_model, bias=False) self.conv3 = nn.Conv1d(d_model, d_model, kernel_size=5, dilation=5, groups=d_model, bias=False) self.branch_weights = nn.Parameter(torch.ones(3)) nn.init.zeros_(self.out_proj.weight) def forward(self, x: torch.Tensor) -> torch.Tensor: u, g = self.in_proj(x).chunk(2, dim=-1) u_t = u.transpose(1, 2) u_padded = F.pad(u_t, (20, 0)) b1 = self.conv1(u_padded[:, :, 18:]) b2 = self.conv2(u_padded[:, :, 12:]) b3 = self.conv3(u_padded) w = F.softmax(self.branch_weights, dim=0) mixed = (w[0] * b1 + w[1] * b2 + w[2] * b3).transpose(1, 2) act = F.silu(g) * mixed return self.out_proj(act) class SRVQ(nn.Module): def __init__(self, n_heads: int, head_dim: int, L: int = 1, M: int = 16, decay: float = 0.999): super().__init__() self.n_heads, self.head_dim = n_heads, head_dim self.L, self.M, self.decay = L, M, decay codebooks = F.normalize(torch.randn(L, n_heads, M, head_dim), p=2, dim=-1) self.register_buffer("codebooks", codebooks) def quantize(self, x: torch.Tensor, is_key: bool = False): B, H, N, D = x.shape T = B * N r_flat = x.permute(1, 0, 2, 3).reshape(H, T, D).float() bucket_ids = torch.zeros((H, T), dtype=torch.int32, device=x.device) bucket_ids_2 = torch.zeros((H, T), dtype=torch.int32, device=x.device) commit_loss = torch.tensor(0.0, device=x.device, dtype=torch.float32) balance_loss = torch.tensor(0.0, device=x.device, dtype=torch.float32) for l in range(self.L): C = self.codebooks[l].float() # [H, M, D] r_norm = F.normalize(r_flat, p=2, dim=-1) # [H, T, D] sim = torch.bmm(r_norm, C.transpose(1, 2)) # [H, T, M] if self.M > 1: top_vals, top_idx = torch.topk(sim, k=2, dim=-1) assignments = top_idx[:, :, 0] assignments_2 = top_idx[:, :, 1] v_top1, v_top2 = top_vals[:, :, 0], top_vals[:, :, 1] else: assignments = torch.argmax(sim, dim=-1) assignments_2 = assignments bucket_ids_2 = bucket_ids * self.M + assignments_2.to(torch.int32) bucket_ids = bucket_ids * self.M + assignments.to(torch.int32) C_chosen = torch.gather( C, 1, assignments.unsqueeze(-1).expand(-1, -1, D) ) # [H, T, D] if self.training: commit_loss = commit_loss + F.mse_loss(r_norm, C_chosen.detach()) if self.M > 1: margin_loss = F.relu(0.1 - (v_top1 - v_top2)).mean() probs = F.softmax(sim * 10.0, dim=-1) mean_probs = probs.mean(dim=1) load_loss = self.M * (mean_probs * mean_probs).sum(dim=-1).mean() - 1.0 balance_loss = balance_loss + margin_loss + load_loss inner = torch.sum(r_norm * C_chosen, dim=-1, keepdim=True) r_flat = r_flat - (inner * C_chosen).detach() if self.training and is_key: with torch.no_grad(): one_hot = F.one_hot(assignments, num_classes=self.M).float() counts = one_hot.sum(dim=1).unsqueeze(-1) sum_r = torch.bmm(one_hot.transpose(1, 2), r_norm) mean_r = F.normalize(sum_r / counts.clamp(min=1.0), p=2, dim=-1) updated = F.normalize(C * self.decay + mean_r * (1.0 - self.decay), p=2, dim=-1) self.codebooks[l].copy_(torch.where(counts > 0, updated, C)) bucket_ids = bucket_ids.view(H, B, N).permute(1, 0, 2).contiguous() bucket_ids_2 = bucket_ids_2.view(H, B, N).permute(1, 0, 2).contiguous() return bucket_ids, bucket_ids_2, commit_loss.to(x.dtype), balance_loss.to(x.dtype) class CausalContextInjector(nn.Module): def __init__(self, d_model: int, kernel_size: int = 3): super().__init__() self.kernel_size = kernel_size self.conv = nn.Conv1d( in_channels=d_model, out_channels=d_model, kernel_size=kernel_size, groups=d_model, bias=False, ) nn.init.zeros_(self.conv.weight) with torch.no_grad(): self.conv.weight[:, 0, -1] = 1.0 def forward(self, x: torch.Tensor) -> torch.Tensor: x_t = x.transpose(1, 2) x_padded = F.pad(x_t, (self.kernel_size - 1, 0)) return self.conv(x_padded).transpose(1, 2) class ResidualPyramidAttention(nn.Module): def __init__( self, d_model: int, n_heads: int, L: int = 1, M: int = 16, G: int = 8, B_max: int = 16, W: int = 8, max_seq_len: int = 8192, causal_kernel_size: int = 3, ): super().__init__() self.d_model, self.n_heads, self.head_dim = d_model, n_heads, d_model // n_heads self.G, self.B_max, self.W = G, B_max, W self.qkv_proj = nn.Linear(d_model, 3 * d_model, bias=False) self.g_proj = nn.Linear(d_model, d_model, bias=False) self.o_proj = nn.Linear(d_model, d_model, bias=False) self.qk_temp = nn.Parameter(torch.full((1, n_heads, 1, 1), math.sqrt(self.head_dim))) self.qkv_context_injector = CausalContextInjector(3 * d_model, kernel_size=causal_kernel_size) self.srvq = SRVQ(self.n_heads, self.head_dim, L=L, M=M) self.register_keys = nn.Parameter(torch.randn(n_heads, G, self.head_dim)) self.recent_bias = nn.Parameter(torch.zeros(1, n_heads, 1, W)) if W > 0 else None self.ret_slot_bias = nn.Parameter(torch.zeros(1, n_heads, 1, B_max)) self.ret_dist_bias = nn.Parameter(torch.zeros(1, n_heads, 1, 1)) self.reg_slot_bias = nn.Parameter(torch.zeros(1, n_heads, 1, G)) self.ret_scale = nn.Parameter(torch.ones(1, n_heads, 1, 1)) self.glob_scale = nn.Parameter(torch.ones(1, n_heads, 1, 1)) self.attn_temp = nn.Parameter(torch.ones(1, n_heads, 1, 1)) cos, sin = precompute_multi_octave_rope( self.head_dim, self.n_heads, max_seq_len, base_min=64.0, base_max=262144.0, device="cuda" if torch.cuda.is_available() else "cpu", ) self.register_buffer("rope_cos", cos, persistent=False) self.register_buffer("rope_sin", sin, persistent=False) self.register_buffer("batch_idx_cache", None, persistent=False) self.register_buffer("head_idx_cache", None, persistent=False) def _compute_global_path_vectorized( self, K: torch.Tensor, V: torch.Tensor, reg_keys: torch.Tensor ) -> torch.Tensor: w_shift = max(1, self.W) if K.size(2) <= w_shift: return torch.zeros( (K.size(0), self.n_heads, self.G, K.size(2), self.head_dim), device=K.device, dtype=V.dtype, ) S_pre = torch.einsum("hgd,bhnd->bhgn", reg_keys, K).float() / math.sqrt(self.head_dim) S = torch.exp(S_pre.clamp(min=-20.0, max=20.0)) S_V = S.unsqueeze(-1) * V.float().unsqueeze(2) num = torch.cumsum(S_V, dim=3) den = torch.cumsum(S, dim=3) num_prev = F.pad(num[:, :, :, :-w_shift, :], (0, 0, w_shift, 0)) den_prev = F.pad(den[:, :, :, :-w_shift], (w_shift, 0)) return (num_prev / den_prev.unsqueeze(-1).clamp(min=1e-6)).to(V.dtype) def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: B, N, D = x.shape qkv = self.qkv_context_injector(self.qkv_proj(x)) q, k, v = qkv.chunk(3, dim=-1) q = q.view(B, N, self.n_heads, self.head_dim).transpose(1, 2).contiguous() k = k.view(B, N, self.n_heads, self.head_dim).transpose(1, 2).contiguous() v = v.view(B, N, self.n_heads, self.head_dim).transpose(1, 2).contiguous() q_norm = F.normalize(q, p=2, dim=-1) * self.qk_temp k_norm = F.normalize(k, p=2, dim=-1) * self.qk_temp reg_keys = F.normalize(self.register_keys, p=2, dim=-1) * self.qk_temp.squeeze(0) k_buckets, _, k_commit, k_bal = self.srvq.quantize(k_norm, is_key=True) q_buckets_1, q_buckets_2, q_commit, q_bal = self.srvq.quantize(q_norm, is_key=False) commit_loss = k_commit + q_commit balance_loss = k_bal + q_bal retrieved_indices = build_causal_inverted_index( q_buckets_1, q_buckets_2, k_buckets, B_max=self.B_max, B_top1=10, num_buckets=self.srvq.M ** self.srvq.L, W=self.W, ) v_reg = self._compute_global_path_vectorized(k_norm, v, reg_keys) q_rot = apply_multi_octave_rope(q_norm, self.rope_cos, self.rope_sin) k_rot = apply_multi_octave_rope(k_norm, self.rope_cos, self.rope_sin) if ( self.batch_idx_cache is None or self.batch_idx_cache.size(0) != B or self.batch_idx_cache.device != x.device ): self.batch_idx_cache = torch.arange(B, device=x.device)[:, None, None, None] self.head_idx_cache = torch.arange(self.n_heads, device=x.device)[None, :, None, None] retrieved_valid = retrieved_indices >= 0 retrieved_safe = retrieved_indices.clamp(min=0).long() k_ret = k_norm[self.batch_idx_cache, self.head_idx_cache, retrieved_safe] v_ret = v [self.batch_idx_cache, self.head_idx_cache, retrieved_safe] sm_scale = 1.0 / math.sqrt(self.head_dim) n_pos = torch.arange(N, device=x.device).view(1, 1, N, 1) ret_dist = (n_pos - retrieved_safe).clamp(min=1).to(q_norm.dtype) scores_ret = (q_norm.unsqueeze(3) * k_ret).sum(dim=-1) * sm_scale scores_ret = ( scores_ret * self.ret_scale + self.ret_slot_bias + self.ret_dist_bias * torch.log2(ret_dist) ) scores_ret = scores_ret.masked_fill(~retrieved_valid, -1e9) if self.W > 0: k_pad = F.pad(k_rot, (0, 0, self.W - 1, 0)) v_pad = F.pad(v, (0, 0, self.W - 1, 0)) k_win = k_pad.unfold(2, self.W, 1).transpose(-1, -2) v_win = v_pad.unfold(2, self.W, 1).transpose(-1, -2) scores_win = (q_rot.unsqueeze(3) * k_win).sum(dim=-1) * sm_scale + self.recent_bias w_abs = torch.arange(self.W, device=x.device).view(1, 1, 1, self.W) win_valid = (n_pos - (self.W - 1) + w_abs) >= 0 scores_win = scores_win.masked_fill(~win_valid, -1e9) scores_glob = torch.einsum("bhnd,hgd->bhng", q_norm, reg_keys) * sm_scale scores_glob = scores_glob * self.glob_scale + self.reg_slot_bias glob_valid = n_pos >= max(1, self.W) scores_glob = scores_glob.masked_fill(~glob_valid, -1e9) if self.W > 0: scores_all = torch.cat([scores_ret, scores_win, scores_glob], dim=-1) else: scores_all = torch.cat([scores_ret, scores_glob], dim=-1) attn_weights = F.softmax(scores_all * self.attn_temp, dim=-1) n_loc = self.B_max + self.W p_ret = attn_weights[..., :self.B_max] if self.W > 0: p_win = attn_weights[..., self.B_max:n_loc] p_glob = attn_weights[..., n_loc:] out_loc = (p_ret.unsqueeze(-1) * v_ret).sum(dim=3) if self.W > 0: out_loc = out_loc + (p_win.unsqueeze(-1) * v_win).sum(dim=3) out_glob = (p_glob.permute(0, 1, 3, 2).unsqueeze(-1) * v_reg).sum(dim=2) out = out_loc + out_glob out = out.transpose(1, 2).reshape(B, N, D) out = out * torch.sigmoid(self.g_proj(x)) return self.o_proj(out), commit_loss, balance_loss class HarmonicDifferentialStarCarrierFFN(nn.Module): def __init__( self, d_model: int = 256, hidden_dim: int = 512, dropout: float = 0.0, bias: bool = False, ): super().__init__() self.d_model = d_model self.hidden_dim = hidden_dim self.w_in = nn.Linear(d_model, 3 * hidden_dim, bias=bias) self.lambda_direct = nn.Parameter(torch.full((hidden_dim,), 1.386)) self.lambda_harmonic = nn.Parameter(torch.full((hidden_dim,), -1.386)) self.star_gamma = nn.Parameter(torch.ones(hidden_dim)) self.star_tau = nn.Parameter(torch.ones(hidden_dim)) self.star_beta = nn.Parameter(torch.full((hidden_dim,), 0.5)) self.lambda_conj = nn.Parameter(torch.full((hidden_dim,), 0.0)) self.gamma2 = nn.Parameter(torch.ones(hidden_dim)) self.tau2 = nn.Parameter(torch.full((hidden_dim,), 0.5)) self.norm = RMSNorm(hidden_dim) self.w_down = nn.Linear(hidden_dim, d_model, bias=bias) self.dropout = nn.Dropout(dropout) if dropout > 0.0 else nn.Identity() def forward(self, x: torch.Tensor) -> torch.Tensor: k1, k2, v = self.w_in(x).chunk(3, dim=-1) k2_roll = torch.roll(k2, 1, -1) k2_shift = k2_roll - k2 diff_k1 = ( k1 - torch.sigmoid(self.lambda_direct) * k2 - torch.sigmoid(self.lambda_harmonic) * k2_shift ) relu_k1 = F.relu(diff_k1) gate1 = self.star_gamma * (relu_k1 * relu_k1) + self.star_tau * F.silu(diff_k1) + self.star_beta m1 = gate1 * v diff_conj = k2 - torch.sigmoid(self.lambda_conj) * k1 gate2 = torch.sigmoid(self.gamma2 * m1 + self.tau2 * diff_conj) m2 = m1 * (1.0 + 2.0 * gate2) normed = self.norm(m2) return self.dropout(self.w_down(normed)) # ============================================================================= # 5. Transformer Block & UnifiedLM Architecture # ============================================================================= class UnifiedTransformerBlock(nn.Module): def __init__(self, d_model: int, n_heads: int, ffn_dropout: float = 0.0, max_seq_len: int = 8192): super().__init__() self.norm_mixer = RMSNorm(d_model) self.time_mixer = MultiScaleCausalStateMixer(d_model) self.gamma_mixer = nn.Parameter(torch.full((d_model,), 0.5)) self.norm_attn = RMSNorm(d_model) self.attn = ResidualPyramidAttention( d_model, n_heads, L=1, M=16, G=8, B_max=16, W=8, max_seq_len=max_seq_len ) self.gamma_attn = nn.Parameter(torch.full((d_model,), 1.0)) self.norm_ffn = RMSNorm(d_model) self.ffn = HarmonicDifferentialStarCarrierFFN( d_model=d_model, hidden_dim=2 * d_model, dropout=ffn_dropout, ) self.gamma_ffn = nn.Parameter(torch.full((d_model,), 1.0)) def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: x = x + self.gamma_mixer * self.time_mixer(self.norm_mixer(x)) attn_out, c_loss, b_loss = self.attn(self.norm_attn(x)) x = x + self.gamma_attn * attn_out x = x + self.gamma_ffn * self.ffn(self.norm_ffn(x)) return x, 0.01 * (c_loss + 0.1 * b_loss) class UnifiedLM(nn.Module): def __init__( self, vocab_size: int = 2048, d_model: int = 192, n_heads: int = 4, num_layers: int = 3, softcap: float = 30.0, max_seq_len: int = 8192, ffn_dropout: float = 0.0, ): super().__init__() self.config = UnifiedLMConfig( vocab_size=vocab_size, d_model=d_model, n_heads=n_heads, n_layers=num_layers, softcap=softcap, max_seq_len=max_seq_len, ffn_dropout=ffn_dropout, ) self.embed = nn.Embedding(vocab_size, d_model) self.layers = nn.ModuleList( [ UnifiedTransformerBlock( d_model, n_heads, ffn_dropout=ffn_dropout, max_seq_len=max_seq_len ) for _ in range(num_layers) ] ) self.norm = RMSNorm(d_model) self.head = nn.Linear(d_model, vocab_size, bias=False) self.head.weight = self.embed.weight self.softcap = softcap self.inv_softcap = 1.0 / softcap if softcap > 0.0 else 0.0 self.apply(self._init_weights) for layer in self.layers: nn.init.zeros_(layer.time_mixer.out_proj.weight) @classmethod def from_config(cls, config: UnifiedLMConfig) -> "UnifiedLM": return cls( vocab_size=config.vocab_size, d_model=config.d_model, n_heads=config.n_heads, num_layers=config.n_layers, softcap=config.softcap, max_seq_len=config.max_seq_len, ffn_dropout=config.ffn_dropout, ) def _init_weights(self, module: nn.Module): if isinstance(module, nn.Linear): nn.init.normal_(module.weight, mean=0.0, std=0.02) if module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, nn.Embedding): nn.init.normal_(module.weight, mean=0.0, std=0.02) elif isinstance(module, RMSNorm): nn.init.ones_(module.weight) def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: h = self.embed(x) total_aux_loss = torch.tensor(0.0, device=x.device, dtype=h.dtype) for layer in self.layers: h, aux_loss = layer(h) total_aux_loss = total_aux_loss + aux_loss logits = self.head(self.norm(h)) if self.softcap > 0.0: logits = self.softcap * torch.tanh(logits * self.inv_softcap) return logits, total_aux_loss @torch.inference_mode() def generate( self, input_ids: torch.Tensor, max_new_tokens: int = 64, temperature: float = 0.7, top_k: int = 40, top_p: float = 1.0, repetition_penalty: float = 1.0, eos_token_id: Optional[int] = None, max_window_len: int = 512, ) -> torch.Tensor: """ Autoregressive generation helper. input_ids: LongTensor of shape [B, N] """ was_training = self.training self.eval() device = next(self.parameters()).device ids = input_ids.to(device) use_amp = device.type == "cuda" for _ in range(max_new_tokens): context = ids[:, -max_window_len:] if ids.size(1) > max_window_len else ids with torch.autocast(device_type=device.type, dtype=torch.float16, enabled=use_amp): logits, _ = self(context) next_logits = logits[:, -1, :].float() if repetition_penalty != 1.0: score = torch.gather(next_logits, 1, ids) score = torch.where(score < 0, score * repetition_penalty, score / repetition_penalty) next_logits.scatter_(1, ids, score) if temperature <= 0.0: next_token = torch.argmax(next_logits, dim=-1, keepdim=True) else: next_logits = next_logits / temperature if top_k > 0: v, _ = torch.topk(next_logits, min(top_k, next_logits.size(-1))) next_logits[next_logits < v[:, [-1]]] = -float("Inf") if 0.0 < top_p < 1.0: sorted_logits, sorted_indices = torch.sort(next_logits, descending=True) cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1) sorted_indices_to_remove = cumulative_probs > top_p sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone() sorted_indices_to_remove[..., 0] = 0 indices_to_remove = sorted_indices_to_remove.scatter( 1, sorted_indices, sorted_indices_to_remove ) next_logits[indices_to_remove] = -float("Inf") probs = F.softmax(next_logits, dim=-1) next_token = torch.multinomial(probs, num_samples=1) ids = torch.cat((ids, next_token), dim=1) if eos_token_id is not None and torch.all(next_token == eos_token_id): break if was_training: self.train() return ids @classmethod def from_pretrained( cls, path: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", dtype: torch.dtype = torch.float32, use_ema_if_available: bool = True, config_override: Optional[UnifiedLMConfig] = None, ) -> "UnifiedLM": """ Loads a UnifiedLM model from: 1. A converted directory containing `model.safetensors` (+ optional `config.json`) 2. A standalone `.safetensors` file 3. A training `.pt` checkpoint (automatically applying EMA weights if saved) """ if not os.path.exists(path): raise FileNotFoundError(f"Model path not found: {path}") cfg = config_override or UnifiedLMConfig() # Case 1: Training .pt checkpoint if os.path.isfile(path) and path.endswith(".pt"): ckpt = torch.load(path, map_location="cpu", weights_only=False) saved_cfg = ckpt.get("config") if saved_cfg is not None and config_override is None: cfg.vocab_size = getattr(saved_cfg, "vocab_size", cfg.vocab_size) cfg.d_model = getattr(saved_cfg, "d_model", cfg.d_model) cfg.n_heads = getattr(saved_cfg, "n_heads", cfg.n_heads) cfg.n_layers = getattr(saved_cfg, "n_layers", cfg.n_layers) cfg.softcap = getattr(saved_cfg, "softcap", cfg.softcap) state_dict = dict(ckpt["model"] if "model" in ckpt else ckpt) if "head.weight" not in state_dict and "embed.weight" in state_dict: state_dict["head.weight"] = state_dict["embed.weight"] model = cls.from_config(cfg) model.load_state_dict(state_dict, strict=True) # Apply EMA shadow weights if present in the training checkpoint ctrl_state = ckpt.get("controller_state") if use_ema_if_available and isinstance(ctrl_state, dict) and "shadow" in ctrl_state: step_count = max(1, int(ctrl_state.get("step_count", ckpt.get("step", 1)))) ema_decay = 0.995 bias_correction = 1.0 / (1.0 - (ema_decay ** step_count)) trainable_params = [p for p in model.parameters() if p.requires_grad] if len(trainable_params) == len(ctrl_state["shadow"]): with torch.no_grad(): for p, s in zip(trainable_params, ctrl_state["shadow"]): p.copy_((s.float() * bias_correction).to(p.dtype)) model.head.weight = model.embed.weight return model.to(device=device, dtype=dtype).eval() # Case 2: Converted directory or .safetensors file if not _SAFETENSORS_AVAILABLE: raise ImportError("Please install safetensors (`pip install safetensors`) to load .safetensors models.") if os.path.isdir(path): model_dir = path safetensors_path = os.path.join(model_dir, "model.safetensors") else: safetensors_path = path model_dir = os.path.dirname(os.path.abspath(path)) config_json_path = os.path.join(model_dir, "config.json") if config_override is None: # Read metadata from safetensors header if present try: with safe_open(safetensors_path, framework="pt", device="cpu") as f: meta = f.metadata() or {} if "vocab_size" in meta: cfg.vocab_size = int(meta["vocab_size"]) if "d_model" in meta: cfg.d_model = int(meta["d_model"]) if "n_heads" in meta: cfg.n_heads = int(meta["n_heads"]) if "n_layers" in meta: cfg.n_layers = int(meta["n_layers"]) if "softcap" in meta: cfg.softcap = float(meta["softcap"]) except Exception: pass # Override with config.json if present if os.path.exists(config_json_path): with open(config_json_path, "r", encoding="utf-8") as f: cfg_dict = json.load(f) cfg.vocab_size = int(cfg_dict.get("vocab_size", cfg.vocab_size)) cfg.d_model = int(cfg_dict.get("d_model", cfg.d_model)) cfg.n_heads = int(cfg_dict.get("n_heads", cfg.n_heads)) cfg.n_layers = int(cfg_dict.get("n_layers", cfg.n_layers)) cfg.softcap = float(cfg_dict.get("softcap", cfg.softcap)) raw_state = load_file(safetensors_path, device="cpu") prepared_state: Dict[str, torch.Tensor] = {} for k, v in raw_state.items(): if v.is_floating_point(): t = v.to(dtype=torch.float32) if k.endswith(".srvq.codebooks"): t = F.normalize(t, p=2, dim=-1) prepared_state[k] = t else: prepared_state[k] = v if "head.weight" not in prepared_state and "embed.weight" in prepared_state: prepared_state["head.weight"] = prepared_state["embed.weight"] model = cls.from_config(cfg) model.load_state_dict(prepared_state, strict=True) model.head.weight = model.embed.weight return model.to(device=device, dtype=dtype).eval() def load_tokenizer(path: Optional[str] = None, vocab_size: int = 2048) -> "PreTrainedTokenizerFast": """ Loads the math-isolated tokenizer from a model directory or local tokenizer cache. """ if not _TRANSFORMERS_AVAILABLE: raise ImportError("Please install transformers (`pip install transformers`) to load the tokenizer.") candidates: List[str] = [] if path is not None: if os.path.isdir(path): candidates.append(path) else: candidates.append(os.path.dirname(os.path.abspath(path))) candidates.append(f"./tokenizer_cache/tok_multidomain_math_isolated_v1_{vocab_size}") candidates.append("./exported_model") for cand in candidates: if cand and os.path.isdir(cand) and os.path.exists(os.path.join(cand, "tokenizer.json")): return AutoTokenizer.from_pretrained(cand) raise FileNotFoundError( f"Could not find tokenizer.json in any of: {candidates}. " f"Pass the directory containing tokenizer.json to `load_tokenizer(path)`." )