teszenofficial commited on
Commit
dcfcfc0
Β·
verified Β·
1 Parent(s): 838fe25

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -195
app.py CHANGED
@@ -1,202 +1,128 @@
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()
 
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()