Spaces:
Running
Running
| """ | |
| ACHRONOS v3 β Live Experiments Space | |
| ===================================== | |
| Self-contained: no pip install from HF repo needed. | |
| Runs the full v3 adaptive portfolio on free Gradio CPU. | |
| """ | |
| import math | |
| import time | |
| import json | |
| import gradio as gr | |
| import numpy as np | |
| from dataclasses import dataclass, field | |
| from typing import Callable, Dict, List, Optional, Tuple, Any | |
| # ββββββββββββββββββ SENTINEL CONSTANTS ββββββββββββββββββ | |
| C1 = -0.007994021805953 | |
| C2 = 0.000200056042968 | |
| INV_E = 1.0 / math.e | |
| KAPPA = INV_E | |
| DEFAULT_TOL = abs(C1) | |
| MACHINE_TOL = 1e-12 | |
| # ββββββββββββββββββ INLINE ACHRONOS V3 ENGINE ββββββββββββββββββ | |
| def _asvec(x): return np.atleast_1d(np.asarray(x, dtype=np.float64)).reshape(-1) | |
| def _unvec(x, t): | |
| if isinstance(t, (float,int)) or np.asarray(t).shape==(): return float(x.reshape(-1)[0]) | |
| return x.reshape(np.asarray(t).shape) | |
| class Cert: | |
| method: str; accepted: bool; res: float; prev_res: float | |
| improvement: float; err_bound: float; kappa: float | |
| coeff_l1: float=0; step_norm: float=0; reason: str="" | |
| def to_dict(self): | |
| return {"method":self.method,"accepted":self.accepted,"res":f"{self.res:.3e}", | |
| "prev":f"{self.prev_res:.3e}","improvement":f"{self.improvement:.2f}x", | |
| "err_bound":f"{self.err_bound:.3e}","reason":self.reason} | |
| class Result: | |
| x: Any; converged: bool; steps: int; res: float; err_bound: float | |
| method: str; wall_us: float; certs: List[Cert]; residuals: List[float] | |
| def summary(self): | |
| return {"converged":self.converged,"steps":self.steps,"res":f"{self.res:.3e}", | |
| "err_bound":f"{self.err_bound:.3e}","method":self.method, | |
| "wall_us":f"{self.wall_us:.0f}","leaps":sum(1 for c in self.certs if c.accepted and c.method!="picard")} | |
| def err_bound(r, k=KAPPA): return r/(1-k) if k<1 else float('inf') | |
| def est_kappa(xs, gs, safety=1.25): | |
| vals=[] | |
| for i in range(len(xs)): | |
| for j in range(i+1,len(xs)): | |
| d=np.linalg.norm(xs[i]-xs[j]) | |
| if d>MACHINE_TOL: vals.append(np.linalg.norm(gs[i]-gs[j])/d) | |
| return min(0.999, max(vals)*safety) if vals else 0.999 | |
| def anderson_cand(xs, gs, beta=1.0, reg=abs(C1)): | |
| if len(xs)<2: return None | |
| xk=xs[-1]; fk=gs[-1]-xs[-1]; m=len(xs)-1 | |
| E=np.column_stack([xs[i+1]-xs[i] for i in range(m)]) | |
| F=np.column_stack([(gs[i+1]-xs[i+1])-(gs[i]-xs[i]) for i in range(m)]) | |
| A=F.T@F+reg*np.eye(m) | |
| try: g=np.linalg.solve(A,F.T@fk) | |
| except: return None | |
| if not np.all(np.isfinite(g)) or np.linalg.norm(g,1)>1e6: return None | |
| return xk+beta*fk-(E+beta*F)@g | |
| def rre_cand(xs, lam=abs(C1)): | |
| if len(xs)<3: return None | |
| m=len(xs)-1; X=np.column_stack(xs[:-1]) | |
| R=np.column_stack([xs[i+1]-xs[i] for i in range(m)]) | |
| A=R.T@R+lam*np.eye(m); one=np.ones(m) | |
| try: z=np.linalg.solve(A,one) | |
| except: return None | |
| d=one@z | |
| if abs(d)<MACHINE_TOL: return None | |
| c=z/d | |
| if not np.all(np.isfinite(c)) or np.linalg.norm(c,1)>1e6: return None | |
| return X@c | |
| def mpe_cand(xs): | |
| if len(xs)<4: return None | |
| U=np.column_stack([xs[i+1]-xs[i] for i in range(len(xs)-1)]) | |
| k=U.shape[1]-1 | |
| if k<1: return None | |
| try: ch,*_=np.linalg.lstsq(U[:,:k],-U[:,k],rcond=1e-12) | |
| except: return None | |
| c=np.r_[ch,1.0]; s=c.sum() | |
| if abs(s)<MACHINE_TOL: return None | |
| gam=c/s | |
| if not np.all(np.isfinite(gam)) or np.linalg.norm(gam,1)>1e6: return None | |
| return np.column_stack(xs[:k+1])@gam | |
| def solve_v3(g, x0, max_steps=200, window=8, tol=DEFAULT_TOL): | |
| template=x0; x=_asvec(x0) | |
| xs=[]; gs_list=[]; residuals=[]; certs=[] | |
| method="init"; t0=time.time_ns() | |
| for step in range(max_steps): | |
| gx=_asvec(g(_unvec(x,template))) | |
| r=gx-x; rn=float(np.linalg.norm(r)); residuals.append(rn) | |
| xs.append(x.copy()); gs_list.append(gx.copy()) | |
| if len(xs)>window+1: xs.pop(0); gs_list.pop(0) | |
| kap=est_kappa(xs,gs_list) if len(xs)>=2 else KAPPA | |
| kap=min(0.999,max(KAPPA,kap)) | |
| if rn<tol: | |
| return Result(_unvec(gx,template),True,step+1,rn,err_bound(rn,kap),method,(time.time_ns()-t0)/1000,certs,residuals) | |
| # candidates | |
| cands=[("picard",gx), ("sentinel_damp",x+KAPPA*(gx-x))] | |
| aa=anderson_cand(xs,gs_list); | |
| if aa is not None: cands.append(("anderson",aa)) | |
| aa_s=anderson_cand(xs,gs_list,beta=KAPPA) | |
| if aa_s is not None: cands.append(("sentinel_aa",aa_s)) | |
| for lam in [abs(C2),abs(C1),abs(C1)*10]: | |
| rr=rre_cand(xs,lam=lam) | |
| if rr is not None: cands.append((f"rre_{lam:.0e}",rr)) | |
| mp=mpe_cand(xs) | |
| if mp is not None: cands.append(("mpe",mp)) | |
| # evaluate | |
| best=None; best_rn=rn | |
| for mn,cx in cands: | |
| sn=float(np.linalg.norm(cx-x)) | |
| if sn>50*max(1,np.linalg.norm(x)): | |
| certs.append(Cert(mn,False,float('inf'),rn,0,float('inf'),kap,reason="trust reject")) | |
| continue | |
| try: | |
| cgx=_asvec(g(_unvec(cx,template))); cn=float(np.linalg.norm(cgx-cx)) | |
| except: | |
| certs.append(Cert(mn,False,float('inf'),rn,0,float('inf'),kap,reason="eval fail")) | |
| continue | |
| imp=rn/max(cn,MACHINE_TOL) | |
| acc=cn<rn*0.98 or mn=="picard" | |
| 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")) | |
| if acc and cn<best_rn: best=(mn,cx); best_rn=cn | |
| if best is None: x=gx; method="picard_fb" | |
| else: method=best[0]; x=best[1] | |
| rn_final=float(np.linalg.norm(_asvec(g(_unvec(x,template)))-x)) | |
| 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) | |
| def solve_picard(g, x0, max_steps=200, tol=DEFAULT_TOL): | |
| template=x0; x=_asvec(x0); residuals=[] | |
| t0=time.time_ns() | |
| for step in range(max_steps): | |
| gx=_asvec(g(_unvec(x,template))) | |
| rn=float(np.linalg.norm(gx-x)); residuals.append(rn) | |
| if rn<tol: return step+1,rn,residuals,(time.time_ns()-t0)/1000 | |
| x=gx | |
| return max_steps,residuals[-1],residuals,(time.time_ns()-t0)/1000 | |
| # ββββββββββββββββββ EXPERIMENTS ββββββββββββββββββ | |
| PROBLEMS = { | |
| "cos(x) [scalar, ΞΊβ0.67]": (math.cos, 1.0), | |
| "Golden ratio Ο [scalar, ΞΊβ0.38]": (lambda x: 1+1/x, 1.0), | |
| "exp(-x) [scalar, ΞΊβ0.57]": (lambda x: math.exp(-x), 0.5), | |
| "Linear ΞΊ=1/e (sentinel rate)": (lambda x: INV_E*x+(1-INV_E), 10.0), | |
| "Linear ΞΊ=0.9 (moderate)": (lambda x: 0.9*x+0.1, 10.0), | |
| "Linear ΞΊ=0.99 (slow)": (lambda x: 0.99*x+0.01, 10.0), | |
| "2D coupled trig": (lambda x: np.array([0.5*np.cos(x[1]),0.5*np.sin(x[0])+0.3]), np.ones(2)), | |
| "10D linear Ο=0.3": (lambda x: 0.3*x+np.arange(10)*0.1, np.zeros(10)), | |
| "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)), | |
| "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)), | |
| "200D two-mode": (lambda x: np.r_[0.9*x[:100]+0.1, 0.2*x[100:]+0.5], np.zeros(200)), | |
| } | |
| def run_experiment(problem_name, max_steps): | |
| max_steps = int(max_steps) | |
| g, x0 = PROBLEMS[problem_name] | |
| # Picard baseline | |
| pic_steps, pic_res, pic_hist, pic_us = solve_picard(g, x0, max_steps=max_steps) | |
| # Achronos v3 portfolio | |
| v3 = solve_v3(g, x0, max_steps=max_steps) | |
| speedup = pic_steps / max(1, v3.steps) | |
| # Build output | |
| summary = f""" | |
| βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| ACHRONOS v3 EXPERIMENT: {problem_name} | |
| βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| ββββ Picard Baseline ββββ | |
| β Steps: {pic_steps} | |
| β Residual: {pic_res:.6e} | |
| β Time: {pic_us:.0f} ΞΌs | |
| βββββββββββββββββββββββββ | |
| ββββ Achronos v3 Portfolio ββββ | |
| β Steps: {v3.steps} | |
| β Residual: {v3.res:.6e} | |
| β Error bound: {v3.err_bound:.6e} | |
| β Method: {v3.method} | |
| β Converged: {v3.converged} | |
| β Time: {v3.wall_us:.0f} ΞΌs | |
| β Accepted leaps: {sum(1 for c in v3.certs if c.accepted and c.method!='picard')} | |
| βββββββββββββββββββββββββββββββ | |
| ββββ Speedup ββββ | |
| β Steps: {speedup:.2f}x fewer iterations | |
| β Picard {pic_steps} β v3 {v3.steps} | |
| βββββββββββββββββ | |
| ββββ Certificate (last accepted non-picard) ββββ | |
| """ | |
| last_leap = [c for c in v3.certs if c.accepted and c.method != "picard"] | |
| if last_leap: | |
| lc = last_leap[-1] | |
| summary += f"""β Method: {lc.method} | |
| β Residual: {lc.res:.6e} | |
| β Improvement: {lc.improvement:.2f}x | |
| β Error bound: {lc.err_bound:.6e} | |
| β ΞΊ_upper: {lc.kappa:.6f} | |
| """ | |
| else: | |
| summary += "β (no extrapolation leap taken)\n" | |
| summary += "ββββββββββββββββββββββββββββββββββββββββββββββββ\n" | |
| # Residual decay comparison (first 30 steps) | |
| summary += "\nββββ Residual Decay (first 30 steps) ββββ\n" | |
| summary += f"{'Step':>5} {'Picard':>14} {'Achronos_v3':>14}\n" | |
| for i in range(min(30, max(len(pic_hist), len(v3.residuals)))): | |
| p = f"{pic_hist[i]:.6e}" if i < len(pic_hist) else "converged" | |
| a = f"{v3.residuals[i]:.6e}" if i < len(v3.residuals) else "converged" | |
| summary += f"{i:>5} {p:>14} {a:>14}\n" | |
| summary += "βββββββββββββββββββββββββββββββββββββββββ\n" | |
| # Method acceptance stats | |
| methods_used = {} | |
| for c in v3.certs: | |
| if c.accepted: | |
| methods_used[c.method] = methods_used.get(c.method, 0) + 1 | |
| summary += f"\nββββ Method Acceptance Stats ββββ\n" | |
| for m, cnt in sorted(methods_used.items(), key=lambda x: -x[1]): | |
| summary += f"β {m:<25} {cnt:>4} accepted\n" | |
| summary += f"β Total candidates evaluated: {len(v3.certs)}\n" | |
| summary += "βββββββββββββββββββββββββββββββββ\n" | |
| return summary | |
| def run_all(): | |
| lines = ["β"*90, " ACHRONOS v3 β ALL EXPERIMENTS (max_steps=200)", "β"*90, ""] | |
| lines.append(f"{'Problem':<35} {'Picard':>8} {'V3':>8} {'Speedup':>9} {'V3_method':<20} {'Residual':>12} {'ErrBound':>12}") | |
| lines.append("β"*110) | |
| for name, (g, x0) in PROBLEMS.items(): | |
| ps, pr, _, _ = solve_picard(g, x0, max_steps=200) | |
| v3 = solve_v3(g, x0, max_steps=200) | |
| sp = ps/max(1,v3.steps) | |
| 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}") | |
| lines.append("") | |
| lines.append("β"*90) | |
| lines.append(" PROOF: Every result carries ||x-x*|| <= ||g(x)-x||/(1-ΞΊ) with ΞΊ=1/e") | |
| lines.append("β"*90) | |
| return "\n".join(lines) | |
| # ββββββββββββββββββ GRADIO UI ββββββββββββββββββ | |
| with gr.Blocks(title="Achronos v3 Experiments", theme=gr.themes.Monochrome()) as demo: | |
| gr.Markdown(""" | |
| # β‘ Achronos v3 β Certified Adaptive Quantum Leap Portfolio | |
| **Generate futures. Verify residuals. Collapse to the best certified result.** | |
| The Sentinel Manifold fixed-point engine with RRE/RNA, MPE, Anderson, topological epsilon. | |
| Every candidate is residual-verified; every result carries a contraction error certificate. | |
| `||x - x*|| β€ ||g(x)-x|| / (1 - 1/e) β 1.582 Β· residual` | |
| """) | |
| with gr.Tab("Single Experiment"): | |
| with gr.Row(): | |
| prob = gr.Dropdown(list(PROBLEMS.keys()), value=list(PROBLEMS.keys())[0], label="Problem") | |
| steps = gr.Slider(10, 500, value=200, step=10, label="Max Steps") | |
| btn = gr.Button("Run Experiment", variant="primary") | |
| out = gr.Textbox(label="Results", lines=40, max_lines=60) | |
| btn.click(run_experiment, [prob, steps], out) | |
| with gr.Tab("Run All"): | |
| btn_all = gr.Button("Run All Problems", variant="primary") | |
| out_all = gr.Textbox(label="All Results", lines=30, max_lines=50) | |
| btn_all.click(run_all, [], out_all) | |
| gr.Markdown(""" | |
| --- | |
| **Sentinel constants:** Cβ=β0.007994, Cβ=0.000200, ΞΊ=1/e=0.3679 | |
| **Repo:** [5dimension/sentinel-manifold-discoveries](https://huggingface.co/5dimension/sentinel-manifold-discoveries) | |
| """) | |
| demo.launch() | |