Text Generation
MLX
Safetensors
PyTorch
English
from-scratch
tiny
chat

Run this model with HF Jobs

Run Jainam59/MangoShake-50M on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/Jainam59/MangoShake-50M. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/Jainam59/MangoShake-50M on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/Jainam59/MangoShake-50M. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.

Quantize for lower memory use

Use HF Jobs to create a 4-bit version of https://huggingface.co/Jainam59/MangoShake-50M. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
MangoShake-50M / model.py
Jainam59's picture
Upload 10 files
0f35d55 verified
Raw History Blame Contribute Delete
5 kB
"""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 ("<name>.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