Delete model.py
Browse files
model.py
DELETED
|
@@ -1,275 +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"""
|
| 9 |
-
|
| 10 |
-
def __init__(self, dim, max_seq_len=2048, 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 MultiHeadSelfAttention(nn.Module):
|
| 35 |
-
"""Multi-Head Self-Attention mejorado con RoPE"""
|
| 36 |
-
|
| 37 |
-
def __init__(self, d_model, n_heads, dropout=0.1, max_seq_len=2048):
|
| 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 |
-
# Proyecciones Q, K, V (sin bias para mejor eficiencia)
|
| 46 |
-
self.q_linear = nn.Linear(d_model, d_model, bias=False)
|
| 47 |
-
self.k_linear = nn.Linear(d_model, d_model, bias=False)
|
| 48 |
-
self.v_linear = nn.Linear(d_model, d_model, bias=False)
|
| 49 |
-
self.out_linear = nn.Linear(d_model, d_model, bias=False)
|
| 50 |
-
|
| 51 |
-
self.dropout = nn.Dropout(dropout)
|
| 52 |
-
self.rope = RotaryPositionalEmbedding(self.d_k, max_seq_len)
|
| 53 |
-
|
| 54 |
-
# Flash Attention si está disponible
|
| 55 |
-
self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
|
| 56 |
-
|
| 57 |
-
def forward(self, x, mask=None):
|
| 58 |
-
batch_size, seq_len, d_model = x.size()
|
| 59 |
-
|
| 60 |
-
# Proyecciones lineales
|
| 61 |
-
Q = self.q_linear(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
|
| 62 |
-
K = self.k_linear(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
|
| 63 |
-
V = self.v_linear(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
|
| 64 |
-
|
| 65 |
-
# Aplicar RoPE
|
| 66 |
-
cos, sin = self.rope(seq_len, x.device)
|
| 67 |
-
cos = cos[None, None, :, :]
|
| 68 |
-
sin = sin[None, None, :, :]
|
| 69 |
-
Q, K = apply_rotary_pos_emb(Q, K, cos, sin)
|
| 70 |
-
|
| 71 |
-
# Attention con Flash Attention si está disponible
|
| 72 |
-
if self.flash and mask is None:
|
| 73 |
-
context = F.scaled_dot_product_attention(
|
| 74 |
-
Q, K, V,
|
| 75 |
-
attn_mask=None,
|
| 76 |
-
dropout_p=self.dropout.p if self.training else 0.0,
|
| 77 |
-
is_causal=True
|
| 78 |
-
)
|
| 79 |
-
else:
|
| 80 |
-
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
|
| 81 |
-
if mask is not None:
|
| 82 |
-
scores = scores.masked_fill(mask == 0, float('-inf'))
|
| 83 |
-
attn_weights = F.softmax(scores, dim=-1)
|
| 84 |
-
attn_weights = self.dropout(attn_weights)
|
| 85 |
-
context = torch.matmul(attn_weights, V)
|
| 86 |
-
|
| 87 |
-
context = context.transpose(1, 2).contiguous().view(batch_size, seq_len, d_model)
|
| 88 |
-
output = self.out_linear(context)
|
| 89 |
-
return output
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
class SwiGLU(nn.Module):
|
| 93 |
-
"""SwiGLU activation - Mejor que GELU"""
|
| 94 |
-
|
| 95 |
-
def __init__(self, d_model, d_ff, dropout=0.1):
|
| 96 |
-
super().__init__()
|
| 97 |
-
self.w1 = nn.Linear(d_model, d_ff, bias=False)
|
| 98 |
-
self.w2 = nn.Linear(d_ff, d_model, bias=False)
|
| 99 |
-
self.w3 = nn.Linear(d_model, d_ff, bias=False)
|
| 100 |
-
self.dropout = nn.Dropout(dropout)
|
| 101 |
-
|
| 102 |
-
def forward(self, x):
|
| 103 |
-
return self.w2(self.dropout(F.silu(self.w1(x)) * self.w3(x)))
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
class FeedForward(nn.Module):
|
| 107 |
-
"""Feed-Forward con GELU (fallback compatible)"""
|
| 108 |
-
|
| 109 |
-
def __init__(self, d_model, d_ff, dropout=0.1):
|
| 110 |
-
super().__init__()
|
| 111 |
-
self.linear1 = nn.Linear(d_model, d_ff)
|
| 112 |
-
self.linear2 = nn.Linear(d_ff, d_model)
|
| 113 |
-
self.dropout = nn.Dropout(dropout)
|
| 114 |
-
|
| 115 |
-
def forward(self, x):
|
| 116 |
-
return self.linear2(self.dropout(F.gelu(self.linear1(x))))
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
class RMSNorm(nn.Module):
|
| 120 |
-
"""RMSNorm - Más eficiente que LayerNorm"""
|
| 121 |
-
|
| 122 |
-
def __init__(self, dim, eps=1e-6):
|
| 123 |
-
super().__init__()
|
| 124 |
-
self.eps = eps
|
| 125 |
-
self.weight = nn.Parameter(torch.ones(dim))
|
| 126 |
-
|
| 127 |
-
def forward(self, x):
|
| 128 |
-
norm = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 129 |
-
return x * norm * self.weight
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
class TransformerBlock(nn.Module):
|
| 133 |
-
"""Transformer Block mejorado con pre-norm"""
|
| 134 |
-
|
| 135 |
-
def __init__(self, d_model, n_heads, d_ff, dropout=0.1, max_seq_len=2048, use_swiglu=True):
|
| 136 |
-
super().__init__()
|
| 137 |
-
self.attention = MultiHeadSelfAttention(d_model, n_heads, dropout, max_seq_len)
|
| 138 |
-
|
| 139 |
-
# Usar SwiGLU o FeedForward estándar
|
| 140 |
-
if use_swiglu:
|
| 141 |
-
self.feed_forward = SwiGLU(d_model, d_ff, dropout)
|
| 142 |
-
else:
|
| 143 |
-
self.feed_forward = FeedForward(d_model, d_ff, dropout)
|
| 144 |
-
|
| 145 |
-
self.norm1 = RMSNorm(d_model)
|
| 146 |
-
self.norm2 = RMSNorm(d_model)
|
| 147 |
-
|
| 148 |
-
def forward(self, x, mask=None):
|
| 149 |
-
# Pre-norm architecture
|
| 150 |
-
x = x + self.attention(self.norm1(x), mask)
|
| 151 |
-
x = x + self.feed_forward(self.norm2(x))
|
| 152 |
-
return x
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
class MTPMiniModel(nn.Module):
|
| 156 |
-
"""MTP Mini - Arquitectura mejorada compatible"""
|
| 157 |
-
|
| 158 |
-
def __init__(self, vocab_size, d_model=256, n_layers=4, n_heads=4,
|
| 159 |
-
d_ff=1024, max_seq_len=128, dropout=0.1, use_swiglu=False):
|
| 160 |
-
super().__init__()
|
| 161 |
-
|
| 162 |
-
self.vocab_size = vocab_size
|
| 163 |
-
self.d_model = d_model
|
| 164 |
-
self.max_seq_len = max_seq_len
|
| 165 |
-
|
| 166 |
-
# Token embeddings (sin positional, usamos RoPE)
|
| 167 |
-
self.token_embedding = nn.Embedding(vocab_size, d_model)
|
| 168 |
-
|
| 169 |
-
# Transformer blocks
|
| 170 |
-
self.blocks = nn.ModuleList([
|
| 171 |
-
TransformerBlock(d_model, n_heads, d_ff, dropout, max_seq_len, use_swiglu)
|
| 172 |
-
for _ in range(n_layers)
|
| 173 |
-
])
|
| 174 |
-
|
| 175 |
-
# Final norm
|
| 176 |
-
self.norm_f = RMSNorm(d_model)
|
| 177 |
-
|
| 178 |
-
# Output projection
|
| 179 |
-
self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
|
| 180 |
-
|
| 181 |
-
# Weight tying
|
| 182 |
-
self.lm_head.weight = self.token_embedding.weight
|
| 183 |
-
|
| 184 |
-
self.dropout = nn.Dropout(dropout)
|
| 185 |
-
|
| 186 |
-
# Mejor inicialización
|
| 187 |
-
self.apply(self._init_weights)
|
| 188 |
-
|
| 189 |
-
def _init_weights(self, module):
|
| 190 |
-
if isinstance(module, nn.Linear):
|
| 191 |
-
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 192 |
-
if module.bias is not None:
|
| 193 |
-
torch.nn.init.zeros_(module.bias)
|
| 194 |
-
elif isinstance(module, nn.Embedding):
|
| 195 |
-
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 196 |
-
|
| 197 |
-
def forward(self, input_ids, targets=None):
|
| 198 |
-
batch_size, seq_len = input_ids.size()
|
| 199 |
-
|
| 200 |
-
# Máscara causal
|
| 201 |
-
mask = torch.tril(torch.ones(seq_len, seq_len, device=input_ids.device)).view(1, 1, seq_len, seq_len)
|
| 202 |
-
|
| 203 |
-
# Token embeddings (RoPE se aplica en attention)
|
| 204 |
-
x = self.dropout(self.token_embedding(input_ids))
|
| 205 |
-
|
| 206 |
-
# Transformer blocks
|
| 207 |
-
for block in self.blocks:
|
| 208 |
-
x = block(x, mask)
|
| 209 |
-
|
| 210 |
-
# Final norm
|
| 211 |
-
x = self.norm_f(x)
|
| 212 |
-
|
| 213 |
-
# Logits
|
| 214 |
-
logits = self.lm_head(x)
|
| 215 |
-
|
| 216 |
-
# Loss con label smoothing
|
| 217 |
-
loss = None
|
| 218 |
-
if targets is not None:
|
| 219 |
-
loss = F.cross_entropy(
|
| 220 |
-
logits.view(-1, self.vocab_size),
|
| 221 |
-
targets.view(-1),
|
| 222 |
-
label_smoothing=0.1
|
| 223 |
-
)
|
| 224 |
-
|
| 225 |
-
return logits, loss
|
| 226 |
-
|
| 227 |
-
def generate(self, input_ids, max_new_tokens=100, temperature=0.8,
|
| 228 |
-
top_k=50, top_p=0.9, repetition_penalty=1.1):
|
| 229 |
-
"""Generación mejorada con repetition penalty"""
|
| 230 |
-
self.eval()
|
| 231 |
-
|
| 232 |
-
generated = input_ids.clone()
|
| 233 |
-
|
| 234 |
-
with torch.no_grad():
|
| 235 |
-
for _ in range(max_new_tokens):
|
| 236 |
-
# Crop context
|
| 237 |
-
input_ids_cond = generated if generated.size(1) <= self.max_seq_len else generated[:, -self.max_seq_len:]
|
| 238 |
-
|
| 239 |
-
# Forward
|
| 240 |
-
logits, _ = self(input_ids_cond)
|
| 241 |
-
logits = logits[:, -1, :]
|
| 242 |
-
|
| 243 |
-
# Repetition penalty
|
| 244 |
-
if repetition_penalty != 1.0:
|
| 245 |
-
for token_id in set(generated[0].tolist()):
|
| 246 |
-
logits[0, token_id] /= repetition_penalty
|
| 247 |
-
|
| 248 |
-
# Temperature
|
| 249 |
-
logits = logits / temperature
|
| 250 |
-
|
| 251 |
-
# Top-k
|
| 252 |
-
if top_k > 0:
|
| 253 |
-
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
| 254 |
-
logits[logits < v[:, [-1]]] = float('-inf')
|
| 255 |
-
|
| 256 |
-
# Top-p (nucleus)
|
| 257 |
-
if top_p < 1.0:
|
| 258 |
-
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 259 |
-
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 260 |
-
sorted_indices_to_remove = cumulative_probs > top_p
|
| 261 |
-
sorted_indices_to_remove[:, 1:] = sorted_indices_to_remove[:, :-1].clone()
|
| 262 |
-
sorted_indices_to_remove[:, 0] = 0
|
| 263 |
-
indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
|
| 264 |
-
logits[indices_to_remove] = float('-inf')
|
| 265 |
-
|
| 266 |
-
# Sample
|
| 267 |
-
probs = F.softmax(logits, dim=-1)
|
| 268 |
-
next_token = torch.multinomial(probs, num_samples=1)
|
| 269 |
-
|
| 270 |
-
generated = torch.cat([generated, next_token], dim=1)
|
| 271 |
-
|
| 272 |
-
return generated
|
| 273 |
-
|
| 274 |
-
def count_parameters(self):
|
| 275 |
-
return sum(p.numel() for p in self.parameters() if p.requires_grad)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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