-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathxray_tensor_diffractometer.py
More file actions
2801 lines (2243 loc) · 117 KB
/
Copy pathxray_tensor_diffractometer.py
File metadata and controls
2801 lines (2243 loc) · 117 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
import argparse
import torch
import torch.nn as nn
import numpy as np
import random
import json
import os
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from typing import Dict, Optional, List, Tuple, Any, Protocol
from abc import ABC, abstractmethod
import seaborn as sns
from scipy.stats import gaussian_kde
from scipy.linalg import eigh
from scipy.optimize import curve_fit
from sklearn.decomposition import PCA
import warnings
import logging
from dataclasses import dataclass
from pathlib import Path
import threading
import time
from collections import deque
@dataclass
class Config:
BATCH_SIZE: int = 32
HIDDEN_DIM: int = 8
TARGET_SLOTS: int = 7
MATRIX_SIZE: int = 2
WEIGHT_DECAY: float = 1e-4
LEARNING_RATE: float = 0.001
EPOCHS: int = 3000
DISCRETIZATION_MARGIN: float = 0.1
HBAR: float = 1e-6
POYNTING_THRESHOLD: float = 1.0
ENERGY_FLOW_SCALE: float = 0.1
RANDOM_SEED: int = 42
DEVICE: str = 'cuda' if torch.cuda.is_available() else 'cpu'
CHECKPOINT_INTERVAL_MINUTES: int = 5
MAX_CHECKPOINTS: int = 10
KDE_BANDWIDTH: str = 'scott'
MIN_VARIANCE_THRESHOLD: float = 1e-8
PCA_COMPONENTS: int = 2
ENTROPY_BINS: int = 50
ENTROPY_METHOD: str = 'shannon'
ENTROPY_EPS: float = 1e-10
LOG_LEVEL: str = 'INFO'
RESULTS_DIR: str = 'boltzmann_results'
UnifiedConfig = Config
import sys
sys.modules['__main__'].UnifiedConfig = Config
def set_seed(seed: int = Config.RANDOM_SEED):
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
if Config.DEVICE == 'cuda':
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
def setup_logger(name: str, level: str = Config.LOG_LEVEL) -> logging.Logger:
logger = logging.getLogger(name)
logger.setLevel(getattr(logging, level.upper()))
if not logger.handlers:
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
def run_epitaxy_from_best_crystal(checkpoint_dir: str, target_sizes: List[int] = [4, 8]) -> Dict[str, Any]:
"""
Pipeline automático: encuentra el mejor cristal y lo usa como semilla.
"""
logger = setup_logger("EpitaxyPipeline")
# Buscar cristales disponibles
checkpoint_path = Path(checkpoint_dir)
if not checkpoint_path.exists():
raise FileNotFoundError(f"Checkpoint directory not found: {checkpoint_dir}")
checkpoint_files = list(checkpoint_path.glob("*.pt"))
if not checkpoint_files:
raise FileNotFoundError(f"No checkpoints found in {checkpoint_dir}")
logger.info(f"Found {len(checkpoint_files)} checkpoints. Analyzing purity...")
# Analizar todos los checkpoints
best_seed = None
best_alpha = 0.0
loader = CheckpointLoader()
for ckpt_file in checkpoint_files:
try:
raw_data = loader.load_checkpoint(str(ckpt_file), Config.DEVICE)
migrated_state = CheckpointMigrator.migrate_checkpoint(raw_data)
if migrated_state is None:
continue
model = BilinearStrassenModel().to(Config.DEVICE)
model.load_state_dict(migrated_state)
coeffs = model.get_coefficients()
alpha = CrystallographyMetrics.compute_alpha_purity(coeffs)
delta = CrystallographyMetrics.compute_discretization_margin(coeffs)
logger.info(f" {ckpt_file.name}: α={alpha:.2f}, δ={delta:.4f}")
if alpha > best_alpha and alpha > 7.0: # Solo cristales puros
best_alpha = alpha
best_seed = ckpt_file
except Exception as e:
logger.warning(f" Failed to analyze {ckpt_file.name}: {e}")
if best_seed is None:
raise ValueError("No crystalline checkpoint found (α > 7.0). Cannot perform epitaxy.")
logger.info(f"\n🌟 Best seed crystal: {best_seed.name} (α={best_alpha:.2f})")
# Ejecutar experimento epitaxial
experiment = EpitaxyExperiment()
results = experiment.run_epitaxial_growth_experiment(str(best_seed), target_sizes)
return results
logger = setup_logger(__name__)
class ICheckpointLoader(Protocol):
def load_checkpoint(self, path: str, device: str) -> Any: ...
class IMetricsCalculator(Protocol):
def compute(self, model: nn.Module) -> Dict[str, Any]: ...
class IDataGenerator(Protocol):
def generate_batch(self, batch_size: int) -> Tuple[torch.Tensor, ...]: ...
class CheckpointLoadingError(Exception):
pass
class MetricsComputationError(Exception):
pass
class TrainingError(Exception):
pass
class StrassenDataGenerator:
@staticmethod
def generate_batch(batch_size: int = Config.BATCH_SIZE) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
A = torch.randn(batch_size, Config.MATRIX_SIZE, Config.MATRIX_SIZE, device=Config.DEVICE)
B = torch.randn(batch_size, Config.MATRIX_SIZE, Config.MATRIX_SIZE, device=Config.DEVICE)
C = torch.bmm(A, B)
return (
A.reshape(batch_size, Config.MATRIX_SIZE * Config.MATRIX_SIZE),
B.reshape(batch_size, Config.MATRIX_SIZE * Config.MATRIX_SIZE),
C.reshape(batch_size, Config.MATRIX_SIZE * Config.MATRIX_SIZE)
)
@staticmethod
def verify_structure(coeffs: Dict[str, torch.Tensor]) -> Dict[str, Any]:
delta = CrystallographyMetrics.compute_discretization_margin(coeffs)
return {
'pass': delta < Config.DISCRETIZATION_MARGIN,
'max_error': delta,
'margin': Config.DISCRETIZATION_MARGIN
}
class BilinearStrassenModel(nn.Module):
def __init__(self, hidden_dim: int = Config.HIDDEN_DIM, matrix_size: int = Config.MATRIX_SIZE):
super().__init__()
self.hidden_dim = hidden_dim
self.matrix_size = matrix_size
input_dim = matrix_size * matrix_size
self.U = nn.Linear(input_dim, hidden_dim, bias=False)
self.V = nn.Linear(input_dim, hidden_dim, bias=False)
self.W = nn.Linear(hidden_dim, input_dim, bias=False)
self._initialize_symmetric()
def _initialize_symmetric(self):
nn.init.xavier_uniform_(self.U.weight)
self.V.weight.data = self.U.weight.data.clone()
nn.init.xavier_uniform_(self.W.weight)
def forward(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
return self.W(self.U(a) * self.V(b))
def get_coefficients(self) -> Dict[str, torch.Tensor]:
return {
'U': self.U.weight.data,
'V': self.V.weight.data,
'W': self.W.weight.data
}
class EpitaxialGrowthEngine:
"""
Motor de crecimiento epitaxial para cristales algorítmicos.
FÍSICA: Imita el crecimiento de cristales en sustratos donde la estructura
atómica del sustrato guía la formación del nuevo cristal.
"""
def __init__(self, seed_checkpoint_path: str, target_matrix_size: int, device: str = Config.DEVICE):
self.seed_path = Path(seed_checkpoint_path)
self.target_size = target_matrix_size
self.device = device
self.logger = setup_logger("EpitaxialGrowthEngine")
# Cargar el cristal semilla
self.seed_crystal = self._load_seed_crystal()
self.seed_size = Config.MATRIX_SIZE # Tamaño original (2x2)
# Calcular factor de escala
self.scale_factor = target_matrix_size // self.seed_size
self.logger.info(f"Epitaxial engine initialized:")
self.logger.info(f" Seed size: {self.seed_size}x{self.seed_size}")
self.logger.info(f" Target size: {target_matrix_size}x{target_matrix_size}")
self.logger.info(f" Scale factor: {self.scale_factor}")
def _load_seed_crystal(self) -> Dict[str, torch.Tensor]:
"""Carga el cristal semilla verificando su pureza"""
loader = CheckpointLoader()
raw_data = loader.load_checkpoint(str(self.seed_path), self.device)
migrated_state = CheckpointMigrator.migrate_checkpoint(raw_data)
if migrated_state is None:
raise ValueError(f"Failed to migrate seed crystal from {self.seed_path}")
model = BilinearStrassenModel().to(self.device)
model.load_state_dict(migrated_state)
coeffs = model.get_coefficients()
delta = CrystallographyMetrics.compute_discretization_margin(coeffs)
alpha = CrystallographyMetrics.compute_alpha_purity(coeffs)
self.logger.info(f"Seed crystal quality: α={alpha:.2f}, δ={delta:.4f}")
if alpha < 7.0:
self.logger.warning("Seed crystal is not fully crystalline - epitaxy may fail")
return coeffs
def grow_epitaxial_crystal(self) -> BilinearStrassenModel:
"""
Crece un cristal epitaxial desde la semilla.
MÉTODO: Kronecker product preserva la estructura periódica:
Si A es cristal Strassen de 2x2, entonces A ⊗ I_n es cristal de (2n)x(2n)
"""
target_input_dim = self.target_size * self.target_size
# Calcular dimensión hidden escalada
# Para preservar el ratio de compresión, escalamos proporcionalmente
hidden_dim_scaled = Config.HIDDEN_DIM * (self.scale_factor ** 2)
self.logger.info(f"Growing crystal with hidden_dim={hidden_dim_scaled}")
# Crear modelo objetivo
model = BilinearStrassenModel(
hidden_dim=hidden_dim_scaled,
matrix_size=self.target_size
).to(self.device)
# Inicialización epitaxial usando producto de Kronecker
with torch.no_grad():
# U: (hidden_seed, input_seed) -> (hidden_target, input_target)
U_seed = self.seed_crystal['U']
identity_input = torch.eye(self.scale_factor, device=self.device)
identity_hidden = torch.eye(self.scale_factor, device=self.device)
# U_epitaxial = I_hidden ⊗ U_seed
# Esto replica la estructura de U_seed en bloques
U_epitaxial = torch.kron(identity_hidden, U_seed)
# Truncar o rellenar para ajustar dimensiones exactas
U_epitaxial = self._adjust_dimensions(
U_epitaxial,
model.U.weight.shape
)
# V: similar a U (por simetría bilineal)
V_epitaxial = torch.kron(identity_hidden, self.seed_crystal['V'])
V_epitaxial = self._adjust_dimensions(
V_epitaxial,
model.V.weight.shape
)
# W: (output_seed, hidden_seed) -> (output_target, hidden_target)
W_seed = self.seed_crystal['W']
W_epitaxial = torch.kron(identity_input, W_seed)
W_epitaxial = self._adjust_dimensions(
W_epitaxial,
model.W.weight.shape
)
# Inyectar estructura cristalina
model.U.weight.copy_(U_epitaxial)
model.V.weight.copy_(V_epitaxial)
model.W.weight.copy_(W_epitaxial)
self.logger.info("Epitaxial initialization complete")
return model
def _adjust_dimensions(self, tensor: torch.Tensor, target_shape: Tuple[int, int]) -> torch.Tensor:
"""
Ajusta dimensiones del tensor epitaxial para coincidir con el modelo objetivo.
Rellena con ruido térmico pequeño o trunca según sea necesario.
"""
current_shape = tensor.shape
target_rows, target_cols = target_shape
# Crear tensor objetivo
adjusted = torch.zeros(target_shape, device=tensor.device)
# Copiar región común
min_rows = min(current_shape[0], target_rows)
min_cols = min(current_shape[1], target_cols)
adjusted[:min_rows, :min_cols] = tensor[:min_rows, :min_cols]
# Rellenar regiones faltantes con ruido térmico (temperatura efectiva baja)
if current_shape[0] < target_rows or current_shape[1] < target_cols:
thermal_noise_scale = 1e-4 # Temperatura efectiva muy baja
if current_shape[0] < target_rows:
adjusted[min_rows:, :min_cols] = torch.randn(
target_rows - min_rows, min_cols, device=tensor.device
) * thermal_noise_scale
if current_shape[1] < target_cols:
adjusted[:min_rows, min_cols:] = torch.randn(
min_rows, target_cols - min_cols, device=tensor.device
) * thermal_noise_scale
if current_shape[0] < target_rows and current_shape[1] < target_cols:
adjusted[min_rows:, min_cols:] = torch.randn(
target_rows - min_rows, target_cols - min_cols, device=tensor.device
) * thermal_noise_scale
return adjusted
def anneal_crystal(self, model: BilinearStrassenModel, max_epochs: int = 50,
early_stop_threshold: float = 1e-4) -> Dict[str, Any]:
"""
Recocido térmico del cristal epitaxial.
FÍSICA: En lugar de "entrenar desde cero", aplicamos temperatura decreciente
para que el cristal se auto-organice alrededor de la semilla.
"""
self.logger.info("\n" + "="*60)
self.logger.info("EPITAXIAL ANNEALING - Crystal Auto-Assembly")
self.logger.info("="*60)
# Generador de datos para el tamaño objetivo
def generate_batch(batch_size: int) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
A = torch.randn(batch_size, self.target_size, self.target_size, device=self.device)
B = torch.randn(batch_size, self.target_size, self.target_size, device=self.device)
C = torch.bmm(A, B)
return (
A.reshape(batch_size, self.target_size * self.target_size),
B.reshape(batch_size, self.target_size * self.target_size),
C.reshape(batch_size, self.target_size * self.target_size)
)
# Optimizador con learning rate decreciente (cooling schedule)
initial_temp = Config.LEARNING_RATE * 0.1 # Temperatura inicial baja
optimizer = torch.optim.AdamW(
model.parameters(),
lr=initial_temp,
weight_decay=Config.WEIGHT_DECAY
)
# Scheduler: enfriamiento exponencial
scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.95)
history = {
'epoch': [],
'loss': [],
'alpha': [],
'delta': [],
'temperature': [],
'assembly_speed': []
}
initial_coeffs = model.get_coefficients()
initial_alpha = CrystallographyMetrics.compute_alpha_purity(initial_coeffs)
for epoch in range(max_epochs):
model.train()
epoch_loss = 0.0
for _ in range(10): # 10 batches por época
A, B, C = generate_batch(Config.BATCH_SIZE)
optimizer.zero_grad()
C_pred = model(A, B)
loss = nn.functional.mse_loss(C_pred, C)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
epoch_loss /= 10
# Métricas cristalográficas
coeffs = model.get_coefficients()
alpha = CrystallographyMetrics.compute_alpha_purity(coeffs)
delta = CrystallographyMetrics.compute_discretization_margin(coeffs)
current_temp = optimizer.param_groups[0]['lr']
# Velocidad de ensamblaje (cambio en pureza)
assembly_speed = alpha - initial_alpha if epoch == 0 else (alpha - history['alpha'][-1])
history['epoch'].append(epoch)
history['loss'].append(epoch_loss)
history['alpha'].append(alpha)
history['delta'].append(delta)
history['temperature'].append(current_temp)
history['assembly_speed'].append(assembly_speed)
if epoch % 5 == 0:
self.logger.info(
f"Epoch {epoch:3d} | Loss: {epoch_loss:.6f} | "
f"α: {alpha:6.2f} | δ: {delta:.4f} | "
f"T: {current_temp:.2e} | v_asm: {assembly_speed:+.4f}"
)
# Early stopping: cristal auto-ensamblado
if delta < early_stop_threshold and alpha > 7.0:
self.logger.info(f"\n🎯 CRYSTAL AUTO-ASSEMBLY COMPLETE at epoch {epoch}")
self.logger.info(f" Final purity: α={alpha:.2f}, δ={delta:.6f}")
break
# Cooling schedule
scheduler.step()
# Análisis final
final_coeffs = model.get_coefficients()
final_metrics = {
'final_alpha': CrystallographyMetrics.compute_alpha_purity(final_coeffs),
'final_delta': CrystallographyMetrics.compute_discretization_margin(final_coeffs),
'final_loss': history['loss'][-1],
'epochs_to_crystallization': len(history['epoch']),
'assembly_efficiency': (history['alpha'][-1] - initial_alpha) / len(history['epoch']),
'thermal_history': history
}
return final_metrics
class EpitaxyExperiment:
"""
Experimento completo de epitaxia: sembrar, crecer, analizar.
"""
def __init__(self, results_dir: str = "epitaxy_results"):
self.results_dir = Path(results_dir)
self.results_dir.mkdir(exist_ok=True)
self.logger = setup_logger("EpitaxyExperiment")
def run_epitaxial_growth_experiment(self, seed_checkpoint: str,
target_sizes: List[int] = [4, 8, 16]) -> Dict[str, Any]:
"""
Experimento completo: cultiva cristales de múltiples tamaños desde una semilla.
"""
self.logger.info("\n" + "="*80)
self.logger.info("EPITAXIAL GROWTH EXPERIMENT - From Seed to Superlattice")
self.logger.info("="*80)
seed_path = Path(seed_checkpoint)
if not seed_path.exists():
raise FileNotFoundError(f"Seed checkpoint not found: {seed_checkpoint}")
results = {
'seed_checkpoint': str(seed_path),
'target_sizes': target_sizes,
'experiments': {}
}
for target_size in target_sizes:
self.logger.info(f"\n{'='*60}")
self.logger.info(f"Growing {target_size}x{target_size} crystal from {seed_path.name}")
self.logger.info(f"{'='*60}")
try:
# Crear motor de crecimiento
engine = EpitaxialGrowthEngine(seed_checkpoint, target_size)
# Crecer cristal epitaxial
epitaxial_model = engine.grow_epitaxial_crystal()
# Validar estructura inicial
initial_coeffs = epitaxial_model.get_coefficients()
initial_validation = StrassenDataGenerator.verify_structure(initial_coeffs)
self.logger.info(f"Initial epitaxial structure:")
self.logger.info(f" Verification: {'PASS' if initial_validation['pass'] else 'FAIL'}")
self.logger.info(f" Max error: {initial_validation['max_error']:.4f}")
# Recocido cristalino
annealing_results = engine.anneal_crystal(epitaxial_model, max_epochs=50)
# Guardar modelo final
save_path = self.results_dir / f"epitaxial_{target_size}x{target_size}_from_{seed_path.stem}.pt"
torch.save(epitaxial_model.state_dict(), save_path)
# Análisis espectroscópico del cristal crecido
final_coeffs = epitaxial_model.get_coefficients()
spectroscopy = SpectroscopyMetrics.compute_weight_diffraction(final_coeffs)
results['experiments'][f'{target_size}x{target_size}'] = {
'initial_validation': initial_validation,
'annealing_results': annealing_results,
'spectroscopy': spectroscopy,
'saved_model_path': str(save_path),
'crystallization_success': annealing_results['final_alpha'] > 7.0
}
# Gráficas de evolución
self._plot_epitaxial_evolution(annealing_results, target_size, seed_path.stem)
except Exception as e:
self.logger.error(f"Failed to grow {target_size}x{target_size} crystal: {e}")
results['experiments'][f'{target_size}x{target_size}'] = {
'error': str(e),
'crystallization_success': False
}
# Resumen comparativo
self._generate_comparative_report(results)
# Guardar resultados completos
with open(self.results_dir / "epitaxy_experiment_results.json", 'w') as f:
json.dump(results, f, indent=2, default=str)
return results
def _plot_epitaxial_evolution(self, annealing_results: Dict[str, Any],
target_size: int, seed_name: str):
"""Visualiza la evolución del cristal durante el recocido"""
history = annealing_results['thermal_history']
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(14, 10))
epochs = history['epoch']
# Loss evolution
ax1.plot(epochs, history['loss'], 'b-', linewidth=2)
ax1.set_xlabel('Epoch')
ax1.set_ylabel('Loss')
ax1.set_title(f'Loss Evolution - {target_size}x{target_size} Crystal')
ax1.set_yscale('log')
ax1.grid(True, alpha=0.3)
# Purity evolution
ax2.plot(epochs, history['alpha'], 'g-', linewidth=2, label='α (purity)')
ax2.axhline(y=7.0, color='r', linestyle='--', label='Crystal threshold')
ax2.set_xlabel('Epoch')
ax2.set_ylabel('Purity (α)')
ax2.set_title('Crystallization Process')
ax2.legend()
ax2.grid(True, alpha=0.3)
# Discretization margin
ax3.plot(epochs, history['delta'], 'r-', linewidth=2)
ax3.set_xlabel('Epoch')
ax3.set_ylabel('Discretization Margin (δ)')
ax3.set_title('Structural Convergence')
ax3.set_yscale('log')
ax3.grid(True, alpha=0.3)
# Assembly speed
ax4.plot(epochs, history['assembly_speed'], 'purple', linewidth=2)
ax4.axhline(y=0, color='k', linestyle='-', alpha=0.3)
ax4.set_xlabel('Epoch')
ax4.set_ylabel('Assembly Speed (dα/dt)')
ax4.set_title('Crystal Growth Dynamics')
ax4.grid(True, alpha=0.3)
plt.suptitle(f'Epitaxial Growth: {seed_name} → {target_size}x{target_size}',
fontsize=14, fontweight='bold')
plt.tight_layout()
plt.savefig(self.results_dir / f"epitaxy_evolution_{target_size}x{target_size}.png", dpi=150)
plt.close()
def _generate_comparative_report(self, results: Dict[str, Any]):
"""Genera reporte comparativo de todos los experimentos epitaxiales"""
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))
sizes = []
epochs_to_crystal = []
final_alphas = []
assembly_efficiencies = []
for size_key, exp_data in results['experiments'].items():
if 'error' not in exp_data:
size = int(size_key.split('x')[0])
sizes.append(size)
epochs_to_crystal.append(exp_data['annealing_results']['epochs_to_crystallization'])
final_alphas.append(exp_data['annealing_results']['final_alpha'])
assembly_efficiencies.append(exp_data['annealing_results']['assembly_efficiency'])
if not sizes:
self.logger.warning("No successful experiments to plot")
plt.close()
return
# Epochs vs Size
ax1.plot(sizes, epochs_to_crystal, 'bo-', linewidth=2, markersize=10)
ax1.set_xlabel('Matrix Size (NxN)', fontsize=12)
ax1.set_ylabel('Epochs to Crystallization', fontsize=12)
ax1.set_title('Epitaxial Efficiency: Assembly Time', fontsize=14)
ax1.grid(True, alpha=0.3)
# Ajuste teórico: si epitaxia es perfecta, debería ser ~constante o log(N)
if len(sizes) > 1:
z = np.polyfit(np.log(sizes), epochs_to_crystal, 1)
p = np.poly1d(z)
ax1.plot(sizes, p(np.log(sizes)), 'r--',
label=f'Log fit: {z[0]:.2f}*log(N) + {z[1]:.2f}')
ax1.legend()
# Final purity vs Size
ax2.bar(sizes, final_alphas, color='green', alpha=0.7, edgecolor='black')
ax2.axhline(y=7.0, color='r', linestyle='--', linewidth=2, label='Crystal threshold')
ax2.set_xlabel('Matrix Size (NxN)', fontsize=12)
ax2.set_ylabel('Final Purity (α)', fontsize=12)
ax2.set_title('Crystal Quality Post-Epitaxy', fontsize=14)
ax2.legend()
ax2.grid(True, alpha=0.3, axis='y')
plt.tight_layout()
plt.savefig(self.results_dir / "epitaxy_comparative_analysis.png", dpi=150)
plt.close()
# Imprimir reporte textual
self.logger.info("\n" + "="*80)
self.logger.info("EPITAXIAL GROWTH COMPARATIVE REPORT")
self.logger.info("="*80)
for size, epochs, alpha, efficiency in zip(sizes, epochs_to_crystal,
final_alphas, assembly_efficiencies):
status = "✓ SUCCESS" if alpha > 7.0 else "✗ PARTIAL"
self.logger.info(
f"{size:2d}x{size:2d} | Epochs: {epochs:3d} | "
f"α: {alpha:6.2f} | Efficiency: {efficiency:.4f} | {status}"
)
if len(epochs_to_crystal) > 1:
avg_speedup = epochs_to_crystal[0] / np.mean(epochs_to_crystal[1:])
self.logger.info(f"\nAverage speedup vs baseline: {avg_speedup:.2f}x")
@dataclass
class ThermodynamicPotential:
"""Potencial de Helmholtz: F = U - T*S + μ*N + α_term*C"""
internal_energy: float # Loss de generalización
temperature: float # T_eff
entropy: float # S_gen
chemical_potential: float # μ para "átomos" de conocimiento
crystallinity: float # α (pureza cristalina)
particle_number: float # N (parámetros activos)
def helmholtz_free_energy(self) -> float:
"""F = U - T*S (a μ y N constantes)"""
return self.internal_energy - self.temperature * self.entropy
def gibbs_free_energy(self) -> float:
"""G = F + μ*N + P*V (presión algorítmica)"""
pressure_term = self.crystallinity * self.particle_number
return self.helmholtz_free_energy() + self.chemical_potential * self.particle_number + pressure_term
def is_stable(self) -> bool:
"""Criterio de estabilidad: dG < 0"""
return self.gibbs_free_energy() < 0
class SpectroscopyMetrics:
@staticmethod
def compute_weight_diffraction(coeffs: Dict[str, torch.Tensor]) -> Dict[str, Any]:
W = torch.cat([c.flatten() for c in coeffs.values()])
W_reshaped = W.reshape(-1, 1)
fft_spectrum = torch.fft.fft(W_reshaped.squeeze())
power_spectrum = torch.abs(fft_spectrum)**2
peaks = []
threshold = torch.mean(power_spectrum) + 2 * torch.std(power_spectrum)
for i, power in enumerate(power_spectrum):
if power > threshold:
peaks.append({'frequency': i, 'intensity': float(power)})
is_crystalline = len(peaks) > 0 and len(peaks) < len(power_spectrum) // 2
return {
'power_spectrum': power_spectrum.cpu().numpy().tolist(),
'bragg_peaks': peaks,
'is_crystalline_structure': is_crystalline,
'spectral_entropy': float(SpectroscopyMetrics._compute_spectral_entropy(power_spectrum))
}
@staticmethod
def _compute_spectral_entropy(power_spectrum: torch.Tensor) -> float:
ps_normalized = power_spectrum / (torch.sum(power_spectrum) + 1e-10)
ps_normalized = ps_normalized[ps_normalized > 1e-10]
entropy = -torch.sum(ps_normalized * torch.log(ps_normalized + 1e-10))
return float(entropy)
@staticmethod
def extract_lattice_parameters(weight_tensor: torch.Tensor, rank: int = 7) -> Dict[str, Any]:
"""
Extrae parámetros de red preservando la geometría física del tensor.
FIX: En lugar de reshape arbitrario, aplicamos SVD sobre la matriz
de covarianza que preserva la estructura de correlaciones.
"""
# Asegurar que trabajamos con un tensor 2D válido
if weight_tensor.dim() == 1:
total_size = weight_tensor.numel()
# Crear matriz cuadrada más cercana posible
side_dim = int(np.ceil(np.sqrt(total_size)))
# Pad con ceros para completar la matriz cuadrada
padded_size = side_dim * side_dim
if total_size < padded_size:
padding = torch.zeros(padded_size - total_size, device=weight_tensor.device)
weight_tensor = torch.cat([weight_tensor, padding])
weight_tensor = weight_tensor[:side_dim * side_dim].reshape(side_dim, side_dim)
# SVD sobre la matriz original (preserva estructura física)
try:
U, S, Vh = torch.linalg.svd(weight_tensor, full_matrices=False)
# Limpieza de ruido térmico usando umbral físico (10% del máximo)
threshold = S[0] * Config.MIN_VARIANCE_THRESHOLD ** 0.5
S_clean = torch.where(S > threshold, S, torch.zeros_like(S))
# Reconstrucción cristalina
rank_truncated = min(rank, len(S_clean))
U_truncated = U[:, :rank_truncated]
S_truncated = S_clean[:rank_truncated]
Vh_truncated = Vh[:rank_truncated, :]
clean_crystal = U_truncated @ torch.diag(S_truncated) @ Vh_truncated
# Error de reconstrucción (pureza cristalina)
reconstruction_error = torch.norm(weight_tensor - clean_crystal) / (torch.norm(weight_tensor) + Config.ENTROPY_EPS)
# Gap espectral (indicador de estructura discreta)
spectral_gap = (S[0] / (S[1] + Config.ENTROPY_EPS)) if len(S) > 1 else float('inf')
return {
'U_basis': U_truncated.cpu().numpy().tolist(),
'singular_values': S.cpu().numpy().tolist(),
'clean_singular_values': S_truncated.cpu().numpy().tolist(),
'V_basis': Vh_truncated.cpu().numpy().tolist(),
'reconstruction_error': float(reconstruction_error),
'effective_rank': int(torch.sum(S_clean > threshold)),
'spectral_gap': float(spectral_gap),
'thermal_noise_threshold': float(threshold)
}
except Exception as e:
return {
'error': str(e),
'tensor_shape': list(weight_tensor.shape),
'total_elements': weight_tensor.numel()
}
@staticmethod
def compute_gibbs_free_energy(loss: float, temp: float, entropy: float) -> float:
return loss + (temp * entropy)
@staticmethod
def extract_canonical_decomposition(coeffs: Dict[str, torch.Tensor], rank: int = 7) -> Dict[str, Any]:
"""
Descomposición Canónica del tensor tripartito (U, V, W).
FIX: Preserva la estructura bilineal en lugar de tratar como matriz plana.
Aplicamos HOSVD (Higher-Order SVD) para tensores de orden 3.
"""
U_weight = coeffs['U'] # (hidden_dim, input_dim)
V_weight = coeffs['V'] # (hidden_dim, input_dim)
W_weight = coeffs['W'] # (output_dim, hidden_dim)
try:
# HOSVD: Descomposición por cada modo del tensor
# Modo 1: SVD de U
U_svd = torch.linalg.svd(U_weight, full_matrices=False)
# Modo 2: SVD de V
V_svd = torch.linalg.svd(V_weight, full_matrices=False)
# Modo 3: SVD de W (transpuesto para consistencia dimensional)
W_svd = torch.linalg.svd(W_weight.t(), full_matrices=False)
# Truncar a rank manteniendo coherencia dimensional
rank_effective = min(rank, U_svd[1].numel(), V_svd[1].numel(), W_svd[1].numel())
# Core tensor: producto de valores singulares (acoplamiento entre modos)
core_tensor_diagonal = (
U_svd[1][:rank_effective] *
V_svd[1][:rank_effective] *
W_svd[1][:rank_effective]
)
factors = {
'factor_A': U_svd[0][:, :rank_effective].cpu().numpy().tolist(),
'factor_B': V_svd[0][:, :rank_effective].cpu().numpy().tolist(),
'factor_C': W_svd[0][:, :rank_effective].cpu().numpy().tolist(),
'core_tensor_approximation': {
'U_singular': U_svd[1][:rank_effective].cpu().numpy().tolist(),
'V_singular': V_svd[1][:rank_effective].cpu().numpy().tolist(),
'W_singular': W_svd[1][:rank_effective].cpu().numpy().tolist(),
'coupled_strength': core_tensor_diagonal.cpu().numpy().tolist()
}
}
# Discretización a red cristalina {-1, 0, 1}
discretized_factors = SpectroscopyMetrics._discretize_to_integers(factors)
return {
'continuous_factors': factors,
'discretized_factors': discretized_factors,
'is_strassen_equivalent': SpectroscopyMetrics._check_strassen_equivalence(discretized_factors),
'tensor_rank': rank_effective,
'mode_coupling': float(torch.mean(core_tensor_diagonal))
}
except Exception as e:
return {'error': str(e)}
@staticmethod
def _discretize_to_integers(factors: Dict[str, Any]) -> Dict[str, Any]:
"""
Proyecta factores continuos a la red cristalina discreta {-1, 0, 1}.
"""
discretized = {}
for key in ['factor_A', 'factor_B', 'factor_C']:
if key in factors:
factor_array = np.array(factors[key])
# Normalización por el máximo absoluto
max_val = np.max(np.abs(factor_array))
if max_val > 1e-6:
normalized = factor_array / max_val
rounded = np.round(normalized)
discretized[key] = rounded.tolist()
else:
discretized[key] = factor_array.tolist()
return discretized
@staticmethod
def _check_strassen_equivalence(discretized_factors: Dict[str, Any]) -> Dict[str, Any]:
"""
Verifica si los factores discretizados corresponden a la estructura de Strassen.
"""
valid_values = {-1, 0, 1}
is_discrete = True
for key in ['factor_A', 'factor_B', 'factor_C']:
if key in discretized_factors:
factor_array = np.array(discretized_factors[key])
unique_vals = set(np.unique(factor_array.flatten()))
if not unique_vals.issubset(valid_values):
is_discrete = False
break
return {
'is_discrete_structure': is_discrete,
'satisfies_strassen_pattern': is_discrete,
'validation': 'Atomic structure confirmed' if is_discrete else 'Continuous residual detected'
}
@staticmethod
def create_superlattice_seed(base_tensor: Dict[str, torch.Tensor], scale_factor: int = 2) -> Dict[str, torch.Tensor]:
U_base = base_tensor['U']
V_base = base_tensor['V']
W_base = base_tensor['W']
U_expanded = torch.kron(U_base, torch.eye(scale_factor, device=U_base.device))
V_expanded = torch.kron(V_base, torch.eye(scale_factor, device=V_base.device))
W_expanded = torch.kron(W_base, torch.eye(scale_factor, device=W_base.device))
return {
'U': U_expanded,
'V': V_expanded,
'W': W_expanded,
'scale_factor': scale_factor,
'original_shape': {
'U': list(U_base.shape),
'V': list(V_base.shape),
'W': list(W_base.shape)
}
}
class ThermodynamicMetrics:
@staticmethod
def compute_effective_temperature(gradient_buffer: List[torch.Tensor], learning_rate: float) -> float:
if len(gradient_buffer) < 2:
return 0.0
grads = torch.stack([g.flatten() for g in gradient_buffer])
second_moment = torch.mean(torch.norm(grads, dim=1)**2)
first_moment_sq = torch.norm(torch.mean(grads, dim=0))**2
variance = second_moment - first_moment_sq
return float((learning_rate / 2.0) * variance)
@staticmethod
def compute_critical_exponents(temp_history: List[float], cv_history: List[float],
alpha_history: List[float]) -> Dict[str, float]:
"""
Calcula exponentes críticos cerca de transiciones de fase.
Leyes de escala:
- C_v ~ |T - T_c|^{-α_exp} (calor específico)
- ξ ~ |T - T_c|^{-ν} (longitud de correlación)
- τ ~ |T - T_c|^{-z} (tiempo de grokking)
"""
if len(temp_history) < 5 or len(cv_history) < 5:
return {
'alpha_exponent': 0.0,
'nu_exponent': 0.0,
'z_exponent': 0.0,
'critical_temperature': 0.0
}
# Identificar temperatura crítica (donde C_v es máximo)
cv_array = np.array(cv_history)
temp_array = np.array(temp_history)
if len(cv_array) == 0 or np.all(cv_array == 0):
return {
'alpha_exponent': 0.0,
'nu_exponent': 0.0,
'z_exponent': 0.0,
'critical_temperature': 0.0
}
critical_idx = np.argmax(cv_array)
T_c = temp_array[critical_idx]
# Exponente α: C_v ~ |T - T_c|^{-α}
delta_T = np.abs(temp_array - T_c) + Config.ENTROPY_EPS
log_delta_T = np.log(delta_T)
log_cv = np.log(cv_array + Config.ENTROPY_EPS)
# Filtrar puntos válidos (cerca de T_c)
near_critical = delta_T < (0.2 * T_c) if T_c > 0 else np.ones_like(delta_T, dtype=bool)
if np.sum(near_critical) > 2:
try:
alpha_exp, _ = np.polyfit(log_delta_T[near_critical], log_cv[near_critical], 1)
alpha_exp = -float(alpha_exp) # El signo negativo viene de la ley de escala
except:
alpha_exp = 0.0
else:
alpha_exp = 0.0
# Exponente ν: estimado desde longitud de correlación (usando α como proxy)
if len(alpha_history) > 2:
alpha_array = np.array(alpha_history)
correlation_length = 1.0 / (alpha_array + Config.ENTROPY_EPS)
log_xi = np.log(correlation_length + Config.ENTROPY_EPS)
if np.sum(near_critical) > 2:
try:
nu_exp, _ = np.polyfit(log_delta_T[near_critical], log_xi[near_critical], 1)
nu_exp = -float(nu_exp)
except:
nu_exp = 0.0
else:
nu_exp = 0.0
else:
nu_exp = 0.0
# Exponente z: dinámica crítica (τ ~ ξ^z)
z_exp = alpha_exp / nu_exp if nu_exp > Config.ENTROPY_EPS else 0.0
return {