diff --git a/.github/workflows/dg-sgrt-learned-dev.yml b/.github/workflows/dg-sgrt-learned-dev.yml new file mode 100644 index 00000000..76704d86 --- /dev/null +++ b/.github/workflows/dg-sgrt-learned-dev.yml @@ -0,0 +1,59 @@ +name: DG-SGRT-02 learned public development + +on: + pull_request: + paths: + - "src/datagoblin/training_gym/sgrt_holoarc.py" + - "src/datagoblin/training_gym/sgrt_holoarc_gym.py" + - "src/datagoblin/training_gym/sgrt_learned.py" + - "tests/unit/test_sgrt_holoarc.py" + - "tests/unit/test_sgrt_learned.py" + - "training/sgrt_holoarc_01/**" + - ".github/workflows/dg-sgrt-learned-dev.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + learned-public-dev: + runs-on: ubuntu-latest + timeout-minutes: 12 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.10" + - run: python -m pip install -e ".[dev]" + - run: python -m pytest tests/unit/test_sgrt_holoarc.py tests/unit/test_sgrt_learned.py -q + - run: ruff check src/datagoblin/training_gym/sgrt_holoarc.py src/datagoblin/training_gym/sgrt_holoarc_gym.py src/datagoblin/training_gym/sgrt_learned.py tests/unit/test_sgrt_holoarc.py tests/unit/test_sgrt_learned.py + - name: Public synthetic CPU learned comparison + run: | + python -m datagoblin.training_gym.sgrt_learned \ + --seed 23 --train-roots 128 --updates 384 --eval-roots 64 \ + --budget 8 --out runs/dg-sgrt-02-public + - name: Check provenance and equal learned capacity + run: | + python - <<'PY' + import json + from pathlib import Path + + report = json.loads(Path("runs/dg-sgrt-02-public/report.json").read_text()) + assert report["claim_boundary"].startswith("CPU-trained synthetic development") + assert len(report["train"]) == 5 + counts = {v["trainable_parameters"] for v in report["train"].values()} + assert counts == {2197}, counts + assert report["results"]["family_ood_mixed"]["holoarc_gear_lowrank"]["roots"] == 16 + print("Registered equal-capacity comparison OK", sorted(counts)) + for group, arms in report["results"].items(): + print(group) + for name, result in arms.items(): + print(" ", name, result["whole_task_solved"], "/", result["roots"], + "reachable", result["target_reachable"], + "calls", result["verifier_calls"]) + PY + - uses: actions/upload-artifact@v4 + with: + name: dg-sgrt-02-public-development + path: runs/dg-sgrt-02-public/ + retention-days: 14 diff --git a/.github/workflows/dg-sgrt-replication.yml b/.github/workflows/dg-sgrt-replication.yml new file mode 100644 index 00000000..dcf9862d --- /dev/null +++ b/.github/workflows/dg-sgrt-replication.yml @@ -0,0 +1,94 @@ +name: DG-SGRT-02R exploratory seed replication + +on: + pull_request: + paths: + - "src/datagoblin/training_gym/sgrt_learned.py" + - "tests/unit/test_sgrt_learned.py" + - "training/sgrt_holoarc_01/REPLICATION.md" + - ".github/workflows/dg-sgrt-replication.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + exploratory-replication: + runs-on: ubuntu-latest + timeout-minutes: 12 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.10" + - run: python -m pip install -e ".[dev]" + - run: python -m pytest tests/unit/test_sgrt_learned.py -q + - run: ruff check src/datagoblin/training_gym/sgrt_learned.py tests/unit/test_sgrt_learned.py + - name: Run declared independent public seed pairs + run: | + python -m datagoblin.training_gym.sgrt_learned \ + --seed 41 --eval-seed 61011 --train-roots 128 --updates 384 \ + --eval-roots 64 --budget 8 --out runs/dg-sgrt-02-repl-41 + python -m datagoblin.training_gym.sgrt_learned \ + --seed 67 --eval-seed 61013 --train-roots 128 --updates 384 \ + --eval-roots 64 --budget 8 --out runs/dg-sgrt-02-repl-67 + python -m datagoblin.training_gym.sgrt_learned \ + --seed 89 --eval-seed 61017 --train-roots 128 --updates 384 \ + --eval-roots 64 --budget 8 --out runs/dg-sgrt-02-repl-89 + - name: Show all predeclared results and pooled descriptive counts + run: | + python - <<'PY' + import json + from pathlib import Path + from datagoblin.training_gym.sgrt_learned import TRAINED_ARMS + + seeds = [(41, 61011), (67, 61013), (89, 61017)] + reports = [] + all_rows = [] + for optimize_seed, eval_seed in seeds: + folder = Path(f"runs/dg-sgrt-02-repl-{optimize_seed}") + report = json.loads((folder / "report.json").read_text()) + assert report["optimization_seed"] == optimize_seed + assert report["evaluation_seed"] == eval_seed + assert all(v["trainable_parameters"] == 2197 for v in report["train"].values()) + rows = [json.loads(line) for line in (folder / "evaluation_scores.jsonl").read_text().splitlines()] + assert len(rows) == 64 + all_rows.extend(rows) + reports.append(report) + print("SEED", optimize_seed, "EVAL", eval_seed) + for arm in TRAINED_ARMS: + total = report["results"]["all"][arm]["whole_task_solved"] + ood = report["results"]["family_ood_mixed"][arm]["whole_task_solved"] + diff = report["paired_contrasts_vs_semantic"]["all"].get(arm) + print(" ", arm, f"{total}/64", f"OOD {ood}/16", + "delta_pp", None if diff is None else diff["absolute_effect_pp"], + "CI", None if diff is None else diff["root_bootstrap_95_pp"]) + assert len({row["root_id"] for row in all_rows}) == 192 + pooled = {} + for group in ("all", "family_ood_mixed", "new_roots_seen_families"): + pooled[group] = {} + for arm in TRAINED_ARMS: + n = sum(r["results"][group][arm]["roots"] for r in reports) + solved = sum(r["results"][group][arm]["whole_task_solved"] for r in reports) + reachable = sum(r["results"][group][arm]["target_reachable"] for r in reports) + pooled[group][arm] = {"n": n, "solved": solved, "reachable": reachable} + print("POOLED", group, arm, solved, "/", n, "reachable", reachable) + out = { + "schema_version": "dg-sgrt-02r-public-exploratory-v1", + "registered_seed_pairs": seeds, + "claim_boundary": "post-development exploratory replication, not sealed confirmation", + "pooled": pooled, + } + Path("runs/dg-sgrt-02-replication-summary.json").write_text( + json.dumps(out, sort_keys=True, indent=2) + "\n" + ) + PY + - uses: actions/upload-artifact@v4 + with: + name: dg-sgrt-02r-public-seed-replication + path: | + runs/dg-sgrt-02-repl-41/ + runs/dg-sgrt-02-repl-67/ + runs/dg-sgrt-02-repl-89/ + runs/dg-sgrt-02-replication-summary.json + retention-days: 14 diff --git a/src/datagoblin/training_gym/sgrt_holoarc.py b/src/datagoblin/training_gym/sgrt_holoarc.py new file mode 100644 index 00000000..c3e52eba --- /dev/null +++ b/src/datagoblin/training_gym/sgrt_holoarc.py @@ -0,0 +1,207 @@ +"""DG-SGRT-01: small, offline geometry for bounded high-dimensional excursions. + +This is an engineering prototype, not a trained transformer or a claim of +creative performance. It changes a 12D coordinate while transporting a 16D +fiber through a fixed orthogonal connection. Exact checker custody belongs +to the companion gym. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from itertools import pairwise +from typing import Literal + +import numpy as np + +BASE_DIM = 12 +FIBER_DIM = 16 +DEFAULT_STEPS = 8 +ConnectionMode = Literal["flat", "curved"] + +# Paired rational gears. Each 2-plane is an exact hypotrochoid over one +# closed sampled circuit. Gear phases and aspect ratios are seed-dependent. +GEARS: tuple[tuple[int, int, float], ...] = ( + (5, 2, 0.80), + (7, 3, 0.65), + (8, 3, 0.70), + (9, 4, 0.55), + (7, 2, 0.75), + (11, 4, 0.60), +) + + +def _anchor(value: np.ndarray) -> np.ndarray: + anchor = np.asarray(value, dtype=np.float64) + if anchor.shape != (BASE_DIM,) or not np.isfinite(anchor).all(): + raise ValueError("anchor must be a finite 12D vector") + return anchor + + +def arc_length(path: np.ndarray) -> float: + return float(np.linalg.norm(np.diff(path, axis=0), axis=1).sum()) + + +def spiro_path(anchor: np.ndarray, *, seed: int, steps: int = DEFAULT_STEPS) -> np.ndarray: + """Return a closed 12D sampled path, anchored at a task coordinate.""" + center = _anchor(anchor) + if steps < 4: + raise ValueError("steps must be at least four") + rng = np.random.default_rng(seed) + phase = rng.uniform(-np.pi, np.pi, len(GEARS)) + scales = rng.uniform(0.13, 0.28, len(GEARS)) + path = np.tile(center, (steps + 1, 1)) + for t in range(steps + 1): + for j, (outer, inner, pen) in enumerate(GEARS): + theta = 2.0 * np.pi * inner * t / steps + phase[j] + theta0 = phase[j] + ratio = (outer - inner) / inner + x = (outer - inner) * np.cos(theta) + pen * np.cos(ratio * theta) + y = (outer - inner) * np.sin(theta) - pen * np.sin(ratio * theta) + x0 = (outer - inner) * np.cos(theta0) + pen * np.cos(ratio * theta0) + y0 = (outer - inner) * np.sin(theta0) - pen * np.sin(ratio * theta0) + radius = outer - inner + pen + path[t, 2 * j] += scales[j] * (x - x0) / radius + path[t, 2 * j + 1] += scales[j] * (y - y0) / radius + path[-1] = center # exact closure despite floating-point trig error + return path + + +def random_smooth_path(anchor: np.ndarray, *, seed: int, steps: int = DEFAULT_STEPS) -> np.ndarray: + """A target-blind, closed Fourier control matched to the spiro path length.""" + center = _anchor(anchor) + if steps < 4: + raise ValueError("steps must be at least four") + rng = np.random.default_rng(seed + 104729) + t = np.arange(steps + 1, dtype=np.float64) / steps + path = np.tile(center, (steps + 1, 1)) + for axis in range(BASE_DIM): + freq = int(rng.integers(1, 4)) + phase = float(rng.uniform(-np.pi, np.pi)) + amp = float(rng.uniform(0.07, 0.22)) + path[:, axis] += amp * ( + np.sin(2.0 * np.pi * freq * t + phase) - np.sin(phase) + ) + path[-1] = center + reference = spiro_path(center, seed=seed, steps=steps) + length = arc_length(path) + if length <= 0.0: + raise RuntimeError("degenerate control path") + path = center + (path - center) * (arc_length(reference) / length) + path[-1] = center + return path + + +def plane_axes(mode: ConnectionMode) -> tuple[tuple[int, int], ...]: + """Flat axes commute; curved axes overlap and generate nonzero brackets.""" + if mode == "flat": + return tuple((2 * (i // 2), 2 * (i // 2) + 1) for i in range(BASE_DIM)) + if mode == "curved": + return tuple( + (2 * (i // 2), 2 * (i // 2) + 1) + if i % 2 == 0 + else (2 * (i // 2) + 1, 2 * (i // 2) + 2) + for i in range(BASE_DIM) + ) + raise ValueError(f"unknown connection: {mode}") + + +def _plane_rotation(a: int, b: int, angle: float) -> np.ndarray: + c = float(np.cos(angle)) + s = float(np.sin(angle)) + rotation = np.eye(FIBER_DIM, dtype=np.float64) + rotation[a, a] = c + rotation[b, b] = c + rotation[a, b] = -s + rotation[b, a] = s + return rotation + + +def step_transport(delta: np.ndarray, *, mode: ConnectionMode, gain: float = 1.6) -> np.ndarray: + """Ordered product of exact orthogonal rotations, one per base direction.""" + delta = _anchor(delta) + if not np.isfinite(gain) or gain <= 0: + raise ValueError("gain must be positive and finite") + result = np.eye(FIBER_DIM, dtype=np.float64) + for (a, b), displacement in zip(plane_axes(mode), delta, strict=True): + result = _plane_rotation(a, b, gain * float(displacement)) @ result + return result + + +@dataclass(frozen=True) +class HolonomyTrace: + path: np.ndarray + states: np.ndarray + holonomy: np.ndarray + mode: ConnectionMode + dual_pairing_drift: float + + def receipt(self) -> dict[str, object]: + matrix = self.holonomy + phases = sorted(float(abs(x)) for x in np.angle(np.linalg.eigvals(matrix))) + return { + "schema_version": "dg-sgrt-01-holonomy-v1", + "mode": self.mode, + "base_dim": BASE_DIM, + "fiber_dim": FIBER_DIM, + "steps": len(self.path) - 1, + "path_arc_length": arc_length(self.path), + "path_closure_l2": float(np.linalg.norm(self.path[-1] - self.path[0])), + "orthogonality_error_fro": float( + np.linalg.norm(matrix.T @ matrix - np.eye(FIBER_DIM), ord="fro") + ), + "determinant": float(np.linalg.det(matrix)), + "identity_loss": float(1.0 - np.trace(matrix) / FIBER_DIM), + "canonical_angles_abs_rad": phases[::2], + "dual_pairing_drift": self.dual_pairing_drift, + } + + +def trace_transport( + path: np.ndarray, + *, + mode: ConnectionMode, + start: np.ndarray | None = None, + covector: np.ndarray | None = None, +) -> HolonomyTrace: + """Parallel transport a feature and dual covector over the same closed path.""" + points = np.asarray(path, dtype=np.float64) + if points.ndim != 2 or points.shape[1] != BASE_DIM or len(points) < 5: + raise ValueError("path requires at least four 12D edges") + if not np.isfinite(points).all() or np.linalg.norm(points[-1] - points[0]) > 1e-9: + raise ValueError("path must be finite and closed") + initial = np.zeros(FIBER_DIM, dtype=np.float64) if start is None else np.asarray(start, dtype=np.float64) + if start is None: + initial[:4] = (0.55, -0.30, 0.45, 0.20) + dual = initial.copy() if covector is None else np.asarray(covector, dtype=np.float64) + if initial.shape != (FIBER_DIM,) or dual.shape != (FIBER_DIM,): + raise ValueError("feature and covector must be 16D") + if not np.isfinite(initial).all() or not np.isfinite(dual).all(): + raise ValueError("feature and covector must be finite") + original_pairing = float(dual @ initial) + state = initial.copy() + states = [state.copy()] + product = np.eye(FIBER_DIM, dtype=np.float64) + maximum_drift = 0.0 + for before, after in pairwise(points): + q = step_transport(after - before, mode=mode) + product = q @ product + state = q @ state + dual = q @ dual # Q^{-T}=Q for orthogonal Q + states.append(state.copy()) + maximum_drift = max(maximum_drift, abs(float(dual @ state) - original_pairing)) + return HolonomyTrace(points, np.stack(states), product, mode, maximum_drift) + + +def transported_residual(state: np.ndarray, holonomy: np.ndarray, *, gate: float = 0.1) -> np.ndarray: + """Removable operator-sidecar sketch; no learned weights are implied.""" + value = np.asarray(state, dtype=np.float64) + if value.ndim != 1 or not 1 <= value.size <= FIBER_DIM: + raise ValueError("state must be a vector of length 1..16") + if not 0 <= gate <= 1: + raise ValueError("gate must be in [0, 1]") + if holonomy.shape != (FIBER_DIM, FIBER_DIM): + raise ValueError("holonomy must be 16 by 16") + lifted = np.zeros(FIBER_DIM, dtype=np.float64) + lifted[: value.size] = value + return value + gate * ((holonomy @ lifted - lifted)[: value.size]) diff --git a/src/datagoblin/training_gym/sgrt_holoarc_gym.py b/src/datagoblin/training_gym/sgrt_holoarc_gym.py new file mode 100644 index 00000000..5daee95a --- /dev/null +++ b/src/datagoblin/training_gym/sgrt_holoarc_gym.py @@ -0,0 +1,364 @@ +"""Verifier-backed, offline DG-SGRT-01 candidate-search wiring experiment. + +All policies here are deterministic, untrained proxies. Synthetic data and +the exact verifier are used to check the harness; no model capability or +causal advantage is claimed. Evaluation targets never reach proposal ranking. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import numpy as np + +from .sgrt_holoarc import ( + BASE_DIM, + DEFAULT_STEPS, + HolonomyTrace, + random_smooth_path, + spiro_path, + trace_transport, +) + +OPERATORS = ( + "id", + "xor1", + "xor2", + "xor4", + "add1", + "add3", + "rol1", + "swap01", + "mask7", + "or8", +) +FAMILIES: dict[str, tuple[str, ...]] = { + "arithmetic": ("add1", "add3", "xor1", "xor2"), + "bitwise": ("xor1", "xor2", "xor4", "swap01"), + "structural": ("rol1", "swap01", "mask7", "or8"), + "mixed": ("mask7", "add3", "xor4", "rol1", "or8"), +} +ARMS = ( + "rigid_top1_proxy", + "semantic_heuristic", + "extra_refinement_proxy", + "flat_holoarc", + "curved_holoarc", + "same_set_phase_shuffle", + "smooth_random_arc", +) +Program = tuple[str, str] + + +def _digest(payload: Any) -> str: + raw = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8") + return hashlib.sha256(raw).hexdigest() + + +def apply_operator(op: str, x: int) -> int: + value = x & 15 + if op == "id": + return value + if op == "xor1": + return value ^ 1 + if op == "xor2": + return value ^ 2 + if op == "xor4": + return value ^ 4 + if op == "add1": + return (value + 1) & 15 + if op == "add3": + return (value + 3) & 15 + if op == "rol1": + return ((value << 1) | (value >> 3)) & 15 + if op == "swap01": + return (value & 12) | ((value & 1) << 1) | ((value & 2) >> 1) + if op == "mask7": + return value & 7 + if op == "or8": + return value | 8 + raise ValueError(f"unknown operator: {op}") + + +def execute(program: Program, x: int) -> int: + return apply_operator(program[1], apply_operator(program[0], x)) + + +def program_coordinate(program: Program) -> np.ndarray: + """Fixed Fourier chart for controls, not a learned semantic representation.""" + parts: list[float] = [] + for op in program: + index = OPERATORS.index(op) + 1 + for frequency in (1, 2, 3): + theta = 2 * np.pi * index * frequency / len(OPERATORS) + parts.extend((float(np.cos(theta)), float(np.sin(theta)))) + coordinate = np.asarray(parts, dtype=np.float64) + assert coordinate.shape == (BASE_DIM,) + return coordinate + + +def legal_one_edit_candidates(anchor: Program) -> tuple[Program, ...]: + alternatives = ( + *((op, anchor[1]) for op in OPERATORS if op != anchor[0]), + *((anchor[0], op) for op in OPERATORS if op != anchor[1]), + ) + return tuple(dict.fromkeys(alternatives)) + + +@dataclass(frozen=True) +class SyntheticTask: + root_id: str + family: str + anchor: Program + demonstrations: tuple[tuple[int, int], ...] + target: Program + + def public(self) -> dict[str, Any]: + return { + "root_id": self.root_id, + "family": self.family, + "anchor": self.anchor, + "demonstrations": self.demonstrations, + "candidate_grammar": "one-operation rewrite", + } + + +def make_task(*, seed: int, root: int) -> SyntheticTask: + rng = np.random.default_rng(seed + 8191 * root) + family = tuple(FAMILIES)[root % len(FAMILIES)] + choices = FAMILIES[family] + target: Program = ( + str(rng.choice(choices)), + str(rng.choice(choices)), + ) + changed = int(rng.integers(0, 2)) + wrong_options = tuple(op for op in OPERATORS if op != target[changed]) + replacement = str(rng.choice(wrong_options)) + anchor = (replacement, target[1]) if changed == 0 else (target[0], replacement) + demos = tuple( + (int(x), execute(target, int(x))) + for x in sorted(rng.choice(16, size=4, replace=False).tolist()) + ) + return SyntheticTask(f"public-dev-{seed}-{root:05d}", family, anchor, demos, target) + + +def policy_seed(seed: int, root: int) -> int: + # Keep the policy seed independent of the generator's private random draws. + return int(_digest({"domain": "dg-sgrt-01-policy", "seed": seed, "root": root})[:15], 16) + + +def semantic_score(program: Program, anchor: Program) -> float: + return float(np.linalg.norm(program_coordinate(program) - program_coordinate(anchor))) + + +def _rank_by_path( + anchor: Program, + *, + seed: int, + budget: int, + connection: str, + random_path: bool = False, +) -> tuple[tuple[Program, ...], HolonomyTrace]: + center = program_coordinate(anchor) + trajectory = ( + random_smooth_path(center, seed=seed, steps=DEFAULT_STEPS) + if random_path + else spiro_path(center, seed=seed, steps=DEFAULT_STEPS) + ) + trace = trace_transport(trajectory, mode="curved" if connection == "curved" else "flat") + pool = list(legal_one_edit_candidates(anchor)) + choices: list[Program] = [] + for step in range(1, len(trajectory)): + if len(choices) >= budget: + break + # This frozen, untrained projection is the interface for a future + # task-conditioned low-rank proposal head. The state difference is + # path-dependent for noncommuting connection generators. + tangent = 0.16 * (trace.states[step, :BASE_DIM] - trace.states[0, :BASE_DIM]) + probe = trajectory[step] + tangent + winner = min( + (p for p in pool if p not in choices), + key=lambda p: ( + float(np.linalg.norm(program_coordinate(p) - probe)), + p, + ), + ) + choices.append(winner) + remainder = sorted( + (p for p in pool if p not in choices), + key=lambda p: (semantic_score(p, anchor), p), + ) + choices.extend(remainder[: budget - len(choices)]) + return tuple(choices), trace + + +def propose( + task_public: dict[str, Any], + *, + seed: int, + arm: str, + budget: int, +) -> tuple[tuple[Program, ...], dict[str, Any] | None]: + """Target-blind proposals. Only public anchor and family enter this function.""" + if arm not in ARMS: + raise ValueError(f"unknown arm: {arm}") + if not 1 <= budget <= 16: + raise ValueError("budget must be in [1, 16]") + anchor: Program = tuple(task_public["anchor"]) # type: ignore[assignment] + pool = legal_one_edit_candidates(anchor) + if arm == "rigid_top1_proxy": + return (anchor,), None + if arm == "semantic_heuristic": + return tuple(sorted(pool, key=lambda p: (semantic_score(p, anchor), p))[:budget]), None + if arm == "extra_refinement_proxy": + # A budget-matched deterministic repeated-edit control, not a TRM. + start = seed % len(pool) + order = pool[start:] + pool[:start] + return order[:budget], None + connection = "flat" if arm == "flat_holoarc" else "curved" + order, trace = _rank_by_path( + anchor, + seed=seed, + budget=budget, + connection=connection, + random_path=arm == "smooth_random_arc", + ) + if arm == "same_set_phase_shuffle": + permutation = np.random.default_rng(seed + 92821).permutation(len(order)) + order = tuple(order[int(i)] for i in permutation) + return order, trace.receipt() + + +def _full_semantic_match(candidate: Program, target: Program) -> bool: + return all(execute(candidate, x) == execute(target, x) for x in range(16)) + + +def verify_and_score(task: SyntheticTask, proposals: tuple[Program, ...]) -> dict[str, Any]: + """Exact demo checker, followed by evaluator-only full-domain assessment.""" + valid = tuple( + p for p in proposals + if all(execute(p, x) == y for x, y in task.demonstrations) + ) + # Canonical survivor selection makes same-candidate-set shuffle a strict + # negative control for final solve. First-hit index remains order-sensitive. + selected = min(valid) if valid else None + first_hit = next( + ( + index + 1 + for index, p in enumerate(proposals) + if all(execute(p, x) == y for x, y in task.demonstrations) + ), + None, + ) + return { + "candidate_set_sha256": _digest(sorted(proposals)), + "candidate_order_sha256": _digest(proposals), + "verifier_calls": len(proposals), + "demo_survivors": len(valid), + "first_demo_hit": first_hit, + "whole_task_solved": selected is not None and _full_semantic_match(selected, task.target), + "target_reachable_in_set": any(_full_semantic_match(p, task.target) for p in proposals), + "selected": selected, + } + + +def run_suite(*, seed: int, roots: int, budget: int) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + if not 1 <= roots <= 128: + raise ValueError("roots must be in [1, 128] to bound CPU and memory") + if not 1 <= budget <= 16: + raise ValueError("budget must be in [1, 16]") + public: list[dict[str, Any]] = [] + scored: list[dict[str, Any]] = [] + for root in range(roots): + task = make_task(seed=seed, root=root) + visible = task.public() + public.append(visible) + pseed = policy_seed(seed, root) + per_arm: dict[str, dict[str, Any]] = {} + for arm in ARMS: + candidates, geometry = propose(visible, seed=pseed, arm=arm, budget=budget) + evaluation = verify_and_score(task, candidates) + per_arm[arm] = { + **evaluation, + "proposals": candidates, + "geometry": geometry, + "policy_seed": pseed, + } + curved = per_arm["curved_holoarc"] + shuffle = per_arm["same_set_phase_shuffle"] + if curved["candidate_set_sha256"] != shuffle["candidate_set_sha256"]: + raise AssertionError("phase shuffle changed the candidate set") + if curved["whole_task_solved"] != shuffle["whole_task_solved"]: + raise AssertionError("same candidate set changed canonical exact solve") + scored.append({ + "root_id": task.root_id, + "family": task.family, + "target": task.target, + "arms": per_arm, + }) + return public, scored + + +def summarize(scored: list[dict[str, Any]]) -> dict[str, Any]: + totals: dict[str, dict[str, Any]] = defaultdict( + lambda: {"solved": 0, "reachable": 0, "verifier_calls": 0, "roots": 0} + ) + for row in scored: + for arm, outcome in row["arms"].items(): + totals[arm]["solved"] += int(outcome["whole_task_solved"]) + totals[arm]["reachable"] += int(outcome["target_reachable_in_set"]) + totals[arm]["verifier_calls"] += outcome["verifier_calls"] + totals[arm]["roots"] += 1 + return { + "schema_version": "dg-sgrt-01-public-development-v1", + "status": "untrained_synthetic_wiring_only", + "results": dict(totals), + "comparability_note": ( + "Rigid top-1 uses one call; all other arms use the same proposal budget. " + "No model has been trained. Same-set shuffle final solves agree by construction." + ), + } + + +def _write_jsonl(path: Path, rows: list[dict[str, Any]]) -> str: + with path.open("w", encoding="utf-8", newline="\n") as handle: + for row in rows: + handle.write(json.dumps(row, sort_keys=True, separators=(",", ":")) + "\n") + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--seed", type=int, default=23, help="public engineering seed") + parser.add_argument("--roots", type=int, default=8, help="root count, max 128") + parser.add_argument("--budget", type=int, default=8, help="candidate checks per arm, max 16") + parser.add_argument("--out", required=True, type=Path, help="ignored local output directory") + args = parser.parse_args(argv) + if args.out.exists() and any(args.out.iterdir()): + parser.error("output directory must be absent or empty") + public, scored = run_suite(seed=args.seed, roots=args.roots, budget=args.budget) + args.out.mkdir(parents=True, exist_ok=True) + public_hash = _write_jsonl(args.out / "public_tasks.jsonl", public) + score_hash = _write_jsonl(args.out / "evaluator_scores.jsonl", scored) + report = summarize(scored) + report["seed"] = args.seed + report["roots"] = args.roots + report["budget"] = args.budget + report["digests"] = { + "public_tasks_sha256": public_hash, + "evaluator_scores_sha256": score_hash, + } + (args.out / "report.json").write_text( + json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + print(json.dumps(report, indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/src/datagoblin/training_gym/sgrt_learned.py b/src/datagoblin/training_gym/sgrt_learned.py new file mode 100644 index 00000000..8820bbcc --- /dev/null +++ b/src/datagoblin/training_gym/sgrt_learned.py @@ -0,0 +1,436 @@ +"""DG-SGRT-02 CPU learned low-rank proposal heads with geometry controls. + +All full-domain supervision comes from public synthetic training roots. +Evaluation targets remain in evaluator-owned SyntheticTask objects. +The geometry is frozen; a task-conditioned gate and low-rank maps are trained. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from dataclasses import dataclass +from itertools import accumulate +from pathlib import Path +from typing import Any + +import numpy as np + +from .sgrt_holoarc import ( + BASE_DIM, + FIBER_DIM, + random_smooth_path, + spiro_path, + step_transport, + trace_transport, +) +from .sgrt_holoarc_gym import ( + OPERATORS, + Program, + SyntheticTask, + execute, + legal_one_edit_candidates, + make_task, + program_coordinate, + propose, + verify_and_score, +) + +TASK_DIM = 85 +CANDIDATE_DIM = 47 +RANK = FIBER_DIM +TRAINED_ARMS = ( + "semantic_lowrank", + "flat_lowrank", + "holoarc_gear_lowrank", + "holoarc_random_path_lowrank", + "holoarc_step_shuffle_lowrank", +) +EVAL_ARMS = (*TRAINED_ARMS, "rigid_top1_proxy", "semantic_heuristic", "extra_refinement_proxy") +PUBLIC_TRAIN_SEED = 31001 +PUBLIC_EVAL_SEED = 61001 + + +def _canonical(value: Any) -> bytes: + return json.dumps(value, separators=(",", ":"), sort_keys=True).encode("utf-8") + + +def _seed_from_public(task: dict[str, Any]) -> int: + visible = {"anchor": task["anchor"], "demonstrations": task["demonstrations"]} + return int(hashlib.sha256(_canonical(visible)).hexdigest()[:15], 16) + + +def _onehot(index: int, size: int) -> np.ndarray: + vector = np.zeros(size, dtype=np.float64) + vector[index] = 1.0 + return vector + + +def task_features(public: dict[str, Any]) -> np.ndarray: + """Public task features. Target and generator family are intentionally unused.""" + anchor: Program = tuple(public["anchor"]) # type: ignore[assignment] + inputs, outputs, delta, residual = (np.zeros(16, dtype=np.float64) for _ in range(4)) + demos = public["demonstrations"] + if len(demos) != 4: + raise ValueError("expected four demonstrations") + for x, y in demos: + if not 0 <= x < 16 or not 0 <= y < 16: + raise ValueError("demonstrations require four-bit values") + inputs[x] += 0.25 + outputs[y] += 0.25 + delta[x ^ y] += 0.25 + residual[execute(anchor, x) ^ y] += 0.25 + features = np.concatenate(( + inputs, + outputs, + delta, + residual, + _onehot(OPERATORS.index(anchor[0]), len(OPERATORS)), + _onehot(OPERATORS.index(anchor[1]), len(OPERATORS)), + np.ones(1, dtype=np.float64), + )) + assert features.shape == (TASK_DIM,) + return features + + +def candidate_features(candidate: Program, anchor: Program) -> np.ndarray: + """Cheap fixed syntactic/Fourier chart with no candidate execution.""" + return np.concatenate(( + _onehot(OPERATORS.index(candidate[0]), len(OPERATORS)), + _onehot(OPERATORS.index(candidate[1]), len(OPERATORS)), + np.array([float(candidate[0] != anchor[0]), float(candidate[1] != anchor[1])]), + program_coordinate(candidate), + program_coordinate(candidate) - program_coordinate(anchor), + np.ones(1, dtype=np.float64), + )) + + +def _direct_context(features: np.ndarray) -> np.ndarray: + """Matched non-geometric context-dependent orthogonal transform.""" + return step_transport(1.3 * (features[:BASE_DIM] - 0.125), mode="curved") + + +def _reorder_steps(path: np.ndarray, *, seed: int) -> np.ndarray: + """Permute the same edge increments while preserving closed-loop distance.""" + increments = np.diff(path, axis=0) + indices = np.random.default_rng(seed + 37).permutation(len(increments)) + output = [path[0]] + output.extend(accumulate(increments[indices], lambda position, step: position + step)) + points = np.stack(output) + points[-1] = path[0] + return points + + +def context_transport(public: dict[str, Any], *, arm: str) -> np.ndarray: + """Frozen task-conditioned geometry, shared param count in learned heads.""" + if arm not in TRAINED_ARMS: + raise ValueError(f"unknown trained arm: {arm}") + features = task_features(public) + if arm == "semantic_lowrank": + return _direct_context(features) + seed = _seed_from_public(public) + center = np.zeros(BASE_DIM, dtype=np.float64) + path = ( + random_smooth_path(center, seed=seed) + if arm == "holoarc_random_path_lowrank" + else spiro_path(center, seed=seed) + ) * 3.0 + if arm == "holoarc_step_shuffle_lowrank": + path = _reorder_steps(path, seed=seed) + mode = "flat" if arm == "flat_lowrank" else "curved" + return trace_transport(path, mode=mode).holonomy + + +@dataclass +class LowRankHead: + task_matrix: np.ndarray + candidate_matrix: np.ndarray + gate_vector: np.ndarray + + @classmethod + def initialize(cls, *, seed: int) -> LowRankHead: + rng = np.random.default_rng(seed) + return cls( + rng.normal(0, 0.06, size=(TASK_DIM, RANK)), + rng.normal(0, 0.06, size=(CANDIDATE_DIM, RANK)), + rng.normal(0, 0.02, size=TASK_DIM), + ) + + @property + def parameter_count(self) -> int: + return self.task_matrix.size + self.candidate_matrix.size + self.gate_vector.size + + def digest(self) -> str: + digest = hashlib.sha256() + for array in (self.task_matrix, self.candidate_matrix, self.gate_vector): + digest.update(array.astype(" tuple[np.ndarray, tuple[np.ndarray, np.ndarray, float, np.ndarray]]: + latent = features @ self.task_matrix + gate = 1.0 / (1.0 + math.exp(-float(np.clip(features @ self.gate_vector, -30, 30)))) + displacement = (transport - np.eye(RANK)) @ latent + updated = latent + gate * displacement + choices = candidates @ self.candidate_matrix + scores = (choices @ updated) / math.sqrt(RANK) + return scores, (latent, displacement, gate, updated) + + +def _training_targets(task: SyntheticTask, candidates: tuple[Program, ...]) -> np.ndarray: + """The exact 16-input oracle is used solely inside the training partition.""" + return np.array([ + all(execute(p, x) == execute(task.target, x) for x in range(16)) + for p in candidates + ], dtype=bool) + + +@dataclass(frozen=True) +class TrainingItem: + features: np.ndarray + candidates: np.ndarray + positives: np.ndarray + transport: np.ndarray + + +def _training_items(*, roots: int, arm: str) -> tuple[TrainingItem, ...]: + items = [] + for index in range(roots): + if index % 4 == 3: + continue # withheld mixed-composition family + task = make_task(seed=PUBLIC_TRAIN_SEED, root=index) + public = task.public() + pool = legal_one_edit_candidates(task.anchor) + targets = _training_targets(task, pool) + if not targets.any(): + raise AssertionError("target should have a legal one-edit neighbor") + items.append(TrainingItem( + task_features(public), + np.stack([candidate_features(p, task.anchor) for p in pool]), + targets, + context_transport(public, arm=arm), + )) + return tuple(items) + + +def _loss_gradients(head: LowRankHead, item: TrainingItem) -> tuple[float, tuple[np.ndarray, ...]]: + logits, (_latent, displacement, gate, updated) = head.logits( + item.features, item.candidates, item.transport + ) + weights = np.exp(logits - np.max(logits)) + probabilities = weights / weights.sum() + positives = weights * item.positives + total_positive = positives.sum() + if total_positive <= 0: + raise ValueError("training item has no exact positive candidate") + loss = float(np.log(weights.sum()) - np.log(total_positive)) + ds = probabilities - (positives / total_positive) + candidate_latents = item.candidates @ head.candidate_matrix + dup = (candidate_latents.T @ ds) / math.sqrt(RANK) + grad_candidate = item.candidates.T @ np.outer(ds, updated) / math.sqrt(RANK) + grad_task = np.outer( + item.features, + dup + gate * ((item.transport - np.eye(RANK)).T @ dup), + ) + grad_gate = item.features * float(dup @ displacement) * gate * (1.0 - gate) + return loss, (grad_task, grad_candidate, grad_gate) + + +def fit( + *, + arm: str, + seed: int, + train_roots: int = 128, + updates: int = 384, + lr: float = 0.025, +) -> tuple[LowRankHead, dict[str, Any]]: + """Same Adam initialization and root order for every trained condition.""" + if arm not in TRAINED_ARMS: + raise ValueError(f"unknown arm: {arm}") + if not 16 <= train_roots <= 384 or not 16 <= updates <= 1500 or lr <= 0: + raise ValueError("bounds: roots 16..384, updates 16..1500, lr positive") + items = _training_items(roots=train_roots, arm=arm) + rng = np.random.default_rng(seed + 411) + order = np.arange(len(items)) + rng.shuffle(order) + head = LowRankHead.initialize(seed=seed) + parameters = (head.task_matrix, head.candidate_matrix, head.gate_vector) + moments = [np.zeros_like(p) for p in parameters] + second = [np.zeros_like(p) for p in parameters] + losses: list[float] = [] + for step in range(1, updates + 1): + if (step - 1) % len(items) == 0: + rng.shuffle(order) + item = items[int(order[(step - 1) % len(items)])] + loss, gradients = _loss_gradients(head, item) + losses.append(loss) + norm = math.sqrt(sum(float(np.sum(g * g)) for g in gradients)) + clip = min(1.0, 5.0 / max(1e-12, norm)) + for i, (weight, gradient) in enumerate(zip(parameters, gradients, strict=True)): + adjusted = gradient * clip + 1e-5 * weight + moments[i] *= 0.9 + moments[i] += 0.1 * adjusted + second[i] *= 0.999 + second[i] += 0.001 * adjusted * adjusted + weight -= lr * (moments[i] / (1 - 0.9**step)) / ( + np.sqrt(second[i] / (1 - 0.999**step)) + 1e-8 + ) + return head, { + "arm": arm, + "train_roots": len(items), + "requested_roots": train_roots, + "updates": updates, + "first32_loss_mean": float(np.mean(losses[:32])), + "last32_loss_mean": float(np.mean(losses[-32:])), + "trainable_parameters": head.parameter_count, + "weights_sha256": head.digest(), + } + + +def ranked_candidates( + head: LowRankHead, public: dict[str, Any], *, arm: str, budget: int +) -> tuple[Program, ...]: + if not 1 <= budget <= 16: + raise ValueError("budget must be 1..16") + anchor: Program = tuple(public["anchor"]) # type: ignore[assignment] + pool = legal_one_edit_candidates(anchor) + candidate_view = np.stack([candidate_features(p, anchor) for p in pool]) + scores, _ = head.logits(task_features(public), candidate_view, context_transport(public, arm=arm)) + sorted_pool = sorted(zip(scores, pool, strict=True), key=lambda row: (-float(row[0]), row[1])) + return tuple(candidate for _score, candidate in sorted_pool[:budget]) + + +def evaluate( + trained: dict[str, LowRankHead], *, eval_roots: int = 64, budget: int = 8, eval_seed: int = PUBLIC_EVAL_SEED +) -> tuple[list[dict[str, Any]], dict[str, Any]]: + if not 4 <= eval_roots <= 256 or not 1 <= budget <= 16: + raise ValueError("eval roots 4..256, candidate budget 1..16") + if set(trained) != set(TRAINED_ARMS): + raise ValueError("all registered trained arms are required") + rows: list[dict[str, Any]] = [] + for index in range(eval_roots): + task = make_task(seed=eval_seed, root=index) + public = task.public() + group = "family_ood_mixed" if task.family == "mixed" else "new_roots_seen_families" + outcomes = {} + for arm in EVAL_ARMS: + if arm in trained: + proposals = ranked_candidates(trained[arm], public, arm=arm, budget=budget) + else: + proposals, _ = propose(public, seed=_seed_from_public(public), arm=arm, budget=budget) + score = verify_and_score(task, proposals) + outcomes[arm] = { + "whole_task_solved": score["whole_task_solved"], + "target_reachable": score["target_reachable_in_set"], + "first_demo_hit": score["first_demo_hit"], + "verifier_calls": score["verifier_calls"], + "candidate_set_sha256": score["candidate_set_sha256"], + } + rows.append({ + "root_id": task.root_id, + "family": task.family, + "group": group, + "arms": outcomes, + }) + report = {} + for group in ("new_roots_seen_families", "family_ood_mixed", "all"): + selected = [r for r in rows if group == "all" or r["group"] == group] + report[group] = {} + for arm in EVAL_ARMS: + scores = [r["arms"][arm] for r in selected] + report[group][arm] = { + "roots": len(selected), + "whole_task_solved": sum(int(s["whole_task_solved"]) for s in scores), + "target_reachable": sum(int(s["target_reachable"]) for s in scores), + "verifier_calls": sum(int(s["verifier_calls"]) for s in scores), + } + return rows, report + + + +def paired_contrasts(rows: list[dict[str, Any]], *, replicates: int = 1024) -> dict[str, Any]: + """Root-paired exploratory bootstrap; fixed RNG and no selection on outputs.""" + report: dict[str, Any] = {} + baseline = "semantic_lowrank" + for group in ("new_roots_seen_families", "family_ood_mixed", "all"): + eligible = [r for r in rows if group == "all" or r["group"] == group] + report[group] = {} + for arm in TRAINED_ARMS: + if arm == baseline: + continue + delta = np.array([ + int(row["arms"][arm]["whole_task_solved"]) - int(row["arms"][baseline]["whole_task_solved"]) + for row in eligible + ], dtype=np.float64) + if len(delta) == 0: + raise ValueError("root group has no evaluation items") + stable_seed = int(hashlib.sha256((group + arm).encode("utf-8")).hexdigest()[:12], 16) + rng = np.random.default_rng(stable_seed) + indices = rng.integers(0, len(delta), size=(replicates, len(delta))) + boot = 100 * np.mean(delta[indices], axis=1) + limits = np.quantile(boot, (0.025, 0.975)) + report[group][arm] = { + "roots": len(delta), + "absolute_effect_pp": 100 * float(np.mean(delta)), + "root_bootstrap_95_pp": [float(limits[0]), float(limits[1])], + "wins": int(np.sum(delta > 0)), + "losses": int(np.sum(delta < 0)), + "ties": int(np.sum(delta == 0)), + "status": "exploratory_public_development", + } + return report + +def _write_jsonl(path: Path, rows: list[dict[str, Any]]) -> str: + with path.open("w", encoding="utf-8", newline="\n") as stream: + for row in rows: + stream.write(_canonical(row).decode("utf-8") + "\n") + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--seed", type=int, default=23) + parser.add_argument("--train-roots", type=int, default=128) + parser.add_argument("--eval-roots", type=int, default=64) + parser.add_argument("--updates", type=int, default=384) + parser.add_argument("--budget", type=int, default=8) + parser.add_argument("--eval-seed", type=int, default=PUBLIC_EVAL_SEED) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args(argv) + if args.out.exists() and any(args.out.iterdir()): + parser.error("output directory must be absent or empty") + models = {} + logs = {} + for arm in TRAINED_ARMS: + models[arm], logs[arm] = fit( + arm=arm, seed=args.seed, train_roots=args.train_roots, updates=args.updates + ) + rows, results = evaluate(models, eval_roots=args.eval_roots, budget=args.budget, eval_seed=args.eval_seed) + args.out.mkdir(parents=True, exist_ok=True) + rows_sha = _write_jsonl(args.out / "evaluation_scores.jsonl", rows) + report = { + "schema_version": "dg-sgrt-02-learned-public-development-v1", + "claim_boundary": "CPU-trained synthetic development, no sealed or 1B-model result", + "train_seed": PUBLIC_TRAIN_SEED, + "evaluation_seed": args.eval_seed, + "optimization_seed": args.seed, + "budget": args.budget, + "train": logs, + "results": results, + "evaluation_rows_sha256": rows_sha, + "paired_contrasts_vs_semantic": paired_contrasts(rows), + } + (args.out / "report.json").write_text( + json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + print(json.dumps(report, indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/tests/unit/test_sgrt_holoarc.py b/tests/unit/test_sgrt_holoarc.py new file mode 100644 index 00000000..d4a56ec3 --- /dev/null +++ b/tests/unit/test_sgrt_holoarc.py @@ -0,0 +1,145 @@ +from __future__ import annotations + +from dataclasses import replace + +import numpy as np +import pytest + +from datagoblin.training_gym.sgrt_holoarc import ( + BASE_DIM, + FIBER_DIM, + arc_length, + random_smooth_path, + spiro_path, + step_transport, + trace_transport, + transported_residual, +) +from datagoblin.training_gym.sgrt_holoarc_gym import ( + ARMS, + OPERATORS, + execute, + make_task, + policy_seed, + propose, + run_suite, + summarize, + verify_and_score, +) + + +@pytest.mark.parametrize("seed", [3, 5, 23, 42]) +def test_multidimensional_closed_gear_geometry(seed: int) -> None: + center = np.linspace(-0.5, 0.5, BASE_DIM) + path = spiro_path(center, seed=seed) + assert path.shape == (9, BASE_DIM) + assert np.array_equal(path[0], center) + assert np.array_equal(path[-1], center) + assert arc_length(path) > 0 + assert np.allclose(spiro_path(center, seed=seed), path) + + +def test_random_arc_length_is_budget_matched() -> None: + anchor = np.zeros(BASE_DIM) + gear = spiro_path(anchor, seed=43) + random_path = random_smooth_path(anchor, seed=43) + assert np.array_equal(random_path[0], anchor) + assert np.array_equal(random_path[-1], anchor) + assert abs(arc_length(gear) - arc_length(random_path)) < 1e-12 + + +def test_flat_holonomy_is_identity_and_curved_is_nontrivial() -> None: + path = spiro_path(np.zeros(BASE_DIM), seed=23) + flat = trace_transport(path, mode="flat") + curved = trace_transport(path, mode="curved") + flat_report = flat.receipt() + curved_report = curved.receipt() + assert flat_report["identity_loss"] == pytest.approx(0.0, abs=1e-12) + assert curved_report["identity_loss"] > 1e-4 + for receipt in (flat_report, curved_report): + assert receipt["determinant"] == pytest.approx(1.0, abs=1e-10) + assert receipt["orthogonality_error_fro"] < 1e-10 + assert receipt["dual_pairing_drift"] < 1e-10 + assert receipt["path_closure_l2"] == 0 + + +def test_holonomy_is_gauge_covariant_and_invariants_are_fixed() -> None: + path = spiro_path(np.zeros(BASE_DIM), seed=5) + trace = trace_transport(path, mode="curved") + gauge = np.eye(FIBER_DIM)[::-1] + # Change fiber basis on every edge. A Wilson loop transforms by conjugation. + product = np.eye(FIBER_DIM) + for delta in np.diff(path, axis=0): + q = step_transport(delta, mode="curved") + product = (gauge @ q @ gauge.T) @ product + assert np.allclose(product, gauge @ trace.holonomy @ gauge.T, atol=1e-10) + assert np.trace(product) == pytest.approx(np.trace(trace.holonomy), abs=1e-10) + assert np.linalg.det(product) == pytest.approx(np.linalg.det(trace.holonomy), abs=1e-10) + + +def test_transport_sidecar_is_bounded_and_identity_gated() -> None: + state = np.linspace(-1, 1, BASE_DIM) + holonomy = trace_transport(spiro_path(np.zeros(BASE_DIM), seed=23), mode="curved").holonomy + assert np.array_equal(transported_residual(state, holonomy, gate=0), state) + assert np.all(np.isfinite(transported_residual(state, holonomy, gate=0.1))) + with pytest.raises(ValueError): + transported_residual(state, holonomy, gate=1.01) + + +def test_dsl_is_total_on_four_bit_states() -> None: + for a in OPERATORS: + for b in OPERATORS: + for x in range(16): + y = execute((a, b), x) + assert isinstance(y, int) and 0 <= y <= 15 + + +def test_candidate_generation_is_target_blind() -> None: + task = make_task(seed=23, root=2) + altered_target = replace(task, target=("id", "id")) + assert task.public() == altered_target.public() + for arm in ARMS: + original = propose(task.public(), seed=71, arm=arm, budget=8) + altered = propose(altered_target.public(), seed=71, arm=arm, budget=8) + candidates_a, receipt_a = original + candidates_b, receipt_b = altered + assert candidates_a == candidates_b + assert receipt_a == receipt_b + assert len(candidates_a) == len(set(candidates_a)) + + +def test_matched_phase_shuffle_preserves_candidate_set_and_selected_result() -> None: + task = make_task(seed=41, root=3) + seed = policy_seed(41, 3) + curved, curved_receipt = propose(task.public(), seed=seed, arm="curved_holoarc", budget=8) + shuffled, shuffled_receipt = propose( + task.public(), seed=seed, arm="same_set_phase_shuffle", budget=8 + ) + assert sorted(curved) == sorted(shuffled) + assert curved_receipt == shuffled_receipt + evaluation_a = verify_and_score(task, curved) + evaluation_b = verify_and_score(task, shuffled) + assert evaluation_a["whole_task_solved"] == evaluation_b["whole_task_solved"] + assert evaluation_a["candidate_set_sha256"] == evaluation_b["candidate_set_sha256"] + + +def test_public_smoke_suite_has_full_matched_coverage() -> None: + public, scored = run_suite(seed=23, roots=4, budget=8) + assert len(public) == len(scored) == 4 + for item in public: + assert "target" not in item + for row in scored: + assert set(row["arms"]) == set(ARMS) + assert row["arms"]["rigid_top1_proxy"]["verifier_calls"] == 1 + for arm in ARMS: + if arm != "rigid_top1_proxy": + assert row["arms"][arm]["verifier_calls"] == 8 + report = summarize(scored) + assert report["status"] == "untrained_synthetic_wiring_only" + assert all(value["roots"] == 4 for value in report["results"].values()) + + +def test_seed_replay_is_exact() -> None: + _, first = run_suite(seed=5, roots=2, budget=4) + _, second = run_suite(seed=5, roots=2, budget=4) + assert first == second diff --git a/tests/unit/test_sgrt_learned.py b/tests/unit/test_sgrt_learned.py new file mode 100644 index 00000000..3f44959b --- /dev/null +++ b/tests/unit/test_sgrt_learned.py @@ -0,0 +1,141 @@ +from __future__ import annotations + +from dataclasses import replace + +import numpy as np +import pytest + +from datagoblin.training_gym.sgrt_holoarc_gym import make_task +from datagoblin.training_gym.sgrt_learned import ( + CANDIDATE_DIM, + EVAL_ARMS, + PUBLIC_EVAL_SEED, + PUBLIC_TRAIN_SEED, + RANK, + TASK_DIM, + TRAINED_ARMS, + LowRankHead, + TrainingItem, + _loss_gradients, + _training_items, + candidate_features, + context_transport, + evaluate, + fit, + paired_contrasts, + ranked_candidates, + task_features, +) + + +def test_observation_contract_ignores_target_and_generator_family() -> None: + task = make_task(seed=PUBLIC_TRAIN_SEED, root=2) + edited = replace(task, target=("id", "id"), family="mixed") + assert task.public() != edited.public() # public metadata includes family + a = task_features(task.public()) + b = task_features(edited.public()) + assert a.shape == b.shape == (TASK_DIM,) + assert np.array_equal(a, b) + candidate = ("xor1", "add1") + assert candidate_features(candidate, task.anchor).shape == (CANDIDATE_DIM,) + for arm in TRAINED_ARMS: + assert np.array_equal( + context_transport(task.public(), arm=arm), + context_transport(edited.public(), arm=arm), + ) + + +def test_geometry_controls_are_orthogonal_and_path_order_sensitive() -> None: + public = make_task(seed=PUBLIC_TRAIN_SEED, root=6).public() + transforms = { + arm: context_transport(public, arm=arm) + for arm in TRAINED_ARMS + } + identity = np.eye(RANK) + assert np.linalg.norm(transforms["flat_lowrank"] - identity) < 1e-10 + assert np.linalg.norm(transforms["holoarc_gear_lowrank"] - identity) > 1e-4 + assert np.linalg.norm( + transforms["holoarc_gear_lowrank"] - transforms["holoarc_step_shuffle_lowrank"] + ) > 1e-5 + for transform in transforms.values(): + assert transform.shape == (RANK, RANK) + assert np.linalg.norm(transform.T @ transform - identity) < 1e-10 + assert np.linalg.det(transform) == pytest.approx(1.0, abs=1e-10) + + +def test_softmax_training_derivative_matches_finite_difference() -> None: + item = _training_items(roots=16, arm="holoarc_gear_lowrank")[0] + head = LowRankHead.initialize(seed=42) + _loss, grads = _loss_gradients(head, item) + params = (head.task_matrix, head.candidate_matrix, head.gate_vector) + eps = 1e-5 + for p, gradient in zip(params, grads, strict=True): + index = (0, 0) if p.ndim == 2 else (0,) + original = float(p[index]) + p[index] = original + eps + high, _ = _loss_gradients(head, item) + p[index] = original - eps + low, _ = _loss_gradients(head, item) + p[index] = original + assert gradient[index] == pytest.approx((high - low) / (2 * eps), abs=1e-6) + + +def test_training_split_excludes_mixed_family() -> None: + for arm in ("semantic_lowrank", "holoarc_gear_lowrank"): + items = _training_items(roots=20, arm=arm) + assert len(items) == 15 + for item in items: + assert isinstance(item, TrainingItem) + assert item.candidates.shape == (18, CANDIDATE_DIM) + assert item.positives.any() + for index in range(20): + if index % 4 == 3: + assert make_task(seed=PUBLIC_TRAIN_SEED, root=index).family == "mixed" + + +def test_learned_heads_share_capacity_and_are_deterministic() -> None: + trained = {} + for arm in TRAINED_ARMS: + head, log = fit(arm=arm, seed=7, train_roots=20, updates=20) + assert log["trainable_parameters"] == TASK_DIM * RANK + CANDIDATE_DIM * RANK + TASK_DIM + assert np.isfinite(log["last32_loss_mean"]) + assert np.all(np.isfinite(head.task_matrix)) + assert np.all(np.isfinite(head.candidate_matrix)) + assert np.all(np.isfinite(head.gate_vector)) + trained[arm] = head + repeat, _ = fit(arm="holoarc_gear_lowrank", seed=7, train_roots=20, updates=20) + assert trained["holoarc_gear_lowrank"].digest() == repeat.digest() + public = make_task(seed=PUBLIC_EVAL_SEED, root=0).public() + candidate_set = ranked_candidates(trained["holoarc_gear_lowrank"], public, arm="holoarc_gear_lowrank", budget=8) + assert len(candidate_set) == len(set(candidate_set)) == 8 + rows, summary = evaluate(trained, eval_roots=8, budget=8) + assert len(rows) == 8 + assert len(summary["family_ood_mixed"]) == len(EVAL_ARMS) + assert summary["family_ood_mixed"]["semantic_lowrank"]["roots"] == 2 + for arm, counts in summary["all"].items(): + assert counts["roots"] == 8 + assert counts["verifier_calls"] == (8 if arm == "rigid_top1_proxy" else 64) + + +def test_root_paired_intervals_and_discordance_are_deterministic() -> None: + rows = [] + for i, (baseline, gear) in enumerate(((0, 1), (1, 0), (1, 1), (0, 0))): + arms = { + name: {"whole_task_solved": bool(baseline)} + for name in TRAINED_ARMS + } + arms["holoarc_gear_lowrank"]["whole_task_solved"] = bool(gear) + rows.append({ + "root_id": f"public-{i}", + "group": "family_ood_mixed" if i >= 2 else "new_roots_seen_families", + "arms": arms, + }) + report = paired_contrasts(rows, replicates=128) + repeated = paired_contrasts(rows, replicates=128) + assert report == repeated + contrast = report["all"]["holoarc_gear_lowrank"] + assert contrast["roots"] == 4 + assert contrast["wins"] == contrast["losses"] == 1 + assert contrast["ties"] == 2 + assert contrast["absolute_effect_pp"] == 0 + assert contrast["root_bootstrap_95_pp"][0] <= 0 <= contrast["root_bootstrap_95_pp"][1] diff --git a/training/sgrt_holoarc_01/LEARNED_PILOT.md b/training/sgrt_holoarc_01/LEARNED_PILOT.md new file mode 100644 index 00000000..6a28b293 --- /dev/null +++ b/training/sgrt_holoarc_01/LEARNED_PILOT.md @@ -0,0 +1,120 @@ +# DG-SGRT-02: learned low-rank HoloArc comparison + +**Status:** CPU-trained public-development study. Add-on to DG-SGRT-01 draft +PR #53. No Aleph 1B weights or current Inky Mini process are changed. + +## Objective and method + +Test whether a task-conditioned HoloArc transport makes a learned candidate +ranking head more effective on executable programs than an equally trained +non-geometric semantic mapper. + +The 4-bit, two-operator program-repair generator is inherited from DG-SGRT-01. +Public tasks carry one erroneous anchor program and four input/output pairs. +A separate evaluator owns the full 16-input target function. Only synthetic +training roots may provide full-domain positive rewrite labels to the trainer. +Learned candidate scores are computed from public task features and +candidate syntax/Fourier features, without executing candidates. + +All five trained arms use the same 16-dimensional bilinear head: + + q = task_features @ A + candidate_latents = candidate_features @ B + gate = sigmoid(task_features @ w) + z = q + gate * (H(task) - I) @ q + score(candidate) = dot(candidate_latents, z) / sqrt(16) + +A, B and w are learned by root-wise Adam, using a multi-positive exact-match +softmax objective; each arm trains the same number of parameters and uses +identical initialization, training-root order, learning rate and optimizer +updates. H(task) is a **frozen** public-task-conditioned transform, chosen +by the arm. The path and connection are not learned in this experiment. +Any learned-model result belongs to the low-rank proposal head plus its +frozen geometric prior. + +## Registered arms + +| Arm | Transport | +|---|---| +| semantic_lowrank | Single task-conditioned direct orthogonal transform, with no circuit | +| flat_lowrank | Closed six-gear trajectory with commuting generators | +| holoarc_gear_lowrank | Closed six-gear trajectory with noncommuting generators | +| holoarc_random_path_lowrank | Smooth random closed Fourier path matched for sampled arc length | +| holoarc_step_shuffle_lowrank | Same gear edge-step multiset in a shuffled order, still closed | + +The earlier rigid, heuristic and repeated-edit proxies are included in the +evaluation but are marked as untrained comparators. All trained arms score the +same 18 possible edits and pass the eight highest-ranked distinct candidates +to an independently owned exact demonstration checker. The full-domain +evaluator then scores canonical selected survivors for real program +equivalence; merely selecting a demonstration-consistent candidate is +insufficient. + +The gear, random and shuffled paths use the same registered radius multiplier +(3.0) and eight microsteps. Transport fiber has dimension 16, while the +parameter base has dimension 12. + +## Public-development split + +Training seed 31001 covers roots of arithmetic, bitwise and structural +families; mixed is withheld at every step. Evaluation seed 61001 produces +fresh roots across all four families. The report separates mixed-family +out-of-distribution items from new roots belonging to seen families. + +Defaults: +- 128 generated training roots; 96 retained by the family split. +- 384 Adam updates per arm, with learning rate 0.025 and one root per update. +- 64 evaluated roots, of which 16 belong to the withheld mixed family. +- 8 candidate evaluations per trained arm and non-rigid control. +- Seed 23 controls paired initialization and optimizer ordering. + +This is exploratory **public** development. The program DSL, seeds and +family generator are transparent. They cannot establish sealed generalization +or confirm a gain on authentic research/creative tasks. + +## Run and verify + + python -m pytest tests/unit/test_sgrt_learned.py tests/unit/test_sgrt_holoarc.py -q + ruff check src/datagoblin/training_gym/sgrt_learned.py tests/unit/test_sgrt_learned.py + python -m datagoblin.training_gym.sgrt_learned --seed 23 --train-roots 128 --updates 384 --eval-roots 64 --budget 8 --out runs/dg-sgrt-02-public + +The separate CI workflow executes the public development run and attaches +its report and individual evaluation scores. Local output directories +must start absent or empty; model weights exist only in process memory, and +their SHA-256 digest appears in report metadata. No network requests, +external teachers or GPU are needed. + +## Result interpretation + +Primary development metric: independently checked whole-task success at +the same candidate-check budget. Record target-reachable candidate sets, +full-domain exact solves, checks per root and per solve, task-family grouping, +and paired per-root deltas. The order-shuffled edge path is a mechanism +control; a benefit over the semantic mapper and smooth-random path would +justify a new confirmation plan. An apparent advantage over a commuting +flat path alone is insufficient to claim geometric utility. + +The baseline's task transform is a single learned-gated direct rotation and +shares the same head parameter count. The geometric arms may have greater +computation cost, which a later end-to-end trained-Aleph experiment must +measure and match. This pilot does not itself equalize wall-clock or +floating-point operations across arms. + +A genuine adaptive path-order claim needs an online policy receiving feedback +between visits. This benchmark ranks a fixed pool once, after an excursion. +Retain all negative and null outcomes, including a possibility that task +labels do not support any useful HoloArc benefit. + +## Promotion boundary + +After development, freeze the rank, gates, a true trainable task-conditioned +connection, regularization, total model FLOPs, independent families, and +experiment seeds. Compare with task-trained semantic and capacity-matched +non-geometric controls from shared optimizer initialization. Keep all +evaluation labels with a separate scorer. Run the first real model experiment +with a frozen host and a single low-rank boundary sidecar, before any Aleph +operator swap. + +The extant Inky Mini llama.cpp server remains outside this public CPU study; +an authorized live experiment must reuse it without restart or paid fallback, +with 12k default and 16k hard context constraints. diff --git a/training/sgrt_holoarc_01/PREREG.md b/training/sgrt_holoarc_01/PREREG.md new file mode 100644 index 00000000..7facee2d --- /dev/null +++ b/training/sgrt_holoarc_01/PREREG.md @@ -0,0 +1,87 @@ +# DG-SGRT-01 preregistration boundary + +**Status:** prospective design and public smoke gates only. Confirmatory training +protocol not frozen; no held-out results may be interpreted as a successful +model experiment before a new frozen protocol and independently held seed. + +## Claims under test + +1. **Geometry fidelity:** a 12D multi-gear base loop closes; a flat 16D + connection has identity Wilson transport; a planted noncommuting connection + has nonzero loop holonomy, determinant +1, low orthogonality drift, and + a gauge-invariant trace/eigenangle spectrum. +2. **Verifier fidelity:** the public demonstrations are matched exactly, + target information stays outside all proposer calls, and evaluator-only + full-domain scoring distinguishes generalizing solutions from demonstration + overfit. Same-set shuffle must preserve candidate-set SHA and canonical + full-task success. +3. **Candidate coverage (exploratory):** compare curved excursions against + flat, smooth random, fixed semantic heuristic, repeated edit and rigid + top-1 under the same root and checker budget. All current policies are + deterministic proxies; this stage tests plumbing. +4. **Learned effect (future only):** a task-conditioned low-rank sidecar + improves independently verified whole-task success over the best learned + non-geometric and extra-refinement baselines at equal wall-time/compute + and candidate budgets on family-level holdouts. +5. **Path-order effect (future only):** a separately registered adaptive + task with decisions between visits is needed to attribute performance to + itinerary history. Fixed-candidate-set canonical selection is deliberately + invariant under any permutation. + +## Public development design + +- Four task families with separate grouped root IDs. +- Two-operation 4-bit typed DSL; exact interpreter and 16-input oracle. +- One deliberately corrupted starting program per root; four public examples. +- Default seed 23, 8 roots, 8 candidate checks per non-rigid policy. +- Fixed 12D base and 16D fiber; eight transport microsteps per circuit. +- Root count hard-capped at 128, proposal count at 16. No model downloads, + server calls, GPUs, asynchronous jobs or paid compute. +- Preserve public inputs separately from evaluator scores. Generated output + belongs in ignored local runs and is not a training label without a new + admission decision. + +## Controls and estimands + +- Geometry: flat identity loss and curved identity loss; orthogonality, + closure and covector pairing errors. Nontrivial curved holonomy alone is + a mathematical construction, not task competence. +- Verifier: chosen candidate success over all 16 inputs, any-target-reachable + candidate coverage, first-valid visit, calls per root and checks per + verified success. Count zero-solve arms explicitly. +- Matched arms: compare all non-rigid controls at eight candidate checks; + report rigid top-1 separately with its one actual call. +- Exact-set shuffle: mandatory identical candidate-set hashes, identical + canonical success under the complete-checker protocol. Differences in + first-hit positions are a diagnostic, not a solve-rate advantage. +- Costs: actual process time, resident memory and invoked model tokens are + required for a trained or externally connected pilot. Toy Python loops + do not stand in for 1B recurrent block compute. + +## New confirmation registration required before training + +Freeze independent train/development/sealed family and operator-pair splits, +source/repo and scorer hashes, the proposer/adapter parameter count, random +initialization, task prompts, recurrence budget, how task-condition signals +enter the gear and connection, learning schedule, budget and halt semantics, +verifier identity, effect threshold and power analysis. Record all losses, +including nulls. For a model-architecture claim, compare from matched +optimizer snapshots with and without the low-rank sidecar. + +Use independent task-root clustered uncertainty estimates, with multiplicity +handling when evaluating several learned variants. Define the minimum gain +from development variance before touching sealed labels. A positive +geometry effect is a prerequisite for mechanistic interpretation, not a +replacement for verified task gain. + +## Safety and interoperability + +- Keep the independent verifier in control of acceptance and simulator moves. +- A proposer may generate candidates but receives no hidden target, oracle + action, heldout continuation, or evaluator-derived utility while selecting. +- Do not route this pilot to the running local Inky Mini server. A future + optional adapter can use the existing server with a 12k default context, + a 16k hard maximum, pinned endpoint revision/quant/tokenizer/sampler, + and zero paid fallback. +- Keep Aleph 1B architecture changes behind separate matched checkpoints; + the current sidecar is CPU mathematics and a program-repair fixture. diff --git a/training/sgrt_holoarc_01/README.md b/training/sgrt_holoarc_01/README.md new file mode 100644 index 00000000..28fd3788 --- /dev/null +++ b/training/sgrt_holoarc_01/README.md @@ -0,0 +1,57 @@ +# DG-SGRT-01 | HoloArc exploratory recurrent sidecar + +**Status:** CPU-only synthetic wiring experiment; no learned model, downstream creative benefit, or confirmatory advantage is claimed. Staged 2026-11-23. + +**Repository baseline:** DataGoblin master at a1646c0318df6942db6c58bc78da4084599df7d6. + +This isolates a possible **one-operator sidecar** for Data Goblin Aleph's four-operator recurrent graph. Aleph's published plan retains four distinct operators, seven tied blocks per operator, a 4x4 message router, two synchronous rounds, and an independently owned verifier. DG-SGRT-01 changes none of the model weights, router, or pretraining schedule. The optional host adapter would receive a bounded residual after a registered recurrent boundary. + +## Original sources and boundaries + +- [Spiroscopic Recursive Transformers, August 2026](https://github.com/MoralityLabAI/morality-lab-site/blob/main/papers/Spiroscopic_Recursive_Transformers.md) reported 47/64 versus 35/64 exact synthetic ARC-like solves for learned neighborhood expansion against its strongest matched residual search. Its same-set order shuffle tied at 47/64; the underlying checkpoint and rows are unavailable after the documented filesystem recovery. Do not treat this historical result as a reproduced model finding. +- [Original SGRT appendix](https://github.com/MoralityLabAI/jinn-or-beast-paper/blob/main/experiments/model_selected_scaffold_mesh_v3/appendix_constitutional_ideology_srt/SRT_PROTOCOL.md) distinguished rolling-gear SGRT from the earlier polar-spiral SRT. Its proposed itinerary was G[5:2:0.8]^12.G[7:3:0.65]^12.S.C^6; the registered SGRT arm remained design-bound. +- [RSI-Topology holonomy construction](https://github.com/MoralityLabAI/RSITopology/blob/main/reports/monitor_holonomy_insight.md) demonstrates path-dependent transport in a planted Grassmannian synthetic setting, including determinant and gauge-invariant loop diagnostics. DG-SGRT-01 independently implements small, explicit plane rotations; these sources are references, not model weights or licensed code imports. + +## Mechanism + +The base coordinate has dimension 12: six independent 2-planes use rational hypotrochoid gears with independently seeded phases, scale and eccentricity. All paths make an exact closed return after eight microsteps. A matched smooth random Fourier path has the same total sampled arc length. + +A 16-dimensional fiber carries a feature vector and its dual. Per-step transport is an ordered product of exact plane rotations, with Q = product_i R_{a_i,b_i}(1.6 * delta_u_i). In the flat control, all generators commute. Curved mode uses overlapping rotation planes, so the ordered product over a closed base path may produce H != I. The computed receipts include path closure, orthogonality error, det(H), 1-tr(H)/16, absolute eigenphases, and the maximum absolute drift of c^T v. A constant orthogonal frame change must conjugate H and leave the registered trace and determinant unchanged. + +The transport remains a **fixed mathematical construction**. The proposed future learned version would condition amplitudes, gear phases, connection generators, and a low-rank output map on the research task. Its host interface is the bounded residual: + + state' = state + gate * project((H-I) * lift(state)) + +with gate in [0,1]. A proper trained adapter needs a matched identity bridge, a learned non-geometric bridge, a direct TRM continuation, and gradient/access parity. No existing Aleph block has been replaced. + +## Exact offline program-repair gym + +The toy world has four-bit states and a two-operation program. Operators include xor, modular addition, bit rotation, bit swap, mask and set-bit. A synthetic hidden program supplies four public input-output demonstrations and a first guess with one altered operator. + +Each target-blind policy receives the same first guess, demonstrations, and root identifier, then proposes at most eight distinct, legal one-step rewrites. The exact checker tests all public demonstrations. An evaluator-only full 16-state truth table determines whether the canonical selected survivor is semantically equivalent to the hidden target. Scoring all candidates and choosing a canonical survivor makes equal-set shuffles a strict final-solve negative control, while first-valid visit index still measures ordering. + +**Arms:** rigid top-1, fixed semantic heuristic, repeated-edit proxy, flat HoloArc, curved HoloArc, same-set phase shuffle, and matched-length smooth random arc. All arms except rigid top-1 use the same verifier-call budget. The semantic coordinate is a fixed Fourier chart, **not** a learned representation. The two proxy arms are **not** pretrained TRMs. + +### Reproduce the public smoke run + + python -m pip install -e ".[dev]" + python -m pytest tests/unit/test_sgrt_holoarc.py -q + ruff check src/datagoblin/training_gym/sgrt_holoarc.py src/datagoblin/training_gym/sgrt_holoarc_gym.py tests/unit/test_sgrt_holoarc.py + python -m datagoblin.training_gym.sgrt_holoarc_gym --seed 23 --roots 8 --budget 8 --out runs/dg-sgrt-01-public-smoke + +Output paths must be new or empty. Maximum local limits are 128 roots, 16 candidates per policy, and eight small 16x16 transport steps; there are no LLM requests, downloads, GPU operations, background workers, or paid-provider calls. Files are written only to the requested local output folder. + +Outputs: +- public_tasks.jsonl: visible predecision program/demonstration packets. +- evaluator_scores.jsonl: target-bearing evaluator results, proposal hashes, full-domain pass results, visit indices and geometry receipts; custody-limited. +- report.json: root counts, exact solves, oracle-reachable candidates, per-arm verifier calls and hashes of both streams. + +The public seed and toy generator test that the code is reproducible. **They are engineering checks and are never a sealed claim.** For real confirmation, generate independent targets and keep the seed key and target tables outside the proposer process and version control. + +## Next scientific decision + +Follow [PREREG.md](PREREG.md) before a trained-model test. First validate the planted flat/curved loop invariants and the exact checker. Train a small task-conditioned low-rank proposal map only on training roots. Freeze the policy, candidate budget and full program-DSL/generator lineage for withheld families. Report candidate-set coverage, canonical exact solves, full-task generalization, checks per solve, first-valid position, loop diagnostics, root-clustered confidence intervals and actual CPU/GPU time. + +An order-sensitive holonomy claim requires an intervention on itinerary order that preserves the candidate multiset, checker access, and evaluation budget. A geometry-specific model claim requires gains beyond a matched learned semantic sampler and a same-capacity nongeometric adapter. Both can fail while the verifier-backed generator remains useful. + +The running local Inky Mini endpoint is explicitly outside this CPU pilot. If a later rollout uses it, preserve the existing server, pin revision/quant/tokenizer/sampler settings, and use 12k context by default with 16k hard max. diff --git a/training/sgrt_holoarc_01/REPLICATION.md b/training/sgrt_holoarc_01/REPLICATION.md new file mode 100644 index 00000000..df5b5ad2 --- /dev/null +++ b/training/sgrt_holoarc_01/REPLICATION.md @@ -0,0 +1,57 @@ +# DG-SGRT-02R: exploratory independent-seed replication + +**Frozen before the replication runs:** 2026-11-23. This follows the +first public-development evaluation on optimization seed 23 and evaluation +seed 61001. Results are exploratory and cannot be described as sealed +confirmation. The initial five-arm scoring design and all architecture +weights remain as in DG-SGRT-02. + +## Motivation and declared seeds + +The first run had 46/64 exact solves for the semantic low-rank control, +44/64 for original curved gear HoloArc, 45/64 for flat transport, +44/64 for smooth random arcs and 50/64 for shuffled gear edges. The 50/64 +descriptive maximum motivated this follow-up; it is a selection on a +public-development outcome. An independent confirmation would need a +further external evaluator and a fresh registration. + +Prospectively run exactly three additional paired matrices: + +| Matrix | Optimizer initialization/order seed | Fresh evaluation seed | +|---|---:|---:| +| R1 | 41 | 61011 | +| R2 | 67 | 61013 | +| R3 | 89 | 61017 | + +Each matrix trains on the same 96 training roots (train seed 31001), +uses 384 steps/arm at fixed learning rate 0.025 and compares the five +learned arms and the three untrained controls. Every learned arm receives +8 proposed candidate checks on each of 64 fresh roots, with a separate +16-root mixed-family OOD stratum. Independent evaluation root IDs differ +across R1/R2/R3 and from the first public run. + +## Primary descriptive comparisons + +- Whole-task exact solves with canonical demo-consistent selection. +- Root-paired difference in exact solves (percentage points) for each + arm versus semantic_lowrank, with percentile 95% bootstrap over + independent evaluation roots and counts of per-root wins/losses/ties. +- Report family-OOD and seen-family fresh-root strata separately. +- Keep target-reachable coverage distinct from canonical whole-task + success and record verifier calls at the same eight-candidate budget. +- Report every seed and its pooled counts; avoid winner selection by + post-hoc seed averages. + +If shuffled-step still exceeds the semantic baseline in all three runs, +register a *new* matched candidate-set and online path-history test. +If it loses or varies sharply, retain the mechanism null and focus on +learned semantic neighborhoods plus exact verification. + +## Reproduce + + python -m datagoblin.training_gym.sgrt_learned --seed 41 --eval-seed 61011 --train-roots 128 --updates 384 --eval-roots 64 --budget 8 --out runs/dg-sgrt-02-repl-41 + +Use corresponding seed and output pairs for 67/61013 and 89/61017. +The GitHub Actions replication workflow emits the per-seed summaries and +root-level, scorer-owned outputs as short-lived artifacts. No GPU or +external language-model endpoints are involved. diff --git a/training/sgrt_holoarc_01/RESULTS.md b/training/sgrt_holoarc_01/RESULTS.md new file mode 100644 index 00000000..c06f54f2 --- /dev/null +++ b/training/sgrt_holoarc_01/RESULTS.md @@ -0,0 +1,108 @@ +# DG-SGRT-02 and 02R: learned low-rank development results + +Date: 2026-11-23. Repository: MoralityLabAI/DataGoblin, PR #53. +Status: completed public synthetic CPU development, with an exploratory +three-seed follow-up. **Architecture promotion: HOLD.** + +## What was trained + +Five equal-capacity 2,197-parameter low-rank proposal heads trained on +96 public synthetic roots in arithmetic, bitwise and structural families. +The mixed-composition family was held out of fitting. Each head used 384 +root-wise Adam updates, identical optimizer initialization/order within +each seed and identical candidate / checker budgets. The task-dependent +holonomy geometry was fixed; only the projections and residual gate +received gradients. Every learned arm presented eight distinct candidates +per 4-bit two-operation program-repair task to the same demonstration +checker; exact success required full 16-input semantic equivalence after +canonical selection. The underlying 1B Aleph model was not modified. + +## Public initial pilot + +GitHub Actions: https://github.com/MoralityLabAI/DataGoblin/actions/runs/45073156589 + +Optimizer seed 23; public evaluation seed 61001; 64 fresh roots, including +16 from mixed-family OOD. + +| Arm | Whole-task solved / 64 | Mixed family / 16 | Candidate checker calls | +|---|---:|---:|---:| +| semantic_lowrank | 46 | 9 | 512 | +| flat_lowrank | 45 | 12 | 512 | +| holoarc_gear_lowrank | 44 | 7 | 512 | +| holoarc_random_path_lowrank | 44 | 9 | 512 | +| holoarc_step_shuffle_lowrank | 50 | 10 | 512 | + +The shuffled-step maximum was a public-development selection. The candidate +sets changed between learned arms, and the original closed-curve ordering +showed no advantage over semantic_lowrank. + +## Declared exploratory seed replication + +Registry: [REPLICATION.md](REPLICATION.md). Frozen seed pairs before run. +GitHub Actions: https://github.com/MoralityLabAI/DataGoblin/actions/runs/45073354861 + +| Learned arm | 41 / eval 61011 | 67 / eval 61013 | 89 / eval 61017 | Pooled / 192 | +|---|---:|---:|---:|---:| +| semantic_lowrank | 49 | 49 | 40 | **138** | +| flat_lowrank | 49 | 45 | 40 | 134 | +| holoarc_gear_lowrank | 50 | 45 | 37 | 132 | +| holoarc_random_path_lowrank | 42 | 39 | 39 | 120 | +| holoarc_step_shuffle_lowrank | 43 | 44 | 40 | 127 | + +All numbers are full-domain exact solves out of 64 in each column, +with eight proposed checker calls per root. The three evaluation seeds +produce 192 distinct root IDs. The corresponding pooled mixed-family +OOD totals are: + +| Arm | Exact mixed OOD / 48 | +|---|---:| +| semantic_lowrank | 20 | +| flat_lowrank | 20 | +| holoarc_gear_lowrank | 21 | +| holoarc_random_path_lowrank | 22 | +| holoarc_step_shuffle_lowrank | 21 | + +The source workflow emits per-seed root-paired bootstrap intervals and +win/loss/tie counts versus semantic_lowrank, alongside JSONL-level +results and short-lived runner artifacts. + +### Interpretation + +The first-run shuffled-step lead did not persist: it trailed the +semantic scorer on the next two seeds and tied it on the third. +The primary gear arm solved 132/192 compared with 138/192 for +semantic_lowrank. Over the three declared replication runs the semantic +low-rank control had the highest total. + +The synthetic families remain narrow and structurally related. The +geometry is a frozen task-conditioned transform, not a trained connection. +An eight-step circuit with fixed candidate ranking cannot measure online +reasoning that adapts after each observed outcome. Step reordering also +changes the learned candidate sets; an advantage from such a contrast +would not isolate the causal effect of visit order independently of +candidate coverage. + +The experiment tests whether a fixed geometric prior helps a small +proposal ranker in a verifier-backed setting. It supplies no positive +evidence for integrating HoloArc into the 1B Aleph architecture. All +results, including failed and null contrasts, should be retained. + +## Next prospective test + +Develop DG-SGRT-03 only after its separate protocol is frozen: + +- Build a genuine sequential task where independent feedback arrives + between proposal visits, with task/state snapshots and typed verifier + receipts. +- Preserve the same *multiset* of available candidate rewrites for all + policies. Cross visit order with final candidate set so coverage and + chronology are independently identified. +- Use real task-conditioned learned transport and an equally expressive, + nongeometric learned recurrence. Match recurrent calls, checker calls, + training data, parameter count and wall-clock cost. +- Group evaluation by independent storyworld program family. Measure + verified discoveries, revision success after evidence changes, and + abstention as well as holistic task completion. + +The current best working baseline for this proxy remains a learned +semantic neighborhood followed by exact verification. diff --git a/training/sgrt_holoarc_01/skills/dg_sgrt_holoarc/SKILL.md b/training/sgrt_holoarc_01/skills/dg_sgrt_holoarc/SKILL.md new file mode 100644 index 00000000..03ad0629 --- /dev/null +++ b/training/sgrt_holoarc_01/skills/dg_sgrt_holoarc/SKILL.md @@ -0,0 +1,60 @@ +--- +name: dg-sgrt-holoarc +description: Explore task-conditioned low-rank parameter arcs using bounded holonomy and exact verification. +--- + +# DG-SGRT-01 | Holonomy exploration skill + +## Allowed scope + +Work only in MoralityLabAI/DataGoblin. Read the recovered SRT paper, SGRT +protocol, and RSI-Topology holonomy report as historical references. +Keep this experiment isolated under training/sgrt_holoarc_01 and the two +sgrt_holoarc training_gym modules. Preserve the four-operator Aleph design, +all existing weights and local model services. + +## First pass + +1. Pin the exact DataGoblin source revision and test/symbol versions. +2. Execute the geometry unit tests and the small public smoke only. +3. Check path closure, determinant, orthogonality, gauge covariance and + dual pairing. Distinguish zero curvature from high curvature. +4. Compare all seven policy arms on identical public tasks; all non-rigid + arms use equal candidate and verifier budgets. +5. Check the exact-set phase shuffle checksum and canonical solve parity. +6. Report first-hit differences separately from candidate-set coverage. +7. Retain malformed cases and failed verifications, including roots with no + valid candidate. + +## When extending toward a learned sidecar + +- Replace fixed Fourier program coordinates with a task-conditioned, + low-rank learned chart trained only on admitted training roots. +- Keep the connection and rank capacity matched to a nongeometric bridge. +- Condition gear frequency/amplitude/phase only on public task context. +- Pass proposals through the environment-owned verifier, preserving + pre-verification predictions and post-verification results. +- Freeze a prospective family-level split and minimum gain before sealed + evaluation. Prevent seed, target and oracle table access in proposer code. +- If holonomy is nonzero but success is unchanged, retain the null. + If flat and curved candidate sets differ, compare against the stronger + coverage baseline before attributing any value to path order. +- Promote a single recurrent boundary only after matched tests; do not + replace an entire Aleph operator during the first pilot. + +## Machine and billing boundary + +CPU smoke only, no provider keys, hidden weights, unapproved downloads, paid +fallback, new background worker, or GPU use. Do not stop, restart or displace +a running llama.cpp/Inky Mini service. If an authorized later pilot uses +that server, pin the live model revision, quant, tokenizer and sampling config, +reuse the existing endpoint, default to 12k context, hard-cap at 16k, +and log real token and inference costs. + +## Evidence contract + +A successful experiment provides code revision, protocol revision, root +and family manifests, exact replay, all policy outcomes, verifier calls, +wall time, memory headroom, and a confidence interval over independent +lineages. Report implementation, synthetic mechanism and learned task results +as separate evidence classes. Document every failed gate.