-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathblt_model.py
More file actions
2315 lines (1912 loc) · 95.1 KB
/
Copy pathblt_model.py
File metadata and controls
2315 lines (1912 loc) · 95.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# blt_model_sin_cache_con_debug.py
import torch
# Habilitar Flash SDP explícitamente
torch.backends.cuda.enable_flash_sdp(enabled=True)
# Verificar si está habilitado
# # print(f"Flash SDP habilitado: {torch.backends.cuda.flash_sdp_enabled()}")
import torch.nn as nn
import torch.nn.functional as F
import math
from dataclasses import dataclass
from typing import Optional, Dict, List
# =============================================================================
# BLOQUES BÁSICOS
# =============================================================================
class RMSNorm(nn.Module):
"""
Normalización RMS (Root Mean Square) utilizada como alternativa
a LayerNorm. Escala la norma RMS de cada vector a 1.
Args:
dim (int): Dimensión del vector de entrada a normalizar
eps (float, opcional): Valor pequeño para evitar división por cero. Por defecto 1e-6
Atributos:
scale (float): Factor de escala precomputado basado en la dimensión
g (nn.Parameter): Parámetro aprendible para reescalar la salida normalizada
eps (float): Epsilon para estabilidad numérica
"""
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.scale = dim ** 0.5
self.g = nn.Parameter(torch.ones(dim))
self.eps = eps
# Inicialización con pequeño offset para evitar ceros exactos
with torch.no_grad():
self.g.add_(self.eps)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Aplica normalización RMS al tensor de entrada.
Args:
x (torch.Tensor): Tensor de entrada de shape (..., dim)
Returns:
torch.Tensor: Tensor normalizado del mismo shape que la entrada
Notas:
- Añade epsilon tanto al numerador como al denominador para estabilidad
- Realiza validaciones para detectar valores inválidos
"""
# Añadir pequeño offset para evitar ceros exactos
x = x + self.eps
# Cálculo de norma con epsilon para estabilidad
norm = torch.norm(x + self.eps, dim=-1, keepdim=True) * self.scale
norm = norm + self.eps # Prevenir división por cero
# Normalización con validación
out = (x / norm) * self.g
return out
class RotaryEmbedding(nn.Module):
"""
Implementación de Rotary Embeddings para inyectar información posicional
en las consultas y claves de la atención.
"""
def __init__(self, dim, theta=500000):
super().__init__()
self.dim = dim
self.theta = theta
inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
self.register_buffer('inv_freq', inv_freq)
def forward(self, positions):
"""
Calcula cosenos y senos correspondientes a las frecuencias rotatorias.
"""
# print("RotaryEmbedding - Positions shape:", positions.shape)
positions = positions.unsqueeze(-1)
freqs = positions.float() * self.inv_freq.unsqueeze(0)
freqs_cos = torch.cos(freqs)
freqs_sin = torch.sin(freqs)
return freqs_cos, freqs_sin
def rotate_queries_and_keys(self, q, k, positions):
"""
Aplica la rotación de RoPE a queries (q) y keys (k).
"""
# print("RotaryEmbedding - rotate Q/K shapes:", q.shape, k.shape)
freqs_cos, freqs_sin = self.forward(positions)
batch_size, num_heads, seq_length, head_dim = q.shape
dim_half = head_dim // 2
freqs_cos = freqs_cos[:seq_length, :dim_half]
freqs_sin = freqs_sin[:seq_length, :dim_half]
freqs_cos = freqs_cos.unsqueeze(0).unsqueeze(0)
freqs_sin = freqs_sin.unsqueeze(0).unsqueeze(0)
q1, q2 = q[..., :dim_half], q[..., dim_half:]
k1, k2 = k[..., :dim_half], k[..., dim_half:]
q_rotate = torch.cat([
q1 * freqs_cos - q2 * freqs_sin,
q2 * freqs_cos + q1 * freqs_sin
], dim=-1)
k_rotate = torch.cat([
k1 * freqs_cos - k2 * freqs_sin,
k2 * freqs_cos + k1 * freqs_sin
], dim=-1)
# print("RotaryEmbedding - Rotated Q/K shapes:", q_rotate.shape, k_rotate.shape)
return q_rotate, k_rotate
class HeadwiseNorm(nn.Module):
"""
Normalización específica por cabeza para atención multi-cabeza.
Normaliza cada cabeza de atención de forma independiente.
"""
def __init__(self, num_heads, head_dim, eps=1e-5):
super().__init__()
self.num_heads = num_heads
self.head_dim = head_dim
self.eps = eps
self.gamma = nn.Parameter(torch.ones(num_heads, 1, 1))
self.beta = nn.Parameter(torch.zeros(num_heads, 1, 1))
def forward(self, x):
"""
Input: x de forma [batch_size, num_heads, seq_length, head_dim].
"""
# print("HeadwiseNorm - Input shape:", x.shape)
mean = x.mean(dim=-1, keepdim=True)
var = x.var(dim=-1, keepdim=True, unbiased=False)
x_norm = (x - mean) / torch.sqrt(var + self.eps)
out = self.gamma * x_norm + self.beta
# print("HeadwiseNorm - Output shape:", out.shape)
return out
# =============================================================================
# ATENCIÓN MULTI-CABEZA
# =============================================================================
class MultiHeadAttention(nn.Module):
"""
MultiHeadAttention con múltiples niveles de dropout y Rotary Embeddings.
"""
def __init__(self, config):
super().__init__()
self.num_heads = config.num_heads
self.hidden_size = config.hidden_size
self.head_dim = self.hidden_size // self.num_heads
assert self.head_dim % 2 == 0, "head_dim must be even for RoPE"
assert self.head_dim * self.num_heads == self.hidden_size, "hidden_size must be divisible by num_heads"
self.q_proj = nn.Linear(config.hidden_size, config.hidden_size)
self.k_proj = nn.Linear(config.hidden_size, config.hidden_size)
self.v_proj = nn.Linear(config.hidden_size, config.hidden_size)
self.o_proj = nn.Linear(config.hidden_size, config.hidden_size)
# Módulos adicionales
self.rotary = RotaryEmbedding(self.head_dim)
self.norm = RMSNorm(config.hidden_size)
self.head_norm = HeadwiseNorm(num_heads=self.num_heads, head_dim=self.head_dim)
# Parámetros de dropout
self.attention_dropout = config.attention_dropout
self.resid_dropout = nn.Dropout(config.resid_dropout)
self.proj_dropout = nn.Dropout(config.resid_dropout)
self.lambda_dropout = nn.Dropout(self.attention_dropout)
# Inicializar parámetros relacionados con lambda
self._initialize_lambda_parameters(config)
def _initialize_lambda_parameters(self, config):
layer_idx = getattr(config, 'layer_idx', 1)
base_lambda = 0.8 - 0.6 * math.exp(-0.3 * (layer_idx - 1))
self.lambda_init = nn.Parameter(torch.full((1, self.num_heads), base_lambda))
dim_scale = 0.01 / math.sqrt(self.hidden_size)
self.lambda_q1 = nn.Parameter(torch.randn(1, self.num_heads, self.head_dim) * dim_scale)
self.lambda_k1 = nn.Parameter(torch.randn(1, self.num_heads, self.head_dim) * dim_scale)
self.lambda_q2 = nn.Parameter(torch.randn(1, self.num_heads, self.head_dim) * dim_scale)
self.lambda_k2 = nn.Parameter(torch.randn(1, self.num_heads, self.head_dim) * dim_scale)
def compute_lambda(self):
qk1 = torch.sum(self.lambda_dropout(self.lambda_q1) * self.lambda_k1, dim=-1)
qk2 = torch.sum(self.lambda_dropout(self.lambda_q2) * self.lambda_k2, dim=-1)
lambda_val = torch.exp(qk1) - torch.exp(qk2) + self.lambda_init
return torch.clamp(lambda_val, min=0.0, max=1.0)
def forward(self, x, mask=None, positions=None, is_causal=False):
# print("\n[MultiHeadAttention] - Input X shape:", x.shape)
batch_size, seq_length, _ = x.size()
x_norm = self.norm(x)
# print("[MultiHeadAttention] - After RMSNorm X shape:", x_norm.shape)
q = self.q_proj(x_norm)
k = self.k_proj(x_norm)
v = self.v_proj(x_norm)
# print("[MultiHeadAttention] - Q/K/V projected shapes:", q.shape, k.shape, v.shape)
def reshape_to_heads(tensor):
return tensor.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
q, k, v = reshape_to_heads(q), reshape_to_heads(k), reshape_to_heads(v)
# print("[MultiHeadAttention] - Q/K/V reshaped to heads:", q.shape, k.shape, v.shape)
# Dividir las cabezas en dos grupos
q1, q2 = torch.chunk(q, 2, dim=1)
k1, k2 = torch.chunk(k, 2, dim=1)
v1, v2 = torch.chunk(v, 2, dim=1)
# Aplicar RoPE
q1, k1 = self.rotary.rotate_queries_and_keys(q1, k1, positions)
q2, k2 = self.rotary.rotate_queries_and_keys(q2, k2, positions)
# Dropout tras RoPE
q1, k1 = self.proj_dropout(q1), self.proj_dropout(k1)
q2, k2 = self.proj_dropout(q2), self.proj_dropout(k2)
if mask is not None:
# Convertir mask a boolean con dropout
mask = self.resid_dropout(mask.float()).bool()
# Atención
attn1 = F.scaled_dot_product_attention(
q1, k1, v1, dropout_p=self.attention_dropout, is_causal=is_causal
)
attn2 = F.scaled_dot_product_attention(
q2, k2, v2, dropout_p=self.attention_dropout, is_causal=is_causal
)
# print("[MultiHeadAttention] - attn1/attn2 shapes:", attn1.shape, attn2.shape)
attn1 = self.proj_dropout(attn1)
attn2 = self.proj_dropout(attn2)
# Calcular lambda para combinar
lambda_val = self.compute_lambda()[:, :self.num_heads//2].unsqueeze(-1).unsqueeze(-1)
out = attn1 - lambda_val * attn2
# Concatenar cabezas
out = torch.cat([out, out], dim=1)
# print("[MultiHeadAttention] - Concat attn shape:", out.shape)
# Normalización por cabeza y dropout posterior
out = self.head_norm(out)
out = self.resid_dropout(out)
out = out.transpose(1, 2).contiguous().view(batch_size, seq_length, self.hidden_size)
out = self.o_proj(out)
out = self.resid_dropout(out)
# print("[MultiHeadAttention] - Output shape:", out.shape)
return out
class CrossAttention(nn.Module):
"""
Atención cruzada (CrossAttention) para mezclar el contexto externo (context)
con la entrada actual (x).
"""
def __init__(self, config):
super().__init__()
self.num_heads = config.num_heads
self.hidden_size = config.hidden_size
self.head_dim = self.hidden_size // self.num_heads
self.q_proj = nn.Linear(config.hidden_size, config.hidden_size)
self.k_proj = nn.Linear(config.hidden_size, config.hidden_size)
self.v_proj = nn.Linear(config.hidden_size, config.hidden_size)
self.o_proj = nn.Linear(config.hidden_size, config.hidden_size)
self.norm = RMSNorm(config.hidden_size)
self.dropout = nn.Dropout(config.attention_dropout)
self.proj_dropout = nn.Dropout(config.resid_dropout)
def forward(self, x, context, patch_mask=None):
# print("\n[CrossAttention] - Input X shape:", x.shape)
batch_size, seq_length, _ = x.size()
context_length = context.size(1)
x_norm = self.norm(x)
# print("[CrossAttention] - After RMSNorm X shape:", x_norm.shape)
q = self.q_proj(x_norm)
k = self.k_proj(context)
v = self.v_proj(context)
# print("[CrossAttention] - Q/K/V shapes:", q.shape, k.shape, v.shape)
q = self.proj_dropout(q)
k = self.proj_dropout(k)
v = self.proj_dropout(v)
q = q.reshape(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
k = k.reshape(batch_size, context_length, self.num_heads, self.head_dim).transpose(1, 2)
v = v.reshape(batch_size, context_length, self.num_heads, self.head_dim).transpose(1, 2)
# print("[CrossAttention] - Q/K/V reshaped to heads:", q.shape, k.shape, v.shape)
attn_mask = None
if patch_mask is not None:
attn_mask = (patch_mask == 0)
out = F.scaled_dot_product_attention(
q, k, v,
attn_mask=attn_mask,
dropout_p=self.dropout.p if self.training else 0.0,
is_causal=False
)
# print("[CrossAttention] - Attn output shape:", out.shape)
out = self.dropout(out)
out = out.transpose(1, 2).reshape(batch_size, seq_length, self.hidden_size)
out = self.o_proj(out)
out = self.dropout(out)
# print("[CrossAttention] - Output shape:", out.shape)
return out
class FeedForward(nn.Module):
"""
Capa FeedForward con activación SwiGLU y múltiples dropouts.
"""
def __init__(self, config):
super().__init__()
self.w1 = nn.Linear(config.hidden_size, config.intermediate_size)
self.w2 = nn.Linear(config.intermediate_size, config.hidden_size)
self.w3 = nn.Linear(config.hidden_size, config.intermediate_size)
self.norm = RMSNorm(config.hidden_size)
self.dropout = nn.Dropout(config.resid_dropout)
self.activation_dropout = nn.Dropout(config.resid_dropout)
def forward(self, x):
# print("\n[FeedForward] - Input shape:", x.shape)
x = self.norm(x)
# print("[FeedForward] - After RMSNorm shape:", x.shape)
swish = F.silu(self.w1(x))
gate = self.w3(x)
x = swish * gate
x = self.activation_dropout(x)
x = self.w2(x)
x = self.dropout(x)
# print("[FeedForward] - Output shape:", x.shape)
return x
class EncoderLayer(nn.Module):
"""
Capa de encoder que combina self-attention, cross-attention (opcional)
y feed-forward.
"""
def __init__(self, config):
super().__init__()
self.self_attn = MultiHeadAttention(config)
self.cross_attn = CrossAttention(config)
self.feed_forward = FeedForward(config)
self.dropout = nn.Dropout(config.resid_dropout)
def forward(self, x, cross_context=None, self_mask=None, cross_mask=None, positions=None):
# print("\n[EncoderLayer] - Input shape:", x.shape)
h = x + self.self_attn(x, mask=self_mask, positions=positions, is_causal=False)
# print("[EncoderLayer] - After Self-Attn shape:", h.shape)
h = self.dropout(h)
if cross_context is not None:
h = h + self.cross_attn(h, cross_context, cross_mask)
# print("[EncoderLayer] - After Cross-Attn shape:", h.shape)
h = self.dropout(h)
out = h + self.feed_forward(h)
# print("[EncoderLayer] - After FeedForward shape:", out.shape)
out = self.dropout(out)
return out
class DecoderLayer(nn.Module):
"""
Capa de decoder con cross-attention, self-attention con enmascaramiento causal
y feed-forward.
"""
def __init__(self, config):
super().__init__()
self.cross_attn = CrossAttention(config)
self.self_attn = MultiHeadAttention(config)
self.feed_forward = FeedForward(config)
self.dropout = nn.Dropout(config.resid_dropout)
def forward(self, x, encoder_output, self_mask=None, cross_mask=None, positions=None):
# print("\n[DecoderLayer] - Input shape:", x.shape)
h = x + self.cross_attn(x, encoder_output, cross_mask)
# print("[DecoderLayer] - After Cross-Attn shape:", h.shape)
h = self.dropout(h)
h = h + self.self_attn(h, self_mask, positions, is_causal=True)
# print("[DecoderLayer] - After Self-Attn shape:", h.shape)
h = self.dropout(h)
out = h + self.feed_forward(h)
# print("[DecoderLayer] - After FeedForward shape:", out.shape)
out = self.dropout(out)
return out
# =============================================================================
# EMBEDDINGS A NIVEL DE BYTE
# =============================================================================
import torch
import torch.nn as nn
class ByteEmbedding(nn.Module):
"""
Genera embeddings a nivel de byte combinando embeddings individuales con n-gram embeddings
mediante concatenación y proyección lineal.
Esta clase implementa un sistema avanzado de embeddings que:
1. Procesa bytes individuales y n-gramas (3 a 8 bytes)
2. Utiliza gating estocástico con ruido Gaussiano para mejorar la robustez
3. Implementa gates residuales aprendibles
4. Concatena y proyecta embeddings en lugar de sumarlos
5. Aplica múltiples capas de dropout para regularización
La arquitectura está diseñada para maximizar la capacidad expresiva mientras
mantiene la robustez y la capacidad de generalización.
"""
def __init__(self, config):
"""
Inicializa la capa ByteEmbedding.
Args:
config (Namespace): Objeto de configuración que debe contener:
- hidden_size (int): Dimensión de los embeddings
- ngram_vocab_size (int): Tamaño del vocabulario para cada n-grama
- resid_dropout (float): Tasa de dropout para embeddings y gating
- noise_std (float): Desviación estándar del ruido Gaussiano
"""
super().__init__()
# Embedding para bytes individuales (256 posibles valores)
self.byte_embeddings = nn.Embedding(256, config.hidden_size)
# Lista de embeddings para n-gramas de tamaño 3 a 8
self.ngram_hash_embeddings = nn.ModuleList([
nn.Embedding(config.ngram_vocab_size, config.hidden_size)
for _ in range(6) # n-gramas de tamaño 3 a 8
])
# Proyecciones lineales para después de la concatenación
self.projections = nn.ModuleList([
nn.Linear(config.hidden_size * 2, config.hidden_size)
for _ in range(6)
])
# Normalización por capa aplicada al final
self.layer_norm = nn.LayerNorm(config.hidden_size)
# Escala adaptativa de ruido
self.noise_scale = nn.Parameter(torch.tensor(0.09))
# Parámetros aprendibles de gating para cada tamaño de n-grama (3 a 8)
self.ngram_gates = nn.Parameter(torch.ones(6))
# Gates residuales aprendibles
self.residual_gates = nn.ModuleList([
nn.Sequential(
nn.Linear(config.hidden_size * 2, config.hidden_size),
nn.LayerNorm(config.hidden_size),
nn.GELU(),
nn.Linear(config.hidden_size, 1),
nn.Sigmoid()
) for _ in range(6)
])
# Dropouts
self.dropout = nn.Dropout(config.resid_dropout) # Dropout en embeddings base
self.gate_dropout = nn.Dropout(config.resid_dropout) # Dropout en gates estocásticos
self.residual_dropout = nn.Dropout(config.resid_dropout) # Dropout en embeddings expandidos
self.residual_gate_dropout = nn.Dropout(config.resid_dropout) # Dropout en gates residuales
self.projection_dropout = nn.Dropout(config.resid_dropout) # Dropout post-proyección
def compute_ngram_hash(self, bytes_sequence, n):
"""
Calcula índices de hash para cada n-grama en la secuencia.
Implementa un esquema de hashing que:
1. Extrae n-gramas consecutivos
2. Calcula hashes usando pesos exponenciales
3. Aplica factores de escala adaptativos
4. Utiliza offsets primos para mejor distribución
Args:
bytes_sequence (torch.Tensor): Tensor de bytes [batch_size, seq_length]
n (int): Tamaño del n-grama (3-8)
Returns:
torch.Tensor: Índices de hash [batch_size, seq_length - n + 1]
"""
device = bytes_sequence.device
batch_size, seq_length = bytes_sequence.shape
if seq_length < n:
return torch.empty((batch_size, 0), dtype=torch.long, device=device)
# Extraer n-gramas: [B, (seq_length - n + 1), n]
ngrams = bytes_sequence.unfold(dimension=1, size=n, step=1)
# Factores adaptativos basados en n
scale_factor = 1.0 - (n - 3) * 0.1 # Decrece con n
offset = ((n - 3) * 37) % 256 # Offset primo
# Pesos exponenciales para el hash
exponents = torch.arange(n, device=device).float()
weights = (256 ** exponents).unsqueeze(0).unsqueeze(0) # [1,1,n]
# Cálculo del hash
hash_values = (ngrams.float() * weights).sum(dim=-1) # [B, seq_length-n+1]
hash_values = hash_values * scale_factor + offset
hash_values = hash_values.long()
# Ajustar al tamaño del vocabulario
vocab_size = self.ngram_hash_embeddings[n-3].num_embeddings
return hash_values % vocab_size
def forward(self, bytes_input):
"""
Procesa la secuencia de bytes para generar embeddings enriquecidos.
El proceso incluye:
1. Generación de embeddings base
2. Procesamiento de n-gramas
3. Aplicación de gates estocásticos y residuales
4. Concatenación y proyección de embeddings
5. Normalización final
Args:
bytes_input (torch.Tensor): Tensor de bytes [batch_size, seq_length]
Returns:
torch.Tensor: Embeddings procesados [batch_size, seq_length, hidden_size]
"""
device = bytes_input.device
batch_size, seq_length = bytes_input.shape
# Embeddings base
embeds = self.byte_embeddings(bytes_input).float()
embeds = self.dropout(embeds)
# Escala de ruido adaptativa
current_noise_scale = torch.sigmoid(self.noise_scale)
# Procesamiento de n-gramas
for i, n in enumerate(range(3, 9)):
if seq_length < n:
continue
# Generar embeddings de n-gramas
ngram_hashes = self.compute_ngram_hash(bytes_input, n)
ngram_embeds = self.ngram_hash_embeddings[i](ngram_hashes)
# Gate estocástico con ruido
noise = torch.randn_like(self.ngram_gates[i]) * current_noise_scale
alpha_n = self.ngram_gates[i] + noise
alpha_n = self.gate_dropout(alpha_n)
alpha_n = torch.relu(alpha_n)
# Aplicar gate y normalización
gated_embeds = (ngram_embeds / n) * alpha_n
# Gate residual
gate_input = torch.cat([
embeds[:, :seq_length - n + 1],
gated_embeds
], dim=-1)
gate_input = self.residual_gate_dropout(gate_input)
residual_gate = self.residual_gates[i](gate_input)
residual_gate = self.residual_gate_dropout(residual_gate)
# Concatenar y proyectar
concatenated = torch.cat([
embeds[:, :seq_length - n + 1],
gated_embeds * residual_gate
], dim=-1)
projected = self.projections[i](concatenated)
embeds[:, :seq_length - n + 1, :] = projected
# Normalización final
embeds = self.layer_norm(embeds)
return embeds
# =============================================================================
# MODELOS DE ENCODER Y DECODER
# =============================================================================
class LocalEncoder(nn.Module):
"""
Encoder local que procesa los bytes de forma detallada.
"""
def __init__(self, config):
super().__init__()
self.byte_embeddings = ByteEmbedding(config)
self.embedding_dropout = nn.Dropout(config.resid_dropout)
self.layers = nn.ModuleList([EncoderLayer(config) for _ in range(config.encoder_layers)])
self.dropout = nn.Dropout(config.resid_dropout)
def forward(self, bytes_input, patch_boundaries=None):
# print("\n[LocalEncoder] - Input shape:", bytes_input.shape)
h = self.byte_embeddings(bytes_input)
# print("[LocalEncoder] - After ByteEmbedding shape:", h.shape)
h = self.embedding_dropout(h)
positions = torch.arange(bytes_input.size(1), device=bytes_input.device)
for idx, layer in enumerate(self.layers):
# print(f"[LocalEncoder] - Passing through EncoderLayer {idx}")
h = layer(h, positions=positions)
# print(f"[LocalEncoder] - EncoderLayer {idx} output shape:", h.shape)
h = self.dropout(h)
# print("[LocalEncoder] - Final output shape:", h.shape)
return h
class GlobalTransformer(nn.Module):
"""
Procesa la información a nivel de parches con atención global.
Optimizado internamente para reducir redundancias y uso de VRAM,
SIN añadir nuevas caches ni eliminar la lógica principal.
Conserva la misma interfaz y atributos para compatibilidad.
"""
def __init__(self, config):
super().__init__()
self.config = config
self.expansion_rate = getattr(config, 'expansion_rate', 2)
# ------------------------------------------------------------
# Submódulos principales: (se mantienen igual para compatibilidad)
# ------------------------------------------------------------
self.layers = nn.ModuleList([
EncoderLayer(config) for _ in range(config.global_layers)
])
# Sistemas de Dropout
self.dropout = nn.Dropout(config.resid_dropout)
self.adaptive_dropout = nn.Dropout(0.0855)
self.gate_dropout = nn.Dropout(0.0855)
self.mem_dropout = nn.Dropout(0.0855)
self.skip_dropout = nn.Dropout(0.0855)
# Normalizaciones
self.layer_norms = nn.ModuleList([
RMSNorm(config.hidden_size, eps=1e-6)
for _ in range(config.global_layers)
])
self.input_norm = RMSNorm(config.hidden_size, eps=1e-6)
self.output_norm = RMSNorm(config.hidden_size, eps=1e-6)
# Normalizaciones específicas
self.pre_width_norm = RMSNorm(config.hidden_size, eps=1e-6)
self.post_width_norm = (
RMSNorm(config.n_states, eps=1e-6) if hasattr(config, 'n_states') else None
)
self.post_alpha_norm = (
RMSNorm(config.n_states, eps=1e-6) if hasattr(config, 'n_states') else None
)
self.pre_gate_norm = RMSNorm(config.hidden_size, eps=1e-6)
self.post_laurel_norm = RMSNorm(config.hidden_size, eps=1e-6)
self.pre_memory_norm = RMSNorm(config.hidden_size, eps=1e-6)
self.post_memory_norm = RMSNorm(config.hidden_size, eps=1e-6)
self.post_combined_norm = RMSNorm(config.hidden_size, eps=1e-6)
# Skip Gates
self.skip_gates = nn.ModuleList([
nn.Sequential(
nn.Linear(config.hidden_size * 2, config.hidden_size),
nn.Dropout(0.0855),
nn.Sigmoid()
) for _ in range(config.global_layers)
])
# LAUREL
self.laurel_alphas = nn.Parameter(torch.ones(config.global_layers))
self.laurel_g = nn.ModuleList([
nn.Linear(config.hidden_size, config.hidden_size)
for _ in range(config.global_layers)
])
# Pesos Adaptativos
self.adaptive_weights = nn.Parameter(torch.ones(config.global_layers))
# Hyper-Connections
self.hyper_static_beta = nn.Parameter(torch.ones(self.expansion_rate))
init_alpha0 = torch.zeros((config.global_layers, self.expansion_rate, 1))
for i in range(config.global_layers):
init_alpha0[i, i % self.expansion_rate, 0] = 1.0
self.hyper_static_alpha = nn.Parameter(
torch.cat([
init_alpha0,
torch.eye(self.expansion_rate).unsqueeze(0).repeat(config.global_layers, 1, 1)
], dim=2)
)
hidden_size = config.hidden_size
self.hyper_dynamic_alpha_fn = nn.Parameter(
torch.zeros((config.global_layers, hidden_size, self.expansion_rate + 1))
)
self.hyper_dynamic_alpha_scale = nn.Parameter(
torch.ones(config.global_layers) * 0.01
)
self.hyper_dynamic_beta_fn = nn.Parameter(
torch.zeros((config.global_layers, hidden_size))
)
self.hyper_dynamic_beta_scale = nn.Parameter(
torch.ones(config.global_layers) * 0.01
)
# Memoria Jerárquica
self.hierarchical_mem = nn.Parameter(
torch.zeros(config.global_layers, config.hidden_size) + 1e-6
)
self.mem_gate = nn.Sequential(
nn.Linear(config.hidden_size * 2, config.hidden_size),
nn.Dropout(0.085),
nn.Sigmoid()
)
# ----------------------------------------------------------------
# Métodos internos para skip+laurel, hyper-connections y memoria
# Se reorganizan para optimizar la implementación, sin añadir caches.
# ----------------------------------------------------------------
def _apply_skip_and_laurel(self, x, residual, layer_output, layer_idx):
"""
Mezcla la salida de la capa (layer_output) con la entrada (x, residual)
mediante gates adaptativos (skip_gates) y el mecanismo LAUREL.
"""
# Normalizaciones fusionadas
norm_x = self.layer_norms[layer_idx](x) * 0.1
norm_r = self.layer_norms[layer_idx](residual) * 0.1
gx = self.pre_gate_norm(norm_x) * 0.1
gr = self.pre_gate_norm(norm_r) * 0.1
# Gate input
gate_input = torch.cat([gx, gr], dim=-1) # (B, S, 2D)
gate_val = self.skip_gates[layer_idx](gate_input) # Sigmoid
gate_val = self.gate_dropout(gate_val)
# Pesos adaptativos
aw = torch.sigmoid(self.adaptive_weights[layer_idx]) * 0.1
aw = aw.view(1, 1, 1)
weighted_r = aw * gate_val * norm_r
weighted_r = self.skip_dropout(weighted_r)
# LAUREL
alpha = torch.sigmoid(self.laurel_alphas[layer_idx]) * 0.1
alpha = self.adaptive_dropout(alpha)
g_x = self.laurel_g[layer_idx](x) * 0.1
g_x = self.skip_dropout(g_x)
laurel_out = layer_output * alpha + g_x
laurel_out = self.post_laurel_norm(laurel_out) * 0.1
combined_output = laurel_out + weighted_r
return combined_output
def _apply_hyper_connections(self, x, hyper_h, layer_idx):
"""
Mezcla la señal x con el tensor hyper_h a través de matrices alpha y beta,
manteniendo la lógica original y sin añadir cache externo.
"""
# Normalizar hyper_h
norm_h = self.layer_norms[layer_idx](hyper_h)
B, S, N, D = norm_h.shape # N = n_states (expansion_rate)
# Flatten + pre_width_norm
h_flat = norm_h.reshape(B * S * N, D)
h_flat = self.pre_width_norm(h_flat)
# dynamic alpha
alpha_fn = self.hyper_dynamic_alpha_fn[layer_idx][:, :N] # (D, N)
wc_weight = torch.matmul(h_flat, alpha_fn)
if self.post_width_norm is not None:
wc_weight = self.post_width_norm(wc_weight.reshape(-1, N))
wc_weight = wc_weight.reshape(B, S, N, N)
wc_weight = torch.tanh(wc_weight)
alpha_scale = self.hyper_dynamic_alpha_scale[layer_idx].view(1, 1, 1, 1)
dynamic_alpha = wc_weight * alpha_scale
static_alpha = self.hyper_static_alpha[layer_idx][:N, :N]
static_alpha = static_alpha.view(1, 1, N, N).expand(B, S, -1, -1)
alpha = dynamic_alpha + static_alpha
if self.post_alpha_norm is not None:
alpha_view = alpha.reshape(-1, N)
alpha_view = self.post_alpha_norm(alpha_view)
alpha = alpha_view.reshape(B, S, N, N)
# dynamic beta
beta_fn = self.hyper_dynamic_beta_fn[layer_idx] # (D,)
dc_weight = torch.matmul(norm_h, beta_fn.view(-1, 1)).squeeze(-1)
dc_weight = torch.tanh(dc_weight)
beta_scale = self.hyper_dynamic_beta_scale[layer_idx].view(1, 1, 1)
dynamic_beta = dc_weight * beta_scale
static_beta = self.hyper_static_beta[:N].view(1, 1, -1)
beta = dynamic_beta + static_beta
# Mezcla final
# alpha: (B,S,N,N), hyper_h: (B,S,N,D)
mix_h = torch.matmul(alpha, hyper_h)
x_expanded = x.unsqueeze(2).expand(-1, -1, N, -1)
depth_conn = x_expanded * beta.unsqueeze(-1)
return mix_h + depth_conn
def _apply_hierarchical_memory(self, x, layer_idx, batch_size):
"""
Integra la memoria jerárquica de la capa layer_idx,
manteniendo la lógica original sin añadir cachés.
"""
# Sumar offset y reescalar
x = (x + 1e-6) * 0.1
x = self.pre_memory_norm(x) + 1e-6
# Extraer y expandir la memoria para esta capa
mem = self.hierarchical_mem[layer_idx:layer_idx+1] + 1e-6
mem = mem.unsqueeze(0).expand(batch_size, x.size(1), -1)
mem = self.mem_dropout(mem)
# Calcular gate
mem_input = torch.cat([x, mem], dim=-1)
mem_gate_val = self.mem_gate(mem_input) * 0.1 + 1e-6
memory_output = mem_gate_val * mem + 1e-6
memory_output = self.post_memory_norm(memory_output) * 0.1 + 1e-6
memory_output = self.mem_dropout(memory_output) * 0.1
result = x + memory_output
if torch.isnan(result).any():
result = torch.nan_to_num(result, nan=1e-6)
return result
# ----------------------------------------------------------------
# Forward principal: igual firma y pasos, sin añadir caches extras
# ----------------------------------------------------------------
def forward(self,
patch_embeddings: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None
) -> torch.Tensor:
"""
Mismo forward y firma, sin cache adicional.
"""
batch_size = patch_embeddings.size(0)
# Normalización de entrada + dropout
h = self.input_norm(patch_embeddings)
h = self.dropout(h)
# Expansión "virtual" para hyper-connections
hyper_h = h.unsqueeze(2).expand(-1, -1, self.expansion_rate, -1)
positions = torch.arange(patch_embeddings.size(1), device=patch_embeddings.device)
for idx, layer in enumerate(self.layers):
# Paso por la capa
prev_h = self.dropout(h)
layer_out = layer(h, self_mask=attention_mask, positions=positions)
# Combinación Skip & Laurel
combined_out = self._apply_skip_and_laurel(prev_h, prev_h, layer_out, idx)
# Hyper-connections
hyper_h = self._apply_hyper_connections(combined_out, hyper_h, idx)
# Suma con la media de hyper_h
combined_features = combined_out + hyper_h.mean(dim=2)
combined_features = self.post_combined_norm(combined_features)
# Memoria jerárquica
h = self._apply_hierarchical_memory(combined_features, idx, batch_size)
h = self.dropout(h)
# Normalización de salida + dropout
h = self.output_norm(h)
h = self.dropout(h)
return h
class LocalDecoder(nn.Module):
"""
Decoder local que reconvierte las representaciones latentes en logits de bytes.
"""
def __init__(self, config):
super().__init__()
self.layers = nn.ModuleList([DecoderLayer(config) for _ in range(config.decoder_layers)])
self.byte_predictor = nn.Linear(config.hidden_size, 256)
self.dropout = nn.Dropout(config.resid_dropout)
def forward(self, encoded_bytes, global_output, byte_mask=None, cross_mask=None):
# print("\n[LocalDecoder] - Input encoded_bytes shape:", encoded_bytes.shape)
h = encoded_bytes
positions = torch.arange(encoded_bytes.size(1), device=encoded_bytes.device)
for idx, layer in enumerate(self.layers):
# print(f"[LocalDecoder] - Passing through DecoderLayer {idx}")
h = layer(h, global_output, self_mask=byte_mask, cross_mask=cross_mask, positions=positions)
# print(f"[LocalDecoder] - DecoderLayer {idx} output shape:", h.shape)
h = self.dropout(h)
logits = self.byte_predictor(h)
# print("[LocalDecoder] - Final logits shape:", logits.shape)
return logits
# =============================================================================
# MODELO DE ENTROPÍA (SIN USO DE CACHÉ)
# =============================================================================
class EntropyLM(nn.Module):
"""
Modelo de lenguaje basado en entropía dual con análisis local y global.
Este modelo implementa un sistema de entropía dual que:
1. Analiza patrones locales en ventanas pequeñas.
2. Captura contexto global en una dimensión reducida.
3. Combina ambas medidas de forma adaptativa mediante pesos aprendidos.
El modelo utiliza skip connections y gates aprendibles para mejorar
la eficiencia y el flujo de información, sin necesidad de cache adicional.
"""
# ========================================================
# SUBMÓDULOS INTERNOS
# ========================================================
class AdaptiveWaveletLayer(nn.Module):
"""
Capa optimizada de análisis global usando wavelets neuronales adaptativos.
Implementa procesamiento por lotes vectorizado sin uso de caché.
"""
def __init__(self, hidden_size, global_size, num_wavelets=8, dropout=0.1, chunk_size=1024):
super().__init__()
self.hidden_size = hidden_size
self.global_size = global_size
self.num_wavelets = num_wavelets
self.chunk_size = chunk_size
# Wavelets optimizados para procesamiento por lotes
self.mother_wavelets = nn.Parameter(
torch.randn(1, num_wavelets, hidden_size, 1) * 0.02
)
# Escalas con broadcasting optimizado
self.scales = nn.Parameter(torch.ones(1, num_wavelets, 1, 1))
# Mixer optimizado con menos parámetros y mejor regularización
self.coeff_mixer = nn.Sequential(
nn.Linear(num_wavelets, hidden_size // 2),
nn.LayerNorm(hidden_size // 2),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(hidden_size // 2, hidden_size)
)
# Proyección con skip connection residual
self.output_proj = nn.Sequential(
nn.LayerNorm(hidden_size),
nn.Linear(hidden_size, global_size),
nn.Dropout(dropout)
)
# MultiheadAttention optimizada
self.num_heads = 4
self.head_dim = hidden_size // self.num_heads
self.scale = self.head_dim ** -0.5
# Proyecciones para Q, K, V
self.q_proj = nn.Linear(hidden_size, hidden_size, bias=False)
self.k_proj = nn.Linear(hidden_size, hidden_size, bias=False)
self.v_proj = nn.Linear(hidden_size, hidden_size, bias=False)
self.out_proj = nn.Linear(hidden_size, hidden_size, bias=False)
self.attention_dropout = nn.Dropout(dropout)
def _scaled_dot_product_attention(self, q, k, v, mask=None):
"""Implementación optimizada de atención sin caché."""
attn_weights = torch.matmul(q, k.transpose(-2, -1)) * self.scale