import torch import torch.nn as nn import torch.nn.functional as F import math def ste_quantize(x, qmin, qmax, scale): q = torch.round(x / scale).clamp(qmin, qmax) x_q = q * scale return x + (x_q - x).detach() class W4A32Linear(nn.Module): def __init__(self, in_features, out_features, bias=True): super().__init__() assert in_features % 2 == 0 self.in_features = in_features self.out_features = out_features self.weight = nn.Parameter(torch.empty(out_features, in_features)) self.weight_scale = nn.Parameter(torch.ones(out_features, 1)) self.bias = nn.Parameter(torch.zeros(out_features)) if bias else None nn.init.normal_(self.weight, mean=0.0, std=0.02) def forward(self, x): w = (self.weight * self.weight_scale).float() scale = w.abs().amax(dim=1, keepdim=True).clamp(min=1e-8) / 7.0 w_q = ste_quantize(w, -8, 7, scale) return F.linear(x.float(), w_q, self.bias).to(x.dtype) class W8A32Linear(nn.Module): def __init__(self, in_features, out_features, bias=True): super().__init__() self.in_features = in_features self.out_features = out_features self.weight = nn.Parameter(torch.empty(out_features, in_features)) self.weight_scale = nn.Parameter(torch.ones(out_features, 1)) self.bias = nn.Parameter(torch.zeros(out_features)) if bias else None nn.init.normal_(self.weight, mean=0.0, std=0.02) def forward(self, x): w = (self.weight * self.weight_scale).float() scale = w.abs().amax(dim=1, keepdim=True).clamp(min=1e-8) / 127.0 w_q = ste_quantize(w, -128, 127, scale) return F.linear(x.float(), w_q, self.bias).to(x.dtype) class Int8Embedding(nn.Module): def __init__(self, n, d): super().__init__() self.weight = nn.Parameter(torch.empty(n, d)) self.weight_scale = nn.Parameter(torch.ones(n, 1)) self.d = d nn.init.normal_(self.weight, mean=0.0, std=0.02) def forward(self, idx): w = (self.weight * self.weight_scale).float() scale = w.abs().amax(dim=1, keepdim=True).clamp(min=1e-8) / 127.0 w_q = ste_quantize(w, -128, 127, scale) flat = idx.view(-1) out = w_q[flat] return out.view(*idx.shape, self.d) class RMSNorm(nn.Module): def __init__(self, dim, eps=1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) self.eps = eps def forward(self, x): n = x.float() * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps) return (n * self.weight).to(x.dtype) class ManifoldConstrainedHyperConnection(nn.Module): def __init__(self, dim): super().__init__() self.alpha = nn.Parameter(torch.tensor(1.0)) self.beta = nn.Parameter(torch.tensor(0.0)) def forward(self, x, y): return self.alpha * x + self.beta * y class ResonantCoordinateEmbeddings(nn.Module): def __init__(self, n_token, d_model, dim_coord=256, grid_size=128): super().__init__() self.token_coord = nn.Embedding(n_token, 2) self.row_embed = Int8Embedding(grid_size, dim_coord) self.col_embed = Int8Embedding(grid_size, dim_coord) self.fc1 = W8A32Linear(dim_coord * 2, 2048) self.norm = RMSNorm(2048) self.fc2 = W8A32Linear(2048, d_model) self.coord_gate = nn.Parameter(torch.ones(1)) self.grid_size = grid_size def forward(self, x): coords = self.token_coord(x).sigmoid() gx = coords[..., 0] * (self.grid_size - 1) gy = coords[..., 1] * (self.grid_size - 1) x0 = gx.floor().long().clamp(0, self.grid_size - 1) x1 = (x0 + 1).clamp(0, self.grid_size - 1) y0 = gy.floor().long().clamp(0, self.grid_size - 1) y1 = (y0 + 1).clamp(0, self.grid_size - 1) wx = (gx - x0.float()).unsqueeze(-1) wy = (gy - y0.float()).unsqueeze(-1) row = self.row_embed(x0) * (1 - wx) + self.row_embed(x1) * wx col = self.col_embed(y0) * (1 - wy) + self.col_embed(y1) * wy emb = torch.cat([row, col], dim=-1) h = self.fc1(emb) h = F.silu(h) h = self.norm(h) h = self.fc2(h) return self.coord_gate * h class Scratchpad(nn.Module): def __init__(self, d_model, max_memory_tokens=8192, n_heads=16, dropout=0.1): super().__init__() self.d_model = d_model self.max_memory_tokens = max_memory_tokens self.n_heads = n_heads self.head_dim = d_model // n_heads assert self.head_dim * n_heads == d_model self.q_proj = nn.Linear(d_model, d_model, bias=False) self.k_proj = nn.Linear(d_model, d_model, bias=False) self.v_proj = nn.Linear(d_model, d_model, bias=False) self.out_proj = nn.Linear(d_model, d_model) self.dropout = nn.Dropout(dropout) self.scale = self.head_dim ** -0.5 self.gate = nn.Parameter(torch.tensor(1.0)) def init_state(self, batch_size, device): return { "memory": torch.zeros( batch_size, 0, self.d_model, dtype=torch.float16, device=device ) } def read_memory(self, x_last, state): memory = state["memory"] if memory.shape[1] == 0: return torch.zeros_like(x_last) q = self.q_proj(x_last).to(torch.float32) k = self.k_proj(memory).to(torch.float32) v = self.v_proj(memory).to(torch.float32) B, L, _ = k.shape q = q.view(B, 1, self.n_heads, self.head_dim).transpose(1, 2) k = k.view(B, L, self.n_heads, self.head_dim).transpose(1, 2) v = v.view(B, L, self.n_heads, self.head_dim).transpose(1, 2) attn = torch.matmul(q, k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn = self.dropout(attn) out = torch.matmul(attn, v) out = out.transpose(1, 2).contiguous().view(B, 1, self.d_model) out = self.out_proj(out).to(x_last.dtype) return out * self.gate def update_memory(self, x_last, state): new_token = x_last.detach().to(torch.float16) memory = state["memory"] new_memory = torch.cat([memory, new_token], dim=1) if new_memory.shape[1] > self.max_memory_tokens: excess = new_memory.shape[1] - self.max_memory_tokens new_memory = new_memory[:, excess:] state["memory"] = new_memory return state def forward(self, x_last, state): read_out = self.read_memory(x_last, state) state = self.update_memory(x_last, state) return read_out, state class DeepMicroExpert(nn.Module): def __init__(self, d_model, d_hidden, num_experts, router, rank=12): super().__init__() self.top_k = 2 self.num_experts = num_experts self.expert_dim = d_hidden // num_experts self.router = router self.rank = rank self.gate = nn.ModuleList([W4A32Linear(d_model, self.expert_dim) for _ in range(num_experts)]) self.up = nn.ModuleList([W4A32Linear(d_model, self.expert_dim) for _ in range(num_experts)]) self.down = nn.ModuleList([W4A32Linear(self.expert_dim, d_model) for _ in range(num_experts)]) self.adapter_B = nn.Parameter(torch.randn(num_experts, d_model, rank) * 0.02) self.adapter_A = nn.Parameter(torch.randn(num_experts, rank, self.expert_dim) * 0.02) self.dropout = nn.Dropout(0.1) def forward(self, x): B, T, D = x.shape x_flat = x.view(-1, D) N = x_flat.shape[0] logits = self.router(x_flat.float()) probs = torch.softmax(logits, -1) w, idx = torch.topk(probs, self.top_k, dim=-1) w = w / (w.sum(-1, keepdim=True) + 1e-8) token_ids = torch.arange(N, device=x.device).unsqueeze(1).expand(-1, self.top_k).reshape(-1) expert_ids = idx.reshape(-1) weights = w.reshape(-1) flat_input = x_flat[token_ids] out = torch.zeros(N, D, device=x.device, dtype=x.dtype) for e in range(self.num_experts): mask = (expert_ids == e) if mask.sum() == 0: continue inp = flat_input[mask] wt = weights[mask].unsqueeze(-1) h = F.silu(self.gate[e](inp)) * self.up[e](inp) delta = torch.matmul(inp, self.adapter_B[e]) delta = torch.matmul(delta, self.adapter_A[e]) h = h + delta h = self.down[e](h) h = self.dropout(h) out.index_add_(0, token_ids[mask], h * wt.to(h.dtype)) return out.view(B, T, D) class TransformerBlock(nn.Module): def __init__(self, d_model, d_hidden, num_experts, router): super().__init__() self.norm = RMSNorm(d_model) self.ffn = DeepMicroExpert(d_model, d_hidden, num_experts, router) self.mhc = ManifoldConstrainedHyperConnection(d_model) def forward(self, x): f = self.ffn(self.norm(x)) return self.mhc(x, f) class GOMETransformer(nn.Module): def __init__(self, n_token, n_layer, d_model, d_hidden, num_experts): super().__init__() self.embed = ResonantCoordinateEmbeddings(n_token, d_model) self.scratchpad = Scratchpad(d_model) self.read_dropout = nn.Dropout(0.1) shared_router = W4A32Linear(d_model, num_experts) self.blocks = nn.ModuleList([ TransformerBlock(d_model, d_hidden, num_experts, shared_router) for _ in range(n_layer) ]) self.norm = RMSNorm(d_model) def forward(self, x, state=None): B, T = x.shape device = x.device if state is None: state = self.scratchpad.init_state(B, device) text_h = self.embed(x) h = text_h read = self.scratchpad.read_memory(h[:, -1:], state) h[:, -1:] = h[:, -1:] + self.read_dropout(read) for block in self.blocks: h = block(h) h = self.norm(h) state = self.scratchpad.update_memory(h[:, -1:], state) h_text = h return h_text, state class Gome(nn.Module): def __init__(self, config): super().__init__() # Pull real values from your config.json d_model = getattr(config, "d_model", 256) d_hidden = getattr(config, "d_hidden", 1024) n_layer = getattr(config, "n_layer", 12) num_experts = getattr(config, "num_experts", 4) n_token = getattr(config, "vocab_size", 50257) self.final_dropout = nn.Dropout(0.1) self.transformer = GOMETransformer( n_token, n_layer, d_model, d_hidden, num_experts ) self.lm_head = nn.Sequential( nn.Linear(d_model, d_model, bias=False), nn.SiLU(), nn.Linear(d_model, n_token, bias=False) ) def forward(self, x, state=None): h, state = self.transformer(x, state=state) h = self.final_dropout(h) logits = self.lm_head(h) return logits, state