Update app.py
Browse files
app.py
CHANGED
|
@@ -1,202 +1,128 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
import torch
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
v = self.value(x)
|
| 25 |
-
out = wei @ v
|
| 26 |
-
return out
|
| 27 |
-
|
| 28 |
-
class MultiHeadAttention(torch.nn.Module):
|
| 29 |
-
def __init__(self, num_heads, head_size, n_embd, block_size):
|
| 30 |
-
super().__init__()
|
| 31 |
-
self.heads = torch.nn.ModuleList([Head(head_size, n_embd, block_size) for _ in range(num_heads)])
|
| 32 |
-
self.proj = torch.nn.Linear(n_embd, n_embd)
|
| 33 |
-
|
| 34 |
-
def forward(self, x):
|
| 35 |
-
out = torch.cat([h(x) for h in self.heads], dim=-1)
|
| 36 |
-
out = self.proj(out)
|
| 37 |
-
return out
|
| 38 |
-
|
| 39 |
-
class FeedFoward(torch.nn.Module):
|
| 40 |
-
def __init__(self, n_embd):
|
| 41 |
-
super().__init__()
|
| 42 |
-
self.net = torch.nn.Sequential(
|
| 43 |
-
torch.nn.Linear(n_embd, 4 * n_embd),
|
| 44 |
-
torch.nn.ReLU(),
|
| 45 |
-
torch.nn.Linear(4 * n_embd, n_embd),
|
| 46 |
-
)
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
def forward(self, idx, targets=None):
|
| 76 |
-
B, T = idx.shape
|
| 77 |
-
if T == 0:
|
| 78 |
-
logits = torch.zeros(B, 0, self.lm_head.out_features, device=idx.device)
|
| 79 |
-
if targets is not None:
|
| 80 |
-
return logits, torch.tensor(0.0, device=idx.device, requires_grad=False)
|
| 81 |
-
return logits
|
| 82 |
-
|
| 83 |
-
tok_emb = self.token_embedding_table(idx) # [B, T, C]
|
| 84 |
-
pos_emb = self.position_embedding_table(torch.arange(T, device=idx.device)) # [T, C]
|
| 85 |
-
pos_emb = pos_emb.unsqueeze(0) # [1, T, C] β broadcasting seguro
|
| 86 |
-
x = tok_emb + pos_emb
|
| 87 |
-
x = self.blocks(x)
|
| 88 |
-
x = self.ln_f(x)
|
| 89 |
-
logits = self.lm_head(x)
|
| 90 |
-
if targets is not None:
|
| 91 |
-
loss = torch.nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
|
| 92 |
-
return logits, loss
|
| 93 |
-
else:
|
| 94 |
-
return logits
|
| 95 |
-
|
| 96 |
-
# === FUNCIONES DE AYUDA ===
|
| 97 |
-
|
| 98 |
-
def encode(s, stoi):
|
| 99 |
-
return [stoi[c] for c in s if c in stoi]
|
| 100 |
-
|
| 101 |
-
def decode(l, itos):
|
| 102 |
-
return ''.join([itos[i] for i in l])
|
| 103 |
-
|
| 104 |
-
# === GENERACIΓN INTELIGENTE DE TEXTO ===
|
| 105 |
-
|
| 106 |
-
def generate_text(model, start_str, stoi, itos, block_size, max_new_tokens=100, temperature=1.0):
|
| 107 |
-
encoded = encode(start_str, stoi)
|
| 108 |
-
if not encoded:
|
| 109 |
-
# Si no hay tokens vΓ‘lidos, usa el primer token del vocabulario (seguro)
|
| 110 |
-
encoded = [0]
|
| 111 |
-
idx = torch.tensor(encoded, dtype=torch.long).unsqueeze(0) # [1, T]
|
| 112 |
-
model.eval()
|
| 113 |
-
|
| 114 |
-
# Caracteres que indican final natural de una oraciΓ³n
|
| 115 |
-
stop_chars = {'.', '!', '?', '\n'}
|
| 116 |
-
|
| 117 |
-
with torch.no_grad():
|
| 118 |
-
for step in range(max_new_tokens):
|
| 119 |
-
# Asegurar no sobrepasar el block_size
|
| 120 |
-
idx_cond = idx[:, -block_size:]
|
| 121 |
-
logits = model(idx_cond)
|
| 122 |
-
logits = logits[:, -1, :] / temperature
|
| 123 |
-
probs = torch.softmax(logits, dim=-1)
|
| 124 |
-
idx_next = torch.multinomial(probs, num_samples=1)
|
| 125 |
-
idx = torch.cat((idx, idx_next), dim=1)
|
| 126 |
-
|
| 127 |
-
# Decodificar el ΓΊltimo token generado
|
| 128 |
-
next_char = itos[idx_next.item()]
|
| 129 |
-
|
| 130 |
-
# Detener si ya generamos una respuesta completa (mΓnimo 4 tokens nuevos)
|
| 131 |
-
generated_so_far = idx.size(1) - len(encoded)
|
| 132 |
-
if generated_so_far >= 4 and next_char in stop_chars:
|
| 133 |
-
break
|
| 134 |
-
|
| 135 |
-
return decode(idx[0].tolist(), itos)
|
| 136 |
-
|
| 137 |
-
# === CARGAR MODELO DESDE HUGGING FACE ===
|
| 138 |
-
|
| 139 |
-
def load_model_from_hub(repo_id, filename):
|
| 140 |
-
local_path = hf_hub_download(repo_id=repo_id, filename=filename)
|
| 141 |
-
with open(local_path, 'rb') as f:
|
| 142 |
-
data = pickle.load(f)
|
| 143 |
-
model_state = data['model_state_dict']
|
| 144 |
-
stoi = data['stoi']
|
| 145 |
-
itos = data['itos']
|
| 146 |
-
vocab_size = data['vocab_size']
|
| 147 |
-
block_size = data['block_size']
|
| 148 |
-
|
| 149 |
-
model = MTP(vocab_size, n_embd=128, n_head=4, n_layer=4, block_size=block_size)
|
| 150 |
-
model.load_state_dict(model_state)
|
| 151 |
-
model.eval()
|
| 152 |
-
return model, stoi, itos, block_size
|
| 153 |
-
|
| 154 |
-
# === CARGAR EL MODELO ===
|
| 155 |
-
|
| 156 |
-
model, stoi, itos, block_size = load_model_from_hub("teszenofficial/mtptz", "model.pkl")
|
| 157 |
-
|
| 158 |
-
# === FUNCIΓN DE RESPUESTA PARA GRADIO ===
|
| 159 |
-
|
| 160 |
-
def respond(
|
| 161 |
-
message,
|
| 162 |
-
history,
|
| 163 |
-
system_message,
|
| 164 |
-
max_tokens,
|
| 165 |
-
temperature,
|
| 166 |
-
top_p, # No usado actualmente, pero mantenido para la interfaz
|
| 167 |
-
):
|
| 168 |
-
response = generate_text(
|
| 169 |
-
model=model,
|
| 170 |
-
start_str=message,
|
| 171 |
-
stoi=stoi,
|
| 172 |
-
itos=itos,
|
| 173 |
-
block_size=block_size,
|
| 174 |
-
max_new_tokens=int(max_tokens),
|
| 175 |
-
temperature=float(temperature)
|
| 176 |
-
)
|
| 177 |
-
yield response
|
| 178 |
-
|
| 179 |
-
# === INTERFAZ DE CHAT ===
|
| 180 |
-
|
| 181 |
-
chatbot = gr.ChatInterface(
|
| 182 |
-
respond,
|
| 183 |
-
type="messages",
|
| 184 |
-
additional_inputs=[
|
| 185 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
| 186 |
-
gr.Slider(minimum=1, maximum=200, value=100, step=1, label="Max new tokens"),
|
| 187 |
-
gr.Slider(minimum=0.1, maximum=2.0, value=1.0, step=0.1, label="Temperature"),
|
| 188 |
-
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
|
| 189 |
-
],
|
| 190 |
)
|
| 191 |
|
| 192 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
gr.Markdown("## π€ MTP AI\nMini modelo de lenguaje entrenado en espaΓ±ol.")
|
| 197 |
-
chatbot.render()
|
| 198 |
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
-
|
| 202 |
-
demo.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
import torch
|
| 4 |
+
import pickle
|
| 5 |
+
import gradio as gr
|
| 6 |
+
from huggingface_hub import snapshot_download
|
| 7 |
+
|
| 8 |
+
# ======================================================
|
| 9 |
+
# CONFIGURACIΓN GENERAL
|
| 10 |
+
# ======================================================
|
| 11 |
+
MODEL_REPO = "teszenofficial/mtptz"
|
| 12 |
+
APP_TITLE = "π€ MTP"
|
| 13 |
+
APP_SUBTITLE = "MTP-1 Β· Modelo de Lenguaje Experimental"
|
| 14 |
+
|
| 15 |
+
# ======================================================
|
| 16 |
+
# DESCARGAR REPO DEL MODELO
|
| 17 |
+
# ======================================================
|
| 18 |
+
repo_path = snapshot_download(
|
| 19 |
+
repo_id=MODEL_REPO,
|
| 20 |
+
repo_type="model",
|
| 21 |
+
local_dir="model_repo",
|
| 22 |
+
local_dir_use_symlinks=False
|
| 23 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
sys.path.append(repo_path)
|
| 26 |
+
|
| 27 |
+
# ======================================================
|
| 28 |
+
# IMPORTAR MODELO Y TOKENIZER
|
| 29 |
+
# ======================================================
|
| 30 |
+
from model import MTPMiniModel
|
| 31 |
+
from tokenizer import MTPTokenizer
|
| 32 |
+
|
| 33 |
+
# ======================================================
|
| 34 |
+
# CARGAR MODELO
|
| 35 |
+
# ======================================================
|
| 36 |
+
MODEL_PATH = os.path.join(repo_path, "mtp_mini.pkl")
|
| 37 |
+
|
| 38 |
+
with open(MODEL_PATH, "rb") as f:
|
| 39 |
+
model_data = pickle.load(f)
|
| 40 |
+
|
| 41 |
+
tokenizer = MTPTokenizer(model_data["tokenizer_path"])
|
| 42 |
+
config = model_data["config"]
|
| 43 |
+
|
| 44 |
+
model = MTPMiniModel(
|
| 45 |
+
vocab_size=model_data["vocab_size"],
|
| 46 |
+
d_model=config["model"]["d_model"],
|
| 47 |
+
n_layers=config["model"]["n_layers"],
|
| 48 |
+
n_heads=config["model"]["n_heads"],
|
| 49 |
+
d_ff=config["model"]["d_ff"],
|
| 50 |
+
max_seq_len=config["model"]["max_seq_len"],
|
| 51 |
+
dropout=0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
)
|
| 53 |
|
| 54 |
+
model.load_state_dict(model_data["model_state_dict"])
|
| 55 |
+
model.eval()
|
| 56 |
+
|
| 57 |
+
# ======================================================
|
| 58 |
+
# FUNCIΓN DE CHAT
|
| 59 |
+
# ======================================================
|
| 60 |
+
def generate_response(message, history, temperature, max_tokens):
|
| 61 |
+
prompt = f"### InstrucciΓ³n:\n{message}\n\n### Respuesta:\n"
|
| 62 |
+
ids = [tokenizer.bos_id()] + tokenizer.encode(prompt)
|
| 63 |
+
input_ids = torch.tensor([ids], dtype=torch.long)
|
| 64 |
+
|
| 65 |
+
with torch.no_grad():
|
| 66 |
+
output = model.generate(
|
| 67 |
+
input_ids,
|
| 68 |
+
max_new_tokens=max_tokens,
|
| 69 |
+
temperature=temperature,
|
| 70 |
+
top_k=50,
|
| 71 |
+
top_p=0.9
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
generated = output[0, len(ids):].tolist()
|
| 75 |
|
| 76 |
+
if tokenizer.eos_id() in generated:
|
| 77 |
+
generated = generated[:generated.index(tokenizer.eos_id())]
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
response = tokenizer.decode(generated).strip()
|
| 80 |
+
history = history + [(message, response)]
|
| 81 |
+
return history, history
|
| 82 |
+
|
| 83 |
+
# ======================================================
|
| 84 |
+
# INTERFAZ GRADIO (ESTILO CHATGPT)
|
| 85 |
+
# ======================================================
|
| 86 |
+
with gr.Blocks(css="""
|
| 87 |
+
footer {visibility: hidden;}
|
| 88 |
+
""") as demo:
|
| 89 |
+
|
| 90 |
+
gr.Markdown(f"# {APP_TITLE}")
|
| 91 |
+
gr.Markdown(APP_SUBTITLE)
|
| 92 |
+
|
| 93 |
+
chatbot = gr.Chatbot(label="MTP")
|
| 94 |
+
state = gr.State([])
|
| 95 |
+
|
| 96 |
+
with gr.Row():
|
| 97 |
+
textbox = gr.Textbox(
|
| 98 |
+
placeholder="Escribe un mensaje...",
|
| 99 |
+
show_label=False
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
with gr.Row():
|
| 103 |
+
temperature = gr.Slider(
|
| 104 |
+
minimum=0.1,
|
| 105 |
+
maximum=2.0,
|
| 106 |
+
value=0.8,
|
| 107 |
+
step=0.1,
|
| 108 |
+
label="Temperature"
|
| 109 |
+
)
|
| 110 |
+
max_tokens = gr.Slider(
|
| 111 |
+
minimum=20,
|
| 112 |
+
maximum=200,
|
| 113 |
+
value=120,
|
| 114 |
+
step=10,
|
| 115 |
+
label="Max tokens"
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
textbox.submit(
|
| 119 |
+
generate_response,
|
| 120 |
+
inputs=[textbox, state, temperature, max_tokens],
|
| 121 |
+
outputs=[chatbot, state]
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
gr.Markdown(
|
| 125 |
+
"β οΈ **MTP puede cometer errores. Verifica la informaciΓ³n importante.**"
|
| 126 |
+
)
|
| 127 |
|
| 128 |
+
demo.launch()
|
|
|