HamerLM / app.py
dharun2049's picture
Rename app (4).py to app.py
a61c8d2 verified
Raw
History Blame Contribute Delete
5.97 kB
"""
"""
from __future__ import annotations
import os
from dataclasses import dataclass
import gradio as gr
import tiktoken
import torch
import torch.nn as nn
import torch.nn.functional as F
CKPT_PATH = os.environ.get("CKPT_PATH", "fable5_transformer.pt")
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# ---------------------------------------------------------------------------
# Model (must match train_transformer.py)
# ---------------------------------------------------------------------------
@dataclass
class Config:
vocab_size: int = 50257
n_layer: int = 6
n_head: int = 8
n_embd: int = 256
block_size: int = 256
dropout: float = 0.0
class CausalSelfAttention(nn.Module):
def __init__(self, cfg: Config):
super().__init__()
self.n_head = cfg.n_head
self.n_embd = cfg.n_embd
self.qkv = nn.Linear(cfg.n_embd, 3 * cfg.n_embd, bias=False)
self.proj = nn.Linear(cfg.n_embd, cfg.n_embd, bias=False)
self.drop = nn.Dropout(cfg.dropout)
def forward(self, x):
B, T, C = x.shape
q, k, v = self.qkv(x).split(self.n_embd, dim=2)
hd = C // self.n_head
q = q.view(B, T, self.n_head, hd).transpose(1, 2)
k = k.view(B, T, self.n_head, hd).transpose(1, 2)
v = v.view(B, T, self.n_head, hd).transpose(1, 2)
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
y = y.transpose(1, 2).contiguous().view(B, T, C)
return self.drop(self.proj(y))
class MLP(nn.Module):
def __init__(self, cfg: Config):
super().__init__()
self.fc = nn.Linear(cfg.n_embd, 4 * cfg.n_embd, bias=False)
self.proj = nn.Linear(4 * cfg.n_embd, cfg.n_embd, bias=False)
self.drop = nn.Dropout(cfg.dropout)
def forward(self, x):
return self.drop(self.proj(F.gelu(self.fc(x))))
class Block(nn.Module):
def __init__(self, cfg: Config):
super().__init__()
self.ln1 = nn.LayerNorm(cfg.n_embd)
self.attn = CausalSelfAttention(cfg)
self.ln2 = nn.LayerNorm(cfg.n_embd)
self.mlp = MLP(cfg)
def forward(self, x):
x = x + self.attn(self.ln1(x))
x = x + self.mlp(self.ln2(x))
return x
class TinyGPT(nn.Module):
def __init__(self, cfg: Config):
super().__init__()
self.cfg = cfg
self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.n_embd)
self.pos_emb = nn.Embedding(cfg.block_size, cfg.n_embd)
self.drop = nn.Dropout(cfg.dropout)
self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.n_layer)])
self.ln_f = nn.LayerNorm(cfg.n_embd)
self.head = nn.Linear(cfg.n_embd, cfg.vocab_size, bias=False)
self.head.weight = self.tok_emb.weight
def forward(self, idx):
B, T = idx.shape
pos = torch.arange(T, device=idx.device)
x = self.drop(self.tok_emb(idx) + self.pos_emb(pos))
for b in self.blocks:
x = b(x)
return self.head(self.ln_f(x))
@torch.no_grad()
def generate(self, idx, max_new=100, temperature=0.9, top_k=50):
for _ in range(max_new):
idx_cond = idx[:, -self.cfg.block_size :]
logits = self(idx_cond)[:, -1, :] / max(temperature, 1e-5)
if top_k:
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
logits[logits < v[:, [-1]]] = -float("inf")
probs = F.softmax(logits, dim=-1)
nxt = torch.multinomial(probs, 1)
idx = torch.cat([idx, nxt], dim=1)
return idx
# ---------------------------------------------------------------------------
# Load
# ---------------------------------------------------------------------------
print(f"[load] device={DEVICE} ckpt={CKPT_PATH}")
ckpt = torch.load(CKPT_PATH, map_location=DEVICE, weights_only=False)
cfg_dict = ckpt.get("cfg", {})
cfg = Config(**{k: v for k, v in cfg_dict.items() if k in Config.__dataclass_fields__})
cfg.dropout = 0.0
model = TinyGPT(cfg).to(DEVICE)
model.load_state_dict(ckpt["model"])
model.eval()
enc = tiktoken.get_encoding("gpt2")
print(f"[load] params={sum(p.numel() for p in model.parameters())/1e6:.2f}M")
# ---------------------------------------------------------------------------
# Inference
# ---------------------------------------------------------------------------
def generate(prompt: str, max_new_tokens: int, temperature: float, top_k: int, seed: int):
if seed >= 0:
torch.manual_seed(seed)
text = prompt if prompt.strip() else "<|endoftext|>"
ids = enc.encode(text, allowed_special={"<|endoftext|>"})
if not ids:
ids = [enc.eot_token]
x = torch.tensor([ids], dtype=torch.long, device=DEVICE)
out = model.generate(x, max_new=int(max_new_tokens), temperature=float(temperature), top_k=int(top_k))
return enc.decode(out[0].tolist())
EXAMPLES = [
["USER: Make a new one, it should be", 120, 0.9, 50, -1],
["<|user|>\nWrite a bash script that", 120, 0.8, 40, 42],
["<|endoftext|>", 150, 1.0, 50, -1],
]
with gr.Blocks(title="Tiny Transformer") as demo:
gr.Markdown(
"# HamerLM\n"
)
with gr.Row():
with gr.Column():
prompt = gr.Textbox(label="Prompt", value="USER: Make a new one, it should be", lines=4)
max_new = gr.Slider(16, 512, value=120, step=8, label="Max new tokens")
temperature = gr.Slider(0.1, 1.5, value=0.9, step=0.05, label="Temperature")
top_k = gr.Slider(1, 200, value=50, step=1, label="Top-k")
seed = gr.Number(value=-1, precision=0, label="Seed (-1 = random)")
btn = gr.Button("Generate", variant="primary")
with gr.Column():
out = gr.Textbox(label="Output", lines=18)
btn.click(generate, [prompt, max_new, temperature, top_k, seed], out)
gr.Examples(EXAMPLES, [prompt, max_new, temperature, top_k, seed])
if __name__ == "__main__":
demo.launch()