TeszenAI2 commited on
Commit
f5d73c6
·
verified ·
1 Parent(s): a71bfcc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +593 -0
app.py ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ================================================================
2
+ # MTP-2.5 - app.py para Hugging Face Space (Gradio, CPU)
3
+ # Generacion 2: RoPE + SwiGLU (reemplaza position embeddings aprendidos y el
4
+ # GELU-MLP de MTP-1.x). Requiere un checkpoint entrenado con la Celda 1/2 de
5
+ # MTP-2.5; NO carga checkpoints de MTP-2.0 (RMSNorm cambia el state_dict) ni de MTP-1.x.
6
+ #
7
+ # OPTIMIZACIÓN DE VELOCIDAD (sin tocar el resto de la logica de muestreo):
8
+ # - KV-cache en la atención: en generación autoregresiva, cada paso
9
+ # antes recomputaba TODO el contexto desde cero (O(n^2) en total).
10
+ # Ahora se reutiliza lo ya calculado y solo se procesa el token
11
+ # nuevo (O(n) en total). Es el mismo cálculo matemático, solo que
12
+ # no se repite trabajo ya hecho.
13
+ # - F.scaled_dot_product_attention: kernel fusionado de PyTorch,
14
+ # mismo resultado que el softmax manual pero más rápido en CPU.
15
+ # Si la versión de PyTorch no lo trae, cae automáticamente al
16
+ # cálculo manual (fallback), así que no se rompe en ningún entorno.
17
+ # - repetition_penalty vectorizado + bloqueo de n-gramas repetidos
18
+ # (evita que la respuesta final copie literalmente un fragmento ya
19
+ # generado, sin que esto sea un "modelo de n-gramas": el modelo que
20
+ # predice sigue siendo 100% transformer).
21
+ # ================================================================
22
+ import os
23
+ import math
24
+ import time
25
+ import logging
26
+ import threading
27
+ import traceback
28
+ import torch
29
+ import torch.nn as nn
30
+ import torch.nn.functional as F
31
+ import gradio as gr
32
+ import sentencepiece as spm
33
+ from starlette.middleware import Middleware
34
+ from fastapi.middleware.cors import CORSMiddleware
35
+ from pydantic import BaseModel
36
+ from typing import Optional
37
+ from huggingface_hub import hf_hub_download
38
+
39
+ # ---------------- Logging ----------------
40
+ # print() se pierde facil entre el ruido de arranque de Gradio/Starlette en
41
+ # los logs de un Space; con logging queda todo con timestamp y nivel, y es
42
+ # mas facil de filtrar si algo sale mal en produccion.
43
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
44
+ logger = logging.getLogger("mtp")
45
+
46
+ # ---------------- Dispositivo ----------------
47
+ # Autodetecta GPU si el Space corre en un tier con GPU (DEVICE=cuda por
48
+ # variable de entorno tambien fuerza el valor si hace falta). Si no hay
49
+ # GPU disponible, cae a CPU como siempre.
50
+ DEVICE = os.environ.get("DEVICE") or ("cuda" if torch.cuda.is_available() else "cpu")
51
+
52
+ if DEVICE == "cpu":
53
+ # Limita hilos a los núcleos disponibles (evita overhead en Spaces pequeños).
54
+ # No tiene sentido en GPU, donde el computo no lo hace la CPU.
55
+ torch.set_num_threads(max(1, os.cpu_count() or 1))
56
+ # set_num_interop_threads solo puede llamarse una vez y antes de cualquier
57
+ # operación paralela; lo protegemos por si el entorno ya lo fijó.
58
+ try:
59
+ torch.set_num_interop_threads(1)
60
+ except RuntimeError:
61
+ pass
62
+
63
+ torch.set_grad_enabled(False) # solo inferencia, nunca necesitamos gradientes
64
+
65
+ # Disponibilidad de scaled_dot_product_attention (PyTorch >= 2.0).
66
+ # Si no está disponible, usamos el softmax manual original como fallback.
67
+ _HAS_SDPA = hasattr(F, "scaled_dot_product_attention")
68
+
69
+ REPO_ID = os.environ.get("MTP_REPO_ID", "TeszenAI/MTP-2.7") # <-- ajusta al nombre real de tu repo/Space en el Hub
70
+ FILENAME = os.environ.get("MTP_FILENAME", "MTP2_7_MODEL.pt")
71
+
72
+ # Origenes permitidos para CORS. Por defecto "*" (como antes), pero se puede
73
+ # restringir en produccion con la variable de entorno MTP_ALLOWED_ORIGINS
74
+ # (separados por coma), por ejemplo: "https://teszen.com,https://www.teszen.com"
75
+ ALLOWED_ORIGINS = [
76
+ o.strip() for o in os.environ.get("MTP_ALLOWED_ORIGINS", "*").split(",") if o.strip()
77
+ ] or ["*"]
78
+
79
+ # Techo de caracteres del input antes de tokenizar. No es por seguridad (el
80
+ # modelo igual solo "ve" los ultimos BLOCK_SIZE tokens), es para no perder
81
+ # tiempo tokenizando un texto absurdamente largo por error o abuso.
82
+ MAX_INPUT_CHARS = 4000
83
+
84
+ # Si es "1", los errores devueltos por /generate incluyen el detalle interno
85
+ # de la excepcion (util mientras desarrollas). En produccion, dejar en "0"
86
+ # para no filtrarle al cliente detalles internos del servidor.
87
+ DEBUG_ERRORS = os.environ.get("MTP_DEBUG_ERRORS", "0") == "1"
88
+
89
+ # Serializa las llamadas a generate(): sin esto, dos requests concurrentes
90
+ # (por ejemplo la UI de Gradio y el endpoint /generate al mismo tiempo, o
91
+ # varias visitas simultaneas al sitio) compiten por los mismos hilos de CPU
92
+ # y todas terminan mas lentas en vez de una rapida y la otra esperando. Con
93
+ # el lock, cada generacion corre de punta a punta antes de que empiece la
94
+ # siguiente -- mismo comportamiento de fondo que antes bajo carga baja, pero
95
+ # estable bajo carga alta en vez de degradarse.
96
+ _generation_lock = threading.Lock()
97
+
98
+ # ---------------- Arquitectura MTP-2.x: RoPE + SwiGLU, con KV-cache ----------------
99
+ def rotate_half(x):
100
+ x1, x2 = x.chunk(2, dim=-1)
101
+ return torch.cat((-x2, x1), dim=-1)
102
+
103
+ def apply_rope(q, k, cos, sin):
104
+ cos = cos.unsqueeze(0).unsqueeze(0)
105
+ sin = sin.unsqueeze(0).unsqueeze(0)
106
+ q_rot = (q * cos) + (rotate_half(q) * sin)
107
+ k_rot = (k * cos) + (rotate_half(k) * sin)
108
+ return q_rot, k_rot
109
+
110
+ class RotaryEmbedding(nn.Module):
111
+ def __init__(self, head_dim, max_seq_len, base=10000):
112
+ super().__init__()
113
+ inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))
114
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
115
+ self._build_cache(max_seq_len)
116
+
117
+ def _build_cache(self, seq_len):
118
+ t = torch.arange(seq_len, dtype=self.inv_freq.dtype, device=self.inv_freq.device)
119
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
120
+ emb = torch.cat((freqs, freqs), dim=-1)
121
+ self.register_buffer("cos_cached", emb.cos(), persistent=False)
122
+ self.register_buffer("sin_cached", emb.sin(), persistent=False)
123
+ self.max_seq_len_cached = seq_len
124
+
125
+ def forward(self, seq_len, device, dtype, offset=0):
126
+ # Con KV-cache, `offset` es cuantos tokens ya estan en la cache: el
127
+ # token nuevo necesita el angulo correspondiente a SU posicion
128
+ # absoluta, no a la posicion relativa dentro de este forward.
129
+ if offset + seq_len > self.max_seq_len_cached:
130
+ self._build_cache(offset + seq_len)
131
+ cos = self.cos_cached[offset:offset + seq_len].to(device=device, dtype=dtype)
132
+ sin = self.sin_cached[offset:offset + seq_len].to(device=device, dtype=dtype)
133
+ return cos, sin
134
+
135
+
136
+ class CausalSelfAttention(nn.Module):
137
+ def __init__(self, n_embd, n_head, block_size, dropout):
138
+ super().__init__()
139
+ self.n_head = n_head
140
+ self.head_dim = n_embd // n_head
141
+ self.qkv = nn.Linear(n_embd, 3 * n_embd)
142
+ self.proj = nn.Linear(n_embd, n_embd)
143
+ self.attn_dropout = nn.Dropout(dropout)
144
+ self.resid_dropout = nn.Dropout(dropout)
145
+ mask = torch.tril(torch.ones(block_size, block_size)).view(1, 1, block_size, block_size)
146
+ self.register_buffer("mask", mask)
147
+
148
+ def forward(self, x, cos, sin, past_kv=None, use_cache=False):
149
+ B, T, C = x.shape
150
+ qkv = self.qkv(x)
151
+ q, k, v = qkv.split(C, dim=2)
152
+ q = q.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
153
+ k = k.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
154
+ v = v.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
155
+
156
+ # RoPE se aplica ANTES de guardar en cache, con el angulo absoluto de
157
+ # cada token (pasado por `cos`/`sin`, ya calculado con el offset
158
+ # correcto en MTP.forward). Asi el k cacheado ya trae rotada su
159
+ # posicion real y no hay que re-rotar nada en pasos futuros.
160
+ q, k = apply_rope(q, k, cos, sin)
161
+
162
+ if past_kv is not None:
163
+ past_k, past_v = past_kv
164
+ k = torch.cat([past_k, k], dim=2)
165
+ v = torch.cat([past_v, v], dim=2)
166
+
167
+ present_kv = (k, v) if use_cache else None
168
+
169
+ is_causal = (past_kv is None) and (T > 1)
170
+
171
+ if _HAS_SDPA:
172
+ out = F.scaled_dot_product_attention(
173
+ q, k, v, attn_mask=None, dropout_p=0.0, is_causal=is_causal,
174
+ )
175
+ else:
176
+ att = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
177
+ if is_causal:
178
+ Tk = k.size(-2)
179
+ causal_mask = torch.tril(torch.ones(T, Tk, device=x.device, dtype=torch.bool))
180
+ att = att.masked_fill(~causal_mask, float("-inf"))
181
+ att = F.softmax(att, dim=-1)
182
+ att = self.attn_dropout(att)
183
+ out = att @ v
184
+
185
+ out = out.transpose(1, 2).contiguous().view(B, T, C)
186
+ out = self.resid_dropout(self.proj(out))
187
+ return out, present_kv
188
+
189
+
190
+ class SwiGLU(nn.Module):
191
+ def __init__(self, n_embd, dropout):
192
+ super().__init__()
193
+ hidden = int(2 * (4 * n_embd) / 3)
194
+ hidden = ((hidden + 7) // 8) * 8
195
+ self.w_gate = nn.Linear(n_embd, hidden, bias=False)
196
+ self.w_up = nn.Linear(n_embd, hidden, bias=False)
197
+ self.w_down = nn.Linear(hidden, n_embd, bias=False)
198
+ self.dropout = nn.Dropout(dropout)
199
+
200
+ def forward(self, x):
201
+ return self.dropout(self.w_down(F.silu(self.w_gate(x)) * self.w_up(x)))
202
+
203
+
204
+ class RMSNorm(nn.Module):
205
+ """Debe coincidir exactamente con la version de entrenamiento. No
206
+ necesita ningun cambio para funcionar con KV-cache: normaliza cada
207
+ posicion de forma independiente, igual que LayerNorm."""
208
+ def __init__(self, dim, eps=1e-6):
209
+ super().__init__()
210
+ self.eps = eps
211
+ self.weight = nn.Parameter(torch.ones(dim))
212
+
213
+ def forward(self, x):
214
+ norm = x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
215
+ return norm * self.weight
216
+
217
+
218
+ class Block(nn.Module):
219
+ def __init__(self, n_embd, n_head, block_size, dropout):
220
+ super().__init__()
221
+ self.ln1 = RMSNorm(n_embd)
222
+ self.attn = CausalSelfAttention(n_embd, n_head, block_size, dropout)
223
+ self.ln2 = RMSNorm(n_embd)
224
+ self.ff = SwiGLU(n_embd, dropout)
225
+
226
+ def forward(self, x, cos, sin, past_kv=None, use_cache=False):
227
+ attn_out, present_kv = self.attn(self.ln1(x), cos, sin, past_kv=past_kv, use_cache=use_cache)
228
+ x = x + attn_out
229
+ x = x + self.ff(self.ln2(x))
230
+ return x, present_kv
231
+
232
+
233
+ class MTP(nn.Module):
234
+ def __init__(self, vocab_size, block_size, n_layer, n_head, n_embd, dropout):
235
+ super().__init__()
236
+ self.block_size = block_size
237
+ self.head_dim = n_embd // n_head
238
+ self.tok_emb = nn.Embedding(vocab_size, n_embd)
239
+ self.rope = RotaryEmbedding(self.head_dim, max_seq_len=block_size)
240
+ self.drop = nn.Dropout(dropout)
241
+ self.blocks = nn.ModuleList([Block(n_embd, n_head, block_size, dropout) for _ in range(n_layer)])
242
+ self.ln_f = RMSNorm(n_embd)
243
+ self.lm_head = nn.Linear(n_embd, vocab_size, bias=False)
244
+ self.lm_head.weight = self.tok_emb.weight
245
+
246
+ def forward(self, idx, past_key_values=None, use_cache=False, pos_offset=0):
247
+ B, T = idx.shape
248
+ x = self.tok_emb(idx)
249
+ x = self.drop(x)
250
+ cos, sin = self.rope(T, idx.device, x.dtype, offset=pos_offset)
251
+
252
+ new_past = [] if use_cache else None
253
+ for i, block in enumerate(self.blocks):
254
+ past_kv = past_key_values[i] if past_key_values is not None else None
255
+ x, present_kv = block(x, cos, sin, past_kv=past_kv, use_cache=use_cache)
256
+ if use_cache:
257
+ new_past.append(present_kv)
258
+
259
+ x = self.ln_f(x)
260
+ logits = self.lm_head(x)
261
+ return logits, new_past
262
+
263
+
264
+ # ---------------- Carga del checkpoint (una sola vez, al iniciar el Space) ----------------
265
+ def _download_checkpoint_with_retries(repo_id, filename, max_retries=5):
266
+ """Reintenta la descarga con backoff. hf_hub_download puede fallar por un
267
+ corte de red momentaneo o un problema del backend Xet de HF; sin esto,
268
+ un solo fallo transitorio tira abajo el arranque completo del Space."""
269
+ last_err = None
270
+ for attempt in range(1, max_retries + 1):
271
+ try:
272
+ logger.info(f"Descargando checkpoint desde el Hub (intento {attempt}/{max_retries})...")
273
+ return hf_hub_download(repo_id=repo_id, filename=filename)
274
+ except Exception as e:
275
+ last_err = e
276
+ logger.warning(f"Fallo la descarga del checkpoint: {e}")
277
+ if attempt < max_retries:
278
+ time.sleep(5 * attempt)
279
+ raise RuntimeError(f"No se pudo descargar el checkpoint tras {max_retries} intentos") from last_err
280
+
281
+ ckpt_path = _download_checkpoint_with_retries(REPO_ID, FILENAME)
282
+ checkpoint = torch.load(ckpt_path, map_location=DEVICE)
283
+
284
+ cfg = checkpoint["config"]
285
+ special = checkpoint["special_tokens"]
286
+ gen_defaults = checkpoint["generation_defaults"]
287
+
288
+ PAD_ID, BOS_ID, EOS_ID, UNK_ID = special["pad_id"], special["bos_id"], special["eos_id"], special["unk_id"]
289
+
290
+ # El tokenizer es BPE (SentencePiece) entrenado desde cero junto con el modelo.
291
+ # No es un modelo preentrenado externo: viene embebido como bytes dentro del
292
+ # mismo checkpoint que los pesos. Se carga directo desde memoria con
293
+ # load_from_serialized_proto, sin necesidad de escribirlo a disco primero.
294
+ sp = spm.SentencePieceProcessor()
295
+ sp.load_from_serialized_proto(checkpoint["spm_model_bytes"])
296
+
297
+ model = MTP(
298
+ vocab_size=cfg["vocab_size"], block_size=cfg["block_size"],
299
+ n_layer=cfg["n_layer"], n_head=cfg["n_head"],
300
+ n_embd=cfg["n_embd"], dropout=cfg["dropout"],
301
+ ).to(DEVICE)
302
+ model.load_state_dict(checkpoint["model_state_dict"])
303
+ model.eval()
304
+
305
+ BLOCK_SIZE = cfg["block_size"]
306
+
307
+ logger.info(
308
+ f"MTP cargado ({checkpoint['meta']['model_name']}, "
309
+ f"entrenado con {checkpoint['meta']['trained_examples']} ejemplos) "
310
+ f"| device={DEVICE} | SDPA={'sí' if _HAS_SDPA else 'no (fallback manual)'}"
311
+ )
312
+
313
+
314
+ import re as _re_indent
315
+
316
+ def protect_indentation(text):
317
+ """Debe coincidir exactamente con la funcion usada en el entrenamiento."""
318
+ lines = text.split("\n")
319
+ new_lines = []
320
+ for line in lines:
321
+ stripped = line.lstrip(" ")
322
+ n_spaces = len(line) - len(stripped)
323
+ n_levels = n_spaces // 4
324
+ remainder = n_spaces % 4
325
+ if n_levels > 0:
326
+ prefix = " " + " ".join(["<tab>"] * n_levels) + " " + " " * remainder
327
+ else:
328
+ prefix = " " * remainder
329
+ new_lines.append(prefix + stripped)
330
+ text = "\n".join(new_lines)
331
+ def _repl(m):
332
+ n = len(m.group())
333
+ return " " + " ".join(["<nl>"] * n) + " "
334
+ text = _re_indent.sub(r"\n+", _repl, text)
335
+ return text
336
+
337
+
338
+ def restore_indentation(text):
339
+ text = _re_indent.sub(r"(<nl>\s*)+", lambda m: "\n" * m.group().count("<nl>"), text)
340
+ text = _re_indent.sub(r"(<tab>\s*)+", lambda m: " " * m.group().count("<tab>"), text)
341
+ return text
342
+
343
+
344
+ def encode_text(s):
345
+ return sp.encode(protect_indentation(s), out_type=int)
346
+
347
+
348
+ def decode_ids(ids):
349
+ text = sp.decode([i for i in ids if i not in (PAD_ID, BOS_ID, EOS_ID)])
350
+ return restore_indentation(text)
351
+
352
+
353
+ def _block_repeated_ngrams(generated_ids, logits, ngram_size):
354
+ """Prohibe repetir literalmente un n-grama ya generado en esta misma
355
+ respuesta (tecnica de decoding tipo GPT-2/3, no un modelo de n-gramas:
356
+ el modelo que predice sigue siendo 100% transformer con KV-cache)."""
357
+ if ngram_size <= 0 or len(generated_ids) < ngram_size:
358
+ return logits
359
+ prefix = tuple(generated_ids[-(ngram_size - 1):])
360
+ banned = set()
361
+ for i in range(len(generated_ids) - ngram_size + 1):
362
+ if tuple(generated_ids[i:i + ngram_size - 1]) == prefix:
363
+ banned.add(generated_ids[i + ngram_size - 1])
364
+ if banned:
365
+ logits[0, list(banned)] = float("-inf")
366
+ return logits
367
+
368
+
369
+ # ---------------- Generación (con KV-cache) ----------------
370
+ @torch.inference_mode()
371
+ def generate(idx, max_new_tokens, temperature, top_k, top_p, repetition_penalty, no_repeat_ngram_size=3):
372
+ past_key_values = None
373
+ cache_len = 0 # cuántos tokens del extremo derecho de `idx` ya están en la caché
374
+
375
+ for _ in range(max_new_tokens):
376
+ total_len = idx.shape[1]
377
+
378
+ if total_len <= BLOCK_SIZE:
379
+ if past_key_values is None:
380
+ # Primer paso: una sola pasada ("prefill") sobre todo el prompt.
381
+ logits, past_key_values = model(idx, use_cache=True)
382
+ cache_len = total_len
383
+ else:
384
+ # Pasos siguientes: solo se procesa el último token generado,
385
+ # reutilizando la caché de todo lo anterior.
386
+ last_token = idx[:, -1:]
387
+ logits, past_key_values = model(
388
+ last_token,
389
+ past_key_values=past_key_values,
390
+ use_cache=True,
391
+ pos_offset=cache_len,
392
+ )
393
+ cache_len += 1
394
+ logits = logits[:, -1, :]
395
+ else:
396
+ # Se superó block_size: mismo comportamiento que el modelo original
397
+ # (ventana deslizante recalculada por completo). Solo ocurre en
398
+ # respuestas muy largas; la caché se reinicia para esa ventana.
399
+ idx_cond = idx[:, -BLOCK_SIZE:]
400
+ logits, past_key_values = model(idx_cond, use_cache=True)
401
+ cache_len = BLOCK_SIZE
402
+ logits = logits[:, -1, :]
403
+
404
+ logits = logits / max(temperature, 1e-5)
405
+
406
+ if repetition_penalty and repetition_penalty != 1.0:
407
+ # Vectorizado: antes era `for token_id in set(idx[0].tolist())`,
408
+ # un bucle Python nuevo por cada token generado.
409
+ unique_ids = torch.unique(idx[0])
410
+ logits[0, unique_ids] /= repetition_penalty
411
+
412
+ logits = _block_repeated_ngrams(idx[0].tolist(), logits, no_repeat_ngram_size)
413
+
414
+ if top_k is not None and top_k > 0:
415
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
416
+ logits[logits < v[:, [-1]]] = float("-inf")
417
+
418
+ probs = F.softmax(logits, dim=-1)
419
+
420
+ if top_p is not None and 0 < top_p < 1:
421
+ sorted_probs, sorted_idx = torch.sort(probs, descending=True)
422
+ cum_probs = torch.cumsum(sorted_probs, dim=-1)
423
+ cutoff = cum_probs > top_p
424
+ cutoff[:, 1:] = cutoff[:, :-1].clone()
425
+ cutoff[:, 0] = False
426
+ sorted_probs[cutoff] = 0.0
427
+ sorted_probs = sorted_probs / sorted_probs.sum(dim=-1, keepdim=True)
428
+ next_id = sorted_idx.gather(-1, torch.multinomial(sorted_probs, 1))
429
+ else:
430
+ next_id = torch.multinomial(probs, num_samples=1)
431
+
432
+ idx = torch.cat([idx, next_id], dim=1)
433
+ if next_id.item() == EOS_ID:
434
+ break
435
+
436
+ return idx
437
+
438
+
439
+ def run_inference(text, max_new_tokens=None, temperature=None, top_k=None, top_p=None, repetition_penalty=None, no_repeat_ngram_size=None):
440
+ """Núcleo de generación, reutilizado por la UI de Gradio y por la API /generate.
441
+ No reduce calidad por estar en CPU: usa exactamente el mismo muestreo
442
+ (top_k + top_p + repetition_penalty + bloqueo de n-gramas repetidos) que
443
+ en la Celda 2 de entrenamiento, solo que ahora con KV-cache es notablemente
444
+ más rápido en respuestas largas."""
445
+ max_new_tokens = int(max_new_tokens) if max_new_tokens else gen_defaults["max_new_tokens"]
446
+ temperature = float(temperature) if temperature is not None else gen_defaults["temperature"]
447
+ top_k = int(top_k) if top_k is not None else gen_defaults["top_k"]
448
+ top_p = float(top_p) if top_p is not None else gen_defaults["top_p"]
449
+ repetition_penalty = float(repetition_penalty) if repetition_penalty is not None else gen_defaults["repetition_penalty"]
450
+ no_repeat_ngram_size = int(no_repeat_ngram_size) if no_repeat_ngram_size is not None else gen_defaults.get("no_repeat_ngram_size", 3)
451
+
452
+ # Techo máximo de generación: 4000 no era realista en CPU (cada token
453
+ # adicional cuesta tiempo real). 700 sigue siendo una respuesta larga y
454
+ # mantiene el tiempo de respuesta bajo control en el peor caso.
455
+ MAX_TOKENS_HARD_LIMIT = 700
456
+ max_new_tokens = max(1, min(max_new_tokens, MAX_TOKENS_HARD_LIMIT))
457
+
458
+ if len(text) > MAX_INPUT_CHARS:
459
+ logger.warning(f"Input de {len(text)} caracteres recortado a {MAX_INPUT_CHARS}")
460
+ text = text[:MAX_INPUT_CHARS]
461
+
462
+ prefix = f"Usuario: {text}\nMTP: "
463
+ ids = [BOS_ID] + encode_text(prefix)
464
+ idx = torch.tensor([ids], dtype=torch.long, device=DEVICE)
465
+
466
+ # Con el lock, si llegan varias generaciones al mismo tiempo (UI + API,
467
+ # o varios usuarios a la vez) se procesan una despues de otra en vez de
468
+ # pisarse los hilos de CPU entre si.
469
+ with _generation_lock:
470
+ out = generate(idx, max_new_tokens, temperature, top_k, top_p, repetition_penalty, no_repeat_ngram_size)
471
+
472
+ new_ids = out[0].tolist()[len(ids):]
473
+ return decode_ids(new_ids).strip()
474
+
475
+
476
+ def chat_fn(message, history, max_new_tokens, temperature, top_k, top_p, repetition_penalty):
477
+ return run_inference(message, max_new_tokens, temperature, top_k, top_p, repetition_penalty)
478
+
479
+
480
+ # ---------------- Interfaz Gradio (para probar el modelo desde el navegador) ----------------
481
+ with gr.Blocks(title="MTP-2.5 Chat") as demo:
482
+ gr.Markdown(f"# MTP-2.5\nModelo GPT (RoPE + SwiGLU + RMSNorm) entrenado desde cero, tokenizer BPE. Ejecutándose en {DEVICE.upper()}.")
483
+
484
+ with gr.Accordion("Parámetros de generación", open=False):
485
+ max_new_tokens_ui = gr.Slider(16, 4000, value=gen_defaults["max_new_tokens"], step=10, label="max_new_tokens")
486
+ temperature_ui = gr.Slider(0.1, 2.0, value=gen_defaults["temperature"], step=0.05, label="temperature")
487
+ top_k_ui = gr.Slider(0, 100, value=gen_defaults["top_k"], step=1, label="top_k")
488
+ top_p_ui = gr.Slider(0.1, 1.0, value=gen_defaults["top_p"], step=0.05, label="top_p")
489
+ repetition_penalty_ui = gr.Slider(1.0, 2.0, value=gen_defaults["repetition_penalty"], step=0.05,
490
+ label="repetition_penalty")
491
+
492
+ chatbot = gr.ChatInterface(
493
+ fn=chat_fn,
494
+ additional_inputs=[max_new_tokens_ui, temperature_ui, top_k_ui, top_p_ui, repetition_penalty_ui],
495
+ title=None,
496
+ examples=[
497
+ ["Hola, ¿cómo estás?"],
498
+ ["¿Cuánto es 8 + 5?"],
499
+ ["Explícame qué es un algoritmo."],
500
+ ],
501
+ cache_examples=False,
502
+ )
503
+
504
+ demo.queue(max_size=16)
505
+
506
+ # ---------------- API REST /generate (la que consume el PHP) ----------------
507
+ # El PHP hace: fetch(url, { method:'POST', body: JSON.stringify({text, max_tokens, temperature}) })
508
+ # y espera de vuelta: { "reply": "..." }
509
+ #
510
+ # IMPORTANTE:
511
+ # - ssr_mode=False: Gradio 6 usa un servidor Node.js aparte para SSR, que
512
+ # intentaba levantarse en el puerto 7861 y chocaba. Lo desactivamos porque
513
+ # no lo necesitamos para servir la API.
514
+ # - El middleware CORS se pasa vía app_kwargs ANTES de llamar a launch(),
515
+ # porque una vez que la app arranca, Starlette ya no permite añadir
516
+ # middleware (por eso fallaba con app.add_middleware() después).
517
+
518
+ class GenerateRequest(BaseModel):
519
+ text: str
520
+ max_tokens: Optional[int] = None
521
+ temperature: Optional[float] = None
522
+ top_k: Optional[int] = None
523
+ top_p: Optional[float] = None
524
+ repetition_penalty: Optional[float] = None
525
+ no_repeat_ngram_size: Optional[int] = None
526
+
527
+
528
+ PORT = int(os.environ.get("PORT", 7860))
529
+ demo.launch(
530
+ server_name="0.0.0.0",
531
+ server_port=PORT,
532
+ prevent_thread_lock=True,
533
+ ssr_mode=False,
534
+ app_kwargs={
535
+ "middleware": [
536
+ Middleware(CORSMiddleware, allow_origins=ALLOWED_ORIGINS, allow_methods=["*"], allow_headers=["*"]),
537
+ ]
538
+ },
539
+ )
540
+
541
+ app = demo.app
542
+
543
+
544
+ @app.post("/generate")
545
+ def generate_endpoint(req: GenerateRequest):
546
+ if not req.text or not req.text.strip():
547
+ return {"reply": "Escribe algo para que pueda responder."}
548
+ try:
549
+ reply = run_inference(
550
+ req.text,
551
+ max_new_tokens=req.max_tokens,
552
+ temperature=req.temperature,
553
+ top_k=req.top_k,
554
+ top_p=req.top_p,
555
+ repetition_penalty=req.repetition_penalty,
556
+ no_repeat_ngram_size=req.no_repeat_ngram_size,
557
+ )
558
+ if not reply:
559
+ reply = "No pude generar una respuesta."
560
+ return {"reply": reply}
561
+ except Exception as e:
562
+ # El detalle completo va al log del Space (con traceback), no a la
563
+ # respuesta publica: devolver la excepcion cruda a quien llama podria
564
+ # filtrar rutas internas, nombres de variables, etc. Con
565
+ # MTP_DEBUG_ERRORS=1 se puede activar el detalle mientras desarrollas.
566
+ logger.error(f"Error generando respuesta: {e}\n{traceback.format_exc()}")
567
+ reply = f"Error del modelo: {e}" if DEBUG_ERRORS else "Ocurrió un error al generar la respuesta. Intenta de nuevo en un momento."
568
+ return {"reply": reply}
569
+
570
+
571
+ @app.get("/generate")
572
+ def generate_health():
573
+ # Solo para poder comprobar en el navegador que la ruta existe (GET no genera texto)
574
+ return {"status": "ok", "info": "Usa POST con JSON {text, max_tokens, temperature}"}
575
+
576
+
577
+ @app.get("/health")
578
+ def health():
579
+ # Health check real: confirma que el modelo esta cargado y listo, no
580
+ # solo que el proceso esta vivo. Util para monitoreo externo (uptime
581
+ # checks) o para que el PHP sepa si conviene reintentar mas tarde.
582
+ return {
583
+ "status": "ok",
584
+ "model": checkpoint["meta"]["model_name"],
585
+ "device": DEVICE,
586
+ "trained_examples": checkpoint["meta"]["trained_examples"],
587
+ }
588
+
589
+
590
+ # demo.launch(prevent_thread_lock=True) ya dejó el servidor corriendo en un
591
+ # hilo en segundo plano (un solo proceso, un solo puerto). Mantenemos vivo
592
+ # el hilo principal para que el contenedor del Space no termine.
593
+ demo.block_thread()