Add holographic_transformer_model.py
Browse files- holographic_transformer_model.py +114 -0
holographic_transformer_model.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.optim as optim
|
| 4 |
+
from torch.optim.lr_scheduler import CosineAnnealingLR
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
|
| 7 |
+
class HolographicMasterCodeTransformer(nn.Module):
|
| 8 |
+
def __init__(self, input_dim=8, d_model=128, nhead=8, num_layers=6, output_dim=1, n_harmonics=4):
|
| 9 |
+
super().__init__()
|
| 10 |
+
self.d_model = d_model
|
| 11 |
+
self.n_harmonics = n_harmonics
|
| 12 |
+
self.alpha_0 = 1.0 / 137.035
|
| 13 |
+
|
| 14 |
+
self.input_proj = nn.Linear(input_dim, d_model)
|
| 15 |
+
|
| 16 |
+
encoder_layer = nn.TransformerEncoderLayer(
|
| 17 |
+
d_model=d_model,
|
| 18 |
+
nhead=nhead,
|
| 19 |
+
dim_feedforward=d_model * 4,
|
| 20 |
+
dropout=0.1,
|
| 21 |
+
activation='gelu',
|
| 22 |
+
batch_first=True,
|
| 23 |
+
norm_first=True
|
| 24 |
+
)
|
| 25 |
+
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
|
| 26 |
+
|
| 27 |
+
self.harmonic_weights = nn.Parameter(torch.randn(n_harmonics, d_model))
|
| 28 |
+
|
| 29 |
+
self.output_head = nn.Sequential(
|
| 30 |
+
nn.LayerNorm(d_model),
|
| 31 |
+
nn.Linear(d_model, d_model // 2),
|
| 32 |
+
nn.GELU(),
|
| 33 |
+
nn.Dropout(0.1),
|
| 34 |
+
nn.Linear(d_model // 2, output_dim)
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
def forward(self, x, alpha=None):
|
| 38 |
+
if alpha is None:
|
| 39 |
+
alpha = self.alpha_0
|
| 40 |
+
|
| 41 |
+
h = self.input_proj(x)
|
| 42 |
+
h = h.unsqueeze(1)
|
| 43 |
+
h = self.transformer(h)
|
| 44 |
+
h = h.squeeze(1)
|
| 45 |
+
|
| 46 |
+
# Master Code Ψ
|
| 47 |
+
psi = torch.zeros_like(h)
|
| 48 |
+
for n in range(self.n_harmonics):
|
| 49 |
+
phase = 2 * torch.pi * (n + 1) * (alpha - self.alpha_0) * 800.0 # Yumuşatıldı
|
| 50 |
+
psi += self.harmonic_weights[n] * torch.cos(h * (n + 1) + phase)
|
| 51 |
+
|
| 52 |
+
# Güvenlik Kilidi (daha yumuşak)
|
| 53 |
+
alpha_dev = torch.abs(alpha - self.alpha_0)
|
| 54 |
+
security_factor = torch.exp(-300.0 * alpha_dev) # Daha yumuşak
|
| 55 |
+
|
| 56 |
+
h = h + 0.35 * psi * security_factor
|
| 57 |
+
return self.output_head(h)
|
| 58 |
+
|
| 59 |
+
def holographic_reg(self):
|
| 60 |
+
reg = sum(torch.norm(w, p=1) for w in self.harmonic_weights)
|
| 61 |
+
return 0.0015 * reg / self.n_harmonics # Daha dengeli
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# Eğitim fonksiyonu (300 epoch)
|
| 65 |
+
def train_holographic(alpha_values, epochs=300):
|
| 66 |
+
results = {}
|
| 67 |
+
for name, alpha_val in alpha_values.items():
|
| 68 |
+
print(f"\n→ Eğitim: {name} (α = {alpha_val:.8f})")
|
| 69 |
+
model = HolographicMasterCodeTransformer()
|
| 70 |
+
optimizer = optim.AdamW(model.parameters(), lr=0.001, weight_decay=1e-5)
|
| 71 |
+
scheduler = CosineAnnealingLR(optimizer, T_max=epochs, eta_min=1e-6)
|
| 72 |
+
criterion = nn.MSELoss()
|
| 73 |
+
|
| 74 |
+
X = torch.randn(300, 8)
|
| 75 |
+
y = torch.sin(X.sum(dim=1, keepdim=True)) * 0.9 + 0.05 * torch.randn(300, 1)
|
| 76 |
+
|
| 77 |
+
best_loss = float('inf')
|
| 78 |
+
for epoch in tqdm(range(epochs)):
|
| 79 |
+
optimizer.zero_grad()
|
| 80 |
+
pred = model(X, alpha=alpha_val)
|
| 81 |
+
loss = criterion(pred, y)
|
| 82 |
+
reg = model.holographic_reg()
|
| 83 |
+
total_loss = loss + reg
|
| 84 |
+
|
| 85 |
+
total_loss.backward()
|
| 86 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 87 |
+
optimizer.step()
|
| 88 |
+
scheduler.step()
|
| 89 |
+
|
| 90 |
+
if loss.item() < best_loss:
|
| 91 |
+
best_loss = loss.item()
|
| 92 |
+
|
| 93 |
+
if epoch % 50 == 0 or epoch == epochs-1:
|
| 94 |
+
print(f"Epoch {epoch:3d} | Loss: {loss.item():.6f} | Reg: {reg.item():.6f}")
|
| 95 |
+
|
| 96 |
+
results[name] = best_loss
|
| 97 |
+
return results
|
| 98 |
+
|
| 99 |
+
# ====================== Çalıştır ======================
|
| 100 |
+
if __name__ == "__main__":
|
| 101 |
+
alpha_values = {
|
| 102 |
+
"Nominal": 1/137.035,
|
| 103 |
+
"Physical": 1/137.035999,
|
| 104 |
+
"Sapma1": 1/137.000,
|
| 105 |
+
"Sapma2": 1/137.070
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
results = train_holographic(alpha_values, epochs=300)
|
| 109 |
+
|
| 110 |
+
# En iyi sonucu yazdır
|
| 111 |
+
best_alpha = min(results, key=lambda k: results[k]['final_loss'])
|
| 112 |
+
print("\n" + "="*70)
|
| 113 |
+
print(f"EN İYİ SONUÇ → {best_alpha} α ile Final Loss = {results[best_alpha]:.6f}")
|
| 114 |
+
print("="*70)
|