Download experiments/run_experiments.py from PureOne/Neuyalun-Phase-Shift-RSI: direct link, hf CLI and curl.
- Browser
- Download file 53.7 kB
-
https://huggingface.co/datasets/PureOne/Neuyalun-Phase-Shift-RSI/resolve/main/experiments/run_experiments.py
- Command line
-
hf download hf://datasets/PureOne/Neuyalun-Phase-Shift-RSI/experiments/run_experiments.py
-
curl -L -o run_experiments.py https://huggingface.co/datasets/PureOne/Neuyalun-Phase-Shift-RSI/resolve/main/experiments/run_experiments.py
53.7 kB
| #!/usr/bin/env python3 | |
| """Reproducible bounded optimizer-state refinement experiments. | |
| No learner receives the hidden Hessian. Objective values are used only by the | |
| recorder, not as a stopping or update signal. Full-space anchors are exact linear | |
| constraints, not claims about semantic alignment. The inverse-oracle comparator | |
| is explicitly privileged. This is a finite synthetic experiment, not an LLM. | |
| """ | |
| from __future__ import annotations | |
| import os | |
| for _thread_var in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS"): | |
| os.environ[_thread_var] = "1" | |
| import argparse | |
| import csv | |
| import hashlib | |
| import json | |
| import math | |
| import platform | |
| import sys | |
| import time | |
| from dataclasses import dataclass | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| import scipy | |
| from scipy.linalg import null_space | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| class Config: | |
| dimension: int = 16 | |
| anchors: int = 8 | |
| seeds: int = 24 | |
| tasks: int = 12 | |
| condition: float = 100.0 | |
| gradient_tolerance: float = 1e-6 | |
| max_gradient_calls: int = 1600 | |
| seed_start: int = 2026110600 | |
| rank_test_targets: int = 32 | |
| sensitivity_targets: int = 16 | |
| LABELS = { | |
| "phase_retained": "Retained probe inverse", | |
| "phase_reset": "Reset probe inverse", | |
| "bfgs_retained": "Retained BFGS", | |
| "bfgs_reset": "Reset BFGS", | |
| "cg_reset": "Conjugate gradient", | |
| "gd_spectral": "GD with spectral bounds", | |
| "bb_reset": "Barzilai–Borwein", | |
| "adam_reset": "Adam", | |
| "oracle_inverse": "Exact inverse oracle", | |
| } | |
| COLORS = { | |
| "phase_retained": "#b32648", "phase_reset": "#e58b99", | |
| "bfgs_retained": "#117c80", "bfgs_reset": "#76adaf", | |
| "cg_reset": "#6b55a1", "gd_spectral": "#8b6b39", | |
| "bb_reset": "#4286b5", "adam_reset": "#8e989d", | |
| "oracle_inverse": "#222222", | |
| } | |
| def orthogonal(rng, d): | |
| q, r = np.linalg.qr(rng.normal(size=(d, d))) | |
| return q * np.where(np.diag(r) < 0, -1.0, 1.0)[None, :] | |
| def hidden_hessian(rng, d, condition): | |
| q = orthogonal(rng, d) | |
| eigenvalues = np.geomspace(1.0, condition, d) | |
| return (q * eigenvalues[None, :]) @ q.T | |
| def unit_targets(rng, n, d): | |
| t = rng.normal(size=(n, d)) | |
| return t / np.linalg.norm(t, axis=1, keepdims=True) | |
| class QuadraticOracle: | |
| """Gradient interface plus an evaluator used only to record trajectories.""" | |
| def __init__(self, hessian, target, noise_std=0.0, rng=None): | |
| self._hessian = hessian | |
| self._target = target | |
| self.dimension = len(target) | |
| self.calls = 0 | |
| self.noise_std = float(noise_std) | |
| self.rng = rng | |
| self._initial_loss = float(0.5 * target @ hessian @ target) | |
| def gradient(self, x): | |
| self.calls += 1 | |
| g = self._hessian @ (x - self._target) | |
| if self.noise_std: | |
| g = g + self.rng.normal(scale=self.noise_std, size=x.shape) | |
| return g | |
| def relative_loss(self, x): | |
| # The returned metric is only recorded; solvers never branch on it. | |
| residual = x - self._target | |
| return float(0.5 * residual @ self._hessian @ residual / self._initial_loss) | |
| def record(history, oracle, x): | |
| history.append((int(oracle.calls), oracle.relative_loss(x))) | |
| def calibrate(gradient, dimension, basis): | |
| """Exactly d+1 gradient calls; no Hessian or target is supplied.""" | |
| g0 = gradient(np.zeros(dimension)) | |
| y = np.column_stack([gradient(basis[:, j]) - g0 for j in range(dimension)]) | |
| estimated = y @ basis.T | |
| return (estimated + estimated.T) / 2, y | |
| def inverse_from_estimate(estimated, eigenvalue_floor=None): | |
| if eigenvalue_floor is None: | |
| return np.linalg.solve(estimated, np.eye(len(estimated))) | |
| eigenvalues, eigenvectors = np.linalg.eigh(estimated) | |
| return (eigenvectors * (1.0 / np.maximum(eigenvalues, eigenvalue_floor))[None, :]) @ eigenvectors.T | |
| def complete_partial_curvature(v, y, dimension, prior): | |
| """SPD Nyström completion matching every observed Hessian action. | |
| Hhat = Y (V.T Y)^-1 Y.T + prior (I - V V.T). | |
| This is a known matrix construction, not a claimed new inverse algorithm. | |
| """ | |
| if v.shape[1] == 0: | |
| return prior * np.eye(dimension) | |
| a = (v.T @ y + y.T @ v) / 2 | |
| estimated = y @ np.linalg.solve(a, y.T) + prior * (np.eye(dimension) - v @ v.T) | |
| return (estimated + estimated.T) / 2 | |
| def finish(oracle, x, gradient, gnorm0, history, state=None): | |
| return { | |
| "x": x, | |
| "calls": int(oracle.calls), | |
| "relative_gradient": float(np.linalg.norm(gradient) / max(gnorm0, 1e-300)), | |
| "relative_loss": oracle.relative_loss(x), | |
| "history": np.asarray(history, dtype=np.float64), | |
| "state": state, | |
| } | |
| def solve_inverse(oracle, inverse, tolerance, max_calls): | |
| x = np.zeros(oracle.dimension) | |
| history = [(0, 1.0)] | |
| g = oracle.gradient(x) | |
| gnorm0 = np.linalg.norm(g) | |
| record(history, oracle, x) | |
| while np.linalg.norm(g) > tolerance * gnorm0 and oracle.calls < max_calls: | |
| x = x - inverse @ g | |
| g = oracle.gradient(x) # Always certify a purported one-step solution. | |
| record(history, oracle, x) | |
| return finish(oracle, x, g, gnorm0, history) | |
| def solve_gd(oracle, mu, upper, tolerance, max_calls): | |
| x = np.zeros(oracle.dimension) | |
| history = [(0, 1.0)] | |
| g = oracle.gradient(x) | |
| gnorm0 = np.linalg.norm(g) | |
| rate = 2.0 / (mu + upper) | |
| record(history, oracle, x) | |
| while np.linalg.norm(g) > tolerance * gnorm0 and oracle.calls < max_calls: | |
| x = x - rate * g | |
| g = oracle.gradient(x) | |
| record(history, oracle, x) | |
| return finish(oracle, x, g, gnorm0, history) | |
| def solve_bb(oracle, upper, tolerance, max_calls): | |
| x = np.zeros(oracle.dimension) | |
| history = [(0, 1.0)] | |
| g = oracle.gradient(x) | |
| gnorm0 = np.linalg.norm(g) | |
| rate = 1.0 / upper | |
| record(history, oracle, x) | |
| iteration = 0 | |
| while np.linalg.norm(g) > tolerance * gnorm0 and oracle.calls < max_calls: | |
| new_x = x - rate * g | |
| new_g = oracle.gradient(new_x) | |
| s, y = new_x - x, new_g - g | |
| curvature = float(s @ y) | |
| if curvature > 1e-300: | |
| rate = float((s @ s) / curvature) if iteration % 2 == 0 else float(curvature / (y @ y)) | |
| rate = float(np.clip(rate, 0.1 / upper, 2.0)) | |
| x, g = new_x, new_g | |
| record(history, oracle, x) | |
| iteration += 1 | |
| return finish(oracle, x, g, gnorm0, history) | |
| def solve_adam(oracle, tolerance, max_calls): | |
| x = np.zeros(oracle.dimension) | |
| history = [(0, 1.0)] | |
| g = oracle.gradient(x) | |
| gnorm0 = np.linalg.norm(g) | |
| m = np.zeros_like(x) | |
| v = np.zeros_like(x) | |
| beta1, beta2, base_rate = 0.9, 0.999, 0.05 | |
| iteration = 0 | |
| record(history, oracle, x) | |
| while np.linalg.norm(g) > tolerance * gnorm0 and oracle.calls < max_calls: | |
| iteration += 1 | |
| m = beta1 * m + (1 - beta1) * g | |
| v = beta2 * v + (1 - beta2) * g * g | |
| mhat, vhat = m / (1 - beta1 ** iteration), v / (1 - beta2 ** iteration) | |
| rate = base_rate / math.sqrt(1 + iteration / 100.0) | |
| x = x - rate * mhat / (np.sqrt(vhat) + 1e-8) | |
| g = oracle.gradient(x) | |
| record(history, oracle, x) | |
| return finish(oracle, x, g, gnorm0, history) | |
| def solve_bfgs(oracle, initial_inverse, tolerance, max_calls): | |
| """BFGS with gradient-only exact quadratic line search. | |
| A probe g(x+p) gives Hp=g(x+p)-g(x). Hence a line optimum and its | |
| gradient are obtained algebraically. The final gradient is actually | |
| queried unless the unit trial itself already certified convergence. | |
| """ | |
| x = np.zeros(oracle.dimension) | |
| b = initial_inverse.copy() | |
| history = [(0, 1.0)] | |
| g = oracle.gradient(x) | |
| gnorm0 = np.linalg.norm(g) | |
| record(history, oracle, x) | |
| while np.linalg.norm(g) > tolerance * gnorm0 and oracle.calls < max_calls: | |
| p = -b @ g | |
| trial_g = oracle.gradient(x + p) | |
| hp = trial_g - g | |
| if np.linalg.norm(trial_g) <= tolerance * gnorm0: | |
| new_x, new_g, step = x + p, trial_g, 1.0 | |
| certified = True | |
| else: | |
| curvature = float(p @ hp) | |
| if curvature <= 0 or not np.isfinite(curvature): | |
| raise ArithmeticError("Nonpositive curvature in the exact SPD baseline") | |
| step = -float(g @ p) / curvature | |
| new_x = x + step * p | |
| new_g = g + step * hp | |
| certified = False | |
| s, y = step * p, step * hp | |
| ys = float(y @ s) | |
| if ys > 1e-300: | |
| by = b @ y | |
| b = b + ((ys + float(y @ by)) / (ys * ys)) * np.outer(s, s) - (np.outer(by, s) + np.outer(s, by)) / ys | |
| b = (b + b.T) / 2 | |
| x, g = new_x, new_g | |
| record(history, oracle, x) | |
| if np.linalg.norm(g) <= tolerance * gnorm0 and not certified and oracle.calls < max_calls: | |
| g = oracle.gradient(x) | |
| record(history, oracle, x) | |
| return finish(oracle, x, g, gnorm0, history, b) | |
| def solve_cg(oracle, tolerance, max_calls): | |
| x = np.zeros(oracle.dimension) | |
| history = [(0, 1.0)] | |
| g = oracle.gradient(x) | |
| gnorm0 = np.linalg.norm(g) | |
| p = -g | |
| record(history, oracle, x) | |
| while np.linalg.norm(g) > tolerance * gnorm0 and oracle.calls < max_calls: | |
| trial_g = oracle.gradient(x + p) | |
| hp = trial_g - g | |
| gg = float(g @ g) | |
| curvature = float(p @ hp) | |
| if curvature <= 0 or not np.isfinite(curvature): | |
| raise ArithmeticError("Nonpositive curvature in exact SPD conjugate gradient") | |
| step = gg / curvature | |
| x = x + step * p | |
| new_g = g + step * hp | |
| p = -new_g + float(new_g @ new_g) / gg * p | |
| g = new_g | |
| record(history, oracle, x) | |
| if np.linalg.norm(g) <= tolerance * gnorm0 and oracle.calls < max_calls: | |
| g = oracle.gradient(x) | |
| record(history, oracle, x) | |
| if np.linalg.norm(g) > tolerance * gnorm0: | |
| p = -g | |
| return finish(oracle, x, g, gnorm0, history) | |
| def write_csv(path, rows): | |
| pd.DataFrame(rows).to_csv(path, index=False, float_format="%.17g") | |
| def main_benchmark(config, output): | |
| rows, histories, calibration_rows = [], {}, [] | |
| methods = list(LABELS) | |
| beginning = time.perf_counter() | |
| for seed_index in range(config.seeds): | |
| seed = config.seed_start + seed_index | |
| rng = np.random.default_rng(seed) | |
| d, a = config.dimension, config.anchors | |
| h = hidden_hessian(rng, d, config.condition) | |
| full_basis = orthogonal(rng, d + a) | |
| anchors, free = full_basis[:, :a].T, full_basis[:, a:] | |
| theta0 = rng.normal(size=d + a) | |
| anchor_value = anchors @ theta0 | |
| source_target = unit_targets(rng, 1, d)[0] | |
| targets = unit_targets(rng, config.tasks, d) | |
| probe_basis = orthogonal(rng, d) | |
| source_oracle = QuadraticOracle(h, source_target) | |
| t0 = time.perf_counter() | |
| estimated, _ = calibrate(source_oracle.gradient, d, probe_basis) | |
| retained_inverse = inverse_from_estimate(estimated) | |
| calibration_ms = 1000.0 * (time.perf_counter() - t0) | |
| calibration_rows.append({ | |
| "seed": seed, "gradient_calls": source_oracle.calls, | |
| "relative_hessian_error": np.linalg.norm(estimated - h, 2) / np.linalg.norm(h, 2), | |
| "inverse_residual": np.linalg.norm(np.eye(d) - retained_inverse @ h, 2), | |
| "wall_ms": calibration_ms, | |
| }) | |
| for method in methods: | |
| cumulative = 0 | |
| retained_bfgs = np.eye(d) / math.sqrt(config.condition) | |
| for episode, target in enumerate(targets, start=1): | |
| calibration_calls, charged_calibration_ms = 0, 0.0 | |
| t0 = time.perf_counter() | |
| oracle = QuadraticOracle(h, target) | |
| if method == "phase_retained": | |
| if episode == 1: | |
| calibration_calls, charged_calibration_ms = source_oracle.calls, calibration_ms | |
| result = solve_inverse(oracle, retained_inverse, config.gradient_tolerance, config.max_gradient_calls) | |
| elif method == "phase_reset": | |
| reset_oracle = QuadraticOracle(h, source_target) | |
| t_cal = time.perf_counter() | |
| reset_h, _ = calibrate(reset_oracle.gradient, d, probe_basis) | |
| reset_inverse = inverse_from_estimate(reset_h) | |
| charged_calibration_ms = 1000.0 * (time.perf_counter() - t_cal) | |
| calibration_calls = reset_oracle.calls | |
| result = solve_inverse(oracle, reset_inverse, config.gradient_tolerance, config.max_gradient_calls) | |
| elif method in ("bfgs_retained", "bfgs_reset"): | |
| initial_b = retained_bfgs if method == "bfgs_retained" else np.eye(d) / math.sqrt(config.condition) | |
| result = solve_bfgs(oracle, initial_b, config.gradient_tolerance, config.max_gradient_calls) | |
| if method == "bfgs_retained": | |
| retained_bfgs = result["state"] | |
| elif method == "cg_reset": | |
| result = solve_cg(oracle, config.gradient_tolerance, config.max_gradient_calls) | |
| elif method == "gd_spectral": | |
| result = solve_gd(oracle, 1.0, config.condition, config.gradient_tolerance, config.max_gradient_calls) | |
| elif method == "bb_reset": | |
| result = solve_bb(oracle, config.condition, config.gradient_tolerance, config.max_gradient_calls) | |
| elif method == "adam_reset": | |
| result = solve_adam(oracle, config.gradient_tolerance, config.max_gradient_calls) | |
| elif method == "oracle_inverse": | |
| # Deliberately privileged reference, never an ordinary learner. | |
| result = solve_inverse(oracle, np.linalg.inv(h), config.gradient_tolerance, config.max_gradient_calls) | |
| else: | |
| raise ValueError(method) | |
| wall_ms = 1000.0 * (time.perf_counter() - t0) | |
| if method == "phase_retained": | |
| wall_ms += charged_calibration_ms | |
| total = calibration_calls + result["calls"] | |
| cumulative += total | |
| theta = theta0 + free @ result["x"] | |
| anchor_residual = float(np.max(np.abs(anchors @ theta - anchor_value))) | |
| rows.append({ | |
| "seed": seed, "method": method, "episode": episode, | |
| "dimension": d, "anchors": a, "condition": config.condition, | |
| "calibration_calls": calibration_calls, "task_calls": result["calls"], | |
| "episode_calls": total, "cumulative_calls": cumulative, | |
| "relative_loss": result["relative_loss"], "relative_gradient": result["relative_gradient"], | |
| "certified_success": int(result["relative_gradient"] <= config.gradient_tolerance * (1 + 1e-10)), | |
| "anchor_max_residual": anchor_residual, | |
| "wall_ms": wall_ms, "calibration_wall_ms": charged_calibration_ms, | |
| "privileged_oracle": int(method == "oracle_inverse"), | |
| }) | |
| key = f"seed{seed}_{method}_task{episode:02d}" | |
| histories[key] = result["history"] | |
| print(f"Main benchmark family {seed_index+1}/{config.seeds} complete", flush=True) | |
| write_csv(output / "raw_episodes.csv", rows) | |
| write_csv(output / "calibration_audit.csv", calibration_rows) | |
| np.savez_compressed(output / "convergence_traces.npz", **histories) | |
| return pd.DataFrame(rows), histories, time.perf_counter() - beginning | |
| def one_step_metrics(hessian, targets, inverse): | |
| """Actually query every fixed candidate's measured one-step protocol. | |
| Query 1 observes the initial gradient. Query 2 certifies the unit trial | |
| and supplies a directional curvature measurement. Query 3 certifies the | |
| exact-line-search trial. Hessian access remains inside the oracle. | |
| """ | |
| unit_ratio, line_ratio, steps = [], [], [] | |
| for target in targets: | |
| oracle = QuadraticOracle(hessian, target) | |
| g = oracle.gradient(np.zeros(len(target))) | |
| p = -(inverse @ g) | |
| trial_g = oracle.gradient(p) | |
| hp = trial_g - g | |
| step = -float(g @ p) / float(p @ hp) | |
| oracle.gradient(step * p) | |
| assert oracle.calls == 3 | |
| unit_ratio.append(oracle.relative_loss(p)) | |
| line_ratio.append(oracle.relative_loss(step * p)) | |
| steps.append(step) | |
| return np.asarray(unit_ratio), np.asarray(line_ratio), np.asarray(steps) | |
| def auxiliary_benchmarks(config, output): | |
| rank_rows, noise_rows, shift_rows, refinement_rows, growth_rows, anchor_rows = [], [], [], [], [], [] | |
| d = config.dimension | |
| for seed_index in range(config.seeds): | |
| seed = config.seed_start + seed_index | |
| rng = np.random.default_rng(seed + 100000) | |
| h = hidden_hessian(rng, d, config.condition) | |
| source_target = unit_targets(rng, 1, d)[0] | |
| basis = orthogonal(rng, d) | |
| source = QuadraticOracle(h, source_target) | |
| estimated, all_y = calibrate(source.gradient, d, basis) | |
| inverse = inverse_from_estimate(estimated) | |
| targets = unit_targets(rng, config.rank_test_targets, d) | |
| for rank in range(d + 1): | |
| completed = complete_partial_curvature(basis[:, :rank], all_y[:, :rank], d, math.sqrt(config.condition)) | |
| b = inverse_from_estimate(completed) | |
| unit_ratio, line_ratio, steps = one_step_metrics(h, targets, b) | |
| eigenvalues, eigenvectors = np.linalg.eigh(completed) | |
| invsqrt = (eigenvectors * (1 / np.sqrt(eigenvalues))[None, :]) @ eigenvectors.T | |
| generalized = np.linalg.eigvalsh(invsqrt @ h @ invsqrt) | |
| condition = generalized[-1] / generalized[0] | |
| for target_index in range(len(targets)): | |
| rank_rows.append({ | |
| "seed": seed, "rank": rank, "source_calls": rank + 1 if rank else 0, | |
| "target_index": target_index, "unit_step_loss_ratio": unit_ratio[target_index], | |
| "line_step_loss_ratio": line_ratio[target_index], "line_step_size": steps[target_index], | |
| "preconditioned_condition": condition, | |
| "hessian_relative_error": np.linalg.norm(completed - h, 2) / np.linalg.norm(h, 2), | |
| "target_gradient_calls_for_line_step_and_certificate": 3, | |
| }) | |
| sensitivity_targets = unit_targets(rng, config.sensitivity_targets, d) | |
| for relative_noise in (0.0, 1e-4, 1e-3, 1e-2, 5e-2, 1e-1): | |
| # The per-coordinate standard deviation makes RMS noise norm | |
| # relative_noise times the RMS norm of an exact unit probe response. | |
| noise_std = relative_noise * np.linalg.norm(h, "fro") / d | |
| noisy = QuadraticOracle(h, source_target, noise_std=noise_std, rng=rng) | |
| noisy_h, _ = calibrate(noisy.gradient, d, basis) | |
| noisy_b = inverse_from_estimate(noisy_h, eigenvalue_floor=0.5) | |
| unit_ratio, line_ratio, steps = one_step_metrics(h, sensitivity_targets, noisy_b) | |
| for target_index in range(len(sensitivity_targets)): | |
| noise_rows.append({ | |
| "seed": seed, "relative_noise": relative_noise, | |
| "noise_per_coordinate_std": noise_std, "target_index": target_index, | |
| "calibration_gradient_calls": noisy.calls, "eigenvalue_floor": 0.5, | |
| "hessian_relative_error_before_floor": np.linalg.norm(noisy_h - h, 2) / np.linalg.norm(h, 2), | |
| "unit_step_loss_ratio": unit_ratio[target_index], | |
| "line_step_loss_ratio": line_ratio[target_index], | |
| "unit_step_worsened": int(unit_ratio[target_index] > 1.0), | |
| "unit_step_target_gradient_calls_with_certificate": 2, | |
| "line_step_target_gradient_calls_with_certificate": 3, | |
| }) | |
| other_h = hidden_hessian(rng, d, config.condition) | |
| old_eigenvalues, old_eigenvectors = np.linalg.eigh(h) | |
| old_invsqrt = (old_eigenvectors * (1 / np.sqrt(old_eigenvalues))[None, :]) @ old_eigenvectors.T | |
| for mixture_fraction in (0.0, 0.01, 0.05, 0.1, 0.25, 0.5, 1.0): | |
| changed = (1 - mixture_fraction) * h + mixture_fraction * other_h | |
| relative_mismatch = np.linalg.norm(old_invsqrt @ (changed - h) @ old_invsqrt, 2) | |
| unit_ratio, line_ratio, steps = one_step_metrics(changed, sensitivity_targets, inverse) | |
| for target_index in range(len(sensitivity_targets)): | |
| shift_rows.append({ | |
| "seed": seed, "mixture_fraction": mixture_fraction, "target_index": target_index, | |
| "relative_spectral_curvature_mismatch": relative_mismatch, | |
| "unit_step_loss_ratio": unit_ratio[target_index], | |
| "line_step_loss_ratio": line_ratio[target_index], "line_step_size": steps[target_index], | |
| "unit_step_worsened": int(unit_ratio[target_index] > 1.0), | |
| "unit_step_target_gradient_calls_with_certificate": 2, | |
| "line_step_target_gradient_calls_with_certificate": 3, | |
| }) | |
| spectral_upper = float(np.linalg.eigvalsh(estimated)[-1]) | |
| refined = np.eye(d) / spectral_upper | |
| initial_residual = np.linalg.norm(np.eye(d) - refined @ estimated, 2) | |
| for iteration in range(19): | |
| unit_ratio, _, _ = one_step_metrics(h, sensitivity_targets, refined) | |
| residual = np.linalg.norm(np.eye(d) - refined @ estimated, 2) | |
| exact_bound = initial_residual ** (2 ** iteration) | |
| refinement_rows.append({ | |
| "seed": seed, "iteration": iteration, "dense_matrix_multiplications": 2 * iteration, | |
| "additional_task_oracle_calls": 0, "spectral_residual": residual, | |
| "diagnostic_evaluation_gradient_calls": 3 * len(sensitivity_targets), | |
| "exact_arithmetic_residual_bound": exact_bound, | |
| "mean_future_one_step_loss_ratio": float(np.mean(unit_ratio)), | |
| "median_future_one_step_loss_ratio": float(np.median(unit_ratio)), | |
| }) | |
| # Stop at the final recorded state: no unreported extra update. | |
| if iteration < 18: | |
| refined = 2 * refined - (refined @ estimated) @ refined | |
| refined = (refined + refined.T) / 2 | |
| # Successor growth: old principal block already known; learn only new | |
| # columns. The new gradient baseline is charged even though the old one | |
| # existed in a different parameter dimension. | |
| extra = 4 | |
| grown = hidden_hessian(rng, d + extra, config.condition) | |
| old = grown[:d, :d] | |
| old_source = QuadraticOracle(old, unit_targets(rng, 1, d)[0]) | |
| old_estimate, _ = calibrate(old_source.gradient, d, orthogonal(rng, d)) | |
| new_source = QuadraticOracle(grown, unit_targets(rng, 1, d + extra)[0]) | |
| new_base = new_source.gradient(np.zeros(d + extra)) | |
| new_columns = [] | |
| for column in range(d, d + extra): | |
| direction = np.zeros(d + extra) | |
| direction[column] = 1.0 | |
| new_columns.append(new_source.gradient(direction) - new_base) | |
| new_columns = np.column_stack(new_columns) | |
| c, dd = new_columns[:d, :], new_columns[d:, :] | |
| dd = (dd + dd.T) / 2 | |
| ai = np.linalg.inv(old_estimate) | |
| schur = dd - c.T @ ai @ c | |
| si = np.linalg.inv(schur) | |
| inverse_grown = np.block([[ai + ai @ c @ si @ c.T @ ai, -ai @ c @ si], [-si @ c.T @ ai, si]]) | |
| full_new = QuadraticOracle(grown, unit_targets(rng, 1, d + extra)[0]) | |
| fresh_h, _ = calibrate(full_new.gradient, d + extra, orthogonal(rng, d + extra)) | |
| fresh_inverse = np.linalg.inv(fresh_h) | |
| growth_rows.append({ | |
| "seed": seed, "old_dimension": d, "new_dimensions": extra, | |
| "old_calibration_calls_already_spent": old_source.calls, | |
| "incremental_gradient_calls": new_source.calls, | |
| "fresh_new_gradient_calls": full_new.calls, | |
| "lifecycle_calls_retained": old_source.calls + new_source.calls, | |
| "lifecycle_calls_reset": old_source.calls + full_new.calls, | |
| "new_scalar_degrees_of_freedom": d * extra + extra * (extra + 1) // 2, | |
| "retained_inverse_residual": np.linalg.norm(np.eye(d + extra) - inverse_grown @ grown, 2), | |
| "fresh_inverse_residual": np.linalg.norm(np.eye(d + extra) - fresh_inverse @ grown, 2), | |
| "relative_inverse_discrepancy": np.linalg.norm(inverse_grown - fresh_inverse, 2) / np.linalg.norm(fresh_inverse, 2), | |
| }) | |
| # Anchor control on a generic full-space objective whose minimizer | |
| # normally violates the selected anchors. Same step size and 50 steps. | |
| total_d = d + config.anchors | |
| q = orthogonal(rng, total_d) | |
| anchors, free = q[:, :config.anchors].T, q[:, config.anchors:] | |
| full_h = hidden_hessian(rng, total_d, config.condition) | |
| full_target = unit_targets(rng, 1, total_d)[0] | |
| for projected in (False, True): | |
| theta = np.zeros(total_d) | |
| for iteration in range(50): | |
| gradient = full_h @ (theta - full_target) | |
| if projected: | |
| gradient = free @ (free.T @ gradient) | |
| theta = theta - gradient / config.condition | |
| anchor_rows.append({ | |
| "seed": seed, "projected": int(projected), "steps": 50, | |
| "anchor_max_residual": np.max(np.abs(anchors @ theta)), | |
| "anchor_l2_residual": np.linalg.norm(anchors @ theta), | |
| "relative_objective": ((theta - full_target) @ full_h @ (theta - full_target)) / (full_target @ full_h @ full_target), | |
| }) | |
| for name, values in [("rank_acquisition", rank_rows), ("gradient_noise", noise_rows), ("curvature_shift", shift_rows), ("inverse_refinement", refinement_rows), ("successor_growth", growth_rows), ("anchor_control", anchor_rows)]: | |
| write_csv(output / f"{name}.csv", values) | |
| return {"rank": pd.DataFrame(rank_rows), "noise": pd.DataFrame(noise_rows), "shift": pd.DataFrame(shift_rows), "refinement": pd.DataFrame(refinement_rows), "growth": pd.DataFrame(growth_rows), "anchor": pd.DataFrame(anchor_rows)} | |
| def plot_style(): | |
| plt.rcParams.update({ | |
| "font.family": "DejaVu Sans", "font.size": 14, | |
| "axes.titlesize": 15, "axes.labelsize": 14, | |
| "xtick.labelsize": 14, "ytick.labelsize": 14, | |
| "axes.spines.top": False, "axes.spines.right": False, | |
| "axes.grid": True, "grid.alpha": 0.18, | |
| "figure.dpi": 160, "savefig.dpi": 240, | |
| "pdf.fonttype": 42, "ps.fonttype": 42, | |
| "legend.frameon": False, | |
| }) | |
| def save_figure(fig, folder, name): | |
| fig.savefig(folder / f"{name}.pdf", bbox_inches="tight") | |
| fig.savefig(folder / f"{name}.png", bbox_inches="tight") | |
| plt.close(fig) | |
| def band(ax, table, x, y, label, color, floor=1e-30, linestyle="-"): | |
| # Seed, not target, is the unit for uncertainty bands. | |
| grouped = table.groupby(["seed", x])[y].mean().reset_index() | |
| stats = grouped.groupby(x)[y].agg(["median", lambda v: np.quantile(v, 0.1), lambda v: np.quantile(v, 0.9)]) | |
| xx = stats.index.to_numpy() | |
| med, lower, upper = (np.maximum(stats.iloc[:, j].to_numpy(), floor) for j in range(3)) | |
| ax.plot(xx, med, label=label, color=color, lw=2, linestyle=linestyle) | |
| ax.fill_between(xx, lower, upper, color=color, alpha=0.13) | |
| def create_figures(config, data, histories, aux, figures): | |
| plot_style() | |
| fig, axes = plt.subplots(1, 2, figsize=(10.5, 5.2)) | |
| chosen = ["phase_retained", "phase_reset", "bfgs_retained", "bfgs_reset", "cg_reset", "gd_spectral", "bb_reset"] | |
| for method in chosen: | |
| sub = data[data.method == method] | |
| stats = sub.groupby("episode").cumulative_calls.agg(["median", lambda v: np.quantile(v, 0.1), lambda v: np.quantile(v, 0.9)]) | |
| xx = stats.index.to_numpy() | |
| axes[0].plot(xx, stats.iloc[:, 0], label=LABELS[method], color=COLORS[method], lw=1.8) | |
| axes[0].fill_between(xx, stats.iloc[:, 1], stats.iloc[:, 2], color=COLORS[method], alpha=0.10) | |
| axes[0].set_yscale("log") | |
| axes[0].set_xlabel("Completed target tasks") | |
| axes[0].set_ylabel("Cumulative gradient queries\nincluding acquisition") | |
| axes[0].set_title("Cumulative adaptation cost") | |
| axes[0].set_xticks([1, 4, 8, 12]) | |
| for method in ["phase_retained", "phase_reset", "bfgs_retained", "bfgs_reset", "cg_reset"]: | |
| sub = data[data.method == method] | |
| stats = sub.groupby("episode").episode_calls.mean() | |
| axes[1].plot(stats.index, stats, marker="o", ms=3, label=LABELS[method], color=COLORS[method], lw=1.8) | |
| axes[1].set_xlabel("Target task") | |
| axes[1].set_ylabel("Mean queries per target") | |
| axes[1].set_title("Queries charged per target") | |
| axes[1].set_xticks([1, 4, 8, 12]) | |
| handles, labels = axes[0].get_legend_handles_labels() | |
| fig.legend(handles, labels, loc="lower center", bbox_to_anchor=(0.5, 0.005), | |
| ncol=3, fontsize=14, handlelength=1.7, columnspacing=0.9, | |
| handletextpad=0.5, labelspacing=0.4) | |
| fig.suptitle("24 independent families · 16 free coordinates · condition number 100", y=0.99, fontsize=14) | |
| fig.tight_layout(rect=(0, 0.20, 1, 0.94)) | |
| save_figure(fig, figures, "01_amortization") | |
| fig, ax = plt.subplots(figsize=(7.3, 5.1)) | |
| grid = np.arange(0, 801) | |
| for method in ["phase_retained", "bfgs_reset", "cg_reset", "gd_spectral", "bb_reset", "adam_reset"]: | |
| curves = [] | |
| for seed in range(config.seed_start, config.seed_start + config.seeds): | |
| history = histories[f"seed{seed}_{method}_task01"] | |
| calibration = config.dimension + 1 if method == "phase_retained" else 0 | |
| calls = history[:, 0] + calibration | |
| values = np.maximum(history[:, 1], 1e-30) | |
| ix = np.searchsorted(calls, grid, side="right") - 1 | |
| curve = np.where(ix >= 0, values[np.maximum(ix, 0)], 1.0) | |
| curves.append(curve) | |
| curves = np.asarray(curves) | |
| median = np.median(curves, axis=0) | |
| ax.plot(grid, np.maximum(median, 1e-30), label=LABELS[method], color=COLORS[method], lw=1.8) | |
| ax.set_yscale("log") | |
| ax.set_ylim(1e-15, 2) | |
| ax.set_xlim(0, 800) | |
| ax.set_xlabel("Gradient queries, including first calibration") | |
| ax.set_ylabel("Median relative objective") | |
| ax.set_title("First-target convergence with acquisition cost") | |
| handles, labels = ax.get_legend_handles_labels() | |
| fig.legend(handles, labels, loc="lower center", bbox_to_anchor=(0.5, 0.005), | |
| ncol=2, fontsize=12, handlelength=1.7, columnspacing=1.0) | |
| fig.tight_layout(rect=(0, 0.23, 1, 1)) | |
| save_figure(fig, figures, "02_first_task_convergence") | |
| fig, axes = plt.subplots(1, 2, figsize=(10.1, 4.4)) | |
| rank = aux["rank"] | |
| band(axes[0], rank, "rank", "line_step_loss_ratio", "One exact line-search step", COLORS["phase_retained"]) | |
| axes[0].set_yscale("log") | |
| axes[0].set_ylim(1e-28, 2) | |
| axes[0].set_xlabel("Acquired directions (rank)") | |
| axes[0].set_ylabel("Mean held-out relative objective") | |
| axes[0].set_title("One measured line step") | |
| axes[0].set_xticks([0, 4, 8, 12, 16]) | |
| axes[0].axvline(config.dimension, color="black", ls=":", lw=1) | |
| band(axes[1], rank, "rank", "preconditioned_condition", "Preconditioned condition number", COLORS["bfgs_retained"]) | |
| axes[1].set_yscale("log") | |
| axes[1].set_xlabel("Acquired directions (rank)") | |
| axes[1].set_ylabel("Condition number") | |
| axes[1].set_title("Conditioning of partial memory") | |
| axes[1].set_xticks([0, 4, 8, 12, 16]) | |
| fig.tight_layout() | |
| save_figure(fig, figures, "03_rank_completion") | |
| fig, axes = plt.subplots(1, 2, figsize=(10.1, 4.8)) | |
| for field, label, color in [("unit_step_loss_ratio", "Stale inverse, unit step", COLORS["phase_retained"]), ("line_step_loss_ratio", "Stale inverse, measured line step", COLORS["bfgs_retained"])]: | |
| band(axes[0], aux["shift"], "mixture_fraction", field, label, color) | |
| axes[0].set_yscale("log") | |
| axes[0].set_ylim(1e-6, 1e4) | |
| axes[0].axhline(1, color="black", lw=1, ls=":") | |
| axes[0].set_xlabel("Curvature mixture fraction") | |
| axes[0].set_ylabel("Mean one-step relative objective") | |
| axes[0].set_title("Changed curvature degrades transfer") | |
| changed = aux["shift"].groupby("mixture_fraction").unit_step_worsened.mean() | |
| axes[1].plot(changed.index, 100 * changed, marker="o", color=COLORS["phase_retained"], lw=2) | |
| axes[1].set_ylim(-2, 102) | |
| axes[1].set_xlabel("Curvature mixture fraction") | |
| axes[1].set_ylabel("Unit updates increasing loss (%)") | |
| axes[1].set_title("Harmful stale unit updates") | |
| handles, labels = axes[0].get_legend_handles_labels() | |
| fig.legend(handles, labels, loc="lower center", bbox_to_anchor=(0.5, 0.005), | |
| ncol=2, fontsize=14, handlelength=1.7, columnspacing=1.0) | |
| fig.tight_layout(rect=(0, 0.13, 1, 1)) | |
| save_figure(fig, figures, "04_curvature_shift") | |
| fig, axes = plt.subplots(1, 2, figsize=(10.1, 4.8)) | |
| noise = aux["noise"].copy() | |
| nonzero = noise[noise.relative_noise > 0] | |
| for field, label, color in [("unit_step_loss_ratio", "Noisy inverse, unit step", COLORS["phase_retained"]), ("line_step_loss_ratio", "Noisy inverse, measured line step", COLORS["bfgs_retained"])]: | |
| band(axes[0], nonzero, "relative_noise", field, label, color) | |
| axes[0].set_xscale("log") | |
| axes[0].set_yscale("log") | |
| axes[0].axhline(1, color="black", ls=":", lw=1) | |
| axes[0].set_xlabel("Relative calibration noise") | |
| axes[0].set_ylabel("Mean one-step relative objective") | |
| axes[0].set_title("Noise degrades update quality") | |
| band(axes[1], nonzero, "relative_noise", "hessian_relative_error_before_floor", "Calibration matrix error", COLORS["cg_reset"]) | |
| axes[1].set_xscale("log") | |
| axes[1].set_yscale("log") | |
| axes[1].set_xlabel("Relative calibration noise") | |
| axes[1].set_ylabel("Relative spectral matrix error") | |
| axes[1].set_title("Calibration matrix error") | |
| handles, labels = axes[0].get_legend_handles_labels() | |
| fig.legend(handles, labels, loc="lower center", bbox_to_anchor=(0.5, 0.005), | |
| ncol=2, fontsize=14, handlelength=1.7, columnspacing=1.0) | |
| fig.tight_layout(rect=(0, 0.13, 1, 1)) | |
| save_figure(fig, figures, "05_gradient_noise") | |
| fig, axes = plt.subplots(1, 2, figsize=(10.1, 4.8)) | |
| refine = aux["refinement"] | |
| band(axes[0], refine, "iteration", "spectral_residual", "Observed inverse residual", COLORS["phase_retained"], floor=1e-18) | |
| bound = refine.groupby("iteration").exact_arithmetic_residual_bound.median() | |
| axes[0].plot(bound.index, np.maximum(bound, 1e-18), color="black", ls="--", label="Real-arithmetic bound") | |
| axes[0].set_ylim(1e-18, 2) | |
| axes[0].set_yscale("log") | |
| axes[0].set_xlabel("Newton–Schulz round") | |
| axes[0].set_ylabel("Spectral residual of I − BH") | |
| axes[0].set_title("Recursive inverse refinement") | |
| band(axes[1], refine, "iteration", "mean_future_one_step_loss_ratio", "Held-out one-step objective", COLORS["bfgs_retained"]) | |
| axes[1].set_yscale("log") | |
| axes[1].set_ylim(1e-30, 2) | |
| axes[1].set_xlabel("Round (two dense products each)") | |
| axes[1].set_ylabel("Mean future relative objective") | |
| axes[1].set_title("Future one-step objective") | |
| handles, labels = axes[0].get_legend_handles_labels() | |
| fig.legend(handles, labels, loc="lower center", bbox_to_anchor=(0.5, 0.005), | |
| ncol=2, fontsize=14, handlelength=1.7, columnspacing=1.0) | |
| fig.tight_layout(rect=(0, 0.13, 1, 1)) | |
| save_figure(fig, figures, "06_inverse_refinement") | |
| fig, axes = plt.subplots(1, 2, figsize=(9.3, 4.6)) | |
| anchor = aux["anchor"] | |
| for ix, projected in enumerate((True, False)): | |
| values = anchor[anchor.projected == int(projected)].anchor_max_residual.to_numpy() | |
| axes[0].scatter(np.full(len(values), ix) + np.linspace(-0.12, 0.12, len(values)), values, | |
| color=COLORS["bfgs_retained"] if projected else COLORS["phase_retained"], s=23, alpha=0.8) | |
| axes[0].set_xticks([0, 1], ["Projected", "Unconstrained"]) | |
| axes[0].set_yscale("log") | |
| axes[0].set_ylabel("Maximum linear-anchor residual") | |
| axes[0].set_title("Preservation of linear anchors") | |
| growth = aux["growth"] | |
| means = [growth.incremental_gradient_calls.mean(), growth.fresh_new_gradient_calls.mean()] | |
| bars = axes[1].bar([0, 1], means, color=[COLORS["bfgs_retained"], COLORS["phase_reset"]], width=0.6) | |
| for rectangle, value in zip(bars, means): | |
| axes[1].text(rectangle.get_x() + rectangle.get_width()/2, value + 0.4, f"{value:.0f}", ha="center", fontsize=16) | |
| axes[1].set_xticks([0, 1], ["Retained old block", "Full recalibration"]) | |
| axes[1].set_ylabel("Additional gradient queries") | |
| axes[1].set_ylim(0, 25) | |
| axes[1].set_title("Growth from 16 to 20 coordinates") | |
| fig.tight_layout() | |
| save_figure(fig, figures, "07_anchors_and_growth") | |
| def bootstrap_ci(values, seed=73421, replications=10000): | |
| values = np.asarray(values, dtype=float) | |
| rng = np.random.default_rng(seed) | |
| resamples = rng.integers(0, len(values), size=(replications, len(values))) | |
| means = values[resamples].mean(axis=1) | |
| return [float(np.quantile(means, 0.025)), float(np.quantile(means, 0.975))] | |
| def build_summary(config, data, aux, output, main_seconds): | |
| summary = {"config": config.__dict__, "main_benchmark_wall_seconds": main_seconds, "methods": {}} | |
| for method, group in data.groupby("method", sort=False): | |
| final = group[group.episode == config.tasks] | |
| warm = group[group.episode > 1] | |
| family_total = final.cumulative_calls.to_numpy() | |
| summary["methods"][method] = { | |
| "name": LABELS[method], "family_calls_mean": float(np.mean(family_total)), | |
| "family_calls_median": float(np.median(family_total)), | |
| "family_calls_mean_bootstrap95": bootstrap_ci(family_total), | |
| "first_task_calls_mean": float(group[group.episode == 1].episode_calls.mean()), | |
| "warm_task_calls_mean": float(warm.episode_calls.mean()), | |
| "successes": int(group.certified_success.sum()), "episodes": len(group), | |
| "mean_wall_ms_per_family": float(group.groupby("seed").wall_ms.sum().mean()), | |
| "median_final_relative_loss": float(group.relative_loss.median()), | |
| "max_anchor_residual": float(group.anchor_max_residual.max()), | |
| } | |
| paired = data[data.episode == config.tasks].pivot(index="seed", columns="method", values="cumulative_calls") | |
| difference = paired.phase_retained - paired.bfgs_retained | |
| summary["paired_retained_minus_retained_bfgs_family_calls"] = { | |
| "mean": float(difference.mean()), "bootstrap95": bootstrap_ci(difference), | |
| "min": float(difference.min()), "max": float(difference.max()), | |
| } | |
| reset_difference = paired.phase_reset - paired.phase_retained | |
| summary["reset_minus_retained_family_calls"] = {"mean": float(reset_difference.mean()), "bootstrap95": bootstrap_ci(reset_difference)} | |
| budget_rows = [] | |
| for budget in (20, 24, 40, 41, 50, 100, 200, 228, 500): | |
| for (seed, method), group in data.groupby(["seed", "method"]): | |
| completed = int(((group.cumulative_calls <= budget) & (group.certified_success == 1)).sum()) | |
| budget_rows.append({"seed": seed, "method": method, "gradient_query_budget": budget, "certified_tasks_completed": completed}) | |
| write_csv(output / "matched_budget.csv", budget_rows) | |
| budget_frame = pd.DataFrame(budget_rows) | |
| summary["matched_budget_41"] = budget_frame[budget_frame.gradient_query_budget == 41].groupby("method").certified_tasks_completed.mean().to_dict() | |
| summary["curvature_shift"] = aux["shift"].groupby("mixture_fraction")[["relative_spectral_curvature_mismatch", "unit_step_loss_ratio", "line_step_loss_ratio", "unit_step_worsened"]].mean().reset_index().to_dict("records") | |
| summary["gradient_noise"] = aux["noise"].groupby("relative_noise")[["unit_step_loss_ratio", "line_step_loss_ratio", "unit_step_worsened", "hessian_relative_error_before_floor"]].mean().reset_index().to_dict("records") | |
| summary["rank_completion"] = aux["rank"].groupby("rank")[["line_step_loss_ratio", "preconditioned_condition"]].mean().reset_index().to_dict("records") | |
| summary["inverse_refinement"] = aux["refinement"].groupby("iteration")[["spectral_residual", "mean_future_one_step_loss_ratio", "dense_matrix_multiplications"]].mean().reset_index().to_dict("records") | |
| summary["successor_growth"] = aux["growth"].drop(columns=["seed"]).mean(numeric_only=True).to_dict() | |
| summary["successor_growth"].update({"n_seeds": config.seeds, "seed_start": config.seed_start, "seed_end": config.seed_start + config.seeds - 1}) | |
| summary["anchor_control"] = {} | |
| for projected, label in [(0, "unprojected"), (1, "projected")]: | |
| subset = aux["anchor"][aux["anchor"].projected == projected] | |
| summary["anchor_control"][label] = { | |
| "n_seeds": int(subset.seed.nunique()), | |
| "mean_max_anchor_residual": float(subset.anchor_max_residual.mean()), | |
| "maximum_anchor_residual": float(subset.anchor_max_residual.max()), | |
| "mean_l2_anchor_residual": float(subset.anchor_l2_residual.mean()), | |
| "maximum_l2_anchor_residual": float(subset.anchor_l2_residual.max()), | |
| } | |
| summary["all_main_anchor_residual_max"] = float(data.anchor_max_residual.max()) | |
| (output / "summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") | |
| lines = [ | |
| "# Executed optimizer-state refinement experiments", "", | |
| "This report is generated from the recorded CSV files. It is a finite synthetic experiment on stable shared-curvature quadratic task families. It does not demonstrate general LLM recursive self-improvement, code rewriting, a new optimization algorithm, or semantic loyalty.", "", | |
| f"Protocol: {config.seeds} independent seeds, {config.tasks} held-out targets per seed, {config.dimension} free coordinates, {config.anchors} protected linear anchors, spectral condition number {config.condition:g}, and a directly evaluated relative gradient certificate ≤ {config.gradient_tolerance:g}. All retained-inverse source calibration costs ({config.dimension+1} gradient calls per acquisition) are charged. Targets used for evaluation are independent of the calibration target.", "", | |
| "## Main results", "", | |
| "| Method | Mean calls for all 12 tasks | Mean first task | Mean later task | Certified successes | Mean wall ms per family |", "|---|---:|---:|---:|---:|---:|", | |
| ] | |
| for method in LABELS: | |
| item = summary["methods"][method] | |
| lines.append(f"| {item['name']} | {item['family_calls_mean']:.3f} | {item['first_task_calls_mean']:.3f} | {item['warm_task_calls_mean']:.3f} | {item['successes']}/{item['episodes']} | {item['mean_wall_ms_per_family']:.3f} |") | |
| diff = summary["paired_retained_minus_retained_bfgs_family_calls"] | |
| lines += ["", "The exact inverse oracle is a privileged lower-bound reference. It receives the true hidden Hessian; no other learner does. GD receives the common spectral bounds [1, 100], which are supplied to all methods as part of the task specification. The Adam schedule is fixed, not asserted to be optimal. BFGS and conjugate gradients receive the same quadratic structure and use measured gradient differences for exact line searches. Final convergence is certified by an actual gradient query. Objective values are evaluator-only and do not determine stopping.", "", | |
| f"The paired retained-probe minus retained-BFGS family-cost difference is {diff['mean']:.3f} queries, with seed-bootstrap 95% interval [{diff['bootstrap95'][0]:.3f}, {diff['bootstrap95'][1]:.3f}]. A positive difference favors BFGS. This comparison is essential: retained probe inversion is not established as superior to a strong classical transferable optimizer.", "", | |
| "Reset versus retained probe inversion is a causal retention ablation with identical probe geometry and calibration procedure. It measures the benefit of retaining known curvature, not the benefit of invented mathematical notation or WAV serialization.", "", | |
| "At a matched budget of 41 gradient queries, retained probe inversion and retained BFGS each finish all 12 targets. The reset probe method, reset BFGS, and conjugate gradients each finish 2. The full per-seed budget comparison is in `matched_budget.csv`. The source-calibration baseline costs an extra query compared with integrating exploration into the first target, which helps explain the one-query BFGS advantage.", "", | |
| "## Negative and boundary results", "", | |
| "| Independent-curvature mixture | Mean relative spectral mismatch | Mean unit-step relative loss | Mean measured-line-step relative loss | Unit steps worsening objective |", "|---:|---:|---:|---:|---:|"] | |
| for item in summary["curvature_shift"]: | |
| lines.append(f"| {item['mixture_fraction']:.2f} | {item['relative_spectral_curvature_mismatch']:.5g} | {item['unit_step_loss_ratio']:.5g} | {item['line_step_loss_ratio']:.5g} | {100*item['unit_step_worsened']:.2f}% |") | |
| lines += ["", "The mixture fraction a in H(a) = (1−a) H0 + a H1 is not a relative spectral perturbation. The separate mismatch column is the spectral norm of H0^(−1/2) [H(a)−H0] H0^(−1/2), and it can greatly exceed a. One-step ratios above 1 mean that the purported improvement worsened the actual objective. A measured exact quadratic line step restores descent but costs one additional target gradient and does not restore one-step solution quality. The sensitivity tests deliberately retain stale memory instead of silently recalibrating it.", "", | |
| "| Relative calibration noise | Mean unit-step relative loss | Mean measured-line-step relative loss | Unit steps worsening objective |", "|---:|---:|---:|---:|"] | |
| for item in summary["gradient_noise"]: | |
| lines.append(f"| {item['relative_noise']:.4g} | {item['unit_step_loss_ratio']:.5g} | {item['line_step_loss_ratio']:.5g} | {100*item['unit_step_worsened']:.2f}% |") | |
| lines += ["", "Noise acts on source calibration gradients only. The RMS noise norm is the listed fraction of the RMS norm of a unit Hessian response. Estimated eigenvalues are clipped below 0.5 before inversion; this is a declared regularization choice. Evaluation gradients are noise free, so the table isolates memory corruption.", "", | |
| "## Recursive inverse refinement and successor growth", "", | |
| "Newton–Schulz refinement uses B(r+1) = 2 B(r) − B(r) Hhat B(r), initialized with I/λmax(Hhat). Each refinement round consumes two dense matrix multiplications and no new learning gradient queries. Separately recorded diagnostic evaluation consumes 48 gradient queries per seed and round (16 targets and 3 queried gradients per target); those responses are never fed into the inverse recursion. It is a classical inverse iteration. The measured future-task update quality improves as the inverse residual falls, until finite precision imposes a floor. It is a literal recursion of optimizer state, not a new RSI theorem by itself.", ""] | |
| for iteration in (0, 4, 8, 10, 12, 18): | |
| item = summary["inverse_refinement"][iteration] | |
| lines.append(f"- Round {iteration}: mean inverse residual {item['spectral_residual']:.6g}; mean future one-step relative loss {item['mean_future_one_step_loss_ratio']:.6g}; {int(item['dense_matrix_multiplications'])} dense products.") | |
| growth = summary["successor_growth"] | |
| lines += ["", f"Growing from 16 to 20 coordinates required {growth['incremental_gradient_calls']:.0f} additional gradient calls when the old block was retained, versus {growth['fresh_new_gradient_calls']:.0f} for complete new calibration. Including the already performed old calibration gives {growth['lifecycle_calls_retained']:.0f} versus {growth['lifecycle_calls_reset']:.0f} lifecycle calls. Mean retained Schur inverse residual: {growth['retained_inverse_residual']:.6g}. The calculation is conditional on the old block staying exactly unchanged.", "", | |
| f"Maximum anchor discrepancy across all main solver episodes: {summary['all_main_anchor_residual_max']:.6g}. The separate unprojected control demonstrates that these invariants require an explicit projection; naming an update 'loyal' does not impose an invariant.", "", | |
| "## Reproduction and interpretation", "", | |
| "Run `python run_experiments.py --output results`. The source declares all random seeds and hyperparameters. Raw per-target metrics, complete objective trajectories, source reconstruction audits, sensitivity runs, figures, package versions, and SHA-256 of the executed script are included. Quantile bands are 10th–90th percentiles across independent seed-level means; they are not confidence intervals. The one reported confidence interval uses 10,000 paired seed bootstrap samples. No inferential independence is attributed to the 32 targets inside one shared-Hessian family.", "", | |
| "The gradient-query cost model excludes dense linear algebra, memory traffic, and protocol setup. Wall times are recorded separately. The examples are small CPU computations. Full inversion costs O(d^3) arithmetic and O(d^2) memory; a one-query task solution is not a one-operation computation. There is no evidence here of unlimited improvement, a thermodynamic transition, speedup from WAV playback, or intelligence extracted from independent randomness.", ""] | |
| (output / "EXPERIMENT_REPORT.md").write_text("\n".join(lines), encoding="utf-8") | |
| return summary | |
| def verify_results(config, data, aux, output): | |
| checks = {} | |
| checks["expected_main_rows"] = len(data) == config.seeds * config.tasks * len(LABELS) | |
| checks["all_main_metrics_finite"] = bool(np.isfinite(data[["relative_loss", "relative_gradient", "anchor_max_residual"]].to_numpy()).all()) | |
| retained = data[data.method == "phase_retained"] | |
| checks["retained_calibration_charged_once"] = bool((retained.groupby("seed").calibration_calls.sum() == config.dimension + 1).all()) | |
| reset = data[data.method == "phase_reset"] | |
| checks["reset_calibration_charged_each_time"] = bool((reset.calibration_calls == config.dimension + 1).all()) | |
| checks["retained_inverse_all_certified"] = bool(retained.certified_success.all()) | |
| checks["retained_bfgs_all_certified"] = bool(data[data.method == "bfgs_retained"].certified_success.all()) | |
| checks["anchors_below_1e_minus_12"] = float(data.anchor_max_residual.max()) < 1e-12 | |
| checks["full_rank_one_step_ratio_below_1e_minus_20"] = float(aux["rank"][aux["rank"]["rank"] == config.dimension].line_step_loss_ratio.max()) < 1e-20 | |
| checks["shift_measured_line_steps_descend"] = float(aux["shift"].line_step_loss_ratio.max()) <= 1 + 1e-12 | |
| checks["noise_measured_line_steps_descend"] = float(aux["noise"].line_step_loss_ratio.max()) <= 1 + 1e-12 | |
| checks["growth_retained_inverse_residual_below_1e_minus_10"] = float(aux["growth"].retained_inverse_residual.max()) < 1e-10 | |
| checks["growth_additional_calls_correct"] = bool((aux["growth"].incremental_gradient_calls == 5).all() and (aux["growth"].fresh_new_gradient_calls == 21).all()) | |
| (output / "verification.json").write_text(json.dumps(checks, indent=2), encoding="utf-8") | |
| if not all(checks.values()): | |
| raise AssertionError({name: status for name, status in checks.items() if not status}) | |
| return checks | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--output", type=Path, default=Path(__file__).parent / "results") | |
| parser.add_argument("--seeds", type=int, default=24) | |
| args = parser.parse_args() | |
| output = args.output.resolve() | |
| output.mkdir(parents=True, exist_ok=True) | |
| figures = output / "figures" | |
| figures.mkdir(exist_ok=True) | |
| config = Config(seeds=args.seeds) | |
| environment = { | |
| "started_utc": datetime.now(timezone.utc).isoformat(), | |
| "python": sys.version, "numpy": np.__version__, "scipy": scipy.__version__, | |
| "pandas": pd.__version__, "matplotlib": matplotlib.__version__, | |
| "platform": platform.platform(), "processor": platform.processor(), | |
| "logical_cpus": os.cpu_count(), "blas_threads_requested": 1, | |
| "script_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), | |
| "command": sys.argv, | |
| } | |
| (output / "environment.json").write_text(json.dumps(environment, indent=2), encoding="utf-8") | |
| (output / "experiment_config.json").write_text(json.dumps(config.__dict__, indent=2), encoding="utf-8") | |
| data, histories, main_seconds = main_benchmark(config, output) | |
| aux = auxiliary_benchmarks(config, output) | |
| verify_results(config, data, aux, output) | |
| create_figures(config, data, histories, aux, figures) | |
| summary = build_summary(config, data, aux, output, main_seconds) | |
| environment["finished_utc"] = datetime.now(timezone.utc).isoformat() | |
| (output / "environment.json").write_text(json.dumps(environment, indent=2), encoding="utf-8") | |
| print(json.dumps({"output": str(output), "main_seconds": main_seconds, "retained": summary["methods"]["phase_retained"], "retained_bfgs": summary["methods"]["bfgs_retained"]}, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |