forked from killermonkyrecordz-ctrl/TopoGPT2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2618 lines (2197 loc) · 108 KB
/
Copy pathapp.py
File metadata and controls
2618 lines (2197 loc) · 108 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
#!/usr/bin/env python3
"""
TopoGPT2: Quaternion-Enhanced Topological Transformer Language Model
Author: Gris Iscomeback
Email: grisiscomeback@gmail.com
License: GPL v3
Mejoras sobre topogpt.py:
- Álgebra de cuaterniones completa (QuaternionLinear, QuaternionSpectralLayer)
con producto de Hamilton en el dominio de frecuencia para capturar la
espectrografía de los datos con kernels reales e imaginarios cruzados.
- SpectralAutoencoder: encoder/decoder espectral que comprime y reconstruye
las representaciones en el dominio de frecuencia.
- QuaternionTorusBrain VECTORIZADA (sin bucles sobre seq_len): proyección
geométrica sobre el toro con asignación blanda usando distancias circulares,
message-passing con rotaciones de cuaterniones.
- 8 nodos (RADIAL=2 × ANGULAR=4), 4 ángulos, 2 radiales (spec del usuario).
- Rotary Position Embeddings (RoPE).
- Flash-attention (scaled_dot_product_attention de PyTorch 2.0+).
- RMSNorm en lugar de LayerNorm (estilo LLaMA).
- Tokenizador BPE via tiktoken (vocab GPT-2, 50k tokens).
- Descargador de corpus: TinyStories, WikiText-103, raw file.
- Entrenamiento con AMP (mixed precision) + acumulación de gradientes.
- Presets de escala: micro, small, medium, gpt2.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint as grad_ckpt
from safetensors.torch import save_file as st_save, load_file as st_load
import numpy as np
import math
import os
import sys
import time
import json
import hashlib
import logging
import warnings
import argparse
from datetime import datetime
from typing import Dict, Tuple, Optional, List, Any
from dataclasses import dataclass, asdict
from collections import deque
warnings.filterwarnings('ignore')
# ============================================================================
# CONFIGURACIÓN
# ============================================================================
@dataclass
class TopoGPT2Config:
"""Configuración completa para TopoGPT2."""
# --- Dispositivo ---
DEVICE: str = 'cuda' if torch.cuda.is_available() else 'cpu'
RANDOM_SEED: int = 42
USE_AMP: bool = True
# --- Escala del modelo: 'micro' | 'small' | 'medium' | 'gpt2' | 'custom' ---
SCALE: str = 'small'
# --- Vocabulario (GPT-2 BPE via tiktoken) ---
VOCAB_SIZE: int = 50257
MAX_SEQ_LEN: int = 512
# --- Arquitectura (sobrescritos por SCALE salvo SCALE='custom') ---
D_MODEL: int = 256 # debe ser divisible por 4 (cuaterniones) y N_HEADS
N_HEADS: int = 8
N_KV_HEADS: int = 0 # GQA: cabezas K/V (0 = N_HEADS//4, -1 = MHA completo)
N_LAYERS: int = 6
DROPOUT: float = 0.1
# --- MoE (Mixture of Experts) ---
MOE_ENABLED: bool = True # activar MoE en cada capa
N_EXPERTS: int = 4 # expertos SwiGLU por capa
MOE_TOP_K: int = 2 # expertos activos por token (sparse)
MOE_AUX_LOSS_WEIGHT: float = 0.01 # load-balancing loss
# --- Topología del toro (spec usuario: 8 nodos = 4 ang × 2 rad) ---
TORUS_GRID_SIZE: int = 8 # Grid para SpectralLayer (8×8 FFT2)
TORUS_RADIAL_BINS: int = 2 # 2 niveles radiales
TORUS_ANGULAR_BINS: int = 4 # 4 ángulos (= 4 nodos por anillo)
# Total nodos en el grafo toro: 2 × 4 = 8
# --- Espectral / Autoencoder ---
SPECTRAL_LATENT_RATIO: float = 0.5 # latent_dim = D_MODEL * ratio
SPECTRAL_KERNEL_INIT_SCALE: float = 0.02
NUM_SPECTRAL_LAYERS: int = 2
AE_RECON_WEIGHT: float = 0.01 # peso de la pérdida de reconstrucción
# --- Entrenamiento ---
BATCH_SIZE: int = 4 # reducido para caber en 6GB VRAM
GRAD_ACCUM_STEPS: int = 8 # batch efectivo = 32
LEARNING_RATE: float = 3e-4
WEIGHT_DECAY: float = 0.1
EPOCHS: int = 10
WARMUP_RATIO: float = 0.05
GRADIENT_CLIP_NORM: float = 1.0
GRADIENT_CHECKPOINTING: bool = True # intercambia cómputo por memoria
# --- Corpus ---
CORPUS: str = 'tinystories' # 'tinystories' | 'wikitext103' | 'file'
CORPUS_FILE: str = '' # Ruta si CORPUS='file'
DATA_DIR: str = 'data_topogpt2'
MAX_TRAIN_TOKENS: int = 50_000_000 # 50M tokens máx por epoch
# --- Checkpoints ---
CHECKPOINT_DIR: str = 'checkpoints_topogpt2'
CHECKPOINT_INTERVAL_MINUTES: int = 10
MAX_CHECKPOINTS: int = 5
# --- Logging ---
LOG_INTERVAL_STEPS: int = 100
EVAL_INTERVAL_STEPS: int = 500
LOG_LEVEL: str = 'INFO'
# --- Temperatura termodinámica (heredada) ---
T_INIT: float = 1.0
def __post_init__(self):
presets = {
'micro': dict(D_MODEL=64, N_HEADS=4, N_LAYERS=2, MAX_SEQ_LEN=128),
'small': dict(D_MODEL=256, N_HEADS=8, N_LAYERS=6, MAX_SEQ_LEN=256),
'medium': dict(D_MODEL=512, N_HEADS=8, N_LAYERS=12, MAX_SEQ_LEN=512),
'gpt2': dict(D_MODEL=768, N_HEADS=12, N_LAYERS=12, MAX_SEQ_LEN=1024),
}
if self.SCALE in presets:
for k, v in presets[self.SCALE].items():
setattr(self, k, v)
assert self.D_MODEL % 4 == 0, "D_MODEL debe ser divisible por 4 (cuaterniones)"
assert self.D_MODEL % self.N_HEADS == 0, "D_MODEL debe ser divisible por N_HEADS"
self.D_QUAT = self.D_MODEL // 4
self.D_HEAD = self.D_MODEL // self.N_HEADS
self.SPECTRAL_LATENT_DIM = max(16, int(self.D_MODEL * self.SPECTRAL_LATENT_RATIO))
self.N_TORUS_NODES = self.TORUS_RADIAL_BINS * self.TORUS_ANGULAR_BINS
# GQA: resolver N_KV_HEADS
if self.N_KV_HEADS == 0:
# Auto: N_HEADS // 4, mínimo 1, divisor de N_HEADS
kv = max(1, self.N_HEADS // 4)
while self.N_HEADS % kv != 0:
kv -= 1
self.N_KV_HEADS = kv
elif self.N_KV_HEADS == -1:
self.N_KV_HEADS = self.N_HEADS # MHA estándar
assert self.N_HEADS % self.N_KV_HEADS == 0, \
"N_HEADS debe ser divisible por N_KV_HEADS"
self.GQA_GROUPS = self.N_HEADS // self.N_KV_HEADS
def setup_logger(name: str, level: str = 'INFO') -> logging.Logger:
logger = logging.getLogger(name)
logger.setLevel(getattr(logging, level.upper(), logging.INFO))
if not logger.handlers:
h = logging.StreamHandler()
h.setFormatter(logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s'))
logger.addHandler(h)
return logger
def set_seed(seed: int, device: str):
torch.manual_seed(seed)
np.random.seed(seed)
if 'cuda' in device and torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
# ============================================================================
# ÁLGEBRA DE CUATERNIONES
# ============================================================================
class QuaternionOps:
"""
Operaciones de cuaterniones puras en PyTorch.
Representación: [..., 4] donde last dim = [w, x, y, z]
q = w + x*i + y*j + z*k
"""
@staticmethod
def hamilton_product(q1: torch.Tensor, q2: torch.Tensor) -> torch.Tensor:
"""Producto de Hamilton q1 ⊗ q2. Ambos [..., 4]."""
w1, x1, y1, z1 = q1[..., 0], q1[..., 1], q1[..., 2], q1[..., 3]
w2, x2, y2, z2 = q2[..., 0], q2[..., 1], q2[..., 2], q2[..., 3]
return torch.stack([
w1*w2 - x1*x2 - y1*y2 - z1*z2,
w1*x2 + x1*w2 + y1*z2 - z1*y2,
w1*y2 - x1*z2 + y1*w2 + z1*x2,
w1*z2 + x1*y2 - y1*x2 + z1*w2,
], dim=-1)
@staticmethod
def normalize(q: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
return q / (q.norm(dim=-1, keepdim=True) + eps)
@staticmethod
def conjugate(q: torch.Tensor) -> torch.Tensor:
sign = q.new_tensor([1, -1, -1, -1])
return q * sign
@staticmethod
def rotate_vector(v: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
"""Rota vector 3D v por cuaternión unitario q. v:[...,3] q:[...,4]"""
zero = torch.zeros(*v.shape[:-1], 1, device=v.device, dtype=v.dtype)
v_q = torch.cat([zero, v], dim=-1) # pure quaternion
q_c = QuaternionOps.conjugate(q)
rotated = QuaternionOps.hamilton_product(
QuaternionOps.hamilton_product(q, v_q), q_c)
return rotated[..., 1:]
class QuaternionLinear(nn.Module):
"""
Capa lineal con pesos cuaterniones.
Implementa la multiplicación W * x en el álgebra de cuaterniones:
- W = Ww + Wx*i + Wy*j + Wz*k (cuaternión de pesos)
- x = xw + xx*i + xy*j + xz*k (cuaternión de entrada)
- out = W * x (producto de Hamilton extendido a vectores)
Parámetros: 4 matrices reales de forma [out_q, in_q]
"""
def __init__(self, in_features: int, out_features: int, bias: bool = True):
super().__init__()
assert in_features % 4 == 0 and out_features % 4 == 0
self.in_q = in_features // 4
self.out_q = out_features // 4
# 4 componentes del cuaternión de pesos
self.Ww = nn.Linear(self.in_q, self.out_q, bias=False)
self.Wx = nn.Linear(self.in_q, self.out_q, bias=False)
self.Wy = nn.Linear(self.in_q, self.out_q, bias=False)
self.Wz = nn.Linear(self.in_q, self.out_q, bias=False)
self.bias = nn.Parameter(torch.zeros(out_features)) if bias else None
for w in [self.Ww, self.Wx, self.Wy, self.Wz]:
nn.init.normal_(w.weight, std=0.02)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""x: [..., in_features] → [..., out_features]"""
d = self.in_q
xw, xx, xy, xz = x[..., :d], x[..., d:2*d], x[..., 2*d:3*d], x[..., 3*d:]
# Producto de Hamilton: W * x
ow = self.Ww(xw) - self.Wx(xx) - self.Wy(xy) - self.Wz(xz)
ox = self.Ww(xx) + self.Wx(xw) + self.Wy(xz) - self.Wz(xy)
oy = self.Ww(xy) - self.Wx(xz) + self.Wy(xw) + self.Wz(xx)
oz = self.Ww(xz) + self.Wx(xy) - self.Wy(xx) + self.Wz(xw)
out = torch.cat([ow, ox, oy, oz], dim=-1)
return out + self.bias if self.bias is not None else out
# ============================================================================
# CAPA ESPECTRAL CON CUATERNIONES
# ============================================================================
class QuaternionSpectralLayer(nn.Module):
"""
Convolución espectral 2D con cuaterniones y producto de Hamilton completo.
Operación en dominio de frecuencia:
P(k) = W(k) ⊗ X(k) (producto de Hamilton de cuaterniones complejos)
Donde:
X(k) = FFT2(x) con 4 canales cuaterniones [Xw, Xx, Xy, Xz]
W(k) = kernel complejo aprendible con componentes [Ww, Wx, Wy, Wz]
Reglas del producto de Hamilton en dominio de frecuencia:
Pw = Ww·Xw - Wx·Xx - Wy·Xy - Wz·Xz
Px = Ww·Xx + Wx·Xw + Wy·Xz - Wz·Xy
Py = Ww·Xy - Wx·Xz + Wy·Xw + Wz·Xx
Pz = Ww·Xz + Wx·Xy - Wy·Xx + Wz·Xw
Cada Wc es un kernel complejo (partes real e imaginaria independientes).
"""
def __init__(self, in_q: int, out_q: int, grid_h: int, grid_w: int,
init_scale: float = 0.02):
super().__init__()
self.in_q = in_q
self.out_q = out_q
self.grid_h = grid_h
self.grid_w = grid_w
# rfft2(x, s=(H, W)) → output shape [..., H, W//2+1]
freq_h = grid_h
freq_w = grid_w // 2 + 1
# Kernel complejo para cada componente cuaternión (w, x, y, z)
for c in ('w', 'x', 'y', 'z'):
self.register_parameter(f'kr_{c}',
nn.Parameter(torch.randn(in_q, out_q, freq_h, freq_w) * init_scale))
self.register_parameter(f'ki_{c}',
nn.Parameter(torch.randn(in_q, out_q, freq_h, freq_w) * init_scale))
def _kernel(self, c: str) -> torch.Tensor:
return torch.complex(getattr(self, f'kr_{c}'), getattr(self, f'ki_{c}'))
def _contract(self, W: torch.Tensor, X: torch.Tensor) -> torch.Tensor:
"""Suma sobre canales in_q: Y[b,o,h,w] = Σ_i W[i,o,h,w]·X[b,i,h,w]"""
return torch.einsum('iohw,bihw->bohw', W, X)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
x: [B, 4*in_q, H, W] (4 canales cuaterniones sobre grid espacial)
→ [B, 4*out_q, H, W]
"""
q = self.in_q
xw, xx, xy, xz = x[:, :q], x[:, q:2*q], x[:, 2*q:3*q], x[:, 3*q:]
# FFT2 por componente cuaternión → dominio de frecuencia
Xw = torch.fft.rfft2(xw, s=(self.grid_h, self.grid_w))
Xx = torch.fft.rfft2(xx, s=(self.grid_h, self.grid_w))
Xy = torch.fft.rfft2(xy, s=(self.grid_h, self.grid_w))
Xz = torch.fft.rfft2(xz, s=(self.grid_h, self.grid_w))
Ww, Wx, Wy, Wz = self._kernel('w'), self._kernel('x'), self._kernel('y'), self._kernel('z')
# Precomputar 16 contracciones (componente de kernel × componente de señal)
C = {}
for wc, W in (('w', Ww), ('x', Wx), ('y', Wy), ('z', Wz)):
for xc, X in (('w', Xw), ('x', Xx), ('y', Xy), ('z', Xz)):
C[(wc, xc)] = self._contract(W, X)
# Producto de Hamilton en dominio de frecuencia
Pw = C[('w','w')] - C[('x','x')] - C[('y','y')] - C[('z','z')]
Px = C[('w','x')] + C[('x','w')] + C[('y','z')] - C[('z','y')]
Py = C[('w','y')] - C[('x','z')] + C[('y','w')] + C[('z','x')]
Pz = C[('w','z')] + C[('x','y')] - C[('y','x')] + C[('z','w')]
# IFFT2 y recombinar
ow = torch.fft.irfft2(Pw, s=(self.grid_h, self.grid_w))
ox = torch.fft.irfft2(Px, s=(self.grid_h, self.grid_w))
oy = torch.fft.irfft2(Py, s=(self.grid_h, self.grid_w))
oz = torch.fft.irfft2(Pz, s=(self.grid_h, self.grid_w))
return torch.cat([ow, ox, oy, oz], dim=1) # [B, 4*out_q, H, W]
# ============================================================================
# SPECTRAL AUTOENCODER
# ============================================================================
class SpectralAutoencoder(nn.Module):
"""
Autoencoder espectral con cuaterniones.
Opera en dos niveles:
1. Espectral 1D sobre el vector de features (FFT sobre dim D_MODEL):
captura la espectrografía global del embedding.
2. Espectral 2D sobre el grid del toro (QuaternionSpectralLayer):
captura correlaciones espaciales en la topología.
Devuelve (latent, recon_loss) para regularización.
"""
def __init__(self, config: TopoGPT2Config):
super().__init__()
d = config.D_MODEL
d_lat = config.SPECTRAL_LATENT_DIM
d_q = config.D_QUAT
g = config.TORUS_GRID_SIZE
r = config.TORUS_RADIAL_BINS
a = config.TORUS_ANGULAR_BINS
init_s = config.SPECTRAL_KERNEL_INIT_SCALE
n_freq = d // 2 + 1
# --- Kernels espectrales 1D (reales e imaginarios) ---
self.enc_kr = nn.Parameter(torch.randn(n_freq) * init_s)
self.enc_ki = nn.Parameter(torch.randn(n_freq) * init_s)
self.dec_kr = nn.Parameter(torch.randn(n_freq) * init_s)
self.dec_ki = nn.Parameter(torch.randn(n_freq) * init_s)
# Proyección al latente y de vuelta
self.enc_proj = QuaternionLinear(d, d_lat)
self.dec_proj = QuaternionLinear(d_lat, d)
# --- Spectral 2D sobre el grid del toro: in/out_q = d_q, grid = r×a ---
# Los 'out_q' en la segunda capa son iguales para reconstruir
self.torus_spectral = nn.ModuleList([
QuaternionSpectralLayer(d_q, d_q, r, a, init_scale=init_s)
for _ in range(config.NUM_SPECTRAL_LAYERS)
])
self.act = nn.GELU()
self.d_model = d
def _filter1d(self, x: torch.Tensor, kr: torch.Tensor, ki: torch.Tensor) -> torch.Tensor:
"""Filtro espectral 1D: x[..., D] → filtrado[..., D]"""
X = torch.fft.rfft(x, dim=-1)
K = torch.complex(kr, ki)
return torch.fft.irfft(X * K, n=self.d_model, dim=-1)
def encode(self, x: torch.Tensor) -> torch.Tensor:
"""x: [..., D_MODEL] → latent: [..., D_LAT]"""
x_filt = self.act(self._filter1d(x, self.enc_kr, self.enc_ki))
return self.enc_proj(x_filt)
def decode(self, z: torch.Tensor) -> torch.Tensor:
"""z: [..., D_LAT] → recon: [..., D_MODEL]"""
x = self.dec_proj(z)
return self._filter1d(x, self.dec_kr, self.dec_ki)
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Devuelve (latent, recon_loss)"""
z = self.encode(x)
recon = self.decode(z)
recon_loss = F.mse_loss(recon, x.detach())
return z, recon_loss
def process_torus_grid(self, grid: torch.Tensor) -> torch.Tensor:
"""
Procesa el grid del toro con QuaternionSpectralLayer.
grid: [B, 4*D_QUAT, RADIAL, ANGULAR] → [B, 4*D_QUAT, RADIAL, ANGULAR]
"""
h = grid
for layer in self.torus_spectral:
h = self.act(layer(h))
return h
# ============================================================================
# QUATERNION TORUS BRAIN (reemplaza MLP, VECTORIZADO)
# ============================================================================
class QuaternionTorusBrain(nn.Module):
"""
Reemplaza el MLP en cada capa del transformer.
Pipeline (completamente vectorizado sobre batch Y secuencia):
1. Flatten: [B, S, D] → [B·S, D]
2. SpectralAutoencoder: filtrado espectral 1D + compresión cuaternión
3. Proyección al toro:
- Calcula 2 ángulos (phi1, phi2) ∈ [-π, π]²
- Asignación blanda a los 8 nodos via distancia circular en el toro
4. Construye grid de nodos: [B·S, N_NODES=8, D_MODEL]
5. QuaternionSpectralLayer 2D sobre el grid [B·S, 4*D_QUAT, RADIAL, ANGULAR]
6. Message-passing con rotaciones cuaterniones sobre el grafo toro
7. Readout: atención sobre los 8 nodos → [B·S, D_MODEL]
8. Reshape: [B·S, D] → [B, S, D]
"""
def __init__(self, d_model: int, config: TopoGPT2Config):
super().__init__()
self.d_model = d_model
self.d_lat = config.SPECTRAL_LATENT_DIM
self.d_q = d_model // 4
self.n_radial = config.TORUS_RADIAL_BINS # 2
self.n_angular = config.TORUS_ANGULAR_BINS # 4
self.n_nodes = config.N_TORUS_NODES # 8
self.config = config
# Autoencoder espectral
self.spectral_ae = SpectralAutoencoder(config)
# Proyección al espacio de ángulos del toro (2 ángulos × 2 = 4 salidas para Q)
self.torus_proj = nn.Sequential(
QuaternionLinear(d_model, d_model),
nn.GELU(),
nn.Linear(d_model, 4), # [phi1, phi2, r_scale, dummy]
)
# Embeddings aprendibles para los 8 nodos del toro
self.node_embed = nn.Parameter(torch.randn(self.n_nodes, d_model) * 0.02)
# Cuaterniones de rotación aprendibles para message-passing
# Un cuaternión por tipo de arista: ang-izq, ang-der, rad-abajo, rad-arriba
self.edge_quat = nn.Parameter(torch.randn(4, 4) * 0.1) # [n_edge_types, 4]
# Red de nodo post-message-passing
self.node_net = QuaternionLinear(d_model, d_model)
# Proyección final desde nodo-pool al espacio de salida
self.readout = nn.Sequential(
nn.Linear(d_model, d_model * 2),
nn.GELU(),
nn.Linear(d_model * 2, d_model),
)
# Grafo del toro: lista de aristas (nodo_i, nodo_j, tipo_arista)
self._build_torus_graph()
def _build_torus_graph(self):
"""
Construye las aristas del grafo toro 2×4.
Nodos indexados como: node = r * N_ANGULAR + a
r ∈ [0, RADIAL-1], a ∈ [0, ANGULAR-1]
Aristas angulares: nodo ↔ nodo a la izquierda/derecha (periódico)
Aristas radiales: nodo ↔ nodo del anillo interior/exterior
"""
edges_i, edges_j, edge_type = [], [], []
R, A = self.n_radial, self.n_angular
for r in range(R):
for a in range(A):
n = r * A + a
# Angular izquierda (tipo 0)
neighbor = r * A + (a - 1) % A
edges_i.append(n); edges_j.append(neighbor); edge_type.append(0)
# Angular derecha (tipo 1)
neighbor = r * A + (a + 1) % A
edges_i.append(n); edges_j.append(neighbor); edge_type.append(1)
# Radial hacia centro (tipo 2) - si existe
if r > 0:
neighbor = (r - 1) * A + a
edges_i.append(n); edges_j.append(neighbor); edge_type.append(2)
# Radial hacia fuera (tipo 3) - si existe
if r < R - 1:
neighbor = (r + 1) * A + a
edges_i.append(n); edges_j.append(neighbor); edge_type.append(3)
self.register_buffer('edges_i', torch.tensor(edges_i, dtype=torch.long))
self.register_buffer('edges_j', torch.tensor(edges_j, dtype=torch.long))
self.register_buffer('edge_type', torch.tensor(edge_type, dtype=torch.long))
def _torus_soft_assign(self, phi1: torch.Tensor, phi2: torch.Tensor) -> torch.Tensor:
"""
Asignación blanda de tokens a los 8 nodos del toro via distancia circular.
phi1: [BS] ángulo angular ∈ [-π, π]
phi2: [BS] ángulo radial ∈ [-π, π]
→ weights: [BS, N_NODES] (suma a 1, softmax de distancias negativas)
"""
BS = phi1.shape[0]
device = phi1.device
# Posiciones de los nodos en el toro
ang_pos = torch.linspace(-math.pi, math.pi, self.n_angular + 1, device=device)[:-1]
rad_pos = torch.linspace(-math.pi, math.pi, self.n_radial + 1, device=device)[:-1]
# Distancias circulares (usando sin para periodicidad suave)
# d_ang[BS, N_ANGULAR], d_rad[BS, N_RADIAL]
d_ang = torch.sin((phi1.unsqueeze(1) - ang_pos.unsqueeze(0)) / 2).pow(2) # [BS, A]
d_rad = torch.sin((phi2.unsqueeze(1) - rad_pos.unsqueeze(0)) / 2).pow(2) # [BS, R]
# Distancia en el toro para cada nodo [r, a]: d[r, a] = d_rad[r] + d_ang[a]
# Resultado: [BS, R, A] → flatten a [BS, N_NODES]
d_torus = d_rad.unsqueeze(2) + d_ang.unsqueeze(1) # [BS, R, A]
d_flat = d_torus.view(BS, -1) # [BS, N_NODES]
return torch.softmax(-d_flat / 0.3, dim=-1) # temperatura 0.3
def _message_passing(self, node_feat: torch.Tensor) -> torch.Tensor:
"""
Message-passing VECTORIZADO con rotaciones cuaterniones.
Sin bucles Python: todas las aristas se procesan en paralelo.
node_feat: [BS, N_NODES, D_MODEL]
→ [BS, N_NODES, D_MODEL]
"""
BS = node_feat.shape[0]
n_edges = self.edges_i.shape[0]
d_q = self.d_q
# Cuaterniones de arista normalizados: [n_edge_types=4, 4]
eq = QuaternionOps.normalize(self.edge_quat)
# Recoger features de nodos fuente para TODAS las aristas: [BS, n_edges, D]
src_feat = node_feat[:, self.edges_j, :] # index [n_edges] → [BS, n_edges, D]
# Cuaternión de cada arista: [n_edges, 4] → [1, n_edges, 1, 4] para broadcasting
edge_q = eq[self.edge_type] # [n_edges, 4]
edge_q = edge_q.unsqueeze(0).unsqueeze(2) # [1, n_edges, 1, 4]
edge_q = edge_q.expand(BS, -1, d_q, -1) # [BS, n_edges, D_QUAT, 4]
# Reshapear fuentes: [BS, n_edges, D] → [BS, n_edges, D_QUAT, 4]
src_q = src_feat.view(BS, n_edges, d_q, 4)
# Rotación cuaternión para todas las aristas en paralelo: [BS, n_edges, D_QUAT, 4]
msg_rot = QuaternionOps.hamilton_product(edge_q, src_q)
msg_rot = msg_rot.view(BS, n_edges, self.d_model) # [BS, n_edges, D]
# Scatter-add a nodos destino: edges_i[e] es el nodo destino de la arista e
agg = torch.zeros_like(node_feat) # [BS, N_NODES, D]
dst_idx = self.edges_i.view(1, n_edges, 1).expand(BS, -1, self.d_model)
agg.scatter_add_(1, dst_idx, msg_rot)
return self.node_net(node_feat + agg)
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
x: [B, S, D_MODEL]
→ output: [B, S, D_MODEL], recon_loss: scalar
"""
B, S, D = x.shape
device = x.device
# 1. Flatten para procesamiento paralelo
x_flat = x.reshape(B * S, D) # [BS, D]
# 2. Spectral Autoencoder: filtrado + compresión
z, recon_loss = self.spectral_ae(x_flat) # z: [BS, D_LAT]
# 3. Proyección al toro
coords = self.torus_proj(x_flat) # [BS, 4]
phi1 = math.pi * torch.tanh(coords[:, 0]) # ángulo angular ∈ [-π, π]
phi2 = math.pi * torch.tanh(coords[:, 1]) # ángulo radial ∈ [-π, π]
# 4. Asignación blanda a 8 nodos
attn_w = self._torus_soft_assign(phi1, phi2) # [BS, N_NODES]
# 5. Construir grid de nodos: weighted combination de embeddings de nodo + input
# node_feat[bs, n, :] = attn_w[bs,n] * node_embed[n] + x_flat[bs] * attn_w[bs,n]
nodes = (
attn_w.unsqueeze(-1) * self.node_embed.unsqueeze(0) # [BS, N, D]
+ attn_w.unsqueeze(-1) * x_flat.unsqueeze(1) # broadcasting [BS, N, D]
) # [BS, N_NODES, D_MODEL]
# 6. QuaternionSpectralLayer 2D sobre el grid del toro
# Reshape: [BS, N_NODES, D_MODEL] → [BS, 4*D_QUAT, RADIAL, ANGULAR]
grid = nodes.view(B * S, self.n_radial, self.n_angular, D)
grid = grid.permute(0, 3, 1, 2) # [BS, D_MODEL, RADIAL, ANGULAR]
# Reorganizar en 4 canales cuaterniones
d_q = self.d_q
grid_q = grid.view(B * S, 4, d_q, self.n_radial, self.n_angular)
# [BS, 4, D_QUAT, RADIAL, ANGULAR] → [BS, 4*D_QUAT, RADIAL, ANGULAR]
grid_q = grid_q.permute(0, 1, 2, 3, 4).reshape(B * S, 4 * d_q, self.n_radial, self.n_angular)
grid_spec = self.spectral_ae.process_torus_grid(grid_q) # [BS, 4*D_QUAT, R, A]
# Volver a [BS, N_NODES, D_MODEL]
grid_back = grid_spec.view(B * S, 4, d_q, self.n_radial, self.n_angular)
grid_back = grid_back.permute(0, 3, 4, 1, 2).reshape(B * S, self.n_nodes, D)
# 7. Message-passing cuaternión sobre el grafo toro
nodes_mp = self._message_passing(grid_back) # [BS, N_NODES, D_MODEL]
# 8. Readout: suma ponderada por los pesos de asignación
out_flat = (attn_w.unsqueeze(-1) * nodes_mp).sum(dim=1) # [BS, D_MODEL]
out_flat = self.readout(out_flat) # [BS, D_MODEL]
# 9. Reshape a secuencia
output = out_flat.reshape(B, S, D) # [B, S, D_MODEL]
return output, recon_loss
# ============================================================================
# ROTARY POSITION EMBEDDINGS (RoPE)
# ============================================================================
class RotaryEmbedding(nn.Module):
"""
Rotary Position Embeddings (RoPE) - Su et al., 2021.
Codifica la posición como rotaciones del espacio de atención,
naturalmente relativas y sin parámetros extra.
"""
def __init__(self, d_head: int, max_seq_len: int = 2048, base: int = 10000):
super().__init__()
inv_freq = 1.0 / (base ** (torch.arange(0, d_head, 2).float() / d_head))
self.register_buffer('inv_freq', inv_freq)
self._build_cache(max_seq_len)
def _build_cache(self, seq_len: int):
t = torch.arange(seq_len, device=self.inv_freq.device).float()
freqs = torch.outer(t, self.inv_freq)
emb = torch.cat([freqs, freqs], dim=-1) # [seq_len, d_head]
self.register_buffer('cos_cache', emb.cos())
self.register_buffer('sin_cache', emb.sin())
def _rotate_half(self, x: torch.Tensor) -> torch.Tensor:
x1, x2 = x[..., :x.shape[-1]//2], x[..., x.shape[-1]//2:]
return torch.cat([-x2, x1], dim=-1)
def forward(self, q: torch.Tensor, k: torch.Tensor,
seq_len: int, offset: int = 0) -> Tuple[torch.Tensor, torch.Tensor]:
"""
q, k: [B, n_heads, S_q/S_k, d_head]
offset: posicion inicial (para KV cache: longitud del cache existente)
Aplica posiciones [offset .. offset+S-1] a q y k.
"""
needed = offset + max(q.shape[2], k.shape[2])
if needed > self.cos_cache.shape[0]:
self._build_cache(needed * 2)
sq, sk = q.shape[2], k.shape[2]
cos_q = self.cos_cache[offset:offset + sq].unsqueeze(0).unsqueeze(0)
sin_q = self.sin_cache[offset:offset + sq].unsqueeze(0).unsqueeze(0)
cos_k = self.cos_cache[offset:offset + sk].unsqueeze(0).unsqueeze(0)
sin_k = self.sin_cache[offset:offset + sk].unsqueeze(0).unsqueeze(0)
q_rot = q * cos_q + self._rotate_half(q) * sin_q
k_rot = k * cos_k + self._rotate_half(k) * sin_k
return q_rot, k_rot
# ============================================================================
# MULTI-HEAD ATTENTION CON FLASH ATTENTION + ROPE
# ============================================================================
class RMSNorm(nn.Module):
"""Root Mean Square Layer Normalization (sin bias). Más estable que LayerNorm."""
def __init__(self, d_model: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(d_model))
def forward(self, x: torch.Tensor) -> torch.Tensor:
rms = x.pow(2).mean(-1, keepdim=True).add(self.eps).sqrt()
return x / rms * self.weight
# ============================================================================
# SWIGLU (activacion de modelos frontier: LLaMA, Qwen, etc.)
# ============================================================================
class SwiGLU(nn.Module):
"""
SwiGLU: SiLU(gate(x)) * up(x) -> down
Usado en LLaMA 2/3, Qwen, Mistral en lugar de GELU-FFN.
Dimension interna: 8/3 * d_model (convención LLaMA, redondeada a múltiplo de 4).
"""
def __init__(self, d_model: int, expansion: float = 8 / 3,
dropout: float = 0.0):
super().__init__()
inner = max(4, int(d_model * expansion))
inner = (inner + 3) // 4 * 4 # redondear a múltiplo de 4
self.gate_proj = nn.Linear(d_model, inner, bias=False)
self.up_proj = nn.Linear(d_model, inner, bias=False)
self.down_proj = nn.Linear(inner, d_model, bias=False)
self.drop = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
# Inicialización estilo GPT
nn.init.normal_(self.gate_proj.weight, std=0.02)
nn.init.normal_(self.up_proj.weight, std=0.02)
nn.init.normal_(self.down_proj.weight, std=0.02)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.drop(self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x)))
# ============================================================================
# MoE: Mixture of Experts topologico
# ============================================================================
class TopoMoEBrain(nn.Module):
"""
Mixture of Experts sobre la capa topologica.
Arquitectura (inspirada en DeepSeek-MoE / Mixtral):
- 1 experto compartido: QuaternionTorusBrain (siempre activo)
- N_EXPERTS expertos SwiGLU ligeros (activacion esparsa: Top-K por token)
- Router: Linear(D, N_EXPERTS) + softmax → top-K
Load-balancing loss (auxiliar): penaliza si un experto acapara todos los tokens.
Activa MOE_TOP_K de N_EXPERTS expertos por token.
Sin MoE (MOE_ENABLED=False): se comporta como QuaternionTorusBrain puro.
"""
def __init__(self, d_model: int, config: 'TopoGPT2Config'):
super().__init__()
self.d_model = d_model
self.moe_enabled = config.MOE_ENABLED
self.n_experts = config.N_EXPERTS
self.top_k = config.MOE_TOP_K
self.aux_weight = config.MOE_AUX_LOSS_WEIGHT
# Experto compartido: el TopoBrain original (siempre activo)
self.shared_expert = QuaternionTorusBrain(d_model, config)
if self.moe_enabled:
# N_EXPERTS expertos SwiGLU ligeros (dimension reducida para eficiencia)
self.experts = nn.ModuleList([
SwiGLU(d_model, expansion=4/3, dropout=config.DROPOUT)
for _ in range(self.n_experts)
])
# Router: produce logits por experto para cada token
self.router = nn.Linear(d_model, self.n_experts, bias=False)
nn.init.normal_(self.router.weight, std=0.02)
def _route(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
x: [N, D] donde N = B*S (tokens aplanados)
Retorna:
expert_out: [N, D] suma ponderada de top-K expertos
aux_loss: escalar load-balancing loss
Routing vectorizado sin boolean indexing ni sincronizacion CUDA.
Usa dispatch por indices agrupados (estilo Mixtral/DeepSeek) para
compatibilidad total con torch.utils.checkpoint.
"""
N, D = x.shape
router_logits = self.router(x) # [N, n_experts]
router_probs = F.softmax(router_logits, dim=-1) # [N, n_experts]
# Top-K seleccion
top_k_probs, top_k_idx = torch.topk(router_probs, self.top_k, dim=-1)
# Renormalizar pesos dentro de los top-K
top_k_probs = top_k_probs / top_k_probs.sum(dim=-1, keepdim=True).clamp(min=1e-9)
# Dispatch vectorizado: agrupar tokens por experto asignado
flat_idx = top_k_idx.reshape(-1) # [N*top_k]
flat_weights = top_k_probs.reshape(-1) # [N*top_k]
token_indices = torch.arange(N, device=x.device, dtype=torch.long)
token_indices = token_indices.unsqueeze(1).expand(-1, self.top_k).reshape(-1) # [N*top_k]
expert_out = torch.zeros_like(x)
# Se elimina la verificacion con .item() porque fuerza una sincronizacion
# CPU-GPU que rompe el recomputado de gradient checkpointing.
# scatter_add_ maneja tensores vacios de forma segura y eficiente.
for e in range(self.n_experts):
expert_mask = (flat_idx == e) # [N*top_k] boolean
src_token_idx = token_indices[expert_mask] # [count] indices en N
w = flat_weights[expert_mask].unsqueeze(-1).to(x.dtype) # [count, 1]
out_e = self.experts[e](x[src_token_idx]) # [count, D]
contrib = w * out_e
expert_out.scatter_add_(0, src_token_idx.unsqueeze(1).expand_as(contrib), contrib)
# Load-balancing loss (Switch Transformer style)
token_frac = router_probs.mean(dim=0) # [n_experts]
one_hot = F.one_hot(top_k_idx, self.n_experts).float()# [N, top_k, n_experts]
dispatch_frac = one_hot.mean(dim=(0, 1)) # [n_experts]
aux_loss = self.n_experts * (token_frac * dispatch_frac).sum()
return expert_out, aux_loss
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
x: [B, S, D]
→ output: [B, S, D], aux_loss: escalar
"""
B, S, D = x.shape
# Experto compartido siempre activo
shared_out, recon_loss = self.shared_expert(x) # [B, S, D], scalar
if not self.moe_enabled:
return shared_out, recon_loss
# Expertos SwiGLU (esparso)
x_flat = x.reshape(B * S, D)
expert_out, aux_loss = self._route(x_flat)
expert_out = expert_out.reshape(B, S, D)
# Combinar: shared + routed (igual peso inicial)
output = shared_out + expert_out
# Combinar losses auxiliares
total_aux = recon_loss + self.aux_weight * aux_loss
return output, total_aux
class MultiHeadAttention(nn.Module):
"""
Multi-head attention con:
- Flash Attention (scaled_dot_product_attention de PyTorch 2.0+)
- Rotary Position Embeddings (RoPE)
- GQA (Grouped Query Attention): N_KV_HEADS < N_HEADS, reduce VRAM de K/V
- KV Cache para inferencia autoregresiva eficiente
- Temperatura termodinámica aprendible
"""
def __init__(self, d_model: int, n_heads: int, config: 'TopoGPT2Config'):
super().__init__()
self.d_model = d_model
self.n_heads = n_heads
self.n_kv = config.N_KV_HEADS # cabezas K/V (GQA)
self.n_groups = config.GQA_GROUPS # n_heads // n_kv
self.d_head = d_model // n_heads
# Q con n_heads completo; K/V con n_kv (GQA)
self.q_proj = nn.Linear(d_model, n_heads * self.d_head, bias=False)
self.k_proj = nn.Linear(d_model, self.n_kv * self.d_head, bias=False)
self.v_proj = nn.Linear(d_model, self.n_kv * self.d_head, bias=False)
self.o_proj = nn.Linear(d_model, d_model, bias=False)
self.rope = RotaryEmbedding(self.d_head, max_seq_len=config.MAX_SEQ_LEN)
self.temperature = nn.Parameter(torch.tensor(config.T_INIT))
self.dropout_p = config.DROPOUT if config.DROPOUT > 0 else 0.0
def forward(self, x: torch.Tensor, is_causal: bool = True,
past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None
) -> Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
"""
Args:
x: [B, S, D]
is_causal: usar mascara causal
past_kv: (K_cache, V_cache) de pasos anteriores o None
Returns:
out: [B, S, D]
kv_cache: (K, V) completos para cachear en generate()
"""
B, S, D = x.shape
Q = self.q_proj(x).view(B, S, self.n_heads, self.d_head).transpose(1, 2)
K = self.k_proj(x).view(B, S, self.n_kv, self.d_head).transpose(1, 2)
V = self.v_proj(x).view(B, S, self.n_kv, self.d_head).transpose(1, 2)
# RoPE con offset: si hay cache, Q y K_new se posicionan a partir de past_len
past_len = past_kv[0].shape[2] if past_kv is not None else 0
Q, K = self.rope(Q, K, seq_len=S, offset=past_len)
# Concatenar K/V con cache (despues de aplicar RoPE al nuevo K)
if past_kv is not None:
K = torch.cat([past_kv[0], K], dim=2)
V = torch.cat([past_kv[1], V], dim=2)
kv_cache = (K, V)
K_full = K
# GQA: expandir K/V al numero de cabezas de Q via repeat_interleave
if self.n_groups > 1:
K_full = K_full.repeat_interleave(self.n_groups, dim=1) # [B, n_heads, S_k, d]
V_exp = V.repeat_interleave(self.n_groups, dim=1)
else:
V_exp = V
scale = (self.d_head ** -0.5) / self.temperature.abs().clamp(min=1e-6)
out = F.scaled_dot_product_attention(
Q, K_full, V_exp,
attn_mask=None,
dropout_p=self.dropout_p if self.training else 0.0,
is_causal=(is_causal and past_kv is None),
scale=scale.item(),
) # [B, n_heads, S, d_head]
out = out.transpose(1, 2).contiguous().view(B, S, D)
return self.o_proj(out), kv_cache
# ============================================================================
# CAPA TRANSFORMER TOPOLÓGICA
# ============================================================================
class TopoGPT2Layer(nn.Module):
"""
Capa del transformer con TopoMoEBrain (TopoBrain + MoE SwiGLU experts).
Esquema pre-norm (estilo LLaMA):
x = x + Attention_GQA(RMSNorm(x))
x = x + TopoMoEBrain(RMSNorm(x))
"""
def __init__(self, d_model: int, n_heads: int, config: 'TopoGPT2Config'):
super().__init__()
self.norm1 = RMSNorm(d_model)
self.norm2 = RMSNorm(d_model)
self.attn = MultiHeadAttention(d_model, n_heads, config)
self.topo_brain = TopoMoEBrain(d_model, config)
self.dropout = nn.Dropout(config.DROPOUT)
self.use_ckpt = config.GRADIENT_CHECKPOINTING
def _forward_impl(self, x: torch.Tensor,
past_kv: Optional[Tuple] = None
) -> Tuple[torch.Tensor, torch.Tensor, Tuple]:
attn_out, kv_cache = self.attn(self.norm1(x), past_kv=past_kv)
x = x + self.dropout(attn_out)
brain_out, aux_loss = self.topo_brain(self.norm2(x))
x = x + self.dropout(brain_out)
return x, aux_loss, kv_cache
def forward(self, x: torch.Tensor,
past_kv: Optional[Tuple] = None
) -> Tuple[torch.Tensor, torch.Tensor, Tuple]:
"""
Retorna (x_out, aux_loss, kv_cache).
Con gradient checkpointing en training (solo cuando no hay KV cache).
"""
if self.use_ckpt and self.training and past_kv is None:
def ckpt_fn(x_in):
out, al, kvc = self._forward_impl(x_in, past_kv=None)
return out, al
out, al = grad_ckpt(ckpt_fn, x, use_reentrant=False)
return out, al, None # kv_cache no disponible con ckpt (solo entrenamiento)
return self._forward_impl(x, past_kv=past_kv)
# ============================================================================
# MODELO COMPLETO
# ============================================================================
class TopoGPT2(nn.Module):
"""
TopoGPT2: Transformer de lenguaje con TopoBrain cuaternión-espectral.
Arquitectura:
Embedding de tokens + RoPE (en Attention)
N_LAYERS × TopoGPT2Layer (Attention + QuaternionTorusBrain)
RMSNorm final
Proyección a vocabulario (weight-tied con embeddings)
"""
def __init__(self, config: TopoGPT2Config):
super().__init__()
self.config = config
self.token_embed = nn.Embedding(config.VOCAB_SIZE, config.D_MODEL)
nn.init.normal_(self.token_embed.weight, std=0.02)
self.layers = nn.ModuleList([
TopoGPT2Layer(config.D_MODEL, config.N_HEADS, config)
for _ in range(config.N_LAYERS)
])
self.final_norm = RMSNorm(config.D_MODEL)
self.lm_head = nn.Linear(config.D_MODEL, config.VOCAB_SIZE, bias=False)