Text Generation
English
aurora80k
Aurora-80K / Inference.py
ThatHungarian's picture
Added Core files
f404f04 verified
Raw History Blame Contribute Delete
6.32 kB
import math, argparse, sys
import torch
import torch.nn as nn
import torch.nn.functional as F
from tokenizers import Tokenizer
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
class RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x):
norm = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
return x * norm * self.weight
class SwiGLU(nn.Module):
def __init__(self, dim, hidden):
super().__init__()
self.gate = nn.Linear(dim, hidden, bias=False)
self.up = nn.Linear(dim, hidden, bias=False)
self.down = nn.Linear(hidden, dim, bias=False)
def forward(self, x):
return self.down(F.silu(self.gate(x)) * self.up(x))
class ALiBiAttn(nn.Module):
def __init__(self, dim=64, rank=48, heads=4, window=256):
super().__init__()
self.heads = heads
self.head_dim = rank // heads
self.window = window
self.q = nn.Linear(dim, rank, bias=False)
self.k = nn.Linear(dim, rank, bias=False)
self.v = nn.Linear(dim, rank, bias=False)
self.o = nn.Linear(rank, dim, bias=False)
slopes = torch.tensor([2.0 ** (-8.0 * (i + 1) / heads) for i in range(heads)])
self.register_buffer("slopes", slopes, persistent=False)
def forward(self, x):
B, T, D = x.shape
H, hd = self.heads, self.head_dim
q = self.q(x).view(B, T, H, hd).transpose(1, 2)
k = self.k(x).view(B, T, H, hd).transpose(1, 2)
v = self.v(x).view(B, T, H, hd).transpose(1, 2)
attn = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(hd)
pos = torch.arange(T, device=x.device)
rel = pos[:, None] - pos[None, :]
alibi = -self.slopes[:, None, None] * rel[None, :, :].to(attn.dtype)
invalid = (rel < 0) | (rel >= self.window)
attn = attn + alibi
attn = attn.masked_fill(invalid[None, :, :], torch.finfo(attn.dtype).min)
attn = F.softmax(attn, dim=-1)
out = torch.matmul(attn, v)
out = out.transpose(1, 2).reshape(B, T, H * hd)
return self.o(out)
class Block(nn.Module):
def __init__(self, dim, attn_rank, ffn_hidden, heads, window):
super().__init__()
self.norm1 = RMSNorm(dim)
self.attn = ALiBiAttn(dim, attn_rank, heads, window)
self.norm2 = RMSNorm(dim)
self.ffn = SwiGLU(dim, ffn_hidden)
def forward(self, x):
x = x + self.attn(self.norm1(x))
x = x + self.ffn(self.norm2(x))
return x
class Aurora80K(nn.Module):
def __init__(self, clusters=64, subs=64, dim=64, depth=2,
attn_rank=48, ffn_hidden=122, heads=4, window=256):
super().__init__()
self.n_sub = subs
self.dim = dim
self.cluster_emb = nn.Embedding(clusters, dim)
self.sub_emb = nn.Embedding(subs, dim)
self.cluster_prior = nn.Parameter(torch.zeros(clusters))
self.blocks = nn.ModuleList([
Block(dim, attn_rank, ffn_hidden, heads, window)
for _ in range(depth)
])
self.final_norm = RMSNorm(dim)
def embed_ids(self, ids):
c = ids // self.n_sub
s = ids % self.n_sub
x = self.cluster_emb(c) + self.sub_emb(s)
return x * math.sqrt(self.dim / 2.0)
def forward(self, ids, targets=None, pred_clusters=None):
x = self.embed_ids(ids)
for block in self.blocks:
x = block(x)
h = self.final_norm(x)
cluster_logits = F.linear(h, self.cluster_emb.weight) + self.cluster_prior
if targets is None:
if pred_clusters is not None:
cond_h = h + self.cluster_emb(pred_clusters)
sub_logits = F.linear(cond_h, self.sub_emb.weight)
return cluster_logits, sub_logits, h
return cluster_logits, None, h
tc = targets // self.n_sub
ts = targets % self.n_sub
cluster_logp = F.log_softmax(cluster_logits, dim=-1)
cond_h = h + self.cluster_emb(tc)
sub_logits = F.linear(cond_h, self.sub_emb.weight)
sub_logp = F.log_softmax(sub_logits, dim=-1)
nll = (
-cluster_logp.gather(-1, tc.unsqueeze(-1)).squeeze(-1)
- sub_logp.gather(-1, ts.unsqueeze(-1)).squeeze(-1)
)
return nll.mean()
def pick(logits, temp=0.8, topk=40):
if temp <= 0:
return logits.argmax(dim=-1).item()
logits = logits / temp
if topk > 0:
vals, _ = torch.topk(logits, min(topk, logits.size(-1)))
logits[logits < vals[..., -1, None]] = float("-inf")
probs = F.softmax(logits, dim=-1)
return torch.multinomial(probs, 1).item()
def run(prompt, max_new=256, temp=0.8, topk=40):
tok_path = BASE_DIR / "tokenizer.json"
pt_path = BASE_DIR / "Aurora-80K.pt"
tok = Tokenizer.from_file(str(tok_path))
model = Aurora80K()
model.load_state_dict(torch.load(str(pt_path), map_location="cpu", weights_only=True))
model.eval()
ids = tok.encode(prompt).ids if prompt.strip() else [tok.token_to_id("<bos>")]
eos = tok.token_to_id("<eos>")
print(prompt, end="", flush=True)
prev_text = prompt
for _ in range(max_new):
ctx = torch.tensor([ids[-512:]])
with torch.no_grad():
cl, _, h = model(ctx)
cid = pick(cl[0, -1], temp, topk)
sub_h = h[0, -1] + model.cluster_emb(torch.tensor(cid))
sl = F.linear(sub_h, model.sub_emb.weight)
sid = pick(sl, temp, topk)
tid = cid * 64 + sid
ids.append(tid)
curr_text = tok.decode(ids)
new_chars = curr_text[len(prev_text):]
print(new_chars, end="", flush=True)
prev_text = curr_text
if tid == eos:
break
print()
if __name__ == "__main__":
torch.set_num_threads(4)
p = argparse.ArgumentParser()
p.add_argument("--Prompt", type=str, default="The sun is")
p.add_argument("--max-new", type=int, default=200)
p.add_argument("--temp", type=float, default=0.8)
p.add_argument("--top-k", type=int, default=40)
a = p.parse_args()
run(a.Prompt, a.max_new, a.temp, a.top_k)