Delete model.py
Browse files
model.py
DELETED
|
@@ -1,331 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import torch.nn as nn
|
| 3 |
-
import torch.nn.functional as F
|
| 4 |
-
import math
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
class RotaryPositionalEmbedding(nn.Module):
|
| 8 |
-
"""RoPE - Rotary Position Embedding con scaling mejorado"""
|
| 9 |
-
|
| 10 |
-
def __init__(self, dim, max_seq_len=4096, base=10000):
|
| 11 |
-
super().__init__()
|
| 12 |
-
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
| 13 |
-
self.register_buffer('inv_freq', inv_freq)
|
| 14 |
-
self.max_seq_len = max_seq_len
|
| 15 |
-
|
| 16 |
-
def forward(self, seq_len, device):
|
| 17 |
-
t = torch.arange(seq_len, device=device).type_as(self.inv_freq)
|
| 18 |
-
freqs = torch.einsum('i,j->ij', t, self.inv_freq)
|
| 19 |
-
emb = torch.cat((freqs, freqs), dim=-1)
|
| 20 |
-
return emb.cos(), emb.sin()
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
def apply_rotary_pos_emb(q, k, cos, sin):
|
| 24 |
-
"""Aplica RoPE a queries y keys"""
|
| 25 |
-
def rotate_half(x):
|
| 26 |
-
x1, x2 = x.chunk(2, dim=-1)
|
| 27 |
-
return torch.cat((-x2, x1), dim=-1)
|
| 28 |
-
|
| 29 |
-
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 30 |
-
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 31 |
-
return q_embed, k_embed
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
class MultiQueryAttention(nn.Module):
|
| 35 |
-
"""Multi-Query Attention (MQA) - Más eficiente que MHA"""
|
| 36 |
-
|
| 37 |
-
def __init__(self, d_model, n_heads, dropout=0.1, max_seq_len=4096):
|
| 38 |
-
super().__init__()
|
| 39 |
-
assert d_model % n_heads == 0
|
| 40 |
-
|
| 41 |
-
self.d_model = d_model
|
| 42 |
-
self.n_heads = n_heads
|
| 43 |
-
self.d_k = d_model // n_heads
|
| 44 |
-
|
| 45 |
-
# Multi-query: Q tiene múltiples heads, K y V tienen 1 head
|
| 46 |
-
self.q_linear = nn.Linear(d_model, d_model, bias=False)
|
| 47 |
-
self.k_linear = nn.Linear(d_model, self.d_k, bias=False)
|
| 48 |
-
self.v_linear = nn.Linear(d_model, self.d_k, bias=False)
|
| 49 |
-
self.out_linear = nn.Linear(d_model, d_model, bias=False)
|
| 50 |
-
|
| 51 |
-
self.dropout = nn.Dropout(dropout)
|
| 52 |
-
self.attn_dropout = nn.Dropout(dropout)
|
| 53 |
-
self.rope = RotaryPositionalEmbedding(self.d_k, max_seq_len)
|
| 54 |
-
|
| 55 |
-
self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
|
| 56 |
-
|
| 57 |
-
def forward(self, x, mask=None, use_cache=False, past_kv=None):
|
| 58 |
-
batch_size, seq_len, d_model = x.size()
|
| 59 |
-
|
| 60 |
-
# Q: [batch, seq, n_heads, d_k]
|
| 61 |
-
Q = self.q_linear(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
|
| 62 |
-
|
| 63 |
-
# K, V: [batch, seq, d_k] -> expandir a [batch, n_heads, seq, d_k]
|
| 64 |
-
K = self.k_linear(x).unsqueeze(1).expand(-1, self.n_heads, -1, -1)
|
| 65 |
-
V = self.v_linear(x).unsqueeze(1).expand(-1, self.n_heads, -1, -1)
|
| 66 |
-
|
| 67 |
-
# Apply RoPE
|
| 68 |
-
cos, sin = self.rope(seq_len, x.device)
|
| 69 |
-
cos = cos[None, None, :, :]
|
| 70 |
-
sin = sin[None, None, :, :]
|
| 71 |
-
Q, K = apply_rotary_pos_emb(Q, K, cos, sin)
|
| 72 |
-
|
| 73 |
-
# KV cache para inferencia
|
| 74 |
-
if use_cache:
|
| 75 |
-
if past_kv is not None:
|
| 76 |
-
K = torch.cat([past_kv[0], K], dim=2)
|
| 77 |
-
V = torch.cat([past_kv[1], V], dim=2)
|
| 78 |
-
cache = (K, V)
|
| 79 |
-
else:
|
| 80 |
-
cache = None
|
| 81 |
-
|
| 82 |
-
# Attention
|
| 83 |
-
if self.flash and mask is None and not use_cache:
|
| 84 |
-
context = F.scaled_dot_product_attention(
|
| 85 |
-
Q, K, V,
|
| 86 |
-
attn_mask=None,
|
| 87 |
-
dropout_p=self.dropout.p if self.training else 0.0,
|
| 88 |
-
is_causal=True
|
| 89 |
-
)
|
| 90 |
-
else:
|
| 91 |
-
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
|
| 92 |
-
if mask is not None:
|
| 93 |
-
scores = scores.masked_fill(mask == 0, float('-inf'))
|
| 94 |
-
attn_weights = F.softmax(scores, dim=-1)
|
| 95 |
-
attn_weights = self.attn_dropout(attn_weights)
|
| 96 |
-
context = torch.matmul(attn_weights, V)
|
| 97 |
-
|
| 98 |
-
context = context.transpose(1, 2).contiguous().view(batch_size, seq_len, d_model)
|
| 99 |
-
output = self.out_linear(context)
|
| 100 |
-
return self.dropout(output), cache
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
class SwiGLU(nn.Module):
|
| 104 |
-
"""SwiGLU activation con eficiencia mejorada"""
|
| 105 |
-
|
| 106 |
-
def __init__(self, d_model, d_ff, dropout=0.1):
|
| 107 |
-
super().__init__()
|
| 108 |
-
# FFN de GPT-3: 4x expansion
|
| 109 |
-
self.w1 = nn.Linear(d_model, d_ff, bias=False)
|
| 110 |
-
self.w2 = nn.Linear(d_ff, d_model, bias=False)
|
| 111 |
-
self.w3 = nn.Linear(d_model, d_ff, bias=False)
|
| 112 |
-
self.dropout = nn.Dropout(dropout)
|
| 113 |
-
|
| 114 |
-
def forward(self, x):
|
| 115 |
-
return self.w2(self.dropout(F.silu(self.w1(x)) * self.w3(x)))
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
class RMSNorm(nn.Module):
|
| 119 |
-
"""RMSNorm - Más estable que LayerNorm"""
|
| 120 |
-
|
| 121 |
-
def __init__(self, dim, eps=1e-6):
|
| 122 |
-
super().__init__()
|
| 123 |
-
self.eps = eps
|
| 124 |
-
self.weight = nn.Parameter(torch.ones(dim))
|
| 125 |
-
|
| 126 |
-
def forward(self, x):
|
| 127 |
-
norm = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 128 |
-
return x * norm * self.weight
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
class TransformerBlock(nn.Module):
|
| 132 |
-
"""Transformer Block optimizado estilo GPT-3"""
|
| 133 |
-
|
| 134 |
-
def __init__(self, d_model, n_heads, d_ff, dropout=0.1, max_seq_len=4096):
|
| 135 |
-
super().__init__()
|
| 136 |
-
self.attention = MultiQueryAttention(d_model, n_heads, dropout, max_seq_len)
|
| 137 |
-
self.feed_forward = SwiGLU(d_model, d_ff, dropout)
|
| 138 |
-
|
| 139 |
-
self.norm1 = RMSNorm(d_model)
|
| 140 |
-
self.norm2 = RMSNorm(d_model)
|
| 141 |
-
|
| 142 |
-
def forward(self, x, mask=None, use_cache=False, past_kv=None):
|
| 143 |
-
# Pre-norm architecture (mejor que post-norm)
|
| 144 |
-
attn_out, cache = self.attention(self.norm1(x), mask, use_cache, past_kv)
|
| 145 |
-
x = x + attn_out
|
| 146 |
-
x = x + self.feed_forward(self.norm2(x))
|
| 147 |
-
return x, cache
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
class MTPModel(nn.Module):
|
| 151 |
-
"""MTP 3 - Arquitectura mejorada nivel GPT-3"""
|
| 152 |
-
|
| 153 |
-
def __init__(self, vocab_size, d_model=1024, n_layers=24, n_heads=16,
|
| 154 |
-
d_ff=4096, max_seq_len=2048, dropout=0.1):
|
| 155 |
-
super().__init__()
|
| 156 |
-
|
| 157 |
-
self.vocab_size = vocab_size
|
| 158 |
-
self.d_model = d_model
|
| 159 |
-
self.max_seq_len = max_seq_len
|
| 160 |
-
|
| 161 |
-
# Embeddings con escalado
|
| 162 |
-
self.token_embedding = nn.Embedding(vocab_size, d_model)
|
| 163 |
-
self.dropout = nn.Dropout(dropout)
|
| 164 |
-
|
| 165 |
-
# Transformer blocks
|
| 166 |
-
self.blocks = nn.ModuleList([
|
| 167 |
-
TransformerBlock(d_model, n_heads, d_ff, dropout, max_seq_len)
|
| 168 |
-
for _ in range(n_layers)
|
| 169 |
-
])
|
| 170 |
-
|
| 171 |
-
# Final norm y projection
|
| 172 |
-
self.norm_f = RMSNorm(d_model)
|
| 173 |
-
self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
|
| 174 |
-
|
| 175 |
-
# Weight tying (reduce parámetros)
|
| 176 |
-
self.token_embedding.weight = self.lm_head.weight
|
| 177 |
-
|
| 178 |
-
# Inicialización mejorada (GPT-3 style)
|
| 179 |
-
self.apply(self._init_weights)
|
| 180 |
-
|
| 181 |
-
# Escalado especial para residual connections
|
| 182 |
-
for pn, p in self.named_parameters():
|
| 183 |
-
if pn.endswith('w2.weight') or pn.endswith('out_linear.weight'):
|
| 184 |
-
torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * n_layers))
|
| 185 |
-
|
| 186 |
-
def _init_weights(self, module):
|
| 187 |
-
if isinstance(module, nn.Linear):
|
| 188 |
-
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 189 |
-
if module.bias is not None:
|
| 190 |
-
torch.nn.init.zeros_(module.bias)
|
| 191 |
-
elif isinstance(module, nn.Embedding):
|
| 192 |
-
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 193 |
-
|
| 194 |
-
def forward(self, input_ids, targets=None):
|
| 195 |
-
batch_size, seq_len = input_ids.size()
|
| 196 |
-
|
| 197 |
-
# Causal mask
|
| 198 |
-
mask = torch.tril(torch.ones(seq_len, seq_len, device=input_ids.device)).view(1, 1, seq_len, seq_len)
|
| 199 |
-
|
| 200 |
-
# Embeddings con escalado
|
| 201 |
-
x = self.dropout(self.token_embedding(input_ids) * math.sqrt(self.d_model))
|
| 202 |
-
|
| 203 |
-
# Transformer blocks
|
| 204 |
-
for block in self.blocks:
|
| 205 |
-
x, _ = block(x, mask)
|
| 206 |
-
|
| 207 |
-
# Final norm y projection
|
| 208 |
-
x = self.norm_f(x)
|
| 209 |
-
logits = self.lm_head(x)
|
| 210 |
-
|
| 211 |
-
loss = None
|
| 212 |
-
if targets is not None:
|
| 213 |
-
# Label smoothing para mejor generalización
|
| 214 |
-
loss = F.cross_entropy(
|
| 215 |
-
logits.view(-1, self.vocab_size),
|
| 216 |
-
targets.view(-1),
|
| 217 |
-
label_smoothing=0.1,
|
| 218 |
-
ignore_index=-100
|
| 219 |
-
)
|
| 220 |
-
|
| 221 |
-
return logits, loss
|
| 222 |
-
|
| 223 |
-
@torch.no_grad()
|
| 224 |
-
def generate(self, input_ids, max_new_tokens=200, temperature=0.8,
|
| 225 |
-
top_k=50, top_p=0.95, repetition_penalty=1.2,
|
| 226 |
-
min_length=30, eos_token_id=3):
|
| 227 |
-
"""Generación optimizada con KV cache"""
|
| 228 |
-
self.eval()
|
| 229 |
-
|
| 230 |
-
device = input_ids.device
|
| 231 |
-
generated = input_ids.clone()
|
| 232 |
-
past_kvs = [None] * len(self.blocks)
|
| 233 |
-
generated_text_tokens = 0
|
| 234 |
-
|
| 235 |
-
for step in range(max_new_tokens):
|
| 236 |
-
# Use cache para tokens ya procesados
|
| 237 |
-
if step == 0:
|
| 238 |
-
current_input = generated
|
| 239 |
-
use_cache = False
|
| 240 |
-
else:
|
| 241 |
-
current_input = generated[:, -1:]
|
| 242 |
-
use_cache = True
|
| 243 |
-
|
| 244 |
-
# Truncate si excede max_seq_len
|
| 245 |
-
if current_input.size(1) > self.max_seq_len:
|
| 246 |
-
current_input = current_input[:, -self.max_seq_len:]
|
| 247 |
-
use_cache = False
|
| 248 |
-
past_kvs = [None] * len(self.blocks)
|
| 249 |
-
|
| 250 |
-
# Forward pass
|
| 251 |
-
batch_size, seq_len = current_input.size()
|
| 252 |
-
mask = torch.tril(torch.ones(seq_len, seq_len, device=device)).view(1, 1, seq_len, seq_len)
|
| 253 |
-
|
| 254 |
-
x = self.token_embedding(current_input) * math.sqrt(self.d_model)
|
| 255 |
-
|
| 256 |
-
new_past_kvs = []
|
| 257 |
-
for i, block in enumerate(self.blocks):
|
| 258 |
-
x, cache = block(x, mask, use_cache, past_kvs[i] if use_cache else None)
|
| 259 |
-
new_past_kvs.append(cache)
|
| 260 |
-
|
| 261 |
-
if use_cache:
|
| 262 |
-
past_kvs = new_past_kvs
|
| 263 |
-
|
| 264 |
-
x = self.norm_f(x)
|
| 265 |
-
logits = self.lm_head(x[:, -1, :])
|
| 266 |
-
|
| 267 |
-
# Repetition penalty
|
| 268 |
-
if repetition_penalty != 1.0:
|
| 269 |
-
for token_id in set(generated[0].tolist()):
|
| 270 |
-
if logits[0, token_id] < 0:
|
| 271 |
-
logits[0, token_id] *= repetition_penalty
|
| 272 |
-
else:
|
| 273 |
-
logits[0, token_id] /= repetition_penalty
|
| 274 |
-
|
| 275 |
-
# Penalizar tokens muy repetidos
|
| 276 |
-
if generated.size(1) > 20:
|
| 277 |
-
recent = generated[0, -20:].tolist()
|
| 278 |
-
for token_id in set(recent):
|
| 279 |
-
count = recent.count(token_id)
|
| 280 |
-
if count > 3:
|
| 281 |
-
logits[0, token_id] -= count * 3.0
|
| 282 |
-
|
| 283 |
-
# Control de longitud mínima
|
| 284 |
-
if generated_text_tokens < min_length:
|
| 285 |
-
logits[0, eos_token_id] = float('-inf')
|
| 286 |
-
else:
|
| 287 |
-
# Boost EOS gradualmente
|
| 288 |
-
eos_boost = min((generated_text_tokens - min_length) * 0.15, 3.0)
|
| 289 |
-
logits[0, eos_token_id] += eos_boost
|
| 290 |
-
|
| 291 |
-
# Temperature scaling
|
| 292 |
-
logits = logits / temperature
|
| 293 |
-
|
| 294 |
-
# Top-k filtering
|
| 295 |
-
if top_k > 0:
|
| 296 |
-
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
| 297 |
-
logits[logits < v[:, [-1]]] = float('-inf')
|
| 298 |
-
|
| 299 |
-
# Top-p (nucleus) filtering
|
| 300 |
-
if top_p < 1.0:
|
| 301 |
-
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 302 |
-
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 303 |
-
sorted_indices_to_remove = cumulative_probs > top_p
|
| 304 |
-
sorted_indices_to_remove[:, 1:] = sorted_indices_to_remove[:, :-1].clone()
|
| 305 |
-
sorted_indices_to_remove[:, 0] = 0
|
| 306 |
-
indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
|
| 307 |
-
logits[indices_to_remove] = float('-inf')
|
| 308 |
-
|
| 309 |
-
# Sample
|
| 310 |
-
probs = F.softmax(logits, dim=-1)
|
| 311 |
-
next_token = torch.multinomial(probs, num_samples=1)
|
| 312 |
-
|
| 313 |
-
# Check EOS
|
| 314 |
-
if next_token.item() == eos_token_id and generated_text_tokens >= min_length:
|
| 315 |
-
break
|
| 316 |
-
|
| 317 |
-
generated = torch.cat([generated, next_token], dim=1)
|
| 318 |
-
generated_text_tokens += 1
|
| 319 |
-
|
| 320 |
-
return generated
|
| 321 |
-
|
| 322 |
-
def count_parameters(self):
|
| 323 |
-
"""Cuenta parámetros entrenables"""
|
| 324 |
-
return sum(p.numel() for p in self.parameters() if p.requires_grad)
|
| 325 |
-
|
| 326 |
-
def get_num_params(self, non_embedding=True):
|
| 327 |
-
"""Cuenta parámetros excluyendo embeddings si se requiere"""
|
| 328 |
-
n_params = sum(p.numel() for p in self.parameters())
|
| 329 |
-
if non_embedding:
|
| 330 |
-
n_params -= self.token_embedding.weight.numel()
|
| 331 |
-
return n_params
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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