"""PyTorch version of the MangoShake-50M model, for running it on any machine. Same architecture and parameter names as the MLX model used for training, so the released model.safetensors loads directly. """ import json import math import os from dataclasses import dataclass import torch import torch.nn as nn import torch.nn.functional as F from safetensors.torch import load_file @dataclass class Config: vocab_size: int = 16384 ctx: int = 512 d_model: int = 512 n_layers: int = 14 n_heads: int = 8 d_ff: int = 1376 rope_base: float = 10000.0 class RMSNorm(nn.Module): def __init__(self, d, eps=1e-5): super().__init__() self.weight = nn.Parameter(torch.ones(d)) self.eps = eps def forward(self, x): x = x.float() return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight def rope(x, base, offset=0): # x: (B, H, T, Dh). Rotate dim i together with dim i + Dh/2 by angle pos * freq_i. T, dh = x.shape[2], x.shape[3] half = dh // 2 freqs = 1.0 / (base ** (torch.arange(half, dtype=torch.float32, device=x.device) / half)) angles = torch.arange(offset, offset + T, dtype=torch.float32, device=x.device)[:, None] * freqs[None, :] cos, sin = angles.cos(), angles.sin() x1, x2 = x[..., :half], x[..., half:] return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1) class Linear(nn.Module): # Weight-only linear layer named like the MLX checkpoint (".weight"). def __init__(self, d_in, d_out): super().__init__() self.weight = nn.Parameter(torch.empty(d_out, d_in)) def forward(self, x): return F.linear(x, self.weight) class Attention(nn.Module): def __init__(self, cfg): super().__init__() self.n_heads = cfg.n_heads self.head_dim = cfg.d_model // cfg.n_heads self.rope_base = cfg.rope_base self.qkv = Linear(cfg.d_model, 3 * cfg.d_model) self.proj = Linear(cfg.d_model, cfg.d_model) def forward(self, x, cache=None): B, T, D = x.shape q, k, v = self.qkv(x).split(D, dim=-1) q, k, v = (t.view(B, T, self.n_heads, self.head_dim).transpose(1, 2) for t in (q, k, v)) offset = 0 if cache is None else cache[0].shape[2] q, k = rope(q, self.rope_base, offset), rope(k, self.rope_base, offset) if cache is not None: k = torch.cat([cache[0], k], dim=2) v = torch.cat([cache[1], v], dim=2) out = F.scaled_dot_product_attention(q, k, v, is_causal=cache is None and T > 1) return self.proj(out.transpose(1, 2).reshape(B, T, D)), (k, v) class MLP(nn.Module): def __init__(self, cfg): super().__init__() self.gate = Linear(cfg.d_model, cfg.d_ff) self.up = Linear(cfg.d_model, cfg.d_ff) self.down = Linear(cfg.d_ff, cfg.d_model) def forward(self, x): return self.down(F.silu(self.gate(x)) * self.up(x)) class Block(nn.Module): def __init__(self, cfg): super().__init__() self.n1 = RMSNorm(cfg.d_model) self.attn = Attention(cfg) self.n2 = RMSNorm(cfg.d_model) self.mlp = MLP(cfg) def forward(self, x, cache=None): a, cache = self.attn(self.n1(x), cache) x = x + a return x + self.mlp(self.n2(x)), cache class GPT(nn.Module): def __init__(self, cfg): super().__init__() self.cfg = cfg self.emb = nn.Parameter(torch.empty(cfg.vocab_size, cfg.d_model)) self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.n_layers)]) self.norm = RMSNorm(cfg.d_model) def forward(self, idx, caches=None): x = self.emb[idx] new_caches = [] for i, block in enumerate(self.blocks): x, c = block(x, None if caches is None else caches[i]) new_caches.append(c) return self.norm(x) @ self.emb.T, new_caches def load(path, device="cpu", weights="model.safetensors"): cfg = Config(**json.load(open(os.path.join(path, "config.json")))) model = GPT(cfg) state = {k: v.float() for k, v in load_file(os.path.join(path, weights)).items()} model.load_state_dict(state) return model.to(device).eval() @torch.no_grad() def sample(model, ids, max_new, stop_id, temperature=0.7, top_k=40): """Generate up to max_new tokens after `ids`, stopping at stop_id. Returns the new ids.""" device = next(model.parameters()).device logits, caches = model(torch.tensor([ids], device=device)) out = [] for _ in range(min(max_new, model.cfg.ctx - len(ids))): last = logits[:, -1, :] / temperature if top_k: kth = torch.topk(last, top_k).values[:, -1:] last = last.masked_fill(last < kth, float("-inf")) nxt = torch.multinomial(F.softmax(last, dim=-1), 1) if nxt.item() == stop_id: break out.append(nxt.item()) logits, caches = model(nxt, caches) return out