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
| 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 con RoPE y Flash Attention"""
|
| 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 |
+
self.q_linear = nn.Linear(d_model, d_model, bias=False)
|
| 46 |
+
self.k_linear = nn.Linear(d_model, d_model, bias=False)
|
| 47 |
+
self.v_linear = nn.Linear(d_model, d_model, bias=False)
|
| 48 |
+
self.out_linear = nn.Linear(d_model, d_model, bias=False)
|
| 49 |
+
|
| 50 |
+
self.dropout = nn.Dropout(dropout)
|
| 51 |
+
self.attn_dropout = nn.Dropout(dropout)
|
| 52 |
+
self.rope = RotaryPositionalEmbedding(self.d_k, max_seq_len)
|
| 53 |
+
|
| 54 |
+
self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
|
| 55 |
+
|
| 56 |
+
def forward(self, x, mask=None):
|
| 57 |
+
batch_size, seq_len, d_model = x.size()
|
| 58 |
+
|
| 59 |
+
Q = self.q_linear(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
|
| 60 |
+
K = self.k_linear(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
|
| 61 |
+
V = self.v_linear(x).view(batch_size, seq_len, self.n_heads, self.d_k).transpose(1, 2)
|
| 62 |
+
|
| 63 |
+
cos, sin = self.rope(seq_len, x.device)
|
| 64 |
+
cos = cos[None, None, :, :]
|
| 65 |
+
sin = sin[None, None, :, :]
|
| 66 |
+
Q, K = apply_rotary_pos_emb(Q, K, cos, sin)
|
| 67 |
+
|
| 68 |
+
if self.flash and mask is None:
|
| 69 |
+
context = F.scaled_dot_product_attention(
|
| 70 |
+
Q, K, V,
|
| 71 |
+
attn_mask=None,
|
| 72 |
+
dropout_p=self.dropout.p if self.training else 0.0,
|
| 73 |
+
is_causal=True
|
| 74 |
+
)
|
| 75 |
+
else:
|
| 76 |
+
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
|
| 77 |
+
if mask is not None:
|
| 78 |
+
scores = scores.masked_fill(mask == 0, float('-inf'))
|
| 79 |
+
attn_weights = F.softmax(scores, dim=-1)
|
| 80 |
+
attn_weights = self.attn_dropout(attn_weights)
|
| 81 |
+
context = torch.matmul(attn_weights, V)
|
| 82 |
+
|
| 83 |
+
context = context.transpose(1, 2).contiguous().view(batch_size, seq_len, d_model)
|
| 84 |
+
output = self.out_linear(context)
|
| 85 |
+
return self.dropout(output)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class SwiGLU(nn.Module):
|
| 89 |
+
"""SwiGLU activation - Mejor que GELU"""
|
| 90 |
+
|
| 91 |
+
def __init__(self, d_model, d_ff, dropout=0.1):
|
| 92 |
+
super().__init__()
|
| 93 |
+
hidden_dim = int(d_ff * 2 / 3)
|
| 94 |
+
self.w1 = nn.Linear(d_model, hidden_dim, bias=False)
|
| 95 |
+
self.w2 = nn.Linear(hidden_dim, d_model, bias=False)
|
| 96 |
+
self.w3 = nn.Linear(d_model, hidden_dim, bias=False)
|
| 97 |
+
self.dropout = nn.Dropout(dropout)
|
| 98 |
+
|
| 99 |
+
def forward(self, x):
|
| 100 |
+
return self.w2(self.dropout(F.silu(self.w1(x)) * self.w3(x)))
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class RMSNorm(nn.Module):
|
| 104 |
+
"""RMSNorm - M谩s eficiente que LayerNorm"""
|
| 105 |
+
|
| 106 |
+
def __init__(self, dim, eps=1e-6):
|
| 107 |
+
super().__init__()
|
| 108 |
+
self.eps = eps
|
| 109 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 110 |
+
|
| 111 |
+
def forward(self, x):
|
| 112 |
+
norm = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 113 |
+
return x * norm * self.weight
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class TransformerBlock(nn.Module):
|
| 117 |
+
"""Transformer Block mejorado"""
|
| 118 |
+
|
| 119 |
+
def __init__(self, d_model, n_heads, d_ff, dropout=0.1, max_seq_len=2048, use_swiglu=True):
|
| 120 |
+
super().__init__()
|
| 121 |
+
self.attention = MultiHeadSelfAttention(d_model, n_heads, dropout, max_seq_len)
|
| 122 |
+
|
| 123 |
+
if use_swiglu:
|
| 124 |
+
self.feed_forward = SwiGLU(d_model, d_ff, dropout)
|
| 125 |
+
else:
|
| 126 |
+
self.feed_forward = nn.Sequential(
|
| 127 |
+
nn.Linear(d_model, d_ff),
|
| 128 |
+
nn.GELU(),
|
| 129 |
+
nn.Dropout(dropout),
|
| 130 |
+
nn.Linear(d_ff, d_model)
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
self.norm1 = RMSNorm(d_model)
|
| 134 |
+
self.norm2 = RMSNorm(d_model)
|
| 135 |
+
|
| 136 |
+
def forward(self, x, mask=None):
|
| 137 |
+
x = x + self.attention(self.norm1(x), mask)
|
| 138 |
+
x = x + self.feed_forward(self.norm2(x))
|
| 139 |
+
return x
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class MTPMiniModel(nn.Module):
|
| 143 |
+
"""MTP Mini - Modelo 20x m谩s grande e inteligente con anti-alucinaci贸n"""
|
| 144 |
+
|
| 145 |
+
def __init__(self, vocab_size, d_model=1024, n_layers=24, n_heads=16,
|
| 146 |
+
d_ff=4096, max_seq_len=2048, dropout=0.15, use_swiglu=True,
|
| 147 |
+
use_confidence_scoring=True, use_gradient_checkpointing=False):
|
| 148 |
+
super().__init__()
|
| 149 |
+
|
| 150 |
+
self.vocab_size = vocab_size
|
| 151 |
+
self.d_model = d_model
|
| 152 |
+
self.max_seq_len = max_seq_len
|
| 153 |
+
self.use_confidence_scoring = use_confidence_scoring
|
| 154 |
+
self.use_gradient_checkpointing = use_gradient_checkpointing
|
| 155 |
+
|
| 156 |
+
self.token_embedding = nn.Embedding(vocab_size, d_model)
|
| 157 |
+
self.dropout = nn.Dropout(dropout)
|
| 158 |
+
|
| 159 |
+
self.blocks = nn.ModuleList([
|
| 160 |
+
TransformerBlock(d_model, n_heads, d_ff, dropout, max_seq_len, use_swiglu)
|
| 161 |
+
for _ in range(n_layers)
|
| 162 |
+
])
|
| 163 |
+
|
| 164 |
+
self.norm_f = RMSNorm(d_model)
|
| 165 |
+
self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
|
| 166 |
+
|
| 167 |
+
# Weight tying
|
| 168 |
+
self.lm_head.weight = self.token_embedding.weight
|
| 169 |
+
|
| 170 |
+
# Confidence scoring head
|
| 171 |
+
if use_confidence_scoring:
|
| 172 |
+
self.confidence_head = nn.Sequential(
|
| 173 |
+
nn.Linear(d_model, d_model // 2),
|
| 174 |
+
nn.ReLU(),
|
| 175 |
+
nn.Dropout(dropout),
|
| 176 |
+
nn.Linear(d_model // 2, 1),
|
| 177 |
+
nn.Sigmoid()
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
self.apply(self._init_weights)
|
| 181 |
+
|
| 182 |
+
def _init_weights(self, module):
|
| 183 |
+
if isinstance(module, nn.Linear):
|
| 184 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 185 |
+
if module.bias is not None:
|
| 186 |
+
torch.nn.init.zeros_(module.bias)
|
| 187 |
+
elif isinstance(module, nn.Embedding):
|
| 188 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 189 |
+
|
| 190 |
+
def forward(self, input_ids, targets=None, use_eos_weight=False, eos_weight=2.0, return_confidence=False):
|
| 191 |
+
batch_size, seq_len = input_ids.size()
|
| 192 |
+
|
| 193 |
+
mask = torch.tril(torch.ones(seq_len, seq_len, device=input_ids.device)).view(1, 1, seq_len, seq_len)
|
| 194 |
+
|
| 195 |
+
x = self.dropout(self.token_embedding(input_ids))
|
| 196 |
+
|
| 197 |
+
for block in self.blocks:
|
| 198 |
+
if self.use_gradient_checkpointing and self.training:
|
| 199 |
+
x = torch.utils.checkpoint.checkpoint(block, x, mask, use_reentrant=False)
|
| 200 |
+
else:
|
| 201 |
+
x = block(x, mask)
|
| 202 |
+
|
| 203 |
+
x = self.norm_f(x)
|
| 204 |
+
logits = self.lm_head(x)
|
| 205 |
+
|
| 206 |
+
confidence = None
|
| 207 |
+
if self.use_confidence_scoring and return_confidence:
|
| 208 |
+
confidence = self.confidence_head(x)
|
| 209 |
+
|
| 210 |
+
loss = None
|
| 211 |
+
if targets is not None:
|
| 212 |
+
if use_eos_weight:
|
| 213 |
+
weights = torch.ones(self.vocab_size, device=logits.device)
|
| 214 |
+
weights[3] = eos_weight
|
| 215 |
+
loss = F.cross_entropy(
|
| 216 |
+
logits.view(-1, self.vocab_size),
|
| 217 |
+
targets.view(-1),
|
| 218 |
+
weight=weights,
|
| 219 |
+
label_smoothing=0.15
|
| 220 |
+
)
|
| 221 |
+
else:
|
| 222 |
+
loss = F.cross_entropy(
|
| 223 |
+
logits.view(-1, self.vocab_size),
|
| 224 |
+
targets.view(-1),
|
| 225 |
+
label_smoothing=0.15
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
if return_confidence:
|
| 229 |
+
return logits, loss, confidence
|
| 230 |
+
return logits, loss
|
| 231 |
+
|
| 232 |
+
def generate(self, input_ids, max_new_tokens=300, temperature=0.65,
|
| 233 |
+
top_k=50, top_p=0.9, repetition_penalty=1.2,
|
| 234 |
+
min_length=30, eos_token_id=3,
|
| 235 |
+
use_confidence_filter=True, min_confidence=0.3,
|
| 236 |
+
use_entropy_threshold=True, max_entropy=4.0):
|
| 237 |
+
"""Generaci贸n con anti-alucinaci贸n"""
|
| 238 |
+
self.eval()
|
| 239 |
+
|
| 240 |
+
generated = input_ids.clone()
|
| 241 |
+
generated_text_tokens = 0
|
| 242 |
+
|
| 243 |
+
with torch.no_grad():
|
| 244 |
+
for step in range(max_new_tokens):
|
| 245 |
+
input_ids_cond = generated if generated.size(1) <= self.max_seq_len else generated[:, -self.max_seq_len:]
|
| 246 |
+
|
| 247 |
+
logits, _, confidence = self(input_ids_cond, return_confidence=True)
|
| 248 |
+
logits = logits[:, -1, :].clone()
|
| 249 |
+
|
| 250 |
+
# Confidence filtering
|
| 251 |
+
if use_confidence_filter and confidence is not None:
|
| 252 |
+
conf_score = confidence[:, -1, :].item()
|
| 253 |
+
if conf_score < min_confidence:
|
| 254 |
+
temperature = min(temperature * 1.2, 1.0)
|
| 255 |
+
|
| 256 |
+
# Repetition penalty
|
| 257 |
+
if repetition_penalty != 1.0:
|
| 258 |
+
for token_id in set(generated[0].tolist()):
|
| 259 |
+
if logits[0, token_id] < 0:
|
| 260 |
+
logits[0, token_id] *= repetition_penalty
|
| 261 |
+
else:
|
| 262 |
+
logits[0, token_id] /= repetition_penalty
|
| 263 |
+
|
| 264 |
+
# Penalizar repeticiones recientes
|
| 265 |
+
if generated.size(1) > 15:
|
| 266 |
+
recent_tokens = generated[0, -15:].tolist()
|
| 267 |
+
for token_id in set(recent_tokens):
|
| 268 |
+
count = recent_tokens.count(token_id)
|
| 269 |
+
if count > 3:
|
| 270 |
+
logits[0, token_id] -= count * 3.0
|
| 271 |
+
|
| 272 |
+
# Control de longitud
|
| 273 |
+
if generated_text_tokens < min_length:
|
| 274 |
+
logits[0, eos_token_id] = float('-inf')
|
| 275 |
+
else:
|
| 276 |
+
eos_boost = (generated_text_tokens - min_length) * 0.15
|
| 277 |
+
logits[0, eos_token_id] += eos_boost
|
| 278 |
+
|
| 279 |
+
# Temperature
|
| 280 |
+
logits = logits / temperature
|
| 281 |
+
|
| 282 |
+
# Top-k
|
| 283 |
+
if top_k > 0:
|
| 284 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
| 285 |
+
logits[logits < v[:, [-1]]] = float('-inf')
|
| 286 |
+
|
| 287 |
+
# Top-p
|
| 288 |
+
if top_p < 1.0:
|
| 289 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 290 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 291 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 292 |
+
sorted_indices_to_remove[:, 1:] = sorted_indices_to_remove[:, :-1].clone()
|
| 293 |
+
sorted_indices_to_remove[:, 0] = 0
|
| 294 |
+
indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
|
| 295 |
+
logits[indices_to_remove] = float('-inf')
|
| 296 |
+
|
| 297 |
+
# Entropy threshold
|
| 298 |
+
probs = F.softmax(logits, dim=-1)
|
| 299 |
+
if use_entropy_threshold:
|
| 300 |
+
entropy = -(probs * torch.log(probs + 1e-10)).sum(dim=-1)
|
| 301 |
+
if entropy.item() > max_entropy:
|
| 302 |
+
temperature = max(temperature * 0.7, 0.3)
|
| 303 |
+
logits = logits / temperature
|
| 304 |
+
probs = F.softmax(logits, dim=-1)
|
| 305 |
+
|
| 306 |
+
# Sample
|
| 307 |
+
next_token = torch.multinomial(probs, num_samples=1)
|
| 308 |
+
|
| 309 |
+
if next_token.item() == eos_token_id and generated_text_tokens >= min_length:
|
| 310 |
+
break
|
| 311 |
+
|
| 312 |
+
generated = torch.cat([generated, next_token], dim=1)
|
| 313 |
+
generated_text_tokens += 1
|
| 314 |
+
|
| 315 |
+
return generated
|
| 316 |
+
|
| 317 |
+
def count_parameters(self):
|
| 318 |
+
return sum(p.numel() for p in self.parameters() if p.requires_grad)
|