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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pickle
|
| 3 |
+
import torch
|
| 4 |
+
from huggingface_hub import hf_hub_download
|
| 5 |
+
|
| 6 |
+
# === CLASES DEL MODELO ===
|
| 7 |
+
|
| 8 |
+
class Head(torch.nn.Module):
|
| 9 |
+
def __init__(self, head_size, n_embd, block_size):
|
| 10 |
+
super().__init__()
|
| 11 |
+
self.key = torch.nn.Linear(n_embd, head_size, bias=False)
|
| 12 |
+
self.query = torch.nn.Linear(n_embd, head_size, bias=False)
|
| 13 |
+
self.value = torch.nn.Linear(n_embd, head_size, bias=False)
|
| 14 |
+
self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
|
| 15 |
+
|
| 16 |
+
def forward(self, x):
|
| 17 |
+
B, T, C = x.shape
|
| 18 |
+
k = self.key(x)
|
| 19 |
+
q = self.query(x)
|
| 20 |
+
wei = q @ k.transpose(-2, -1) * k.shape[-1]**-0.5
|
| 21 |
+
wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf'))
|
| 22 |
+
wei = torch.softmax(wei, dim=-1)
|
| 23 |
+
v = self.value(x)
|
| 24 |
+
out = wei @ v
|
| 25 |
+
return out
|
| 26 |
+
|
| 27 |
+
class MultiHeadAttention(torch.nn.Module):
|
| 28 |
+
def __init__(self, num_heads, head_size, n_embd, block_size):
|
| 29 |
+
super().__init__()
|
| 30 |
+
self.heads = torch.nn.ModuleList([Head(head_size, n_embd, block_size) for _ in range(num_heads)])
|
| 31 |
+
self.proj = torch.nn.Linear(n_embd, n_embd)
|
| 32 |
+
self.dropout = torch.nn.Dropout(0.1)
|
| 33 |
+
|
| 34 |
+
def forward(self, x):
|
| 35 |
+
out = torch.cat([h(x) for h in self.heads], dim=-1)
|
| 36 |
+
out = self.dropout(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.GELU(),
|
| 45 |
+
torch.nn.Dropout(0.1),
|
| 46 |
+
torch.nn.Linear(4 * n_embd, n_embd),
|
| 47 |
+
torch.nn.Dropout(0.1),
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
def forward(self, x):
|
| 51 |
+
return self.net(x)
|
| 52 |
+
|
| 53 |
+
class Block(torch.nn.Module):
|
| 54 |
+
def __init__(self, n_embd, n_head, block_size):
|
| 55 |
+
super().__init__()
|
| 56 |
+
head_size = n_embd // n_head
|
| 57 |
+
self.sa = MultiHeadAttention(n_head, head_size, n_embd, block_size)
|
| 58 |
+
self.ffwd = FeedFoward(n_embd)
|
| 59 |
+
self.ln1 = torch.nn.LayerNorm(n_embd)
|
| 60 |
+
self.ln2 = torch.nn.LayerNorm(n_embd)
|
| 61 |
+
|
| 62 |
+
def forward(self, x):
|
| 63 |
+
x = x + self.sa(self.ln1(x))
|
| 64 |
+
x = x + self.ffwd(self.ln2(x))
|
| 65 |
+
return x
|
| 66 |
+
|
| 67 |
+
class MTP(torch.nn.Module):
|
| 68 |
+
def __init__(self, vocab_size, n_embd, n_head, n_layer, block_size):
|
| 69 |
+
super().__init__()
|
| 70 |
+
self.token_embedding_table = torch.nn.Embedding(vocab_size, n_embd)
|
| 71 |
+
self.position_embedding_table = torch.nn.Embedding(block_size, n_embd)
|
| 72 |
+
self.blocks = torch.nn.Sequential(*[Block(n_embd, n_head, block_size) for _ in range(n_layer)])
|
| 73 |
+
self.ln_f = torch.nn.LayerNorm(n_embd)
|
| 74 |
+
self.lm_head = torch.nn.Linear(n_embd, vocab_size)
|
| 75 |
+
self.dropout = torch.nn.Dropout(0.1)
|
| 76 |
+
|
| 77 |
+
def forward(self, idx, targets=None):
|
| 78 |
+
B, T = idx.shape
|
| 79 |
+
tok_emb = self.token_embedding_table(idx)
|
| 80 |
+
pos_emb = self.position_embedding_table(torch.arange(T, device=idx.device))
|
| 81 |
+
x = self.dropout(tok_emb + pos_emb)
|
| 82 |
+
x = self.blocks(x)
|
| 83 |
+
x = self.ln_f(x)
|
| 84 |
+
logits = self.lm_head(x)
|
| 85 |
+
if targets is not None:
|
| 86 |
+
loss = torch.nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
|
| 87 |
+
return logits, loss
|
| 88 |
+
else:
|
| 89 |
+
return logits
|
| 90 |
+
|
| 91 |
+
# === FUNCIONES DE AYUDA ===
|
| 92 |
+
|
| 93 |
+
def encode(s, stoi):
|
| 94 |
+
return [stoi[c] for c in s if c in stoi]
|
| 95 |
+
|
| 96 |
+
def decode(l, itos):
|
| 97 |
+
return ''.join([itos[i] for i in l])
|
| 98 |
+
|
| 99 |
+
# === GENERACIΓN DE TEXTO ===
|
| 100 |
+
|
| 101 |
+
def generate_text(model, start_str, stoi, itos, block_size, max_new_tokens=500, temperature=1.0, top_p=0.9):
|
| 102 |
+
encoded = encode(start_str, stoi)
|
| 103 |
+
if not encoded:
|
| 104 |
+
return "No se pudo procesar la entrada: caracteres desconocidos."
|
| 105 |
+
idx = torch.tensor(encoded, dtype=torch.long).unsqueeze(0)
|
| 106 |
+
if idx.size(1) == 0:
|
| 107 |
+
return "No se pudo procesar la entrada: caracteres desconocidos."
|
| 108 |
+
model.eval()
|
| 109 |
+
with torch.no_grad():
|
| 110 |
+
generated = idx
|
| 111 |
+
for _ in range(max_new_tokens):
|
| 112 |
+
idx_cond = generated[:, -block_size:]
|
| 113 |
+
if idx_cond.size(1) == 0:
|
| 114 |
+
break
|
| 115 |
+
logits = model(idx_cond)
|
| 116 |
+
logits = logits[:, -1, :] / temperature
|
| 117 |
+
probs = torch.softmax(logits, dim=-1)
|
| 118 |
+
|
| 119 |
+
# NΓΊcleo de muestreo (top_p)
|
| 120 |
+
sorted_probs, sorted_indices = torch.sort(probs, descending=True)
|
| 121 |
+
cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
|
| 122 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 123 |
+
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
| 124 |
+
sorted_indices_to_remove[..., 0] = 0
|
| 125 |
+
indices_to_remove = sorted_indices[sorted_indices_to_remove]
|
| 126 |
+
probs.scatter_(1, indices_to_remove, 0)
|
| 127 |
+
probs = probs / probs.sum()
|
| 128 |
+
|
| 129 |
+
idx_next = torch.multinomial(probs, num_samples=1)
|
| 130 |
+
generated = torch.cat((generated, idx_next), dim=1)
|
| 131 |
+
return decode(generated[0].tolist(), itos)
|
| 132 |
+
|
| 133 |
+
# === CARGAR MODELO DESDE HUGGING FACE ===
|
| 134 |
+
|
| 135 |
+
def load_model_from_hub(repo_id, filename):
|
| 136 |
+
local_path = hf_hub_download(repo_id=repo_id, filename=filename)
|
| 137 |
+
with open(local_path, 'rb') as f:
|
| 138 |
+
data = pickle.load(f)
|
| 139 |
+
|
| 140 |
+
model_state = data['model_state_dict']
|
| 141 |
+
stoi = data['stoi']
|
| 142 |
+
itos = data['itos']
|
| 143 |
+
vocab_size = data['vocab_size']
|
| 144 |
+
block_size = data['block_size']
|
| 145 |
+
|
| 146 |
+
# Recrear el modelo con los mismos parΓ‘metros
|
| 147 |
+
model = MTP(vocab_size, n_embd=256, n_head=8, n_layer=6, block_size=block_size)
|
| 148 |
+
model.load_state_dict(model_state)
|
| 149 |
+
model.eval()
|
| 150 |
+
|
| 151 |
+
return model, stoi, itos, block_size
|
| 152 |
+
|
| 153 |
+
# === CARGAR EL MODELO ===
|
| 154 |
+
|
| 155 |
+
model, stoi, itos, block_size = load_model_from_hub("teszenofficial/mtptz", "MTP.pkl")
|
| 156 |
+
|
| 157 |
+
def respond(
|
| 158 |
+
message,
|
| 159 |
+
history: list[dict[str, str]],
|
| 160 |
+
system_message,
|
| 161 |
+
max_tokens,
|
| 162 |
+
temperature,
|
| 163 |
+
top_p,
|
| 164 |
+
):
|
| 165 |
+
try:
|
| 166 |
+
response = generate_text(model, message, stoi, itos, block_size, max_new_tokens=max_tokens, temperature=temperature, top_p=top_p)
|
| 167 |
+
response = response[:5000]
|
| 168 |
+
yield response
|
| 169 |
+
except Exception as e:
|
| 170 |
+
yield f"Error: {str(e)}"
|
| 171 |
+
|
| 172 |
+
# === INTERFAZ DE CHAT ===
|
| 173 |
+
|
| 174 |
+
chatbot = gr.ChatInterface(
|
| 175 |
+
respond,
|
| 176 |
+
type="messages",
|
| 177 |
+
additional_inputs=[
|
| 178 |
+
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
| 179 |
+
gr.Slider(minimum=1, maximum=5000, value=500, step=10, label="Max new tokens"),
|
| 180 |
+
gr.Slider(minimum=0.1, maximum=2.0, value=1.2, step=0.1, label="Temperature"),
|
| 181 |
+
gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="Top-p (nucleus sampling)"),
|
| 182 |
+
],
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
with gr.Blocks() as demo:
|
| 186 |
+
with gr.Sidebar():
|
| 187 |
+
gr.Markdown("## MTP Chat v3")
|
| 188 |
+
chatbot.render()
|
| 189 |
+
|
| 190 |
+
if __name__ == "__main__":
|
| 191 |
+
demo.launch()
|