Tived / app.py
DAINOO's picture
Update app.py
35c52b0 verified
Raw History Blame Contribute Delete
4.95 kB
import gradio as gr
import torch
import math
from transformers import GPT2TokenizerFast
from huggingface_hub import hf_hub_download
class TivedConfig:
vocab_size = 50257
block_size = 512
n_embd = 384
n_head = 8
n_layer = 8
dropout = 0.1
config = TivedConfig()
class TivedAttention(torch.nn.Module):
def __init__(self, config):
super().__init__()
self.n_head = config.n_head
self.n_embd = config.n_embd
self.attn = torch.nn.Linear(config.n_embd, 3 * config.n_embd)
self.proj = torch.nn.Linear(config.n_embd, config.n_embd)
self.dropout = torch.nn.Dropout(config.dropout)
self.register_buffer("mask", torch.tril(torch.ones(config.block_size, config.block_size)))
def forward(self, x):
B, T, C = x.shape
q, k, v = self.attn(x).split(self.n_embd, dim=2)
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
att = att.masked_fill(self.mask[:T, :T] == 0, float('-inf'))
att = torch.softmax(att, dim=-1)
att = self.dropout(att)
y = att @ v
y = y.transpose(1, 2).contiguous().view(B, T, C)
return self.proj(y)
class TivedBlock(torch.nn.Module):
def __init__(self, config):
super().__init__()
self.ln1 = torch.nn.LayerNorm(config.n_embd)
self.attn = TivedAttention(config)
self.ln2 = torch.nn.LayerNorm(config.n_embd)
self.ff = torch.nn.Sequential(
torch.nn.Linear(config.n_embd, 4 * config.n_embd),
torch.nn.GELU(),
torch.nn.Linear(4 * config.n_embd, config.n_embd),
torch.nn.Dropout(config.dropout)
)
def forward(self, x):
x = x + self.attn(self.ln1(x))
x = x + self.ff(self.ln2(x))
return x
class Tived(torch.nn.Module):
def __init__(self, config):
super().__init__()
self.tok_emb = torch.nn.Embedding(config.vocab_size, config.n_embd)
self.pos_emb = torch.nn.Embedding(config.block_size, config.n_embd)
self.drop = torch.nn.Dropout(config.dropout)
self.blocks = torch.nn.Sequential(*[TivedBlock(config) for _ in range(config.n_layer)])
self.ln = torch.nn.LayerNorm(config.n_embd)
self.head = torch.nn.Linear(config.n_embd, config.vocab_size, bias=False)
def forward(self, idx, targets=None):
B, T = idx.shape
pos = torch.arange(T, device=idx.device)
x = self.drop(self.tok_emb(idx) + self.pos_emb(pos))
x = self.blocks(x)
x = self.ln(x)
logits = self.head(x)
loss = None
if targets is not None:
loss = torch.nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
return logits, loss
def generate(self, idx, max_new_tokens, temperature=0.8):
for _ in range(max_new_tokens):
idx_cond = idx[:, -config.block_size:]
logits, _ = self(idx_cond)
logits = logits[:, -1, :] / temperature
probs = torch.softmax(logits, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
idx = torch.cat([idx, next_token], dim=1)
return idx
print("Cargando Tived v2...")
tokenizer = GPT2TokenizerFast.from_pretrained("gpt2")
model = Tived(config)
model_path = hf_hub_download(repo_id="DAINOO/Tived", filename="tived_v2.pt")
state_dict = torch.load(model_path, map_location="cpu")
new_state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()}
model.load_state_dict(new_state_dict)
model.eval()
print("Tived v2 listo ✅")
def generar(prompt, temperature=0.8, max_tokens=150):
if not prompt.strip():
return "Dame un prompt 💀"
tokens = tokenizer.encode(prompt)
idx = torch.tensor([tokens], dtype=torch.long)
with torch.no_grad():
output = model.generate(idx, max_new_tokens=int(max_tokens), temperature=float(temperature))
return tokenizer.decode(output[0].tolist()[len(tokens):])
demo = gr.Interface(
fn=generar,
inputs=[
gr.Textbox(label="Prompt", placeholder="what if gravity worked backwards on..."),
gr.Slider(0.1, 1.5, value=0.8, step=0.1, label="Temperature"),
gr.Slider(50, 300, value=150, step=10, label="Max tokens")
],
outputs=gr.Textbox(label="Tived responde"),
title="Tived v2 — CAICD Creative AI",
description="Modelo de lenguaje creativo de 53M parámetros entrenado desde cero en 50k historias de WritingPrompts. Proyecto CAICD.",
examples=[
["what if gravity worked backwards on", 0.8, 150],
["the world ended and nobody noticed because", 0.9, 150],
["a dragon walks into a library and", 0.8, 200],
]
)
demo.launch()