5dimension commited on
Commit
d1dc441
Β·
verified Β·
1 Parent(s): 36bc0e8

Add Achronos v3 live demo + experiments Space

Browse files
Files changed (1) hide show
  1. app.py +292 -0
app.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ACHRONOS v3 β€” Live Experiments Space
3
+ =====================================
4
+ Self-contained: no pip install from HF repo needed.
5
+ Runs the full v3 adaptive portfolio on free Gradio CPU.
6
+ """
7
+ import math
8
+ import time
9
+ import json
10
+ import gradio as gr
11
+ import numpy as np
12
+ from dataclasses import dataclass, field
13
+ from typing import Callable, Dict, List, Optional, Tuple, Any
14
+
15
+ # ══════════════════ SENTINEL CONSTANTS ══════════════════
16
+ C1 = -0.007994021805953
17
+ C2 = 0.000200056042968
18
+ INV_E = 1.0 / math.e
19
+ KAPPA = INV_E
20
+ DEFAULT_TOL = abs(C1)
21
+ MACHINE_TOL = 1e-12
22
+
23
+ # ══════════════════ INLINE ACHRONOS V3 ENGINE ══════════════════
24
+
25
+ def _asvec(x): return np.atleast_1d(np.asarray(x, dtype=np.float64)).reshape(-1)
26
+ def _unvec(x, t):
27
+ if isinstance(t, (float,int)) or np.asarray(t).shape==(): return float(x.reshape(-1)[0])
28
+ return x.reshape(np.asarray(t).shape)
29
+
30
+ @dataclass
31
+ class Cert:
32
+ method: str; accepted: bool; res: float; prev_res: float
33
+ improvement: float; err_bound: float; kappa: float
34
+ coeff_l1: float=0; step_norm: float=0; reason: str=""
35
+ def to_dict(self):
36
+ return {"method":self.method,"accepted":self.accepted,"res":f"{self.res:.3e}",
37
+ "prev":f"{self.prev_res:.3e}","improvement":f"{self.improvement:.2f}x",
38
+ "err_bound":f"{self.err_bound:.3e}","reason":self.reason}
39
+
40
+ @dataclass
41
+ class Result:
42
+ x: Any; converged: bool; steps: int; res: float; err_bound: float
43
+ method: str; wall_us: float; certs: List[Cert]; residuals: List[float]
44
+ def summary(self):
45
+ return {"converged":self.converged,"steps":self.steps,"res":f"{self.res:.3e}",
46
+ "err_bound":f"{self.err_bound:.3e}","method":self.method,
47
+ "wall_us":f"{self.wall_us:.0f}","leaps":sum(1 for c in self.certs if c.accepted and c.method!="picard")}
48
+
49
+ def err_bound(r, k=KAPPA): return r/(1-k) if k<1 else float('inf')
50
+
51
+ def est_kappa(xs, gs, safety=1.25):
52
+ vals=[]
53
+ for i in range(len(xs)):
54
+ for j in range(i+1,len(xs)):
55
+ d=np.linalg.norm(xs[i]-xs[j])
56
+ if d>MACHINE_TOL: vals.append(np.linalg.norm(gs[i]-gs[j])/d)
57
+ return min(0.999, max(vals)*safety) if vals else 0.999
58
+
59
+ def anderson_cand(xs, gs, beta=1.0, reg=abs(C1)):
60
+ if len(xs)<2: return None
61
+ xk=xs[-1]; fk=gs[-1]-xs[-1]; m=len(xs)-1
62
+ E=np.column_stack([xs[i+1]-xs[i] for i in range(m)])
63
+ F=np.column_stack([(gs[i+1]-xs[i+1])-(gs[i]-xs[i]) for i in range(m)])
64
+ A=F.T@F+reg*np.eye(m)
65
+ try: g=np.linalg.solve(A,F.T@fk)
66
+ except: return None
67
+ if not np.all(np.isfinite(g)) or np.linalg.norm(g,1)>1e6: return None
68
+ return xk+beta*fk-(E+beta*F)@g
69
+
70
+ def rre_cand(xs, lam=abs(C1)):
71
+ if len(xs)<3: return None
72
+ m=len(xs)-1; X=np.column_stack(xs[:-1])
73
+ R=np.column_stack([xs[i+1]-xs[i] for i in range(m)])
74
+ A=R.T@R+lam*np.eye(m); one=np.ones(m)
75
+ try: z=np.linalg.solve(A,one)
76
+ except: return None
77
+ d=one@z
78
+ if abs(d)<MACHINE_TOL: return None
79
+ c=z/d
80
+ if not np.all(np.isfinite(c)) or np.linalg.norm(c,1)>1e6: return None
81
+ return X@c
82
+
83
+ def mpe_cand(xs):
84
+ if len(xs)<4: return None
85
+ U=np.column_stack([xs[i+1]-xs[i] for i in range(len(xs)-1)])
86
+ k=U.shape[1]-1
87
+ if k<1: return None
88
+ try: ch,*_=np.linalg.lstsq(U[:,:k],-U[:,k],rcond=1e-12)
89
+ except: return None
90
+ c=np.r_[ch,1.0]; s=c.sum()
91
+ if abs(s)<MACHINE_TOL: return None
92
+ gam=c/s
93
+ if not np.all(np.isfinite(gam)) or np.linalg.norm(gam,1)>1e6: return None
94
+ return np.column_stack(xs[:k+1])@gam
95
+
96
+ def solve_v3(g, x0, max_steps=200, window=8, tol=DEFAULT_TOL):
97
+ template=x0; x=_asvec(x0)
98
+ xs=[]; gs_list=[]; residuals=[]; certs=[]
99
+ method="init"; t0=time.time_ns()
100
+ for step in range(max_steps):
101
+ gx=_asvec(g(_unvec(x,template)))
102
+ r=gx-x; rn=float(np.linalg.norm(r)); residuals.append(rn)
103
+ xs.append(x.copy()); gs_list.append(gx.copy())
104
+ if len(xs)>window+1: xs.pop(0); gs_list.pop(0)
105
+ kap=est_kappa(xs,gs_list) if len(xs)>=2 else KAPPA
106
+ kap=min(0.999,max(KAPPA,kap))
107
+ if rn<tol:
108
+ return Result(_unvec(gx,template),True,step+1,rn,err_bound(rn,kap),method,(time.time_ns()-t0)/1000,certs,residuals)
109
+ # candidates
110
+ cands=[("picard",gx), ("sentinel_damp",x+KAPPA*(gx-x))]
111
+ aa=anderson_cand(xs,gs_list);
112
+ if aa is not None: cands.append(("anderson",aa))
113
+ aa_s=anderson_cand(xs,gs_list,beta=KAPPA)
114
+ if aa_s is not None: cands.append(("sentinel_aa",aa_s))
115
+ for lam in [abs(C2),abs(C1),abs(C1)*10]:
116
+ rr=rre_cand(xs,lam=lam)
117
+ if rr is not None: cands.append((f"rre_{lam:.0e}",rr))
118
+ mp=mpe_cand(xs)
119
+ if mp is not None: cands.append(("mpe",mp))
120
+ # evaluate
121
+ best=None; best_rn=rn
122
+ for mn,cx in cands:
123
+ sn=float(np.linalg.norm(cx-x))
124
+ if sn>50*max(1,np.linalg.norm(x)):
125
+ certs.append(Cert(mn,False,float('inf'),rn,0,float('inf'),kap,reason="trust reject"))
126
+ continue
127
+ try:
128
+ cgx=_asvec(g(_unvec(cx,template))); cn=float(np.linalg.norm(cgx-cx))
129
+ except:
130
+ certs.append(Cert(mn,False,float('inf'),rn,0,float('inf'),kap,reason="eval fail"))
131
+ continue
132
+ imp=rn/max(cn,MACHINE_TOL)
133
+ acc=cn<rn*0.98 or mn=="picard"
134
+ certs.append(Cert(mn,acc,cn,rn,imp,err_bound(cn,kap),kap,np.linalg.norm(cx-x),sn,"ok" if acc else "no improve"))
135
+ if acc and cn<best_rn: best=(mn,cx); best_rn=cn
136
+ if best is None: x=gx; method="picard_fb"
137
+ else: method=best[0]; x=best[1]
138
+ rn_final=float(np.linalg.norm(_asvec(g(_unvec(x,template)))-x))
139
+ return Result(_unvec(x,template),rn_final<tol,max_steps,rn_final,err_bound(rn_final,KAPPA),method,(time.time_ns()-t0)/1000,certs,residuals)
140
+
141
+ def solve_picard(g, x0, max_steps=200, tol=DEFAULT_TOL):
142
+ template=x0; x=_asvec(x0); residuals=[]
143
+ t0=time.time_ns()
144
+ for step in range(max_steps):
145
+ gx=_asvec(g(_unvec(x,template)))
146
+ rn=float(np.linalg.norm(gx-x)); residuals.append(rn)
147
+ if rn<tol: return step+1,rn,residuals,(time.time_ns()-t0)/1000
148
+ x=gx
149
+ return max_steps,residuals[-1],residuals,(time.time_ns()-t0)/1000
150
+
151
+ # ══════════════════ EXPERIMENTS ══════════════════
152
+
153
+ PROBLEMS = {
154
+ "cos(x) [scalar, ΞΊβ‰ˆ0.67]": (math.cos, 1.0),
155
+ "Golden ratio Ο† [scalar, ΞΊβ‰ˆ0.38]": (lambda x: 1+1/x, 1.0),
156
+ "exp(-x) [scalar, ΞΊβ‰ˆ0.57]": (lambda x: math.exp(-x), 0.5),
157
+ "Linear ΞΊ=1/e (sentinel rate)": (lambda x: INV_E*x+(1-INV_E), 10.0),
158
+ "Linear ΞΊ=0.9 (moderate)": (lambda x: 0.9*x+0.1, 10.0),
159
+ "Linear ΞΊ=0.99 (slow)": (lambda x: 0.99*x+0.01, 10.0),
160
+ "2D coupled trig": (lambda x: np.array([0.5*np.cos(x[1]),0.5*np.sin(x[0])+0.3]), np.ones(2)),
161
+ "10D linear ρ=0.3": (lambda x: 0.3*x+np.arange(10)*0.1, np.zeros(10)),
162
+ "50D nonlinear ring": (lambda x: np.array([0.3*np.sin(x[(i+1)%50])+0.1*x[i]+0.2 for i in range(50)]), np.zeros(50)),
163
+ "100D stiff spectrum": (lambda x: np.linspace(0.01,0.9,100)*x+(1-np.linspace(0.01,0.9,100))*np.sin(np.arange(100)*0.1), np.zeros(100)),
164
+ "200D two-mode": (lambda x: np.r_[0.9*x[:100]+0.1, 0.2*x[100:]+0.5], np.zeros(200)),
165
+ }
166
+
167
+ def run_experiment(problem_name, max_steps):
168
+ max_steps = int(max_steps)
169
+ g, x0 = PROBLEMS[problem_name]
170
+
171
+ # Picard baseline
172
+ pic_steps, pic_res, pic_hist, pic_us = solve_picard(g, x0, max_steps=max_steps)
173
+
174
+ # Achronos v3 portfolio
175
+ v3 = solve_v3(g, x0, max_steps=max_steps)
176
+
177
+ speedup = pic_steps / max(1, v3.steps)
178
+
179
+ # Build output
180
+ summary = f"""
181
+ ═══════════════════════════════════════════════════
182
+ ACHRONOS v3 EXPERIMENT: {problem_name}
183
+ ═══════════════════════════════════════════════════
184
+
185
+ β”Œβ”€β”€β”€ Picard Baseline ───┐
186
+ β”‚ Steps: {pic_steps}
187
+ β”‚ Residual: {pic_res:.6e}
188
+ β”‚ Time: {pic_us:.0f} ΞΌs
189
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
190
+
191
+ β”Œβ”€β”€β”€ Achronos v3 Portfolio ───┐
192
+ β”‚ Steps: {v3.steps}
193
+ β”‚ Residual: {v3.res:.6e}
194
+ β”‚ Error bound: {v3.err_bound:.6e}
195
+ β”‚ Method: {v3.method}
196
+ β”‚ Converged: {v3.converged}
197
+ β”‚ Time: {v3.wall_us:.0f} ΞΌs
198
+ β”‚ Accepted leaps: {sum(1 for c in v3.certs if c.accepted and c.method!='picard')}
199
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
200
+
201
+ β”Œβ”€β”€β”€ Speedup ───┐
202
+ β”‚ Steps: {speedup:.2f}x fewer iterations
203
+ β”‚ Picard {pic_steps} β†’ v3 {v3.steps}
204
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
205
+
206
+ β”Œβ”€β”€β”€ Certificate (last accepted non-picard) ───┐
207
+ """
208
+ last_leap = [c for c in v3.certs if c.accepted and c.method != "picard"]
209
+ if last_leap:
210
+ lc = last_leap[-1]
211
+ summary += f"""β”‚ Method: {lc.method}
212
+ β”‚ Residual: {lc.res:.6e}
213
+ β”‚ Improvement: {lc.improvement:.2f}x
214
+ β”‚ Error bound: {lc.err_bound:.6e}
215
+ β”‚ ΞΊ_upper: {lc.kappa:.6f}
216
+ """
217
+ else:
218
+ summary += "β”‚ (no extrapolation leap taken)\n"
219
+ summary += "β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜\n"
220
+
221
+ # Residual decay comparison (first 30 steps)
222
+ summary += "\nβ”Œβ”€β”€β”€ Residual Decay (first 30 steps) ───┐\n"
223
+ summary += f"{'Step':>5} {'Picard':>14} {'Achronos_v3':>14}\n"
224
+ for i in range(min(30, max(len(pic_hist), len(v3.residuals)))):
225
+ p = f"{pic_hist[i]:.6e}" if i < len(pic_hist) else "converged"
226
+ a = f"{v3.residuals[i]:.6e}" if i < len(v3.residuals) else "converged"
227
+ summary += f"{i:>5} {p:>14} {a:>14}\n"
228
+ summary += "β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜\n"
229
+
230
+ # Method acceptance stats
231
+ methods_used = {}
232
+ for c in v3.certs:
233
+ if c.accepted:
234
+ methods_used[c.method] = methods_used.get(c.method, 0) + 1
235
+ summary += f"\nβ”Œβ”€β”€β”€ Method Acceptance Stats ───┐\n"
236
+ for m, cnt in sorted(methods_used.items(), key=lambda x: -x[1]):
237
+ summary += f"β”‚ {m:<25} {cnt:>4} accepted\n"
238
+ summary += f"β”‚ Total candidates evaluated: {len(v3.certs)}\n"
239
+ summary += "β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜\n"
240
+
241
+ return summary
242
+
243
+ def run_all():
244
+ lines = ["═"*90, " ACHRONOS v3 β€” ALL EXPERIMENTS (max_steps=200)", "═"*90, ""]
245
+ lines.append(f"{'Problem':<35} {'Picard':>8} {'V3':>8} {'Speedup':>9} {'V3_method':<20} {'Residual':>12} {'ErrBound':>12}")
246
+ lines.append("─"*110)
247
+ for name, (g, x0) in PROBLEMS.items():
248
+ ps, pr, _, _ = solve_picard(g, x0, max_steps=200)
249
+ v3 = solve_v3(g, x0, max_steps=200)
250
+ sp = ps/max(1,v3.steps)
251
+ lines.append(f"{name:<35} {ps:>8} {v3.steps:>8} {sp:>8.2f}x {v3.method:<20} {v3.res:>12.2e} {v3.err_bound:>12.2e}")
252
+ lines.append("")
253
+ lines.append("═"*90)
254
+ lines.append(" PROOF: Every result carries ||x-x*|| <= ||g(x)-x||/(1-ΞΊ) with ΞΊ=1/e")
255
+ lines.append("═"*90)
256
+ return "\n".join(lines)
257
+
258
+ # ══════════════════ GRADIO UI ══════════════════
259
+
260
+ with gr.Blocks(title="Achronos v3 Experiments", theme=gr.themes.Monochrome()) as demo:
261
+ gr.Markdown("""
262
+ # ⚑ Achronos v3 β€” Certified Adaptive Quantum Leap Portfolio
263
+
264
+ **Generate futures. Verify residuals. Collapse to the best certified result.**
265
+
266
+ The Sentinel Manifold fixed-point engine with RRE/RNA, MPE, Anderson, topological epsilon.
267
+ Every candidate is residual-verified; every result carries a contraction error certificate.
268
+
269
+ `||x - x*|| ≀ ||g(x)-x|| / (1 - 1/e) β‰ˆ 1.582 Β· residual`
270
+ """)
271
+
272
+ with gr.Tab("Single Experiment"):
273
+ with gr.Row():
274
+ prob = gr.Dropdown(list(PROBLEMS.keys()), value=list(PROBLEMS.keys())[0], label="Problem")
275
+ steps = gr.Slider(10, 500, value=200, step=10, label="Max Steps")
276
+ btn = gr.Button("Run Experiment", variant="primary")
277
+ out = gr.Textbox(label="Results", lines=40, max_lines=60)
278
+ btn.click(run_experiment, [prob, steps], out)
279
+
280
+ with gr.Tab("Run All"):
281
+ btn_all = gr.Button("Run All Problems", variant="primary")
282
+ out_all = gr.Textbox(label="All Results", lines=30, max_lines=50)
283
+ btn_all.click(run_all, [], out_all)
284
+
285
+ gr.Markdown("""
286
+ ---
287
+ **Sentinel constants:** C₁=βˆ’0.007994, Cβ‚‚=0.000200, ΞΊ=1/e=0.3679
288
+
289
+ **Repo:** [5dimension/sentinel-manifold-discoveries](https://huggingface.co/5dimension/sentinel-manifold-discoveries)
290
+ """)
291
+
292
+ demo.launch()