Datasets:
Formats:
csv
Languages:
English
Size:
< 1K
Tags:
recursive-self-improvement
meta-learning
learned-optimizers
homological-algebra
formal-methods
synthetic-data
Download src/relational.py from PureOne/Nemoriu-Research: direct link, hf CLI and curl.
- Browser
- Download file 19.1 kB
-
https://huggingface.co/datasets/PureOne/Nemoriu-Research/resolve/main/src/relational.py
- Command line
-
hf download hf://datasets/PureOne/Nemoriu-Research/src/relational.py
-
curl -L -o relational.py https://huggingface.co/datasets/PureOne/Nemoriu-Research/resolve/main/src/relational.py
19.1 kB
| """Two distinct, exactly coupled repair/proposal kernels. | |
| This revision tests an empirical question; it does not assume success. | |
| Run from research/: python3 src/relational.py --output results/revision | |
| Standard library only. All training, including unsuccessful auditions, is | |
| charged. Parent and held-out child streams are disjoint. See the protocol. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| from collections import Counter | |
| import csv | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import platform | |
| import random | |
| import resource | |
| import statistics | |
| import sys | |
| import time | |
| from core import (BudgetExhausted, K, Mat, Meter, Problem, add, differential, | |
| equal, mul, nnz, normalize, positions, proposal, | |
| repaired_candidate, valid, zero) | |
| from domains import CoordinateMoves, from_scratch_contraction, generate | |
| from experiment import audit, fresh_tasks, interval, summarize | |
| def digest(h: Mat) -> str: | |
| return hashlib.sha256(json.dumps(h).encode()).hexdigest()[:16] | |
| def matrix_bytes(h: Mat) -> int: | |
| return sys.getsizeof(h) + sum(sys.getsizeof(row) for row in h) | |
| def discover(p: Problem, generator: Mat, budget: int, seed: int, | |
| forbidden: tuple[Mat, ...] = (), mode: str = "fixed"): | |
| """Fresh child from h0; generator data are used only in proposal repair. | |
| Modes fixed/current/rebuild use identical validation and acceptance. | |
| Direct coordinate reconstruction is the strongest simple control here. | |
| All supplied parent matrices can be forbidden simultaneously, avoiding a | |
| free exact parent installation. Nearby states remain possible, so this | |
| is a within-complex procedural transfer test, not cross-domain learning. | |
| """ | |
| m = Meter(budget) | |
| rng = random.Random(seed) | |
| start, cpu = time.perf_counter(), time.process_time() | |
| h = best = p.h0 | |
| initial_score = current_score = best_score = sum(row.bit_count() for row in h) | |
| stats = Counter() | |
| events = [] | |
| try: | |
| m.use(p.n, "setup") | |
| current_score = best_score = nnz(h, m) | |
| if not valid(p, h, m): | |
| raise AssertionError("Invalid initial contraction") | |
| available = positions(p, -1, m) | |
| chart = None | |
| if mode == "rebuild": | |
| c = from_scratch_contraction(p, m) | |
| ok = valid(p, c, m) | |
| score = nnz(c, m) | |
| blocked = any(equal(c, x, m) for x in forbidden) | |
| if ok and not blocked and score <= current_score: | |
| h = best = c | |
| current_score = best_score = score | |
| events.append((m.used, score)) | |
| stats["rebuild_accepted"] += 1 | |
| chart = CoordinateMoves.build(p, h, m) | |
| while True: | |
| m.use(12, "bookkeeping") | |
| stats["attempts"] += 1 | |
| if mode == "rebuild": | |
| c = chart.propose(h, rng, m) | |
| else: | |
| a = proposal(p, available, rng, m) | |
| parent = h if mode == "current" else generator | |
| c = repaired_candidate(p, h, parent, a, m) | |
| ok = valid(p, c, m) | |
| stats["completed"] += 1 | |
| if not ok: | |
| stats["invalid"] += 1 | |
| continue | |
| score = nnz(c, m) | |
| blocked = False | |
| for excluded in forbidden: | |
| blocked = equal(c, excluded, m) or blocked | |
| if blocked: | |
| stats["parent_copy_rejected"] += 1 | |
| continue | |
| if equal(c, h, m): | |
| stats["unchanged"] += 1 | |
| continue | |
| if score <= current_score: | |
| h = c | |
| stats["strict_accepts" if score < current_score else | |
| "neutral_accepts"] += 1 | |
| current_score = score | |
| if score < best_score: | |
| best, best_score = c, score | |
| events.append((m.used, score)) | |
| else: | |
| stats["worse_rejected"] += 1 | |
| except BudgetExhausted: | |
| stats["budget_interrupts"] += 1 | |
| result = dict(stats) | |
| result.update({"mode": mode, "budget": budget, "work": m.used, | |
| "initial_nnz": initial_score, "final_nnz": best_score, | |
| "nnz_gain": initial_score - best_score, | |
| "wall_s": time.perf_counter() - start, | |
| "cpu_s": time.process_time() - cpu, | |
| "work_categories": dict(m.counts), "events": events, | |
| "operator_digest": digest(best), | |
| "operator_bytes": matrix_bytes(best), | |
| "zero_progress": initial_score == best_score}) | |
| return best, result | |
| def pair_witness(p: Problem, w: Mat, g: Mat, m: Meter): | |
| """partial(w g)=g-w=g+w in characteristic two; verify before commit.""" | |
| b = mul(w, g, m) | |
| ok = equal(differential(p, b, m), add(g, w, m), m) | |
| return b, ok | |
| def train_dual(p: Problem, budget: int, seed: int, probe_budget: int = 50000, | |
| probes: int = 2, audition_interval: int = 8, | |
| max_auditions: int = 24): | |
| """g proposes its own replacements; w and g have different acceptance. | |
| Selection of g is deliberately conservative on the finite paired probe | |
| sample, but no statistical confidence guarantee is claimed. A fresh final | |
| child batch is required. Audition children may be retained as w only; | |
| their entire search cost is in the training ledger. | |
| """ | |
| m = Meter(budget) | |
| rng = random.Random(seed) | |
| w = g = p.h0 | |
| witness = zero(p.n) | |
| initial_score = w_score = sum(row.bit_count() for row in w) | |
| stats = Counter() | |
| events, auditions = [], [] | |
| start, cpu_start = time.perf_counter(), time.process_time() | |
| nested_cpu = nested_wall = 0.0 | |
| def retain_work(c: Mat, score: int, source: str): | |
| nonlocal w, w_score, witness | |
| if score >= w_score: | |
| return | |
| b, ok = pair_witness(p, c, g, m) | |
| if not ok: | |
| stats["pair_certificate_failures"] += 1 | |
| return | |
| # Commit only after the full exact certificate has completed. | |
| w, w_score, witness = c, score, b | |
| stats["strict_accepts"] += 1 | |
| stats["work_from_" + source] += 1 | |
| events.append({"work": m.used, "kind": "work", "source": source, | |
| "w_nnz": w_score, "g_digest": digest(g)}) | |
| def charge_nested(row, label): | |
| nonlocal nested_cpu, nested_wall | |
| for kind, amount in row["work_categories"].items(): | |
| m.use(amount, "audition_" + label + ":" + kind) | |
| nested_cpu += row["cpu_s"] | |
| nested_wall += row["wall_s"] | |
| try: | |
| m.use(p.n, "setup") | |
| w_score = nnz(w, m) | |
| if not valid(p, w, m): | |
| raise AssertionError("Invalid initial contraction") | |
| available = positions(p, -1, m) | |
| witness, ok = pair_witness(p, w, g, m) | |
| if not ok: | |
| raise AssertionError("Initial pair certificate failed") | |
| while True: | |
| m.use(12, "bookkeeping") | |
| stats["attempts"] += 1 | |
| a = proposal(p, available, rng, m) | |
| z = add(a, K(p, g, differential(p, a, m), m), m) | |
| c_work = normalize(p, add(w, z, m), m) | |
| ok = valid(p, c_work, m) | |
| stats["completed"] += 1 | |
| if ok: | |
| retain_work(c_work, nnz(c_work, m), "outer") | |
| else: | |
| stats["invalid"] += 1 | |
| continue | |
| if stats["attempts"] % audition_interval: | |
| continue | |
| if stats["auditions"] >= max_auditions: | |
| continue | |
| # Reserve the entire paired audition, plus certificate/selection | |
| # room. If it does not fit, use remaining fuel for w alone. | |
| required = 2 * probes * probe_budget + 10000 | |
| if budget - m.used < required: | |
| stats["auditions_skipped_for_budget"] += 1 | |
| continue | |
| candidate_g = normalize(p, add(g, z, m), m) | |
| if not valid(p, candidate_g, m): | |
| stats["generator_invalid"] += 1 | |
| continue | |
| if equal(candidate_g, g, m): | |
| stats["generator_unchanged"] += 1 | |
| continue | |
| retain_work(candidate_g, nnz(candidate_g, m), "generator_candidate") | |
| # Reserve again after actual proposal/validation work. | |
| if budget - m.used < required: | |
| stats["auditions_skipped_for_budget"] += 1 | |
| continue | |
| index = stats["auditions"] | |
| stats["auditions"] += 1 | |
| incumbent = g | |
| excluded = (incumbent, candidate_g) | |
| scores = {"incumbent": [], "candidate": []} | |
| children = [] | |
| probe_rows = [] | |
| for repeat in range(probes): | |
| # Separate from both outer proposals and final child seeds. | |
| probe_seed = seed * 1000 + 30000000 + index * 100 + repeat | |
| for label, generator in (("incumbent", incumbent), | |
| ("candidate", candidate_g)): | |
| child, row = discover(p, generator, probe_budget, probe_seed, | |
| forbidden=excluded) | |
| charge_nested(row, label) | |
| scores[label].append(row["final_nnz"]) | |
| children.append((child, row["final_nnz"])) | |
| probe_rows.append({"label": label, "repeat": repeat, | |
| "score": row["final_nnz"], | |
| "work": row["work"], "cpu_s": row["cpu_s"]}) | |
| m.use(4 * probes + 4, "audition_selection") | |
| accept = (all(c <= old for c, old in zip(scores["candidate"], | |
| scores["incumbent"])) | |
| and sum(scores["candidate"]) < sum(scores["incumbent"])) | |
| # These children belong to training, not the final held-out test. | |
| for child, score in children: | |
| retain_work(child, score, "audition") | |
| if accept: | |
| b, certified = pair_witness(p, w, candidate_g, m) | |
| if certified: | |
| g, witness = candidate_g, b | |
| stats["generator_accepts"] += 1 | |
| events.append({"work": m.used, "kind": "generator", | |
| "w_nnz": w_score, "g_digest": digest(g)}) | |
| else: | |
| stats["pair_certificate_failures"] += 1 | |
| accept = False | |
| else: | |
| stats["generator_rejections"] += 1 | |
| auditions.append({"index": index, "work_after": m.used, | |
| "incumbent_digest": digest(incumbent), | |
| "candidate_digest": digest(candidate_g), | |
| "scores": scores, "accepted": accept, | |
| "probes": probe_rows}) | |
| except BudgetExhausted: | |
| stats["budget_interrupts"] += 1 | |
| row = dict(stats) | |
| row.update({"mode": "dual", "budget": budget, "work": m.used, | |
| "generator_accepts": stats["generator_accepts"], | |
| "generator_rejections": stats["generator_rejections"], | |
| "auditions": stats["auditions"], | |
| "pair_certificate_failures": stats["pair_certificate_failures"], | |
| "initial_nnz": initial_score, "final_nnz": w_score, | |
| "nnz_gain": initial_score - w_score, | |
| "generator_nnz": sum(x.bit_count() for x in g), | |
| "generator_changed": g != p.h0, | |
| "wall_s": time.perf_counter() - start, | |
| "cpu_s": time.process_time() - cpu_start, | |
| "nested_cpu_s": nested_cpu, "nested_wall_s": nested_wall, | |
| "audition_work": sum(v for k, v in m.counts.items() | |
| if k.startswith("audition_")), | |
| "work_categories": dict(m.counts), | |
| "events": events, "auditions_detail": auditions, | |
| "operator_digest": digest(w), "generator_digest": digest(g), | |
| "witness_digest": digest(witness), | |
| "operator_bytes": matrix_bytes(w), | |
| "pair_bytes": matrix_bytes(w) + matrix_bytes(g) + matrix_bytes(witness), | |
| "zero_progress": initial_score == w_score}) | |
| return w, g, witness, row | |
| def run(args): | |
| outdir = Path(args.output) | |
| outdir.mkdir(parents=True, exist_ok=True) | |
| records, descendants = [], [] | |
| started = time.perf_counter() | |
| for offset in range(args.seeds): | |
| seed = args.seed_start + offset | |
| p = generate(seed, rank=args.rank, homology=1, | |
| grades_count=4, scramble=args.scramble) | |
| w, g, witness, dual_row = train_dual( | |
| p, args.budget, seed * 100000 + 11001, | |
| probe_budget=args.probe_budget, probes=args.probes, | |
| audition_interval=args.audition_interval, | |
| max_auditions=args.max_auditions) | |
| tasks = fresh_tasks(p, seed * 100000 + 81001) | |
| dual_row.update({"seed": seed, "arm": "dual", "n": p.n}) | |
| dual_row.update(audit(p, w, tasks)) | |
| records.append(dual_row) | |
| parent_outputs = {} | |
| for label, mode in (("static", "fixed"), ("collapsed", "current"), | |
| ("rebuild_coordinate", "rebuild")): | |
| h, row = discover(p, p.h0, args.budget, | |
| seed * 100000 + 11001, mode=mode) | |
| parent_outputs[label] = h | |
| row.update({"seed": seed, "arm": label, "n": p.n}) | |
| row.update(audit(p, h, tasks)) | |
| records.append(row) | |
| # Final discovery seeds have never been used for training or selection. | |
| final_seed = seed * 100000 + 91001 | |
| child_tasks = fresh_tasks(p, seed * 100000 + 92001) | |
| exclusions = tuple(dict.fromkeys((g, w, p.h0, parent_outputs["collapsed"]))) | |
| for label, generator, parent_work, parent_cpu in ( | |
| ("dual_generator", g, dual_row["work"], dual_row["cpu_s"]), | |
| ("initial_generator", p.h0, 0, 0.0), | |
| ("collapse_same_training", w, dual_row["work"], dual_row["cpu_s"]), | |
| ("collapsed_trained", parent_outputs["collapsed"], | |
| next(r["work"] for r in records if r["seed"] == seed and r["arm"] == "collapsed"), | |
| next(r["cpu_s"] for r in records if r["seed"] == seed and r["arm"] == "collapsed"))): | |
| child, row = discover(p, generator, args.child_budget, final_seed, | |
| forbidden=exclusions) | |
| row.update({"seed": seed, "arm": label, "n": p.n, | |
| "parent_training_work": parent_work, | |
| "parent_training_cpu_s": parent_cpu, | |
| "total_work_including_parent": parent_work + row["work"], | |
| "total_cpu_including_parent_s": parent_cpu + row["cpu_s"]}) | |
| row.update(audit(p, child, child_tasks)) | |
| descendants.append(row) | |
| for label, mode in (("initial_full_budget", "fixed"), | |
| ("rebuild_full_budget", "rebuild")): | |
| child, row = discover(p, p.h0, args.budget + args.child_budget, | |
| final_seed, forbidden=exclusions, mode=mode) | |
| row.update({"seed": seed, "arm": label, "n": p.n, | |
| "parent_training_work": 0, "parent_training_cpu_s": 0.0, | |
| "total_work_including_parent": row["work"], | |
| "total_cpu_including_parent_s": row["cpu_s"]}) | |
| row.update(audit(p, child, child_tasks)) | |
| descendants.append(row) | |
| print(json.dumps({"seed": seed, "progress": offset + 1, | |
| "w_nnz": dual_row["final_nnz"], | |
| "g_nnz": dual_row["generator_nnz"], | |
| "g_accepts": dual_row.get("generator_accepts", 0), | |
| "auditions": dual_row.get("auditions", 0)}), flush=True) | |
| (outdir / "raw_checkpoint.json").write_text(json.dumps( | |
| {"records": records, "descendants": descendants}, indent=2)) | |
| by_seed = {(r["seed"], r["arm"]): r for r in descendants} | |
| paired = {} | |
| for control in ("initial_generator", "collapse_same_training", | |
| "collapsed_trained", "initial_full_budget", "rebuild_full_budget"): | |
| # Positive means dual generator yielded the less costly descendant. | |
| values = [by_seed[(seed, control)]["final_nnz"] - | |
| by_seed[(seed, "dual_generator")]["final_nnz"] | |
| for seed in range(args.seed_start, args.seed_start + args.seeds)] | |
| paired["dual_generator_vs_" + control] = interval(values) | |
| result = {"config": vars(args), "platform": platform.platform(), | |
| "python": sys.version, "total_wall_s": time.perf_counter() - started, | |
| "process_peak_rss_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, | |
| "summary": summarize(records), | |
| "descendant_summary": summarize(descendants), | |
| "paired_nnz_differences": paired, | |
| "generator_accepts_total": sum(r.get("generator_accepts", 0) for r in records | |
| if r["arm"] == "dual"), | |
| "generator_changed_count": sum(r.get("generator_changed", False) for r in records | |
| if r["arm"] == "dual"), | |
| "records": records, "descendants": descendants} | |
| (outdir / "results.json").write_text(json.dumps(result, indent=2)) | |
| for filename, rows in (("runs.csv", records), ("descendants.csv", descendants)): | |
| simple = [{k: v for k, v in row.items() if not isinstance(v, (list, dict))} | |
| for row in rows] | |
| keys = sorted(set().union(*(set(row) for row in simple))) | |
| with (outdir / filename).open("w", newline="") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=keys) | |
| writer.writeheader() | |
| writer.writerows(simple) | |
| print(json.dumps({"finished": True, "total_wall_s": result["total_wall_s"], | |
| "results": str(outdir / "results.json")}), flush=True) | |
| return result | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--seeds", type=int, default=24) | |
| parser.add_argument("--seed-start", type=int, default=3000) | |
| parser.add_argument("--budget", type=int, default=3000000) | |
| parser.add_argument("--child-budget", type=int, default=750000) | |
| parser.add_argument("--rank", type=int, default=4) | |
| parser.add_argument("--scramble", type=int, default=16) | |
| parser.add_argument("--probe-budget", type=int, default=50000) | |
| parser.add_argument("--probes", type=int, default=2) | |
| parser.add_argument("--audition-interval", type=int, default=8) | |
| parser.add_argument("--max-auditions", type=int, default=24) | |
| parser.add_argument("--output", default="results/revision") | |
| run(parser.parse_args()) | |