beanapologist commited on
Commit
b330d24
·
verified ·
1 Parent(s): 4bac7d4

Upload folder using huggingface_hub

Browse files
Files changed (4) hide show
  1. README.md +20 -7
  2. __pycache__/app.cpython-313.pyc +0 -0
  3. app.py +679 -0
  4. requirements.txt +5 -0
README.md CHANGED
@@ -1,12 +1,25 @@
1
  ---
2
- title: Mu Train
3
- emoji: 🌖
4
- colorFrom: green
5
- colorTo: blue
6
  sdk: gradio
7
- sdk_version: 6.11.0
8
  app_file: app.py
9
- pinned: false
 
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: "μ-Net Training Lab"
3
+ emoji: 🧬
4
+ colorFrom: indigo
5
+ colorTo: purple
6
  sdk: gradio
7
+ sdk_version: "5.23.0"
8
  app_file: app.py
9
+ pinned: true
10
+ license: mit
11
+ short_description: "Train neural networks grounded in the Eigenverse"
12
  ---
13
 
14
+ # 🧬 μ-Net Training Lab
15
+
16
+ **Train neural networks whose architecture IS the Eigenverse.**
17
+
18
+ - 8 layers (μ⁸ = 1)
19
+ - μ^k phase-modulated activations (135° rotation per layer)
20
+ - Coherence loss regularization C(r) = 2r/(1+r²)
21
+ - Silver-gated skip connections (η = 1/√2)
22
+
23
+ 552 Lean theorems → network architecture → trained weights.
24
+
25
+ [Eigenverse](https://github.com/beanapologist/Eigenverse) · [COINjecture](https://huggingface.co/COINjecture)
__pycache__/app.cpython-313.pyc ADDED
Binary file (33.2 kB). View file
 
app.py ADDED
@@ -0,0 +1,679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ μ-Net: Eigenverse-Grounded Neural Network
3
+ ==========================================
4
+
5
+ Train a neural network whose architecture IS the Eigenverse:
6
+ - 8 layers (μ⁸ = 1, orbit closure)
7
+ - Phase-modulated activations (μ^k rotation per layer)
8
+ - Coherence loss (C(r) = 2r/(1+r²) as regularizer)
9
+ - Silver/Golden threshold gating
10
+
11
+ The network learns to predict coherence from raw signals.
12
+ Training happens live on HuggingFace hardware.
13
+
14
+ Source: github.com/beanapologist/Eigenverse (552 theorems, 0 sorry)
15
+ """
16
+
17
+ import gradio as gr
18
+ import numpy as np
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.optim as optim
22
+ import json
23
+ import time
24
+ import os
25
+ from datetime import datetime
26
+
27
+ # ── Eigenverse Constants ─────────────────────────────────────────────
28
+
29
+ η = 1 / np.sqrt(2)
30
+ μ_complex = np.exp(1j * 3 * np.pi / 4) # −η + iη
31
+ δ_S = 1 + np.sqrt(2)
32
+ φ = (1 + np.sqrt(5)) / 2
33
+
34
+ def C(r):
35
+ """Coherence function. Lean-verified: C(1)=1 max, C(r)=C(1/r)."""
36
+ if isinstance(r, (np.ndarray, torch.Tensor)):
37
+ return 2 * r / (1 + r ** 2)
38
+ if r <= 0:
39
+ return 0.0
40
+ return 2 * r / (1 + r ** 2)
41
+
42
+
43
+ # ── μ-Activation Function ────────────────────────────────────────────
44
+
45
+ class MuActivation(nn.Module):
46
+ """
47
+ Phase-modulated activation: applies μ^k rotation at layer k.
48
+
49
+ For real-valued networks, this decomposes to:
50
+ x → x · cos(k·3π/4) + learnable_bias · sin(k·3π/4)
51
+
52
+ The 135° rotation mixes dissipation (cos) and oscillation (sin).
53
+ After 8 layers: cos(8·3π/4) = cos(6π) = 1, sin = 0 → identity.
54
+ """
55
+ def __init__(self, phase_k: int):
56
+ super().__init__()
57
+ self.phase = phase_k % 8
58
+ angle = self.phase * 3 * np.pi / 4
59
+ self.cos_k = np.cos(angle)
60
+ self.sin_k = np.sin(angle)
61
+ self.gate = nn.Parameter(torch.tensor(float(η))) # learnable gate at η
62
+
63
+ def forward(self, x):
64
+ # Phase rotation: mix real (dissipation) and imaginary (oscillation)
65
+ real_part = x * self.cos_k
66
+ imag_part = torch.tanh(x * self.gate) * self.sin_k
67
+ return real_part + imag_part
68
+
69
+
70
+ # ── Coherence Loss ───────────────────────────────────────────────────
71
+
72
+ class CoherenceLoss(nn.Module):
73
+ """
74
+ Loss that penalizes decoherence.
75
+
76
+ L = MSE(pred, target) + λ · (1 - C(r_weights))
77
+
78
+ where r_weights = ||W||/||W_init|| measures weight drift from initialization.
79
+ Regularizes toward coherent (balanced) weight distributions.
80
+ """
81
+ def __init__(self, lambda_coherence=0.01):
82
+ super().__init__()
83
+ self.mse = nn.MSELoss()
84
+ self.lambda_c = lambda_coherence
85
+
86
+ def forward(self, pred, target, model):
87
+ base_loss = self.mse(pred, target)
88
+
89
+ # Coherence regularization
90
+ total_norm = 0.0
91
+ n_params = 0
92
+ for p in model.parameters():
93
+ if p.requires_grad:
94
+ r = torch.norm(p) / (torch.norm(p.data) + 1e-8)
95
+ c = 2 * r / (1 + r ** 2)
96
+ total_norm += (1 - c)
97
+ n_params += 1
98
+
99
+ coherence_penalty = total_norm / max(n_params, 1)
100
+ return base_loss + self.lambda_c * coherence_penalty
101
+
102
+
103
+ # ── μ-Net Architecture ───────────────────────────────────────────────
104
+
105
+ class MuNet(nn.Module):
106
+ """
107
+ 8-layer network grounded in the Eigenverse.
108
+
109
+ Architecture:
110
+ Input → [Linear → MuActivation(k) → LayerNorm] × 8 → Output
111
+
112
+ Each layer applies the μ^k phase rotation.
113
+ After 8 layers the phase returns to identity (μ⁸ = 1).
114
+ Hidden dimension = 64 (8² = number of distinct orbit states).
115
+ """
116
+ def __init__(self, input_dim=8, hidden_dim=64, output_dim=1):
117
+ super().__init__()
118
+
119
+ self.input_proj = nn.Linear(input_dim, hidden_dim)
120
+
121
+ self.layers = nn.ModuleList()
122
+ for k in range(8):
123
+ self.layers.append(nn.ModuleDict({
124
+ 'linear': nn.Linear(hidden_dim, hidden_dim),
125
+ 'activation': MuActivation(k),
126
+ 'norm': nn.LayerNorm(hidden_dim),
127
+ }))
128
+
129
+ self.output_proj = nn.Linear(hidden_dim, output_dim)
130
+
131
+ # Silver gate: skip connection weighted by C(δ_S) = η
132
+ self.silver_gate = nn.Parameter(torch.tensor(float(C(δ_S))))
133
+
134
+ self._init_weights()
135
+
136
+ def _init_weights(self):
137
+ """Initialize with balanced weights (coherence-aware)."""
138
+ for name, p in self.named_parameters():
139
+ if 'weight' in name and p.dim() >= 2:
140
+ # Xavier init scaled by η
141
+ nn.init.xavier_uniform_(p, gain=float(η))
142
+ elif 'bias' in name:
143
+ nn.init.zeros_(p)
144
+
145
+ def forward(self, x):
146
+ h = self.input_proj(x)
147
+ h_skip = h # residual from input
148
+
149
+ for k, layer in enumerate(self.layers):
150
+ h_new = layer['linear'](h)
151
+ h_new = layer['activation'](h_new)
152
+ h_new = layer['norm'](h_new)
153
+
154
+ # Residual connection gated by silver coherence
155
+ h = h + self.silver_gate * h_new
156
+
157
+ # Add skip connection (8-cycle closure: input ≈ output structure)
158
+ h = h + h_skip
159
+
160
+ return self.output_proj(h)
161
+
162
+ def get_coherence_state(self):
163
+ """Measure the model's internal coherence."""
164
+ norms = []
165
+ for p in self.parameters():
166
+ if p.requires_grad and p.dim() >= 2:
167
+ norms.append(torch.norm(p).item())
168
+
169
+ if len(norms) < 2:
170
+ return 1.0
171
+
172
+ ratios = [norms[i+1] / (norms[i] + 1e-8) for i in range(len(norms)-1)]
173
+ coherences = [C(r) for r in ratios]
174
+ return float(np.mean(coherences))
175
+
176
+
177
+ # ── Data Generation ──────────────────────────────────────────────────
178
+
179
+ def generate_coherence_data(n_samples=10000, seq_len=8):
180
+ """
181
+ Generate training data: sequences of ratios → coherence prediction.
182
+
183
+ Input: 8 consecutive ratio values (one per μ-phase)
184
+ Output: mean coherence of the sequence
185
+
186
+ This teaches the network to compute C(r) from raw signals.
187
+ """
188
+ X = np.zeros((n_samples, seq_len))
189
+ y = np.zeros((n_samples, 1))
190
+
191
+ for i in range(n_samples):
192
+ # Generate ratio sequences with different characteristics
193
+ mode = np.random.choice(['equilibrium', 'silver', 'golden', 'chaotic', 'oscillating'])
194
+
195
+ if mode == 'equilibrium':
196
+ # Near r=1 (high coherence)
197
+ ratios = 1.0 + np.random.normal(0, 0.05, seq_len)
198
+ elif mode == 'silver':
199
+ # Near δ_S (silver coherence)
200
+ center = np.random.choice([δ_S, 1/δ_S])
201
+ ratios = center + np.random.normal(0, 0.2, seq_len)
202
+ elif mode == 'golden':
203
+ # Near φ² (Koide coherence)
204
+ center = np.random.choice([φ**2, 1/φ**2])
205
+ ratios = center + np.random.normal(0, 0.3, seq_len)
206
+ elif mode == 'chaotic':
207
+ # Far from equilibrium
208
+ ratios = np.random.exponential(2, seq_len) + 0.01
209
+ else:
210
+ # 8-cycle oscillation (μ-pattern)
211
+ base = np.random.uniform(0.5, 2.0)
212
+ phases = [base * np.cos(k * 3 * np.pi / 4) + 1.5 for k in range(seq_len)]
213
+ ratios = np.array(phases) + np.random.normal(0, 0.1, seq_len)
214
+
215
+ ratios = np.clip(ratios, 0.01, 20.0)
216
+ X[i] = ratios
217
+ coherences = [C(r) for r in ratios]
218
+ y[i] = np.mean(coherences)
219
+
220
+ return torch.tensor(X, dtype=torch.float32), torch.tensor(y, dtype=torch.float32)
221
+
222
+
223
+ def generate_np_prediction_data(n_samples=10000, seq_len=8):
224
+ """
225
+ Generate data for NP-solution-style prediction.
226
+
227
+ Input: 8 values from a sequence
228
+ Output: predicted next value (regression)
229
+
230
+ Sequences follow coherence-governed dynamics.
231
+ """
232
+ X = np.zeros((n_samples, seq_len))
233
+ y = np.zeros((n_samples, 1))
234
+
235
+ for i in range(n_samples):
236
+ # Generate a coherence-governed sequence
237
+ start = np.random.uniform(0.1, 5.0)
238
+ decay = np.random.uniform(0.8, 1.2)
239
+ noise = np.random.uniform(0.01, 0.2)
240
+
241
+ seq = [start]
242
+ for j in range(seq_len):
243
+ r = seq[-1]
244
+ c = C(r)
245
+ # Next value pulled toward equilibrium by coherence
246
+ next_val = r + (1.0 - r) * (1.0 - c) * decay + np.random.normal(0, noise)
247
+ next_val = max(0.01, next_val)
248
+ seq.append(next_val)
249
+
250
+ X[i] = seq[:seq_len]
251
+ y[i] = seq[seq_len]
252
+
253
+ return torch.tensor(X, dtype=torch.float32), torch.tensor(y, dtype=torch.float32)
254
+
255
+
256
+ # ── Training ─────────────────────────────────────────────────────────
257
+
258
+ def train_model(task, epochs, learning_rate, lambda_coherence, progress=gr.Progress()):
259
+ """Train the μ-Net and return results."""
260
+
261
+ epochs = int(epochs)
262
+ lr = float(learning_rate)
263
+ lam = float(lambda_coherence)
264
+
265
+ # Generate data
266
+ progress(0, desc="Generating training data...")
267
+ if task == "Coherence Prediction":
268
+ X_train, y_train = generate_coherence_data(8000)
269
+ X_val, y_val = generate_coherence_data(2000)
270
+ else:
271
+ X_train, y_train = generate_np_prediction_data(8000)
272
+ X_val, y_val = generate_np_prediction_data(2000)
273
+
274
+ # Create model
275
+ model = MuNet(input_dim=8, hidden_dim=64, output_dim=1)
276
+ criterion = CoherenceLoss(lambda_coherence=lam)
277
+ optimizer = optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01)
278
+ scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs)
279
+
280
+ # Training loop
281
+ history = {
282
+ 'epoch': [], 'train_loss': [], 'val_loss': [],
283
+ 'coherence': [], 'silver_gate': []
284
+ }
285
+
286
+ batch_size = 256
287
+ n_batches = len(X_train) // batch_size
288
+
289
+ log_lines = []
290
+ log_lines.append(f"🧬 μ-Net Training Started")
291
+ log_lines.append(f"Task: {task}")
292
+ log_lines.append(f"Architecture: 8 layers × 64 hidden (μ^k activation)")
293
+ log_lines.append(f"Parameters: {sum(p.numel() for p in model.parameters()):,}")
294
+ log_lines.append(f"Epochs: {epochs} | LR: {lr} | λ_coherence: {lam}")
295
+ log_lines.append(f"{'─'*50}")
296
+
297
+ best_val = float('inf')
298
+
299
+ for epoch in range(epochs):
300
+ model.train()
301
+ epoch_loss = 0.0
302
+
303
+ # Shuffle
304
+ perm = torch.randperm(len(X_train))
305
+ X_shuf = X_train[perm]
306
+ y_shuf = y_train[perm]
307
+
308
+ for b in range(n_batches):
309
+ start = b * batch_size
310
+ end = start + batch_size
311
+ xb = X_shuf[start:end]
312
+ yb = y_shuf[start:end]
313
+
314
+ optimizer.zero_grad()
315
+ pred = model(xb)
316
+ loss = criterion(pred, yb, model)
317
+ loss.backward()
318
+
319
+ # Gradient clipping (coherence-bounded)
320
+ torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
321
+
322
+ optimizer.step()
323
+ epoch_loss += loss.item()
324
+
325
+ scheduler.step()
326
+
327
+ # Validation
328
+ model.eval()
329
+ with torch.no_grad():
330
+ val_pred = model(X_val)
331
+ val_loss = nn.MSELoss()(val_pred, y_val).item()
332
+
333
+ train_loss = epoch_loss / n_batches
334
+ model_coherence = model.get_coherence_state()
335
+ gate_val = model.silver_gate.item()
336
+
337
+ history['epoch'].append(epoch + 1)
338
+ history['train_loss'].append(train_loss)
339
+ history['val_loss'].append(val_loss)
340
+ history['coherence'].append(model_coherence)
341
+ history['silver_gate'].append(gate_val)
342
+
343
+ if val_loss < best_val:
344
+ best_val = val_loss
345
+ best_state = {k: v.clone() for k, v in model.state_dict().items()}
346
+
347
+ # Log every 10 epochs or last
348
+ if (epoch + 1) % max(1, epochs // 20) == 0 or epoch == epochs - 1:
349
+ log_lines.append(
350
+ f"Epoch {epoch+1:4d} | "
351
+ f"Train: {train_loss:.6f} | Val: {val_loss:.6f} | "
352
+ f"C(model): {model_coherence:.4f} | "
353
+ f"gate: {gate_val:.4f}"
354
+ )
355
+
356
+ progress((epoch + 1) / epochs, desc=f"Epoch {epoch+1}/{epochs}")
357
+
358
+ # Load best model
359
+ model.load_state_dict(best_state)
360
+
361
+ # Final evaluation
362
+ model.eval()
363
+ with torch.no_grad():
364
+ val_pred = model(X_val).numpy()
365
+ val_true = y_val.numpy()
366
+
367
+ mae = np.mean(np.abs(val_pred - val_true))
368
+ r2 = 1 - np.sum((val_true - val_pred)**2) / np.sum((val_true - np.mean(val_true))**2)
369
+ final_coherence = model.get_coherence_state()
370
+
371
+ log_lines.append(f"{'─'*50}")
372
+ log_lines.append(f"✅ Training complete!")
373
+ log_lines.append(f"Best validation loss: {best_val:.6f}")
374
+ log_lines.append(f"MAE: {mae:.6f}")
375
+ log_lines.append(f"R²: {r2:.6f}")
376
+ log_lines.append(f"Final model coherence: {final_coherence:.4f}")
377
+ log_lines.append(f"Silver gate (learned): {model.silver_gate.item():.6f} (init: {C(δ_S):.6f})")
378
+
379
+ # Check if gate stayed near η
380
+ gate_drift = abs(model.silver_gate.item() - C(δ_S))
381
+ if gate_drift < 0.1:
382
+ log_lines.append(f"→ Silver gate preserved! Drift = {gate_drift:.4f} (< 0.1)")
383
+ log_lines.append(f" The network learned that η = 1/√2 is optimal.")
384
+ else:
385
+ log_lines.append(f"→ Silver gate drifted: {gate_drift:.4f}")
386
+ log_lines.append(f" Learned gate: {model.silver_gate.item():.4f} vs η={C(δ_S):.4f}")
387
+
388
+ # Phase activations
389
+ log_lines.append(f"\n**μ-Phase gate values (learned):**")
390
+ for k, layer in enumerate(model.layers):
391
+ act = layer['activation']
392
+ log_lines.append(
393
+ f" k={k}: gate={act.gate.item():.4f} "
394
+ f"(cos={act.cos_k:.3f}, sin={act.sin_k:.3f})"
395
+ )
396
+
397
+ # Save model
398
+ save_path = "mu_net_trained.pt"
399
+ torch.save({
400
+ 'model_state': model.state_dict(),
401
+ 'config': {
402
+ 'input_dim': 8, 'hidden_dim': 64, 'output_dim': 1,
403
+ 'task': task, 'epochs': epochs, 'lr': lr,
404
+ 'best_val_loss': best_val, 'mae': mae, 'r2': r2,
405
+ 'final_coherence': final_coherence,
406
+ },
407
+ 'history': history,
408
+ }, save_path)
409
+ log_lines.append(f"\n💾 Model saved to {save_path}")
410
+
411
+ # Format training curve as text
412
+ curve_lines = ["**Training Curve:**\n"]
413
+ curve_lines.append("```")
414
+ curve_lines.append(f"{'Epoch':>6} {'Train':>10} {'Val':>10} {'C(model)':>10} {'Gate':>8}")
415
+ for i in range(len(history['epoch'])):
416
+ if i % max(1, len(history['epoch']) // 20) == 0 or i == len(history['epoch']) - 1:
417
+ curve_lines.append(
418
+ f"{history['epoch'][i]:6d} "
419
+ f"{history['train_loss'][i]:10.6f} "
420
+ f"{history['val_loss'][i]:10.6f} "
421
+ f"{history['coherence'][i]:10.4f} "
422
+ f"{history['silver_gate'][i]:8.4f}"
423
+ )
424
+ curve_lines.append("```")
425
+
426
+ training_log = "\n".join(log_lines)
427
+ training_curve = "\n".join(curve_lines)
428
+
429
+ return training_log, training_curve
430
+
431
+
432
+ # ── Inference ────────────────────────────────────────────────────────
433
+
434
+ def run_inference(input_text):
435
+ """Run inference on trained model."""
436
+ save_path = "mu_net_trained.pt"
437
+ if not os.path.exists(save_path):
438
+ return "No trained model found. Train first!"
439
+
440
+ try:
441
+ values = [float(x.strip()) for x in input_text.strip().split(",")]
442
+ except ValueError:
443
+ return "Enter 8 comma-separated numbers (e.g.: 1.0, 1.2, 0.9, 1.5, 2.0, 1.8, 1.1, 0.95)"
444
+
445
+ if len(values) != 8:
446
+ return f"Need exactly 8 values, got {len(values)}"
447
+
448
+ # Load model
449
+ checkpoint = torch.load(save_path, weights_only=False)
450
+ model = MuNet(input_dim=8, hidden_dim=64, output_dim=1)
451
+ model.load_state_dict(checkpoint['model_state'])
452
+ model.eval()
453
+
454
+ x = torch.tensor([values], dtype=torch.float32)
455
+ with torch.no_grad():
456
+ pred = model(x).item()
457
+
458
+ # Also compute true coherence for comparison
459
+ true_coherences = [C(v) for v in values]
460
+ true_mean = np.mean(true_coherences)
461
+
462
+ config = checkpoint['config']
463
+
464
+ lines = [
465
+ f"**Input:** {values}",
466
+ f"",
467
+ f"**μ-Net prediction:** {pred:.6f}",
468
+ f"**True mean C(r):** {true_mean:.6f}",
469
+ f"**Error:** {abs(pred - true_mean):.6f}",
470
+ f"",
471
+ f"**Per-value coherence:**",
472
+ ]
473
+ for i, (v, c) in enumerate(zip(values, true_coherences)):
474
+ zone = "⚖️" if c > 0.98 else "🥈" if c > C(δ_S) else "🥇" if c > C(φ**2) else "🌀"
475
+ lines.append(f" {zone} r={v:.4f} → C(r)={c:.6f}")
476
+
477
+ lines.append(f"")
478
+ lines.append(f"**Model info:** R²={config['r2']:.4f}, MAE={config['mae']:.6f}")
479
+ lines.append(f"**Model coherence:** {model.get_coherence_state():.4f}")
480
+
481
+ return "\n".join(lines)
482
+
483
+
484
+ # ── Push to Hub ──────────────────────────────────────────────────────
485
+
486
+ def push_to_hub(repo_name):
487
+ """Push trained model to HuggingFace Hub."""
488
+ save_path = "mu_net_trained.pt"
489
+ if not os.path.exists(save_path):
490
+ return "No trained model found. Train first!"
491
+
492
+ try:
493
+ from huggingface_hub import upload_file, create_repo
494
+
495
+ # Create model repo
496
+ repo_id = repo_name if "/" in repo_name else f"COINjecture/{repo_name}"
497
+ create_repo(repo_id, repo_type="model", exist_ok=True)
498
+
499
+ # Upload model
500
+ upload_file(
501
+ path_or_fileobj=save_path,
502
+ path_in_repo="mu_net_trained.pt",
503
+ repo_id=repo_id,
504
+ repo_type="model",
505
+ )
506
+
507
+ # Create model card
508
+ checkpoint = torch.load(save_path, weights_only=False)
509
+ config = checkpoint['config']
510
+
511
+ card = f"""---
512
+ tags:
513
+ - eigenverse
514
+ - quantum
515
+ - coherence
516
+ - mu-net
517
+ license: mit
518
+ ---
519
+
520
+ # μ-Net — Eigenverse-Grounded Neural Network
521
+
522
+ 8-layer network with μ^k phase-modulated activations, trained on coherence data.
523
+
524
+ ## Architecture
525
+ - **Layers:** 8 (μ⁸ = 1, orbit closure)
526
+ - **Hidden dim:** 64
527
+ - **Activation:** MuActivation (135° phase rotation per layer)
528
+ - **Loss:** MSE + coherence regularization
529
+ - **Parameters:** ~{sum(p.numel() for p in MuNet().parameters()):,}
530
+
531
+ ## Results
532
+ - **R²:** {config['r2']:.4f}
533
+ - **MAE:** {config['mae']:.6f}
534
+ - **Best val loss:** {config['best_val_loss']:.6f}
535
+ - **Model coherence:** {config['final_coherence']:.4f}
536
+
537
+ ## Source
538
+ - [Eigenverse](https://github.com/beanapologist/Eigenverse) — 552 Lean theorems, 0 sorry
539
+ - [COINjecture](https://huggingface.co/COINjecture)
540
+ """
541
+ upload_file(
542
+ path_or_fileobj=card.encode(),
543
+ path_in_repo="README.md",
544
+ repo_id=repo_id,
545
+ repo_type="model",
546
+ )
547
+
548
+ return f"✅ Model pushed to [{repo_id}](https://huggingface.co/{repo_id})"
549
+
550
+ except Exception as e:
551
+ return f"❌ Push failed: {e}"
552
+
553
+
554
+ # ── UI ────────────────────────────────────────────────────���──────────
555
+
556
+ HEADER = """
557
+ # 🧬 μ-Net Training Lab
558
+
559
+ **Train neural networks grounded in the Eigenverse.**
560
+
561
+ The architecture IS the math:
562
+ - **8 layers** → μ⁸ = 1 (orbit closure)
563
+ - **μ^k activations** → 135° phase rotation per layer
564
+ - **Coherence loss** → C(r) = 2r/(1+r²) regularization
565
+ - **Silver gate** → skip connections weighted by η = 1/√2
566
+
567
+ 552 Lean theorems → network architecture → trained weights.
568
+
569
+ [Eigenverse](https://github.com/beanapologist/Eigenverse) · [COINjecture](https://huggingface.co/COINjecture)
570
+ """
571
+
572
+ with gr.Blocks(title="μ-Net Training Lab") as demo:
573
+ gr.Markdown(HEADER)
574
+
575
+ with gr.Tab("🏋️ Train"):
576
+ gr.Markdown("Train the μ-Net live on this hardware.")
577
+
578
+ with gr.Row():
579
+ task = gr.Dropdown(
580
+ ["Coherence Prediction", "Sequence Prediction"],
581
+ value="Coherence Prediction",
582
+ label="Task"
583
+ )
584
+ epochs = gr.Slider(50, 500, value=200, step=10, label="Epochs")
585
+
586
+ with gr.Row():
587
+ lr = gr.Number(value=0.001, label="Learning Rate")
588
+ lambda_c = gr.Number(value=0.01, label="λ (coherence regularization)")
589
+
590
+ train_btn = gr.Button("🚀 Train μ-Net", variant="primary")
591
+
592
+ train_log = gr.Markdown(label="Training Log")
593
+ train_curve = gr.Markdown(label="Training Curve")
594
+
595
+ train_btn.click(
596
+ train_model,
597
+ inputs=[task, epochs, lr, lambda_c],
598
+ outputs=[train_log, train_curve]
599
+ )
600
+
601
+ with gr.Tab("🔮 Inference"):
602
+ gr.Markdown("Run the trained μ-Net on new data.")
603
+
604
+ input_box = gr.Textbox(
605
+ value="1.0, 1.2, 0.9, 1.5, 2.0, 1.8, 1.1, 0.95",
606
+ label="8 ratio values (comma-separated)"
607
+ )
608
+ infer_btn = gr.Button("Predict", variant="primary")
609
+ infer_output = gr.Markdown()
610
+ infer_btn.click(run_inference, inputs=input_box, outputs=infer_output)
611
+
612
+ with gr.Tab("📤 Push to Hub"):
613
+ gr.Markdown("Save the trained model to HuggingFace Hub.")
614
+
615
+ repo_input = gr.Textbox(
616
+ value="COINjecture/mu-net",
617
+ label="Repository ID"
618
+ )
619
+ push_btn = gr.Button("Push Model", variant="primary")
620
+ push_output = gr.Markdown()
621
+ push_btn.click(push_to_hub, inputs=repo_input, outputs=push_output)
622
+
623
+ with gr.Tab("🧠 Architecture"):
624
+ gr.Markdown("""
625
+ ## μ-Net Architecture
626
+
627
+ ```
628
+ Input (8 ratios)
629
+
630
+ Linear(8 → 64)
631
+
632
+ ┌─────────────────────────────────────┐
633
+ │ Layer 0: Linear → μ⁰-Act → LN │ k=0: cos(0)=1, sin(0)=0 (pure real)
634
+ │ Layer 1: Linear → μ¹-Act → LN │ k=1: cos(135°)=−η, sin(135°)=η
635
+ │ Layer 2: Linear → μ²-Act → LN │ k=2: cos(270°)=0, sin(270°)=−1
636
+ │ Layer 3: Linear → μ³-Act → LN │ k=3: cos(405°)=η, sin(405°)=η
637
+ │ Layer 4: Linear → μ⁴-Act → LN │ k=4: cos(540°)=−1, sin(540°)=0
638
+ │ Layer 5: Linear → μ⁵-Act → LN │ k=5: cos(675°)=η, sin(675°)=−η
639
+ │ Layer 6: Linear → μ⁶-Act → LN │ k=6: cos(810°)=0, sin(810°)=1
640
+ │ Layer 7: Linear → μ⁷-Act → LN │ k=7: cos(945°)=−η, sin(945°)=−η
641
+ │ │
642
+ │ Each layer: h = h + η·f(h) │ Silver-gated residual
643
+ │ μ⁸ = 1 → orbit closes │
644
+ └─────────────────────────────────────┘
645
+
646
+ + skip connection (8-cycle closure)
647
+
648
+ Linear(64 → 1)
649
+
650
+ Output (predicted coherence)
651
+ ```
652
+
653
+ ### Key Design Choices
654
+
655
+ **Why 8 layers?** μ⁸ = 1. The orbit closes. 8 × 135° = 3 × 360°.
656
+ Three full turns in 8 steps, gear ratio coprime (gcd(3,8)=1).
657
+
658
+ **Why μ^k activations?** Each layer applies a different phase of the
659
+ eigenvalue rotation. Layer 0 is pure real (dissipation). Layer 2 is
660
+ pure imaginary (oscillation). The mix changes every layer, covering
661
+ all 8 distinct phases.
662
+
663
+ **Why silver gate?** The skip connections are weighted by a learnable
664
+ parameter initialized at C(δ_S) = η = 1/√2. During training, if the
665
+ network discovers that η is optimal, the gate stays near its init.
666
+ This is empirically testable: does the math hold?
667
+
668
+ **Why coherence loss?** Standard L2 regularization penalizes weight
669
+ magnitude. Coherence regularization penalizes *deviation from balance*.
670
+ Weights that drift from their initialized ratio lose coherence.
671
+ """)
672
+
673
+ gr.Markdown("""
674
+ ---
675
+ *552 Lean theorems → architecture → trained weights. The math builds the network.*
676
+ """)
677
+
678
+ if __name__ == "__main__":
679
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio>=5.0
2
+ numpy
3
+ torch
4
+ audioop-lts
5
+ huggingface-hub