File size: 12,983 Bytes
d1dc441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
"""
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)<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()