""" 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) @dataclass 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} @dataclass 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)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)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 rn50*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=cn5} {'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()