import sys, json, time from pathlib import Path import numpy as np import torch sys.path.insert(0, '/home/maxwelhelp/all/math2nn') from bench import make_model, train_model from bench.protocol import sweep_baseline, evaluate, make_report from phase_track import N, EDGES, get_dataset SEEDS = tuple(range(8)) # Union is shared by baseline and idea; the baseline is swept at all idea rates. LR_GRID = [1e-3, 3e-3, 1e-2] EPOCHS = 24 BATCH = 64 def spectral_align(x): """Align each sample's 8 two-dimensional views using its noisy phases.""" a = np.asarray(x, dtype=np.float32).copy() out = a[:, :2*N].reshape(-1, N, 2).copy() ph = a[:, 2*N:] aligned = np.empty_like(out) for k in range(len(a)): C = np.zeros((N, N), dtype=np.complex64) for e, (i, j) in enumerate(EDGES): z = np.exp(1j * ph[k, e]) C[i, j] = z C[j, i] = np.conj(z) v = np.ones(N, dtype=np.complex64) / np.sqrt(N) for _ in range(15): q = C @ v nq = np.linalg.norm(q) if nq > 1e-8: v = q / nq theta = np.angle(v) theta -= theta[0] # R(-theta) removes the estimated view rotation. for i in range(N): c, s = np.cos(theta[i]), np.sin(theta[i]) aligned[k, i] = (np.array([[c, s], [-s, c]], dtype=np.float32) @ out[k, i]) return np.concatenate([aligned.reshape(len(a), -1), ph], axis=1).astype(np.float32) def ds(seed, aligned): d = get_dataset(seed, 400, 200) for k in ('xtr', 'ytr', 'xte', 'yte'): d[k] = torch.as_tensor(d[k], dtype=torch.float32) if aligned: d['xtr'] = torch.from_numpy(spectral_align(d['xtr'].numpy())) d['xte'] = torch.from_numpy(spectral_align(d['xte'].numpy())) return d def set_seed(seed): np.random.seed(seed); torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) def train_one(seed, lr, aligned): set_seed(seed + (10000 if aligned else 0)) d = ds(seed, aligned) model = make_model('mlp_tiny', tuple(d['xtr'].shape[1:]), 1) _, metric, hist = train_model(model, d, epochs=EPOCHS, lr=lr, batch=BATCH, log=lambda *_: None) return float(metric) def make_side(aligned): return lambda cfg: (lambda seed: train_one(seed, cfg['lr'], aligned)) def mechanism_signature(): # NN-scale check: compare model predictions on identical raw vs aligned views, # and use the trained idea model's test MSE to assess the predicted stabilization. rows=[] for seed in SEEDS: set_seed(seed + 20000) raw=ds(seed, False); ali=ds(seed, True) m=make_model('mlp_tiny', tuple(raw['xtr'].shape[1:]), 1) m,_,_=train_model(m, ali, epochs=EPOCHS, lr=3e-3, batch=BATCH, log=lambda *_: None) m = m.cpu(); m.eval() with torch.no_grad(): pr=m(ali['xte'].cpu()).numpy().ravel() y=ali['yte'].numpy().ravel() # observed task prediction error and residual variation, measured from trained NN rows.append((float(np.mean((pr-y)**2)), float(np.std(pr-y)))) mse=float(np.mean([r[0] for r in rows])); resid=float(np.mean([r[1] for r in rows])) # Prediction: synchronization should reduce downstream error versus random/raw input. rawm=float(np.mean([train_one(s,3e-3,False) for s in SEEDS])) return {'prediction':'spectral alignment reduces downstream test MSE and residual spread', 'predicted_baseline_mse':rawm, 'observed_aligned_mse':mse, 'observed_aligned_residual_std':resid, 'confirmed': bool(mse < rawm)} def main(): t=time.time() base=sweep_baseline(make_side(False), [{'lr':x} for x in LR_GRID], seeds=(0,1,2,3)) # Same three settings on idea side, including best baseline setting and neighbors. idea_cfgs=[{'lr':x} for x in LR_GRID] idea_trials=[] for cfg in idea_cfgs: r=evaluate(make_side(True)(cfg), seeds=SEEDS) idea_trials.append({'cfg':cfg,'result':r}) best=min(idea_trials, key=lambda z:z['result']['mean']) sig=mechanism_signature() report=make_report('phase_synchronization_regression','mlp_tiny',base,best['result'],{ 'custom_track':{'name':'phase_synchronization_regression','file':'phase_track.py','domain':'geometry/graph synchronization'}, 'idea_sweep':idea_trials,'mechanism_signature':sig, 'runtime_sec':time.time()-t}) Path('bench_report.json').write_text(json.dumps(report,indent=2)) print(json.dumps(report,indent=2)) if __name__=='__main__': main()