Download code/polynomial_echo.py from PureOne/Echo-Mirror-RSI: direct link, hf CLI and curl.
- Browser
- Download file 9.13 kB
-
https://huggingface.co/datasets/PureOne/Echo-Mirror-RSI/resolve/main/code/polynomial_echo.py
- Command line
-
hf download hf://datasets/PureOne/Echo-Mirror-RSI/code/polynomial_echo.py
-
curl -L -o polynomial_echo.py https://huggingface.co/datasets/PureOne/Echo-Mirror-RSI/resolve/main/code/polynomial_echo.py
9.13 kB
| """Exact polynomial echo certificate and bounded self-application demo. | |
| The closure is classical constrained polynomial lumping (CLUE), reimplemented | |
| here to expose exactly which optimizer variables a compressor must retain. | |
| This is not a demonstration of open-ended recursive self-improvement. | |
| """ | |
| from __future__ import annotations | |
| import csv | |
| import json | |
| import hashlib | |
| import sys | |
| from fractions import Fraction as F | |
| from pathlib import Path | |
| import numpy as np | |
| ROOT = Path(__file__).resolve().parents[1] | |
| OUT = ROOT / "results" | |
| def rref(rows, n): | |
| """Exact rational row basis, with pivot columns.""" | |
| a = [[F(v) for v in row] for row in rows if any(row)] | |
| k, piv = 0, [] | |
| for j in range(n): | |
| p = next((i for i in range(k, len(a)) if a[i][j]), None) | |
| if p is None: | |
| continue | |
| a[k], a[p] = a[p], a[k] | |
| z = a[k][j] | |
| a[k] = [v/z for v in a[k]] | |
| for i in range(len(a)): | |
| if i != k and a[i][j]: | |
| z = a[i][j] | |
| a[i] = [v-z*w for v, w in zip(a[i], a[k])] | |
| piv.append(j) | |
| k += 1 | |
| if k == len(a): | |
| break | |
| return a[:k], piv | |
| def jacobian_coefficients(polys, n): | |
| """Matrices M_alpha in D Psi(x) = sum_alpha M_alpha x^alpha.""" | |
| mats = {} | |
| m = len(polys) | |
| for i, poly in enumerate(polys): | |
| for powers, coeff in poly.items(): | |
| for j, power in enumerate(powers): | |
| if power: | |
| alpha = list(powers) | |
| alpha[j] -= 1 | |
| key = tuple(alpha) | |
| mat = mats.setdefault(key, [[F(0) for _ in range(n)] for _ in range(m)]) | |
| mat[i][j] += F(coeff)*power | |
| return mats | |
| def closure(polys, observables, initial_rows, n): | |
| matrices = list(jacobian_coefficients(polys, n).values()) | |
| rows = list(initial_rows) | |
| for mat in jacobian_coefficients(observables, n).values(): | |
| rows.extend(mat) | |
| rows, piv = rref(rows, n) | |
| ranks = [len(rows)] | |
| while True: | |
| more = list(rows) | |
| for mat in matrices: | |
| more.extend([[sum(row[k]*mat[k][j] for k in range(n)) for j in range(n)] for row in rows]) | |
| new, piv = rref(more, n) | |
| if len(new) == len(rows): | |
| break | |
| rows = new | |
| ranks.append(len(rows)) | |
| return rows, piv, ranks | |
| def mono(n, **powers): | |
| p = [0]*n | |
| for index, exponent in powers.items(): | |
| p[int(index)] = exponent | |
| return tuple(p) | |
| def self_application_polys(n=8): | |
| # x' = x - a*x; a' = a+b-a*b; b' = 2*b-b*b. | |
| polys = [ | |
| {mono(n, **{'0':1}):1, mono(n, **{'0':1, '1':1}):-1}, | |
| {mono(n, **{'1':1}):1, mono(n, **{'2':1}):1, mono(n, **{'1':1, '2':1}):-1}, | |
| {mono(n, **{'2':1}):2, mono(n, **{'2':2}):-1}, | |
| ] | |
| for j in range(3, n): | |
| polys.append({mono(n, **{str(j):1}):F(1,2)}) | |
| return polys | |
| def evaluate(polys, state): | |
| return np.array([sum(float(c)*np.prod([state[j]**p for j,p in enumerate(powers) if p]) | |
| for powers,c in poly.items()) for poly in polys], dtype=float) | |
| def step3(state): | |
| x,a,b=state | |
| return np.array([(1-a)*x, a+b*(1-a), b+b*(1-b)]) | |
| def exact_checks(): | |
| n=8 | |
| polys=self_application_polys(n) | |
| obs=[{mono(n, **{'0':1}):1}] | |
| rows,piv,ranks=closure(polys,obs,[],n) | |
| assert piv==[0,1,2] and ranks==[1,2,3] | |
| # Every coefficient matrix preserves the certificate rowspace. | |
| for mat in jacobian_coefficients(polys,n).values(): | |
| for row in rows: | |
| product=[sum(row[k]*mat[k][j] for k in range(n)) for j in range(n)] | |
| assert all(product[j]==0 for j in range(3,n)) | |
| # Nonlinear square-shift: local first-order output probes miss every echo. | |
| h=5; m=h+1 | |
| chain=[{mono(m, **{str(j+1):2}):1} for j in range(h)] | |
| chain.append({mono(m, **{str(h):1}):1}) | |
| _,chain_piv,chain_ranks=closure(chain,[{mono(m, **{'0':1}):1}],[],m) | |
| assert chain_piv==list(range(m)) and chain_ranks==list(range(1,m+1)) | |
| v=np.zeros(m); v[-1]=0.8 | |
| w=v.copy() | |
| for _ in range(h): | |
| w=evaluate(chain,w) | |
| assert abs(w[0]-0.8**(2**h))<1e-15 | |
| # Exact rank-one edit example: Vandermonde with rational eigenvalues. | |
| d=6 | |
| lam=[F(i+1, 2*(d+1)) for i in range(d)] | |
| e=[F(1)]+[F(0)]*(d-1) | |
| b=[F(0)]+[F(1)]*(d-1) | |
| vand=[e]+[[b[i]*lam[i]**k for i in range(d)] for k in range(d-1)] | |
| rank=len(rref(vand,d)[0]) | |
| assert rank==d | |
| # Spherical diagonal chain-level exactness in degree zero. | |
| dim=3 | |
| eta=np.vstack([np.eye(dim),np.eye(dim)]) | |
| difference=np.hstack([-np.eye(dim),np.eye(dim)]) | |
| assert np.linalg.norm(difference@eta)==0 | |
| assert np.linalg.matrix_rank(eta)==dim | |
| assert np.linalg.matrix_rank(difference)==dim | |
| # Counit of diagonal/direct-sum adjunction has kernel (V,U). | |
| u,v=2,3 | |
| counit=np.zeros((u+v,2*(u+v))) | |
| counit[:u,:u]=np.eye(u) | |
| counit[u:,u+v+u:]=np.eye(v) | |
| assert 2*(u+v)-np.linalg.matrix_rank(counit)==u+v | |
| return { | |
| 'exact_polynomial_certificate': {'ambient_dimension':n,'retained_dimension':len(rows), | |
| 'rank_trace':ranks,'pivot_coordinates':['task_error','learning_rule','improvement_rule']}, | |
| 'square_shift': {'depth':h,'response_degree':2**h,'rank_trace':chain_ranks, | |
| 'b':0.8,'future_response':float(w[0]),'derivatives_below_degree_are_zero':True}, | |
| 'rank_one_edit': {'dimension':d,'exact_certificate_rank_after_edit':rank, | |
| 'exact_certificate_rank_before_edit':1}, | |
| 'diagonal_chain_checks':'passed; finite-dimensional identities, not formal verification of the infinity-categorical theorem', | |
| } | |
| def run_demo(): | |
| OUT.mkdir(parents=True,exist_ok=True) | |
| checks=exact_checks() | |
| # Final evaluation seeds and distributions fixed before running. | |
| n=64; steps=8; all_rows=[]; finals={} | |
| methods=['full','echo_3','task_rule_2','task_only_1','frozen_improver','frozen_learner','oracle_step_1'] | |
| trajectory_error=0.0; formula_error=0.0 | |
| for seed in range(32): | |
| rng=np.random.default_rng(12000+seed) | |
| x0=float(rng.uniform(0.5,2.0)); a0=float(rng.uniform(0.02,0.15)); b0=float(rng.uniform(0.02,0.15)) | |
| initial=np.r_[x0,a0,b0,rng.normal(size=n-3)] | |
| states={m:initial[:3].copy() for m in methods} | |
| states['task_rule_2'][2]=0.0 | |
| states['task_only_1'][1:]=0.0 | |
| full=initial.copy() | |
| for t in range(steps+1): | |
| formula=x0*(1-a0)**t*(1-b0)**(2**t-1-t) | |
| formula_error=max(formula_error,abs(states['full'][0]-formula)) | |
| for method in methods: | |
| x,a,b=states[method] | |
| all_rows.append({'seed':seed,'generation':t,'method':method, | |
| 'task_error':float(x),'loss':float(0.5*x*x), | |
| 'learner_gain':float(a),'improver_gain':float(b)}) | |
| if t==steps: | |
| finals.setdefault(method,[]).append(float(0.5*x*x)) | |
| trajectory_error=max(trajectory_error,float(np.max(np.abs(states['full']-states['echo_3'])))) | |
| if t==steps: | |
| break | |
| full[:3]=step3(full[:3]); full[3:]*=0.5 | |
| states['full']=full[:3].copy() | |
| states['echo_3']=step3(states['echo_3']) | |
| temp=np.r_[states['task_rule_2'][:2],0.0] | |
| states['task_rule_2']=step3(temp); states['task_rule_2'][2]=0.0 | |
| states['task_only_1']=np.array([states['task_only_1'][0],0.0,0.0]) | |
| x,a,b=states['frozen_improver'] | |
| states['frozen_improver']=np.array([(1-a)*x,a+b0*(1-a),b0]) | |
| x,a,b=states['frozen_learner'] | |
| states['frozen_learner']=np.array([(1-a0)*x,a0,b0]) | |
| states['oracle_step_1']=np.array([0.0,1.0,1.0]) | |
| with (OUT/'self_application_trajectories.csv').open('w',newline='') as f: | |
| writer=csv.DictWriter(f,fieldnames=list(all_rows[0]));writer.writeheader();writer.writerows(all_rows) | |
| summary={ | |
| 'status':'Engineered scalar self-application sanity experiment; not autonomous discovery, not LLM RSI.', | |
| 'environment':{'python':sys.version,'numpy':np.__version__}, | |
| 'source_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), | |
| 'seed_count':32,'seed_range':[12000,12031],'generations':steps, | |
| 'ambient_state_coordinates':n,'retained_state_coordinates':3, | |
| 'maximum_full_echo_trajectory_absolute_error':trajectory_error, | |
| 'maximum_closed_form_absolute_error':formula_error, | |
| 'mean_final_loss':{m:float(np.mean(v)) for m,v in finals.items()}, | |
| 'median_final_loss':{m:float(np.median(v)) for m,v in finals.items()}, | |
| 'oracle_limitation':'A known unit step solves this unit-curvature quadratic in one update. The prototype does not outperform it.', | |
| 'storage_limitation':'Coordinate counts exclude encoders, code, certificates, and data. No hardware speedup claimed.', | |
| 'exact_checks':checks, | |
| } | |
| assert trajectory_error<1e-14 and formula_error<1e-12 | |
| (OUT/'self_application_summary.json').write_text(json.dumps(summary,indent=2)+'\n') | |
| print(json.dumps(summary,indent=2)) | |
| if __name__=='__main__': | |
| run_demo() | |