"""Resource-accounted recursive verifier purification; no hardware claims. The exact signal verifier is a q-ary symmetric channel. Two independent child outputs are accepted when they agree; otherwise the pair is retried. The code compares closed recursion against an independent absorbing Markov chain over the recursive program's pending-symbol stack. A gate's saved acquisition cost can fund stronger exported E_q(t,u) experiments at fixed expected cost. The binary hierarchy is a classical SPRT realization. These calculations do not establish a new sequential-testing principle or general intelligence RSI. """ from __future__ import annotations import argparse import itertools import json import math from pathlib import Path import numpy as np from scipy.optimize import linprog def _validate(q: int, u: float, level: int = 0, m: int = 2) -> None: if int(q) != q or q < 2: raise ValueError("q must be an integer >= 2") if not math.isfinite(u) or not 0 <= u <= 1: raise ValueError("u must be in [0,1]") if int(level) != level or level < 0: raise ValueError("level must be a nonnegative integer") if int(m) != m or m < 2: raise ValueError("m must be an integer >= 2") def pure_level(q: int, u: float, level: int, m: int = 2) -> dict: """Closed distribution and expected raw SIGNAL calls for one level. Calls at each recursion node are independent conditional on the same hidden target. The recursion's depth is not its computational cost. """ _validate(q, u, level, m) d = q - 1 initial = u raw_calls = 1.0 acceptance = [] for _ in range(level): p = (1 + d * u) / q r = (1 - u) / q s = p ** m + d * r ** m acceptance.append(s) raw_calls *= m / s u = (p ** m - r ** m) / s # Use odds independently of the preceding contrast recursion to retain # very small errors and identify floating-point saturation explicitly. if initial == 1: log_error = None error = 0.0 else: log_x = math.log((1 - initial) / (1 + d * initial)) log_y = m ** level * log_x y = math.exp(log_y) log_error = math.log(d) + log_y - math.log1p(d * y) error = math.exp(log_error) contrast_from_odds = 1 - q * error / d return { "level": level, "m": m, "q": q, "initial_contrast": initial, "contrast": contrast_from_odds, "contrast_recursion": u, "accepted_signal_correct_probability": 1 - error, "accepted_signal_error_probability": error, "log_accepted_signal_error_probability": log_error, "contrast_rounded_to_one": contrast_from_odds == 1 and initial < 1, "expected_raw_signal_calls": raw_calls, "node_acceptance_probabilities": acceptance, "scope": "independent repeated signals of ONE fixed target", } def stack_chain(q: int, u: float, level: int) -> dict: """Independent absorbing-chain computation for the actual binary tree. Each stack slot is empty (-1) or holds one pending child symbol. One raw signal is fed at the bottom. Agreeing pairs ripple upward; mismatches clear their slot and restart there. The transition matrix is constructed from raw symbols without using the closed purification or cost formula. """ _validate(q, u, level) if level == 0: probs = np.full(q, (1 - u) / q) probs[0] += u return {"expected_raw_signal_calls": 1.0, "output_probabilities_given_target_zero": probs.tolist(), "transient_states": 0, "linear_residual": 0.0} states = list(itertools.product(range(-1, q), repeat=level)) lookup = {state: index for index, state in enumerate(states)} nstates = len(states) transition = np.zeros((nstates, nstates)) absorb = np.zeros((nstates, q)) raw = np.full(q, (1 - u) / q) raw[0] += u for row, state in enumerate(states): for symbol, probability in enumerate(raw): if probability == 0: continue next_state = list(state) absorbed = True for slot in range(level): if next_state[slot] == -1: next_state[slot] = symbol absorbed = False break if next_state[slot] == symbol: next_state[slot] = -1 continue next_state[slot] = -1 absorbed = False break if absorbed: absorb[row, symbol] += probability else: transition[row, lookup[tuple(next_state)]] += probability matrix = np.eye(nstates) - transition rhs = np.column_stack((np.ones(nstates), absorb)) solution = np.linalg.solve(matrix, rhs) origin = lookup[(-1,) * level] return { "expected_raw_signal_calls": float(solution[origin, 0]), "output_probabilities_given_target_zero": solution[origin, 1:].tolist(), "transient_states": nstates, "linear_residual": float(np.max(np.abs(matrix @ solution - rhs))), "transition_row_sum_error": float(np.max(np.abs( transition.sum(axis=1) + absorb.sum(axis=1) - 1))), } def exported_levels(q: int, u: float, t: float, overhead: float, readout_cost: float = 1.0, max_level: int = 3) -> list[dict]: """Same outer retention t at every level; costs include all retries. overhead h must cover ALL nonreadout per-primitive-trial costs. An outer target-independent Bernoulli(t) requests a signal only on nonerasure. A raw accepted signal costs (h+tE)/t in expectation. Hence unconditional exported cost equals (h+tE)*expected_raw_signal_calls; t cancels. """ if not 0 < t <= 1 or overhead < 0 or readout_cost <= 0: raise ValueError("Require 0=0, E>0") cg = overhead + t * readout_cost rows = [] for k in range(max_level + 1): row = pure_level(q, u, k) row["outer_retention"] = t row["expected_logical_cost"] = cg * row["expected_raw_signal_calls"] row["uniform_prior_full_call_MAP_error"] = ( (q - 1) / q * (1 - t * row["contrast"])) rows.append(row) return rows def upper_concave_hull(levels: list[dict]) -> list[dict]: """Upper hull of (expected_cost,contrast), restricted to supplied levels.""" points = sorted(levels, key=lambda row: row["expected_logical_cost"]) hull = [] for row in points: x, y = row["expected_logical_cost"], row["contrast"] if hull and x == hull[-1]["expected_logical_cost"]: if y <= hull[-1]["contrast"]: continue hull.pop() while len(hull) >= 2: a, b = hull[-2:] # Upper concavity requires nonincreasing consecutive slopes. cross = ((b["expected_logical_cost"] - a["expected_logical_cost"]) * (y - b["contrast"]) - (b["contrast"] - a["contrast"]) * (x - b["expected_logical_cost"])) if cross < 0: break hull.pop() hull.append(row) return hull def budget_mixture(levels: list[dict], budget: float) -> dict: """Optimal contrast at budget among mixtures of the supplied levels. This is a finite-family optimum. It is not optimal over all possible sequential/posterior confidence acquisition programs. """ hull = upper_concave_hull(levels) if not hull or budget < hull[0]["expected_logical_cost"]: raise ValueError("Budget cannot fund even the least costly supplied level") left = right = hull[-1] weight_right = 0.0 for a, b in zip(hull, hull[1:]): if budget <= b["expected_logical_cost"]: left, right = a, b weight_right = ((budget - a["expected_logical_cost"]) / (b["expected_logical_cost"] - a["expected_logical_cost"])) break contrast = (1 - weight_right) * left["contrast"] + weight_right * right["contrast"] cost = ((1 - weight_right) * left["expected_logical_cost"] + weight_right * right["expected_logical_cost"]) q, t = left["q"], left["outer_retention"] error = (q - 1) / q * (1 - contrast) initial = left["initial_contrast"] original_error = (q - 1) / q * (1 - initial) return { "family": "finite-level recursive unanimous signal verifiers", "hull_levels": [row["level"] for row in hull], "left_level": left["level"], "right_level": right["level"], "right_probability": weight_right, "budget": budget, "expected_logical_cost": cost, "unused_budget": max(0.0, budget - cost), "contrast": contrast, "outer_retention": t, "accepted_signal_error_probability": error, "accepted_error_relative_reduction": (original_error - error) / original_error if original_error > 0 else 0.0, "original_uniform_prior_full_call_MAP_error": (q - 1) / q * (1 - t * initial), "uniform_prior_full_call_MAP_error": (q - 1) / q * (1 - t * contrast), "old_to_new_deficiency": (q - 1) / q * t * (contrast - initial), "new_to_old_deficiency": 0.0, "claims": "same outer retention and expected cost; not constant latency; not hardware evidence", } def _independent_checks() -> dict: records = [] max_cost_relative_error = max_prob_error = max_linear_residual = 0.0 cases = [(q, u, k) for q in (2, 3, 5) for u in (0.2, 0.6, 0.9) for k in (1, 2)] cases += [(q, 0.6, 3) for q in (2, 3, 5)] for q, u, k in cases: closed = pure_level(q, u, k) chain = stack_chain(q, u, k) expected = np.full(q, closed["accepted_signal_error_probability"] / (q - 1)) expected[0] = closed["accepted_signal_correct_probability"] cost_error = abs(chain["expected_raw_signal_calls"] - closed["expected_raw_signal_calls"]) / closed["expected_raw_signal_calls"] probability_error = float(np.max(np.abs(np.asarray( chain["output_probabilities_given_target_zero"]) - expected))) max_cost_relative_error = max(max_cost_relative_error, cost_error) max_prob_error = max(max_prob_error, probability_error) max_linear_residual = max(max_linear_residual, chain["linear_residual"]) records.append({"q": q, "u": u, "level": k, "relative_expected_cost_error": cost_error, "max_output_probability_error": probability_error, "independent_absorbing_chain": chain}) binary_error = 0.0 for u, k in itertools.product((.1, .2, .6, .9), range(5)): row = pure_level(2, u, k) n = 2 ** k v = math.tanh(n * math.atanh(u)) expected_cost = n * v / u binary_error = max(binary_error, abs(row["contrast"] - v), abs(row["expected_raw_signal_calls"] - expected_cost) / expected_cost) passed = max(max_cost_relative_error, max_prob_error, max_linear_residual, binary_error) < 1e-9 return {"status": "PASS" if passed else "FAIL", "cases": len(cases), "method": "full raw-symbol absorbing Markov chain on recursive pending stack", "max_relative_cost_error": max_cost_relative_error, "max_output_probability_error": max_prob_error, "max_linear_system_residual": max_linear_residual, "binary_SPRT_identity_checks": 20, "max_binary_identity_error": binary_error, "records": records} def _hull_lp_checks() -> dict: """Independent unrestricted mixture LP, with no hull assumptions.""" records = [] max_error = 0.0 for q, u, t, h in ((2, .55, .25, .1), (3, .4, 1 / 9, .1), (5, .6, .04, .1)): levels = exported_levels(q, u, t, h, max_level=3) costs = np.asarray([row["expected_logical_cost"] for row in levels]) contrasts = np.asarray([row["contrast"] for row in levels]) for budget in np.linspace(costs[0], costs[-1], 9): answer = budget_mixture(levels, float(budget)) lp = linprog(-contrasts, A_ub=costs[None, :], b_ub=[budget], A_eq=np.ones((1, len(levels))), b_eq=[1.0], bounds=[(0, None)] * len(levels), method="highs") if not lp.success: raise RuntimeError(lp.message) error = abs(answer["contrast"] + lp.fun) max_error = max(max_error, error) records.append({"q": q, "u": u, "budget": float(budget), "hull_contrast": answer["contrast"], "unrestricted_mixture_LP_contrast": float(-lp.fun), "absolute_error": error}) return {"status": "PASS" if max_error < 1e-9 else "FAIL", "cases": len(records), "max_contrast_error": max_error, "scope": "all mixtures of supplied finite levels, not all sequential programs", "records": records} def run() -> dict: checks = _independent_checks() hull_checks = _hull_lp_checks() levels = exported_levels(5, .6, .04, .1, max_level=3) mixture = budget_mixture(levels, 1.1) old_map = mixture["original_uniform_prior_full_call_MAP_error"] new_map = mixture["uniform_prior_full_call_MAP_error"] mixture["full_call_MAP_error_absolute_reduction"] = old_map - new_map mixture["full_call_MAP_error_relative_reduction"] = (old_map - new_map) / old_map return { "status": "PASS" if checks["status"] == hull_checks["status"] == "PASS" else "FAIL", "research": "Evie's Pure Form RSI", "scope": "mathematical verifier-strengthening component under explicit conditional-independent channels", "physical_measurements": False, "general_intelligence_gain_established": False, "prior_art_boundary": "binary hierarchy equals classical SPRT; neither consensus nor sequential testing is claimed as invention", "cost_contract": "h includes every nonreadout cost per primitive trial; E is acquisition cost; expected cost, unbounded retry tails", "independent_checks": checks, "finite_mixture_LP_checks": hull_checks, "q5_example": { "q": 5, "base_retention": .04, "base_contrast": .6, "overhead_h_over_E": .1, "readout_E": 1.0, "ungated_expected_cost": 1.1, "gated_primitive_expected_cost": .14, "gate_saving_ratio": 1.1 / .14, "levels": levels, "fixed_budget_mixture": mixture, }, } if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", default=str(Path(__file__).resolve().parent / "data" / "bootstrap.json")) args = parser.parse_args() report = run() path = Path(args.output) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") print(json.dumps({"status": report["status"], "independent_checks": {k: v for k, v in report["independent_checks"].items() if k != "records"}, "fixed_budget_mixture": report["q5_example"]["fixed_budget_mixture"]}, indent=2)) raise SystemExit(0 if report["status"] == "PASS" else 1)