Datasets:
Formats:
csv
Languages:
English
Size:
10K - 100K
Tags:
recursive-self-improvement
symmetry-reduction
finite-groups
exact-compilation
dynamic-programming
reproducible-research
Download heap_baseline.py from PureOne/Neyaru-Reciprocal-Stabilizer-Compilation: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/datasets/PureOne/Neyaru-Reciprocal-Stabilizer-Compilation/resolve/main/heap_baseline.py
- Command line
-
hf download hf://datasets/PureOne/Neyaru-Reciprocal-Stabilizer-Compilation/heap_baseline.py
-
curl -L -o heap_baseline.py https://huggingface.co/datasets/PureOne/Neyaru-Reciprocal-Stabilizer-Compilation/resolve/main/heap_baseline.py
11.3 kB
| #!/usr/bin/env python3 | |
| """Supplemental exact best-first convolution baseline; Python 3.10+, stdlib. | |
| Run development: python research/heap_baseline.py --seeds 1:4 --output research/heap_dev | |
| The frozen core is imported unchanged. Only its fast compose dispatch is replaced. | |
| Sorted finite-cost rows are merged in increasing pair cost. The first pair for a | |
| boundary is optimal; enumeration stops when every boundary has been assigned or | |
| the heap is empty. Costs may be signed; the multiplication order remains a * b. | |
| Meter units are explicit abstract operations, not processor instructions. All | |
| sorting and heap comparisons run through instrumented __lt__ methods. Timing | |
| includes instrumentation, sorting, heap management, and certificate validation. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import hashlib | |
| import heapq | |
| import json | |
| import random | |
| import time | |
| from pathlib import Path | |
| import relational_compiler as core | |
| ORIGINAL_COMPOSE = core.compose | |
| class SortItem: | |
| __slots__ = ("cost", "index", "meter") | |
| def __init__(self, cost, index, meter): | |
| self.cost, self.index, self.meter = cost, index, meter | |
| def __lt__(self, other): | |
| self.meter.tick("sorting_comparisons") | |
| return (self.cost, self.index) < (other.cost, other.index) | |
| class HeapItem: | |
| __slots__ = ("cost", "row", "column", "meter") | |
| def __init__(self, cost, row, column, meter): | |
| self.cost, self.row, self.column, self.meter = cost, row, column, meter | |
| def __lt__(self, other): | |
| self.meter.tick("heap_comparisons") | |
| return (self.cost, self.row, self.column) < (other.cost, other.row, other.column) | |
| def sorted_support(kernel, meter): | |
| items = [] | |
| for index in kernel.support: | |
| meter.tick("sorting_items") | |
| items.append(SortItem(kernel.costs[index], index, meter)) | |
| items.sort() | |
| meter.tick("sorting_materialization", len(items)) | |
| return tuple(item.index for item in items) | |
| def best_first_compose(a, b, g, meter, kind="dense", discover=False, audit=None): | |
| if kind != "fast": | |
| return ORIGINAL_COMPOSE(a, b, g, meter, kind, discover, audit) | |
| # Preserve the already specified strongest constant-factor specialization. | |
| if a.uniform or b.uniform or not a.support or not b.support: | |
| return ORIGINAL_COMPOSE(a, b, g, meter, kind, discover, audit) | |
| audit = {} if audit is None else audit | |
| meter.tick("role_concatenation", len(a.word) + len(b.word)) | |
| word = a.word + b.word | |
| n = g.n | |
| meter.tick("array_allocation", 2 * n) | |
| costs, split = [core.INF] * n, [None] * n | |
| sa, sb = sorted_support(a, meter), sorted_support(b, meter) | |
| left_rows = len(sa) <= len(sb) | |
| rows, columns = (sa, sb) if left_rows else (sb, sa) | |
| queue = [] | |
| def push(row, column): | |
| meter.tick("pair_materialization") | |
| i, j = (rows[row], columns[column]) if left_rows else (columns[column], rows[row]) | |
| meter.tick("candidate_additions") | |
| value = a.costs[i] + b.costs[j] | |
| meter.tick("heap_item_allocation") | |
| item = HeapItem(value, row, column, meter) | |
| meter.tick("heap_pushes") | |
| heapq.heappush(queue, item) | |
| for row in range(len(rows)): | |
| push(row, 0) | |
| audit["transient_max_heap_items"] = max(audit.get("transient_max_heap_items", 0), len(rows)) | |
| audit["transient_max_sorted_items"] = max(audit.get("transient_max_sorted_items", 0), len(sa) + len(sb)) | |
| assigned = 0 | |
| while queue: | |
| meter.tick("heap_pops") | |
| item = heapq.heappop(queue) | |
| meter.tick("finite_sum_checks") | |
| if item.cost >= core.INF: | |
| # Match the core's finite sentinel convention; later sums are no less. | |
| break | |
| meter.tick("pair_materialization") | |
| i, j = (rows[item.row], columns[item.column]) if left_rows else (columns[item.column], rows[item.row]) | |
| meter.tick("group_operations") | |
| boundary = g.mul[i][j] | |
| meter.tick("boundary_assignment_checks") | |
| if split[boundary] is None: | |
| meter.tick("witness_materialization") | |
| costs[boundary], split[boundary] = item.cost, (i, j) | |
| assigned += 1 | |
| meter.tick("completion_checks") | |
| if assigned == n: | |
| break | |
| meter.tick("row_advances") | |
| if item.column + 1 < len(columns): | |
| push(item.row, item.column + 1) | |
| kernel = core.inherited( | |
| core.Kernel(word, tuple(costs), tuple(split), a, b, | |
| generation=1 + max(a.generation, b.generation)), a, b) | |
| # Exactly the local semantic/witness check used by the frozen core. | |
| for boundary, pair in enumerate(split): | |
| meter.tick("local_witness_validation") | |
| if pair is not None: | |
| i, j = pair | |
| if g.mul[i][j] != boundary or a.costs[i] + b.costs[j] != costs[boundary]: | |
| raise AssertionError("invalid best-first witness") | |
| audit["best_first_compositions"] = audit.get("best_first_compositions", 0) + 1 | |
| return core.finish(kernel, g, meter, discover, audit) | |
| # Compiler, parser, dictionary, transaction handling, and witness expansion stay | |
| # unchanged; their existing fast calls resolve this instrumented implementation. | |
| core.compose = best_first_compose | |
| def self_checks(m): | |
| """Independent dense comparison, including signed costs and sparse support.""" | |
| g, rng, meter = core.Group(m), random.Random(71991), core.Meter() | |
| cases = [] | |
| for _ in range(40): | |
| cases.append([ | |
| tuple((z, rng.randrange(-4, 9)) for z in range(g.n) if rng.random() < .45) | |
| for _ in range(2) | |
| ]) | |
| cases.extend([ | |
| [(), ((0, 3),)], | |
| [((1, -2),), ((g.m, 5),)], | |
| [tuple((z, 2) for z in range(g.n)), ((1, -3), (g.m, 4))], | |
| [((1, -3), (g.m, 4)), tuple((z, -2) for z in range(g.n))], | |
| ]) | |
| for types in cases: | |
| a, b = [core.leaf(t, types[t], g, meter, False, {}) for t in range(2)] | |
| dense = ORIGINAL_COMPOSE(a, b, g, meter, "dense") | |
| best = best_first_compose(a, b, g, meter, "fast") | |
| assert best.costs == dense.costs | |
| for z in best.support: | |
| assert core.verify((0, 1), z, best.choices(z, meter), best.costs[z], types, g, meter) | |
| assert g.mul[1][g.m] != g.mul[g.m][1] | |
| return dict(exact_dense_equivalence_cases=len(cases), signed_costs=True, | |
| empty_support=True, noncommutative_order=True, | |
| validation_work=meter.total) | |
| def run_case(seed, m, condition, budget): | |
| g, types, train, test = core.make_world(seed, m, condition) | |
| oracle = core.Meter() | |
| start = time.perf_counter_ns() | |
| truth = [core.sequential(w, b, types, g, oracle) for w, b in train + test] | |
| oracle_ns = time.perf_counter_ns() - start | |
| meter = core.Meter(budget) | |
| start = time.perf_counter_ns() | |
| compiler = core.Compiler(g, types, meter, "fast") | |
| init_work = meter.total | |
| correct = wrong = exhausted = train_work = 0 | |
| rows = [] | |
| for i, (word, target) in enumerate(train + test): | |
| before, tick = meter.total, time.perf_counter_ns() | |
| status, cost = "ok", None | |
| try: | |
| cost = compiler.solve(word, target) | |
| if cost != truth[i]: | |
| status = "wrong" | |
| wrong += 1 | |
| elif i >= len(train): | |
| correct += 1 | |
| except core.Exhausted: | |
| status = "budget" | |
| exhausted += 1 | |
| rows.append(dict(seed=seed, condition=condition, method="best_first", index=i, | |
| phase="train" if i < len(train) else "fresh", length=len(word), target=target, | |
| work=meter.total - before, ns=time.perf_counter_ns() - tick, status=status, | |
| cost=cost, oracle_cost=truth[i])) | |
| if i == len(train) - 1: | |
| train_work = meter.total | |
| if status == "budget": | |
| exhausted += len(train) + len(test) - i - 1 | |
| break | |
| elapsed = time.perf_counter_ns() - start | |
| summary = dict(seed=seed, condition=condition, method="best_first", work=meter.total, | |
| total_with_shared_oracle=meter.total + oracle.total, wall_ns=elapsed, | |
| setup_work=init_work, training_work=train_work, fresh_correct=correct, | |
| fresh_total=len(test), wrong=wrong, budget_failures=exhausted, | |
| counters=meter.counts, kernels=len(compiler.cache), | |
| scalar_slots=compiler.memory_slots(), audit=compiler.audit) | |
| return dict(seed=seed, condition=condition, oracle_work=oracle.total, oracle_ns=oracle_ns, | |
| training_words=[list(w) for w, _ in train], fresh_words=[list(w) for w, _ in test], | |
| summaries=[summary], rows=rows) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--seeds", default="1:4", help="half-open START:STOP or comma list") | |
| parser.add_argument("--order", type=int, default=16, help="rotation order; group size is twice this") | |
| parser.add_argument("--budget", type=int, default=2000000) | |
| parser.add_argument("--output", default="heap_dev") | |
| args = parser.parse_args() | |
| seeds = list(range(*map(int, args.seeds.split(":")))) if ":" in args.seeds else list(map(int, args.seeds.split(","))) | |
| checks = self_checks(args.order) | |
| results = [run_case(seed, args.order, condition, args.budget) | |
| for seed in seeds for condition in ("structured", "asymmetric", "constant")] | |
| payload = dict(source_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), | |
| core_source_sha256=hashlib.sha256(Path(core.__file__).read_bytes()).hexdigest(), | |
| parameters=vars(args), checks=checks, results=results, | |
| operation_unit="sum of explicit labeled counters; comparison tuples count as one comparison", | |
| oracle_accounting="shared oracle reported separately and added equally; algorithm budget excludes shared oracle", | |
| baseline="sorted-cost row merge, exact first boundary assignment, existing constant fast path", | |
| unchanged="core Compiler, parser, dictionary, composition order, witnesses, and finish") | |
| out = Path(args.output) | |
| out.mkdir(parents=True, exist_ok=True) | |
| (out / "results.json").write_text(json.dumps(payload, indent=2)) | |
| rows = [row for result in results for row in result["rows"]] | |
| with (out / "tasks.csv").open("w", newline="") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=list(rows[0])) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| for condition in ("structured", "asymmetric", "constant"): | |
| summaries = [result["summaries"][0] for result in results if result["condition"] == condition] | |
| print(condition, "work", round(sum(s["work"] for s in summaries) / len(summaries)), | |
| "fresh", sum(s["fresh_correct"] for s in summaries), "/", sum(s["fresh_total"] for s in summaries), | |
| "wrong", sum(s["wrong"] for s in summaries), | |
| "wall_ms", round(sum(s["wall_ns"] for s in summaries) / len(summaries) / 1e6, 3)) | |
| print("source_sha256", payload["source_sha256"]) | |
| print("core_source_sha256", payload["core_source_sha256"]) | |
| print("self_checks", json.dumps(checks)) | |
| if __name__ == "__main__": | |
| main() | |