teszenofficial commited on
Commit
76f3d48
·
verified ·
1 Parent(s): e6b1b5c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +202 -0
app.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pickle
3
+ import torch
4
+ import numpy as np
5
+ from huggingface_hub import hf_hub_download
6
+
7
+ # === CLASES DEL MODELO ===
8
+
9
+ class Head(torch.nn.Module):
10
+ def __init__(self, head_size, n_embd, block_size):
11
+ super().__init__()
12
+ self.key = torch.nn.Linear(n_embd, head_size, bias=False)
13
+ self.query = torch.nn.Linear(n_embd, head_size, bias=False)
14
+ self.value = torch.nn.Linear(n_embd, head_size, bias=False)
15
+ self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
16
+
17
+ def forward(self, x):
18
+ B, T, C = x.shape
19
+ k = self.key(x)
20
+ q = self.query(x)
21
+ wei = q @ k.transpose(-2, -1) * k.shape[-1]**-0.5
22
+ wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf'))
23
+ wei = torch.softmax(wei, dim=-1)
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
+ def forward(self, x):
49
+ return self.net(x)
50
+
51
+ class Block(torch.nn.Module):
52
+ def __init__(self, n_embd, n_head, block_size):
53
+ super().__init__()
54
+ head_size = n_embd // n_head
55
+ self.sa = MultiHeadAttention(n_head, head_size, n_embd, block_size)
56
+ self.ffwd = FeedFoward(n_embd)
57
+ self.ln1 = torch.nn.LayerNorm(n_embd)
58
+ self.ln2 = torch.nn.LayerNorm(n_embd)
59
+
60
+ def forward(self, x):
61
+ x = x + self.sa(self.ln1(x))
62
+ x = x + self.ffwd(self.ln2(x))
63
+ return x
64
+
65
+ class MTP(torch.nn.Module):
66
+ def __init__(self, vocab_size, n_embd, n_head, n_layer, block_size):
67
+ super().__init__()
68
+ self.token_embedding_table = torch.nn.Embedding(vocab_size, n_embd)
69
+ self.position_embedding_table = torch.nn.Embedding(block_size, n_embd)
70
+ self.blocks = torch.nn.Sequential(*[Block(n_embd, n_head, block_size) for _ in range(n_layer)])
71
+ self.ln_f = torch.nn.LayerNorm(n_embd)
72
+ self.lm_head = torch.nn.Linear(n_embd, vocab_size)
73
+ self.block_size = block_size
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
+ # === LAYOUT ===
193
+
194
+ with gr.Blocks(title="MTP AI") as demo:
195
+ with gr.Sidebar():
196
+ gr.Markdown("## 🤖 MTP AI\nMini modelo de lenguaje entrenado en español.")
197
+ chatbot.render()
198
+
199
+ # === EJECUTAR ===
200
+
201
+ if __name__ == "__main__":
202
+ demo.launch()