Echo-Mirror-RSI / code /run_experiments.py
PureOne's picture
Publish Echo-Mirror RSI v2 research dataset and reproducibility files
0a4f337 verified
Raw History Blame Contribute Delete
27 kB
#!/usr/bin/env python3
"""Echo-Mirror: finite-dimensional recursive response-preservation experiments.
This program tests exact simulation of linear edit maps and adaptive selection
from their linear span. It does not demonstrate autonomous recursive
self-improvement, LLM improvement, or a computational advantage over classical
observability reduction. The classical baseline is intentionally equivalent.
Reproduce:
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 python run_experiments.py \
--output ../results --seeds 32
Requires Python 3.10+ and NumPy. Every seed and test protocol is fixed by Config.
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import math
import os
import platform
import sys
import time
from dataclasses import asdict, dataclass
from pathlib import Path
import numpy as np
@dataclass(frozen=True)
class Config:
ambient_dimension: int = 64
coarse_rank: int = 4
response_rank: int = 4
invariant_rank: int = 16
library_size: int = 3
sequences_per_seed: int = 16
horizon: int = 24
adaptive_candidates: int = 9
seeds: int = 32
seed_offset: int = 20261108
rank_tolerance: float = 1e-11
diagnostic_tolerance: float = 1e-10
METHODS = (
"full_state",
"wave_only",
"immediate_echo",
"random_echo_matched_rank",
"recursive_echo",
"classical_observable_quotient",
)
def haar_matrix(n: int) -> np.ndarray:
"""Orthonormal Haar analysis matrix; rows ordered coarse to fine."""
if n < 1 or n & (n - 1):
raise ValueError("Haar dimension must be a positive power of two")
h = np.array([[1.0]])
size = 1
while size < n:
h = np.vstack((np.kron(h, [1.0, 1.0]),
np.kron(np.eye(size), [1.0, -1.0]))) / math.sqrt(2.0)
size *= 2
return h
def row_basis(matrix: np.ndarray, tol: float = 1e-11) -> np.ndarray:
"""Orthonormal row basis, with a recorded relative numerical rank rule."""
if matrix.shape[0] == 0:
return np.empty((0, matrix.shape[1]))
_, s, vh = np.linalg.svd(matrix, full_matrices=False)
rank = int(np.count_nonzero(s > tol * max(float(s[0]), 1.0)))
return vh[:rank]
def invariant_row_closure(initial: np.ndarray, maps: np.ndarray,
tol: float = 1e-11) -> tuple[np.ndarray, list[int]]:
"""Smallest row space W containing initial with W T_i subset W.
Stabilization of dimension is sufficient because every step is an
inclusion. This is the usual finite observability/Krylov closure.
"""
q = row_basis(initial, tol)
trace = [int(q.shape[0])]
for _ in range(maps.shape[-1] + 1):
new = row_basis(np.vstack([q, *(q @ t for t in maps)]), tol)
trace.append(int(new.shape[0]))
if new.shape[0] == q.shape[0]:
return new, trace
q = new
raise RuntimeError("Closure did not stabilize in the finite-dimensional bound")
def rotation(theta: float) -> np.ndarray:
return np.array([[math.cos(theta), -math.sin(theta)],
[math.sin(theta), math.cos(theta)]])
def make_system(seed: int, cfg: Config) -> dict[str, np.ndarray]:
"""Structured stress test, constructed independently of evaluation seeds.
In latent wave coordinates the first 16 coordinates form an observable
upper-triangular chain; the remaining 48 coordinates cannot affect it.
A seed-specific rotation mixes detail coefficients but leaves the first
four coarse Haar coordinates fixed. The low observability rank is imposed
by construction, not an empirical discovery about natural tasks.
"""
rng = np.random.default_rng(cfg.seed_offset + 1000 * seed)
d, m, r = cfg.ambient_dimension, cfg.coarse_rank, cfg.invariant_rank
h = haar_matrix(d)
detail, _ = np.linalg.qr(rng.normal(size=(d - m, d - m)))
u = np.eye(d)
u[m:, m:] = detail
transform = u @ h
params = ((0.68, 0.26, 0.30), (0.70, 0.24, -0.50),
(0.72, 0.22, 0.90))
latent_maps = []
for index, (diagonal, coupling, angle) in enumerate(params):
a = np.zeros((d, d))
a[:r, :r] = diagonal * np.eye(r)
for block in range(r // 2 - 1):
a[2 * block:2 * block + 2,
2 * block + 2:2 * block + 4] = coupling * rotation(angle)
nuisance, _ = np.linalg.qr(rng.normal(size=(d - r, d - r)))
a[r:, r:] = (0.80 + 0.02 * index) * nuisance
# Top-right block is zero. Bottom-left need not be zero for the
# quotient theorem, but is zero here to keep the stress test simple.
latent_maps.append(a)
latent_maps = np.asarray(latent_maps)
maps = np.asarray([transform.T @ a @ transform for a in latent_maps])
p = h[:m]
output_selector = np.eye(d)[[0, 1, 4, 5]]
j = output_selector @ transform
return {"maps": maps, "P": p, "J": j,
"transform": transform, "latent_maps": latent_maps}
def make_views(system: dict[str, np.ndarray], seed: int, cfg: Config):
p, j, maps = system["P"], system["J"], system["maps"]
timings = {}
start = time.perf_counter()
immediate = row_basis(np.vstack((p, j)), cfg.rank_tolerance)
timings["immediate_echo"] = time.perf_counter() - start
start = time.perf_counter()
recursive, trace = invariant_row_closure(np.vstack((p, j)), maps,
cfg.rank_tolerance)
timings["recursive_echo"] = time.perf_counter() - start
start = time.perf_counter()
classical, classical_trace = invariant_row_closure(j, maps,
cfg.rank_tolerance)
timings["classical_observable_quotient"] = time.perf_counter() - start
rng = np.random.default_rng(cfg.seed_offset + 1000 * seed + 17)
start = time.perf_counter()
extra = rng.normal(size=(recursive.shape[0] - immediate.shape[0],
cfg.ambient_dimension))
extra -= (extra @ immediate.T) @ immediate
random_echo = row_basis(np.vstack((immediate, extra)), cfg.rank_tolerance)
timings["random_echo_matched_rank"] = time.perf_counter() - start
views = {
"full_state": np.eye(cfg.ambient_dimension),
"wave_only": p,
"immediate_echo": immediate,
"random_echo_matched_rank": random_echo,
"recursive_echo": recursive,
"classical_observable_quotient": classical,
}
traces = {"recursive_echo": trace,
"classical_observable_quotient": classical_trace}
return views, timings, traces
def residuals(q: np.ndarray, j: np.ndarray, maps: np.ndarray) -> dict[str, float]:
projection = q.T @ q
complement = np.eye(q.shape[1]) - projection
return {
"response_factorization_frobenius": float(np.linalg.norm(j @ complement)),
"invariance_frobenius_max": float(max(
np.linalg.norm(q @ t @ complement) for t in maps)),
"orthonormality_frobenius": float(np.linalg.norm(q @ q.T - np.eye(len(q)))),
}
def summarize_errors(predicted: np.ndarray, truth: np.ndarray) -> dict[str, float]:
difference = predicted - truth
sum_error = float(np.sum(difference ** 2))
sum_truth = float(np.sum(truth ** 2))
final_error = float(np.sum(difference[-1] ** 2))
final_truth = float(np.sum(truth[-1] ** 2))
return {
"rms_absolute_error": float(np.sqrt(np.mean(difference ** 2))),
"max_absolute_error": float(np.max(np.abs(difference))),
"relative_trajectory_error": math.sqrt(sum_error / max(sum_truth, 1e-300)),
"relative_final_error": math.sqrt(final_error / max(final_truth, 1e-300)),
"initial_max_absolute_error": float(np.max(np.abs(difference[0]))),
"squared_error": sum_error,
"squared_reference": sum_truth,
}
def run_open_loop(system, views, seed, cfg):
rng = np.random.default_rng(cfg.seed_offset + 1000 * seed + 101)
d, n = cfg.ambient_dimension, cfg.sequences_per_seed
# Evaluation states and edit mixtures are never used to construct bases.
initial = rng.normal(size=(n, d)) / math.sqrt(d)
weights = rng.dirichlet(np.ones(cfg.library_size), size=(cfg.horizon, n))
trajectories = {}
for name, q in views.items():
state = initial @ q.T
output = system["J"] @ q.T
reduced_maps = np.asarray([q @ t @ q.T for t in system["maps"]])
recorded = [state @ output.T]
for step in range(cfg.horizon):
next_state = np.zeros_like(state)
for k, t in enumerate(reduced_maps):
next_state += weights[step, :, k, None] * (state @ t.T)
state = next_state
recorded.append(state @ output.T)
trajectories[name] = np.asarray(recorded)
truth = trajectories["full_state"]
records = []
for name in METHODS:
row = {"seed": seed, "mode": "held_out_open_loop", "method": name,
"retained_coordinates": views[name].shape[0]}
row.update(summarize_errors(trajectories[name], truth))
row.update({"action_disagreement_fraction": 0.0,
"shadow_relative_trajectory_error": row["relative_trajectory_error"],
"shadow_final_response_energy_ratio": 1.0})
records.append(row)
return records, trajectories
def run_adaptive(system, views, seed, cfg):
rng = np.random.default_rng(cfg.seed_offset + 1000 * seed + 211)
initial = rng.normal(size=(cfg.sequences_per_seed, cfg.ambient_dimension))
initial /= math.sqrt(cfg.ambient_dimension)
# Held-out candidate operators are positive mixtures of the training
# library, hence inside the certified span. They are not used for closure.
weights = rng.dirichlet(np.ones(cfg.library_size),
size=cfg.adaptive_candidates)
candidates = np.einsum("ci,ijk->cjk", weights, system["maps"])
trajectories, shadows, actions = {}, {}, {}
for name, q in views.items():
state = initial @ q.T
shadow = initial.copy()
output = system["J"] @ q.T
reduced_maps = np.asarray([q @ t @ q.T for t in candidates])
recorded = [state @ output.T]
shadow_recorded = [shadow @ system["J"].T]
selected = []
for _ in range(cfg.horizon):
next_candidates = np.asarray([state @ t.T for t in reduced_maps])
next_outputs = np.einsum("cnr,pr->cnp", next_candidates, output)
costs = np.sum(next_outputs ** 2, axis=2)
chosen = np.argmin(costs, axis=0)
state = next_candidates[chosen, np.arange(len(state))]
# Every selected policy is also executed on uncompressed full
# state. Inaccurate predicted improvements are therefore exposed.
shadow = np.einsum("nij,nj->ni", candidates[chosen], shadow)
recorded.append(state @ output.T)
shadow_recorded.append(shadow @ system["J"].T)
selected.append(chosen)
trajectories[name] = np.asarray(recorded)
shadows[name] = np.asarray(shadow_recorded)
actions[name] = np.asarray(selected)
truth = trajectories["full_state"]
records = []
for name in METHODS:
row = {"seed": seed, "mode": "adaptive_closed_loop", "method": name,
"retained_coordinates": views[name].shape[0]}
row.update(summarize_errors(trajectories[name], truth))
shadow_error = summarize_errors(trajectories[name], shadows[name])
row.update({
"action_disagreement_fraction": float(np.mean(
actions[name] != actions["full_state"])),
"shadow_relative_trajectory_error": shadow_error["relative_trajectory_error"],
"shadow_final_response_energy_ratio": float(
np.sum(shadows[name][-1] ** 2) /
max(float(np.sum(truth[-1] ** 2)), 1e-300)),
})
records.append(row)
return records, trajectories, shadows, actions
def counterexamples(cfg: Config) -> dict:
"""Exact rational constructions, plus a numerical mirror of the examples."""
# Three-dimensional shift example needs no random matrices or tolerances.
p = np.array([[1.0, 0.0, 0.0]])
j = p.copy()
t = np.array([[1.0, 1.0, 0.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]])
x, y = np.zeros(3), np.array([0.0, 0.0, 1.0])
output_pairs = []
for step in range(4):
output_pairs.append({"step": step, "first_output": float((j @ x)[0]),
"second_output": float((j @ y)[0])})
x, y = t @ x, t @ y
q, trace = invariant_row_closure(np.vstack((p, j)), np.asarray([t]))
system = make_system(0, cfg)
views, _, _ = make_views(system, 0, cfg)
q16 = views["recursive_echo"]
# A new map outside the certified library span reads discarded coordinate
# 16 directly into response 0. No all-words certificate covers this map.
bad_latent = system["latent_maps"][0].copy()
bad_latent[0, cfg.invariant_rank] = 0.25
transform = system["transform"]
bad_map = transform.T @ bad_latent @ transform
discarded = transform.T @ np.eye(cfg.ambient_dimension)[cfg.invariant_rank]
full = system["J"] @ bad_map @ discarded
reduced = system["J"] @ q16.T @ (q16 @ bad_map @ q16.T) @ q16 @ discarded
enlarged_maps = np.concatenate((system["maps"], bad_map[None]), axis=0)
renewed, renewed_trace = invariant_row_closure(q16, enlarged_maps,
cfg.rank_tolerance)
renewed_response = (system["J"] @ renewed.T @
(renewed @ bad_map @ renewed.T) @ renewed @ discarded)
return {
"current_equal_future_different": {
"P": p.tolist(), "J": j.tolist(), "T": t.tolist(),
"x": [0.0, 0.0, 0.0], "y": [0.0, 0.0, 1.0],
"outputs": output_pairs, "closure_rank_trace": trace,
"minimal_recursive_coordinates": int(q.shape[0]),
"interpretation": "Same current response and same one-step response, different two-step response.",
},
"outside_certified_span": {
"new_map_added_entry": [0, cfg.invariant_rank, 0.25],
"full_next_response": full.tolist(),
"compressed_next_response": reduced.tolist(),
"absolute_response_error": float(np.linalg.norm(full - reduced)),
"renewed_closure_rank_trace": renewed_trace,
"renewed_retained_coordinates": int(renewed.shape[0]),
"renewed_absolute_response_error": float(np.linalg.norm(full - renewed_response)),
"interpretation": "Expected failure after a previously unmodelled edit reads a discarded direction.",
},
}
def structural_checks(cfg: Config) -> list[dict]:
checks = []
h = haar_matrix(cfg.ambient_dimension)
err = float(np.linalg.norm(h @ h.T - np.eye(len(h))))
assert err < cfg.diagnostic_tolerance
checks.append({"name": "Haar orthonormality", "passed": True, "error": err})
system = make_system(0, cfg)
views, _, traces = make_views(system, 0, cfg)
assert views["wave_only"].shape[0] == 4
assert views["immediate_echo"].shape[0] == 6
assert views["recursive_echo"].shape[0] == cfg.invariant_rank
assert views["random_echo_matched_rank"].shape[0] == cfg.invariant_rank
checks.append({"name": "Designed coarse, immediate, recursive ranks",
"passed": True, "ranks": [4, 6, cfg.invariant_rank],
"trace": traces["recursive_echo"]})
for name in ("recursive_echo", "classical_observable_quotient"):
res = residuals(views[name], system["J"], system["maps"])
assert max(res.values()) < cfg.diagnostic_tolerance
checks.append({"name": name + " factorization and invariance",
"passed": True, **res})
qa, qb = views["recursive_echo"], views["classical_observable_quotient"]
projector_error = float(np.linalg.norm(qa.T @ qa - qb.T @ qb))
assert projector_error < cfg.diagnostic_tolerance
checks.append({"name": "Classical quotient equivalence", "passed": True,
"projector_error": projector_error})
examples = counterexamples(cfg)
equal = examples["current_equal_future_different"]
assert equal["outputs"][0]["second_output"] == 0
assert equal["outputs"][1]["second_output"] == 0
assert equal["outputs"][2]["second_output"] == 1
assert abs(examples["outside_certified_span"]["absolute_response_error"] - 0.25) < 1e-12
assert examples["outside_certified_span"]["renewed_retained_coordinates"] == cfg.ambient_dimension
assert examples["outside_certified_span"]["renewed_absolute_response_error"] < cfg.diagnostic_tolerance
checks.append({"name": "Analytic blind-pair and new-map failures", "passed": True})
return checks
def grouped_summary(rows: list[dict]) -> list[dict]:
result = []
metrics = ("relative_trajectory_error", "rms_absolute_error",
"max_absolute_error", "relative_final_error",
"action_disagreement_fraction", "shadow_relative_trajectory_error",
"shadow_final_response_energy_ratio")
for mode in ("held_out_open_loop", "adaptive_closed_loop"):
for method in METHODS:
selected = [r for r in rows if r["mode"] == mode and r["method"] == method]
stats = {"mode": mode, "method": method, "number_of_seeds": len(selected),
"retained_coordinates": selected[0]["retained_coordinates"]}
for metric in metrics:
values = np.asarray([r[metric] for r in selected])
stats[metric + "_mean"] = float(values.mean())
stats[metric + "_min"] = float(values.min())
stats[metric + "_max"] = float(values.max())
stats[metric + "_standard_deviation"] = float(values.std(ddof=1)) if len(values) > 1 else 0.0
stats["pooled_relative_trajectory_error"] = math.sqrt(
sum(r["squared_error"] for r in selected) /
max(sum(r["squared_reference"] for r in selected), 1e-300))
result.append(stats)
return result
def storage_counts(cfg: Config) -> list[dict]:
ranks = dict(zip(METHODS, (64, 4, 6, 16, 16, 16)))
rows = []
for name, r in ranks.items():
basis = 0 if name == "full_state" else cfg.ambient_dimension * r
operators = cfg.library_size * r * r
readout = cfg.response_rank * r
rows.append({
"method": name, "state_scalars": r,
"basis_scalars": basis, "library_operator_scalars": operators,
"readout_scalars": readout,
"total_persistent_dense_scalars_one_state": basis + operators + readout + r,
"state_bytes_float64": 8 * r,
"note": "Dense executable representation; construction/evaluation workspace excluded. Full identity basis stored implicitly in this count.",
})
return rows
def microbenchmark(cfg: Config) -> dict:
"""Small-array throughput only; explicitly excludes basis construction.
Fixed linear updates on a batch test quotient arithmetic, not training or
LLM execution speed. Timings are hardware-dependent descriptive values.
"""
system = make_system(0, cfg)
views, _, _ = make_views(system, 0, cfg)
rng = np.random.default_rng(cfg.seed_offset + 991)
initial = rng.normal(size=(128, cfg.ambient_dimension))
results = {}
steps, repeats = 160, 5
for name in ("full_state", "recursive_echo"):
q = views[name]
t = q @ system["maps"][0] @ q.T
start_state = initial @ q.T
durations = []
checksum = 0.0
for _ in range(repeats):
state = start_state.copy()
start = time.perf_counter()
for _ in range(steps):
state = state @ t.T
durations.append(time.perf_counter() - start)
checksum = float(np.sum(state))
results[name] = {"seconds_median": float(np.median(durations)),
"seconds_all": durations, "checksum": checksum}
return {"batch_states": 128, "steps": steps, "repeats": repeats,
"results": results,
"caveat": "Arithmetic microbenchmark only. Excludes closure and Jacobian/operator construction, transfer, evaluation, basis storage, and model training. No end-to-end speed claim."}
def write_csv(path: Path, records: list[dict]):
with path.open("w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=list(records[0]))
writer.writeheader()
writer.writerows(records)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, default=Path(__file__).resolve().parent.parent / "results")
parser.add_argument("--seeds", type=int, default=32)
parser.add_argument("--self-test", action="store_true", help="Run structural checks only")
args = parser.parse_args()
if args.seeds < 1:
parser.error("--seeds must be positive")
cfg = Config(seeds=args.seeds)
checks = structural_checks(cfg)
if args.self_test:
print(json.dumps({"checks": checks}, indent=2))
return
args.output.mkdir(parents=True, exist_ok=True)
start_all = time.perf_counter()
records, diagnostics, closure_records, timings = [], [], [], []
example_trajectories = {}
for seed in range(cfg.seeds):
system = make_system(seed, cfg)
views, elapsed, traces = make_views(system, seed, cfg)
for name, q in views.items():
diagnostics.append({"seed": seed, "method": name,
"retained_coordinates": int(q.shape[0]),
**residuals(q, system["J"], system["maps"])})
for name, trace in traces.items():
closure_records.append({"seed": seed, "method": name, "rank_trace": trace})
for name, duration in elapsed.items():
timings.append({"seed": seed, "method": name, "seconds": duration})
open_records, open_trajectories = run_open_loop(system, views, seed, cfg)
adaptive_records, adaptive_trajectories, shadows, actions = run_adaptive(system, views, seed, cfg)
records.extend(open_records + adaptive_records)
for row in open_records + adaptive_records:
if row["method"] in ("recursive_echo", "classical_observable_quotient"):
assert row["max_absolute_error"] < cfg.diagnostic_tolerance, row
assert row["action_disagreement_fraction"] == 0.0, row
if seed == 0:
for name in METHODS:
example_trajectories["open_" + name] = open_trajectories[name]
example_trajectories["adaptive_" + name] = adaptive_trajectories[name]
example_trajectories["shadow_" + name] = shadows[name]
example_trajectories["actions_" + name] = actions[name]
elapsed_all = time.perf_counter() - start_all
summary_rows = grouped_summary(records)
summary = {
"experiment": "Finite-dimensional recursive response preservation",
"status": "Executed synthetic mechanism test; not an autonomous RSI or LLM benchmark",
"config": asdict(cfg),
"protocol": {
"construction_seeds": "seed_offset + 1000 * seed; seed=0,...,seeds-1",
"random_echo_seeds": "construction seed + 17",
"open_loop_evaluation_seeds": "construction seed + 101",
"adaptive_evaluation_seeds": "construction seed + 211",
"basis_access": "Full P, J, and the three edit matrices; never evaluation states, mixtures, or paths.",
"scope_of_held_out": "New states, continuous mixtures, and composition sequences within the certified edit span; not new natural task families.",
"designed_structure": "Observable invariant rank 16 in ambient dimension 64 is imposed by construction.",
"adaptive_policy": "Greedy argmin of squared predicted next response among 9 held-out convex mixtures. Every compressed policy also executes on a full-state shadow.",
"no_post_test_tuning": "Configuration fixed in this script. No method selection or parameter fitting uses evaluation outcomes.",
},
"environment": {"python": sys.version, "numpy": np.__version__,
"platform": platform.platform(),
"OPENBLAS_NUM_THREADS": os.environ.get("OPENBLAS_NUM_THREADS"),
"OMP_NUM_THREADS": os.environ.get("OMP_NUM_THREADS")},
"source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
"structural_checks": checks,
"execution_seconds_excluding_microbenchmark": elapsed_all,
"results": summary_rows,
"storage": storage_counts(cfg),
"closure_traces": closure_records,
"closure_timings": timings,
"counterexamples": counterexamples(cfg),
"microbenchmark": microbenchmark(cfg),
"interpretation_limits": [
"The row-space closure is classical observability/finite realization algebra, not a new linear algebra theorem.",
"The recursive_echo and classical_observable_quotient baselines recover the same subspace and are expected to agree.",
"Preserving a recursive computation is distinct from proving that computation improves its own learning algorithm.",
"The prototype does not implement a Waldhausen S-construction or claim that a categorical label causes computational gains.",
"No LLM training, natural task transfer, general RSI, unbounded compounding, or independent replication was performed.",
"Dense operators, readouts, and bases are supplied; no cost-free access to real-model Jacobians is assumed.",
"Response-invisible coordinates may become relevant after an edit outside the certified operator span; the explicit counterexample tests this failure.",
],
}
write_csv(args.output / "per_seed_metrics.csv", records)
write_csv(args.output / "aggregate_metrics.csv", summary_rows)
write_csv(args.output / "algebraic_diagnostics.csv", diagnostics)
write_csv(args.output / "closure_timings.csv", timings)
(args.output / "summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
np.savez_compressed(args.output / "seed0_trajectories.npz", **example_trajectories)
print(json.dumps({"output": str(args.output.resolve()), "seeds": cfg.seeds,
"seconds": elapsed_all,
"summary": [{"mode": r["mode"], "method": r["method"],
"rank": r["retained_coordinates"],
"pooled_relative_error": r["pooled_relative_trajectory_error"],
"action_disagreement_mean": r["action_disagreement_fraction_mean"]}
for r in summary_rows]}, indent=2))
if __name__ == "__main__":
main()