diff --git a/.github/workflows/dg-sgrt-history.yml b/.github/workflows/dg-sgrt-history.yml new file mode 100644 index 00000000..2378e344 --- /dev/null +++ b/.github/workflows/dg-sgrt-history.yml @@ -0,0 +1,75 @@ +name: DG-SGRT-03 sequential history development + +on: + pull_request: + paths: + - "src/datagoblin/training_gym/sgrt_history.py" + - "src/datagoblin/training_gym/sgrt_holoarc.py" + - "src/datagoblin/training_gym/sgrt_holoarc_gym.py" + - "tests/unit/test_sgrt_history.py" + - "training/sgrt_holoarc_03/**" + - ".github/workflows/dg-sgrt-history.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + sequential-history: + 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_history.py tests/unit/test_sgrt_holoarc.py tests/unit/test_sgrt_learned.py -q + - run: ruff check src/datagoblin/training_gym/sgrt_history.py tests/unit/test_sgrt_history.py + - name: Matched public synthetic world-history experiment + run: | + python -m datagoblin.training_gym.sgrt_history \ + --seed 23 --updates 384 --train-per-family 24 \ + --eval-per-family 12 --out runs/dg-sgrt-03-public + - name: Independent custody, geometry and budget receipts + run: | + python - <<'PY' + import json + from pathlib import Path + + root = Path("runs/dg-sgrt-03-public") + summary = json.loads((root / "report.json").read_text()) + assert summary["status"] == "synthetic_cpu_development_only" + assert summary["train_root_count"] == 72 + assert summary["eval_root_count"] == 48 + assert {v["trainable_parameters"] for v in summary["training"].values()} == {937} + g = summary["geometry"] + assert g["flat_commutator_fro_max"] < 1e-9 + assert g["curved_commutator_fro_max"] > 1e-5 + assert g["flat_curved_trace_mismatch_max"] < 1e-8 + scores = summary["scores"]["all"] + assert scores["exact_oracle"]["both_orders_correct"] == 48 + assert scores["bag"]["both_orders_correct"] == 0 + assert all(v["verifier_calls"] == 192 for v in scores.values()) + public = [json.loads(x) for x in (root / "public_eval.jsonl").read_text().splitlines()] + scored = [json.loads(x) for x in (root / "scorer_only.jsonl").read_text().splitlines()] + assert len(public) == 96 and len(scored) == 48 + assert all("truth" not in r and "target" not in r for r in public) + assert all(r["evaluator_only"] for r in scored) + hashes = { + a["candidate_pool_sha256"] + for row in scored for a in row["arms"].values() + } + assert len(hashes) == 1 + print("DG-SGRT-03 registered checks passed") + for arm, result in scores.items(): + print(arm, "both-order", result["both_orders_correct"], "/48", + "final", result["last_correct"], "/96", + "first", result["first_correct"], "/96") + print("paired effects:", summary["paired_vs_direct"]) + PY + - uses: actions/upload-artifact@v4 + with: + name: dg-sgrt-03-public-history-development + path: runs/dg-sgrt-03-public/ + retention-days: 14 diff --git a/src/datagoblin/training_gym/sgrt_history.py b/src/datagoblin/training_gym/sgrt_history.py new file mode 100644 index 00000000..4461034f --- /dev/null +++ b/src/datagoblin/training_gym/sgrt_history.py @@ -0,0 +1,549 @@ +"""DG-SGRT-03: sequential storyworld evidence and holonomy-history CPU pilot. + +Each root has two episodes containing the identical events in opposite order. +The trusted simulator owns expected states. Models only receive the initial +public state and one event at a time. All models choose from the same 16 +candidate outcomes, with one exact verifier check after each event. + +This is synthetic mechanism development, not a trained Aleph integration. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from dataclasses import dataclass +from functools import cache +from pathlib import Path +from typing import Any, Literal + +import numpy as np + +from .sgrt_holoarc import BASE_DIM, FIBER_DIM, spiro_path, trace_transport +from .sgrt_holoarc_gym import apply_operator + +EVENTS = ("xor1", "xor2", "xor4", "add1", "add3", "rol1", "swap01", "mask7", "or8") +EVENT_STORY = { + "xor1": "courier reverses the witness flag", + "xor2": "council swaps the registry parity", + "xor4": "archive inverts the signal lamp", + "add1": "clock advances the public state", + "add3": "festival advances three calendar ticks", + "rol1": "messenger rotates the four seals", + "swap01": "scribe exchanges two witness seals", + "mask7": "archive seals the highest register", + "or8": "archive opens the highest register", +} +FAMILIES = ("courier", "council", "archive", "heldout_mixed") +TRAINED = ("bag", "direct", "flat", "curved", "random") +EVALUATED = (*TRAINED, "curved_transport_swap", "exact_oracle") +D = FIBER_DIM +CHOICES = tuple(range(16)) +BATCH_SEED = 31003 +EVAL_SEED = 61003 + + +def _canonical(value: Any) -> bytes: + return json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + + +def _digest(value: Any) -> str: + return hashlib.sha256(_canonical(value)).hexdigest() + + +def _world_key(state: int, a: str, b: str) -> str: + return f"{state}|{a}|{b}" + + +def _is_train_lineage(state: int, a: str, b: str) -> bool: + # Same unordered event pair and starting state can never enter both splits. + share = int(hashlib.sha256(_world_key(state, a, b).encode()).hexdigest()[:8], 16) / (2**32) + return share < 0.60 + + +@dataclass(frozen=True) +class PublicEpisode: + root_id: str + family: str + initial_state: int + events: tuple[str, str] + candidate_states: tuple[int, ...] = CHOICES + + def public(self) -> dict[str, Any]: + return { + "schema_version": "dg-sgrt-03-public-episode-v1", + "root_id": self.root_id, + "family": self.family, + "initial_state": self.initial_state, + "event_stream": [ + {"step": idx + 1, "type": "fictional_rule_update", "event": event, "description": EVENT_STORY[event]} + for idx, event in enumerate(self.events) + ], + "candidate_states": list(self.candidate_states), + } + + +@dataclass(frozen=True) +class WorldRoot: + root_id: str + family: str + initial_state: int + event_a: str + event_b: str + + def episode(self, reverse: bool = False) -> PublicEpisode: + events = (self.event_b, self.event_a) if reverse else (self.event_a, self.event_b) + return PublicEpisode(self.root_id, self.family, self.initial_state, events) + + def truth(self, reverse: bool = False) -> tuple[int, int]: + """Evaluator only. The two exact intermediate states are private labels.""" + ep = self.episode(reverse) + first = apply_operator(ep.events[0], ep.initial_state) + second = apply_operator(ep.events[1], first) + return first, second + + +def make_roots(*, split: Literal["train", "eval"], seed: int, per_family: int) -> tuple[WorldRoot, ...]: + """Deterministic family/lineage-disjoint, noncommuting two-event world pairs.""" + if split not in ("train", "eval") or not 1 <= per_family <= 24: + raise ValueError("split must be train/eval and per_family 1..24") + families = range(3) if split == "train" else range(4) + roots: list[WorldRoot] = [] + for family in families: + eligible = [] + for i, a in enumerate(EVENTS): + for j in range(i + 1, len(EVENTS)): + b = EVENTS[j] + if (i + j) % 4 != family: + continue + for state in CHOICES: + direct = apply_operator(b, apply_operator(a, state)) + reversed_outcome = apply_operator(a, apply_operator(b, state)) + if direct == reversed_outcome: + continue + training = _is_train_lineage(state, a, b) + if family != 3 and (training != (split == "train")): + continue + eligible.append((state, a, b)) + rng = np.random.default_rng(seed + 1213 * family) + order = rng.permutation(len(eligible)) + if per_family > len(eligible): + raise ValueError(f"family {family} only has {len(eligible)} roots in {split}") + for pos in order[:per_family]: + state, a, b = eligible[int(pos)] + root_id = _digest({"state": state, "a": a, "b": b})[:20] + roots.append(WorldRoot(root_id, FAMILIES[family], state, a, b)) + if len({r.root_id for r in roots}) != len(roots): + raise AssertionError("root collision") + return tuple(roots) + + +def _rotation(angles: list[float]) -> np.ndarray: + out = np.eye(D, dtype=np.float64) + for i, angle in enumerate(angles): + a, b = 2 * i, 2 * i + 1 + co, si = math.cos(angle), math.sin(angle) + out[a, a] = co + out[a, b] = -si + out[b, a] = si + out[b, b] = co + return out + + +@cache +def event_transport(mode: str, op: str) -> np.ndarray: + """Spectrally matched flat, curved and random orthogonal connections.""" + if mode not in TRAINED or op not in EVENTS: + raise ValueError("unknown mode or event") + if mode in ("bag", "direct"): + return np.eye(D, dtype=np.float64) + ix = EVENTS.index(op) + path = 3.0 * spiro_path(np.zeros(BASE_DIM), seed=901 + 97 * ix) + curved = trace_transport(path, mode="curved").holonomy + if mode == "curved": + return curved + phases = np.angle(np.linalg.eigvals(curved)) + positive = sorted(float(v) for v in phases if v > 1e-9) + positive = (positive + [0.0] * (D // 2))[: D // 2] + flat = _rotation(positive) + if mode == "flat": + return flat + rng = np.random.default_rng(3047 + 97 * ix) + orthogonal, _ = np.linalg.qr(rng.standard_normal((D, D))) + return orthogonal @ flat @ orthogonal.T + + +def transport_diagnostics() -> dict[str, Any]: + identity = np.eye(D, dtype=np.float64) + commute_flat = 0.0 + commute_curved = 0.0 + max_spec = 0.0 + max_orthogonal = 0.0 + for a in EVENTS: + curved = event_transport("curved", a) + flat = event_transport("flat", a) + max_spec = max(max_spec, abs(float(np.trace(curved - flat)))) + for mode in ("curved", "flat", "random"): + q = event_transport(mode, a) + max_orthogonal = max(max_orthogonal, float(np.linalg.norm(q.T @ q - identity))) + for b in EVENTS: + f2 = event_transport("flat", b) + c2 = event_transport("curved", b) + commute_flat = max(commute_flat, float(np.linalg.norm(flat @ f2 - f2 @ flat))) + commute_curved = max(commute_curved, float(np.linalg.norm(curved @ c2 - c2 @ curved))) + return { + "flat_commutator_fro_max": commute_flat, + "curved_commutator_fro_max": commute_curved, + "flat_curved_trace_mismatch_max": max_spec, + "orthogonality_error_max": max_orthogonal, + "event_count": len(EVENTS), + "fiber_dim": D, + "gear_base_dim": BASE_DIM, + "gear_microsteps": 8, + } + + +@dataclass +class HistoryHead: + initial: np.ndarray + recurrent: np.ndarray + evidence: np.ndarray + output: np.ndarray + bias: np.ndarray + gates: np.ndarray + + @classmethod + def initialize(cls, seed: int) -> HistoryHead: + rng = np.random.default_rng(seed) + return cls( + rng.normal(0, 0.14, (16, D)), + 0.32 * np.eye(D) + rng.normal(0, 0.04, (D, D)), + rng.normal(0, 0.12, (len(EVENTS), D)), + rng.normal(0, 0.11, (D, 16)), + np.zeros(16, dtype=np.float64), + np.full(len(EVENTS), -0.6, dtype=np.float64), + ) + + @property + def weights(self) -> tuple[np.ndarray, ...]: + return self.initial, self.recurrent, self.evidence, self.output, self.bias, self.gates + + @property + def parameter_count(self) -> int: + return sum(v.size for v in self.weights) + + def digest(self) -> str: + sha = hashlib.sha256() + for v in self.weights: + sha.update(v.astype(" tuple[float, np.ndarray]: + shifted = logits - logits.max() + exponent = np.exp(shifted) + probs = exponent / exponent.sum() + loss = float(np.log(exponent.sum()) - shifted[target]) + probs[target] -= 1.0 + return loss, probs + + +def forward( + head: HistoryHead, + ep: PublicEpisode, + *, + mode: str, + swap_transport: bool = False, +) -> tuple[tuple[np.ndarray, np.ndarray], list[dict[str, Any]], np.ndarray]: + """Public-only forward, with retained states for the CPU training derivative.""" + h0 = np.tanh(head.initial[ep.initial_state]) + events = tuple(EVENTS.index(e) for e in ep.events) + records: list[dict[str, Any]] = [] + if mode == "bag": + first = np.tanh(h0 @ head.recurrent + head.evidence[events[0]]) + last = np.tanh(h0 @ head.recurrent + head.evidence[events[0]] + head.evidence[events[1]]) + logits = (first @ head.output + head.bias, last @ head.output + head.bias) + return logits, [ + {"prev": h0, "h": first, "event": events[0]}, + {"prev": h0, "h": last, "event": events[1]}, + ], h0 + state = h0 + for t, event_id in enumerate(events): + transport_id = events[1 - t] if swap_transport else event_id + matrix = event_transport(mode, EVENTS[transport_id]) + gate = float(1.0 / (1.0 + math.exp(-float(np.clip(head.gates[event_id], -30, 30))))) + difference = (matrix - np.eye(D)) @ state + updated = np.tanh(state @ head.recurrent + head.evidence[event_id] + gate * difference) + records.append({ + "prev": state, + "h": updated, + "event": event_id, + "gate": gate, + "difference": difference, + "matrix": matrix, + }) + state = updated + logits = tuple(r["h"] @ head.output + head.bias for r in records) + return (logits[0], logits[1]), records, h0 + + +def gradients( + head: HistoryHead, + ep: PublicEpisode, + truth: tuple[int, int], + *, + mode: str, +) -> tuple[float, tuple[np.ndarray, ...]]: + logits, records, h0 = forward(head, ep, mode=mode) + derivative = [np.zeros_like(p) for p in head.weights] + weights = (0.35, 1.0) + dlogits = [] + loss = 0.0 + for t in range(2): + item_loss, probs = _softmax_loss(logits[t], truth[t]) + loss += weights[t] * item_loss + dlogits.append(weights[t] * probs) + derivative[3] += np.outer(records[t]["h"], dlogits[t]) + derivative[4] += dlogits[t] + if mode == "bag": + total_initial = np.zeros(D) + for t in range(2): + dpre = (head.output @ dlogits[t]) * (1 - records[t]["h"] ** 2) + derivative[1] += np.outer(h0, dpre) + derivative[2][records[0]["event"]] += dpre + if t == 1: + derivative[2][records[1]["event"]] += dpre + total_initial += head.recurrent @ dpre + else: + carry = np.zeros(D, dtype=np.float64) + for t in (1, 0): + rec = records[t] + dpre = (head.output @ dlogits[t] + carry) * (1 - rec["h"] ** 2) + derivative[1] += np.outer(rec["prev"], dpre) + derivative[2][rec["event"]] += dpre + gate = rec["gate"] + derivative[5][rec["event"]] += float(dpre @ rec["difference"]) * gate * (1 - gate) + carry = head.recurrent @ dpre + gate * ((rec["matrix"] - np.eye(D)).T @ dpre) + total_initial = carry + derivative[0][ep.initial_state] += total_initial * (1 - h0**2) + return loss / 1.35, tuple(gradient / 1.35 for gradient in derivative) + + +def train( + mode: str, + *, + roots: tuple[WorldRoot, ...], + seed: int = 23, + updates: int = 384, + lr: float = 0.014, +) -> tuple[HistoryHead, dict[str, Any]]: + if mode not in TRAINED or not 16 <= updates <= 2000 or lr <= 0: + raise ValueError("invalid mode or training budget") + rng = np.random.default_rng(seed + 101) + head = HistoryHead.initialize(seed) + order = rng.permutation(len(roots)) + m = [np.zeros_like(p) for p in head.weights] + v = [np.zeros_like(p) for p in head.weights] + losses = [] + for step in range(1, updates + 1): + if (step - 1) % len(order) == 0: + order = rng.permutation(len(roots)) + root = roots[int(order[(step - 1) % len(order)])] + loss_a, grad_a = gradients(head, root.episode(), root.truth(), mode=mode) + loss_b, grad_b = gradients(head, root.episode(reverse=True), root.truth(reverse=True), mode=mode) + losses.append((loss_a + loss_b) / 2) + combined = [(a + b) / 2 for a, b in zip(grad_a, grad_b, strict=True)] + norm = math.sqrt(sum(float(np.sum(g * g)) for g in combined)) + scale = min(1.0, 5.0 / max(norm, 1e-12)) + for idx, (p, g) in enumerate(zip(head.weights, combined, strict=True)): + gradient = scale * g + 1e-5 * p + m[idx] = 0.9 * m[idx] + 0.1 * gradient + v[idx] = 0.999 * v[idx] + 0.001 * gradient * gradient + p -= lr * (m[idx] / (1 - 0.9**step)) / ( + np.sqrt(v[idx] / (1 - 0.999**step)) + 1e-8 + ) + return head, { + "mode": mode, + "train_roots": len(roots), + "training_episodes": len(roots) * 2, + "updates": updates, + "trainable_parameters": head.parameter_count, + "weights_sha256": head.digest(), + "initial32_loss": float(np.mean(losses[:32])), + "final32_loss": float(np.mean(losses[-32:])), + } + + +def _prediction( + model: HistoryHead, + ep: PublicEpisode, + mode: str, + *, + swap_transport: bool = False, +) -> tuple[int, int]: + logits, _, _ = forward(model, ep, mode=mode, swap_transport=swap_transport) + return int(np.argmax(logits[0])), int(np.argmax(logits[1])) + + +def evaluate( + models: dict[str, HistoryHead], + *, + roots: tuple[WorldRoot, ...], +) -> tuple[list[dict[str, Any]], dict[str, Any]]: + if set(models) != set(TRAINED): + raise ValueError("all matched learned arms are required") + rows = [] + for root in roots: + outcomes: dict[str, Any] = {} + truth = (root.truth(), root.truth(reverse=True)) + for arm in EVALUATED: + predictions = [] + for reverse in (False, True): + if arm == "exact_oracle": + predicted = root.truth(reverse) + elif arm == "curved_transport_swap": + predicted = _prediction(models["curved"], root.episode(reverse), "curved", swap_transport=True) + else: + predicted = _prediction(models[arm], root.episode(reverse), arm) + predictions.append(predicted) + per_episode = [ + { + "first_correct": predictions[i][0] == truth[i][0], + "last_correct": predictions[i][1] == truth[i][1], + "joint_correct": predictions[i] == truth[i], + } + for i in (0, 1) + ] + outcomes[arm] = { + "first_correct_count": sum(int(x["first_correct"]) for x in per_episode), + "last_correct_count": sum(int(x["last_correct"]) for x in per_episode), + "joint_correct_count": sum(int(x["joint_correct"]) for x in per_episode), + "both_order_last_correct": all(x["last_correct"] for x in per_episode), + "distinguished_order": predictions[0][1] != predictions[1][1], + "predictions": predictions, + "verifier_calls": 4, + "candidate_pool_sha256": _digest(CHOICES), + } + rows.append({ + "root_id": root.root_id, + "family": root.family, + "initial_state": root.initial_state, + "events": [root.event_a, root.event_b], + "truth": truth, + "arms": outcomes, + "evaluator_only": True, + }) + results: dict[str, Any] = {} + for group in (*FAMILIES, "all"): + selection = [row for row in rows if group == "all" or row["family"] == group] + results[group] = {} + for arm in EVALUATED: + stats = [r["arms"][arm] for r in selection] + results[group][arm] = { + "roots": len(stats), + "episodes": len(stats) * 2, + "first_correct": sum(s["first_correct_count"] for s in stats), + "last_correct": sum(s["last_correct_count"] for s in stats), + "both_orders_correct": sum(int(s["both_order_last_correct"]) for s in stats), + "order_distinguished": sum(int(s["distinguished_order"]) for s in stats), + "verifier_calls": sum(s["verifier_calls"] for s in stats), + } + return rows, results + + +def paired_contrasts(rows: list[dict[str, Any]], *, replicates: int = 512) -> dict[str, Any]: + """Root-clustered contrasts, no pseudo-replication of the swapped episode.""" + output: dict[str, Any] = {} + for arm in TRAINED: + if arm == "direct": + continue + diffs = np.asarray([ + int(r["arms"][arm]["both_order_last_correct"]) - + int(r["arms"]["direct"]["both_order_last_correct"]) + for r in rows + ], dtype=np.float64) + rng = np.random.default_rng(int(_digest(arm)[:12], 16)) + samples = rng.integers(0, len(diffs), (replicates, len(diffs))) + ci = np.quantile(100 * diffs[samples].mean(axis=1), (0.025, 0.975)) + output[arm] = { + "roots": len(diffs), + "delta_pp": float(100 * diffs.mean()), + "root_bootstrap_95_pp": [float(ci[0]), float(ci[1])], + "wins": int(np.sum(diffs > 0)), + "losses": int(np.sum(diffs < 0)), + "ties": int(np.sum(diffs == 0)), + } + return output + + +def _write_jsonl(path: Path, rows: list[dict[str, Any]]) -> str: + with path.open("w", encoding="utf-8", newline="\n") as stream: + for item in rows: + stream.write(_canonical(item).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("--updates", type=int, default=384) + parser.add_argument("--train-per-family", type=int, default=24) + parser.add_argument("--eval-per-family", type=int, default=12) + parser.add_argument("--out", required=True, type=Path) + args = parser.parse_args(argv) + if args.out.exists() and any(args.out.iterdir()): + parser.error("output directory must be absent or empty") + training = make_roots(split="train", seed=BATCH_SEED, per_family=args.train_per_family) + evaluation = make_roots(split="eval", seed=EVAL_SEED, per_family=args.eval_per_family) + if set(r.root_id for r in training) & set(r.root_id for r in evaluation): + raise AssertionError("data lineage crossed train/eval split") + models, train_logs = {}, {} + for arm in TRAINED: + models[arm], train_logs[arm] = train(arm, roots=training, seed=args.seed, updates=args.updates) + rows, scores = evaluate(models, roots=evaluation) + args.out.mkdir(parents=True, exist_ok=True) + public_hash = _write_jsonl( + args.out / "public_eval.jsonl", + [r.episode(reverse=rev).public() for r in evaluation for rev in (False, True)], + ) + scored_hash = _write_jsonl(args.out / "scorer_only.jsonl", rows) + report = { + "schema_version": "dg-sgrt-03-public-sequential-v1", + "status": "synthetic_cpu_development_only", + "optimizer_seed": args.seed, + "train_root_count": len(training), + "eval_root_count": len(evaluation), + "per_family_train": args.train_per_family, + "per_family_eval": args.eval_per_family, + "updates_per_arm": args.updates, + "candidate_set_size": len(CHOICES), + "verifier_calls_per_root": 4, + "training": train_logs, + "geometry": transport_diagnostics(), + "scores": scores, + "paired_vs_direct": paired_contrasts(rows), + "public_eval_sha256": public_hash, + "scorer_only_sha256": scored_hash, + "claim_boundary": ( + "Fictional 4-bit sequential event simulator; evaluates chronological" + " learning and frozen transport priors, not general creativity or" + " an Aleph-1B architecture gain." + ), + } + (args.out / "report.json").write_text( + json.dumps(report, sort_keys=True, indent=2) + "\n", encoding="utf-8" + ) + print(json.dumps({ + "status": report["status"], + "train_roots": len(training), + "eval_roots": len(evaluation), + "geometry": report["geometry"], + "scores_all": scores["all"], + "paired_vs_direct": report["paired_vs_direct"], + }, sort_keys=True, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/tests/unit/test_sgrt_history.py b/tests/unit/test_sgrt_history.py new file mode 100644 index 00000000..cfc69752 --- /dev/null +++ b/tests/unit/test_sgrt_history.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +import numpy as np +import pytest + +from datagoblin.training_gym.sgrt_history import ( + CHOICES, + EVENTS, + FAMILIES, + TRAINED, + D, + HistoryHead, + _digest, + _prediction, + evaluate, + event_transport, + forward, + gradients, + make_roots, + paired_contrasts, + train, + transport_diagnostics, +) + + +def test_train_eval_lineage_and_composition_holdout() -> None: + training = make_roots(split="train", seed=31003, per_family=24) + evaluation = make_roots(split="eval", seed=61003, per_family=12) + assert len(training) == 72 + assert len(evaluation) == 48 + assert not set(x.root_id for x in training) & set(x.root_id for x in evaluation) + assert {r.family for r in training} == set(FAMILIES[:3]) + assert {r.family for r in evaluation} == set(FAMILIES) + train_events = {x for r in training for x in (r.event_a, r.event_b)} + assert train_events == set(EVENTS) + train_pairs = {frozenset((r.event_a, r.event_b)) for r in training} + heldout_pairs = { + frozenset((r.event_a, r.event_b)) + for r in evaluation if r.family == "heldout_mixed" + } + assert not train_pairs & heldout_pairs + assert make_roots(split="eval", seed=61003, per_family=12) == evaluation + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_executable_two_step_storyworld_and_private_targets(reverse: bool) -> None: + root = make_roots(split="eval", seed=61003, per_family=1)[0] + ep = root.episode(reverse) + payload = ep.public() + assert payload["candidate_states"] == list(CHOICES) + assert len(payload["event_stream"]) == 2 + assert payload["event_stream"][0]["step"] == 1 + assert "truth" not in payload + assert "target" not in payload + assert set(CHOICES) == set(range(16)) + assert 0 <= root.truth(reverse)[0] < 16 + assert 0 <= root.truth(reverse)[1] < 16 + assert root.truth()[1] != root.truth(reverse=True)[1] + + +def test_closed_curve_and_matched_noncommuting_spectrum() -> None: + diagnostic = transport_diagnostics() + assert diagnostic["flat_commutator_fro_max"] < 1e-9 + assert diagnostic["curved_commutator_fro_max"] > 1e-5 + assert diagnostic["flat_curved_trace_mismatch_max"] < 1e-8 + assert diagnostic["orthogonality_error_max"] < 1e-9 + for op in EVENTS: + curved = event_transport("curved", op) + flat = event_transport("flat", op) + random = event_transport("random", op) + assert curved.shape == flat.shape == random.shape == (D, D) + assert np.trace(curved) == pytest.approx(np.trace(flat), abs=1e-8) + assert np.trace(random) == pytest.approx(np.trace(flat), abs=1e-8) + assert np.linalg.det(curved) == pytest.approx(1, abs=1e-8) + assert np.linalg.det(flat) == pytest.approx(1, abs=1e-8) + + +def test_bag_policy_has_exact_order_alias() -> None: + root = make_roots(split="train", seed=31003, per_family=1)[0] + model = HistoryHead.initialize(seed=7) + logits_ab, _, _ = forward(model, root.episode(), mode="bag") + logits_ba, _, _ = forward(model, root.episode(reverse=True), mode="bag") + assert np.allclose(logits_ab[1], logits_ba[1], atol=1e-12) + assert _prediction(model, root.episode(), "bag")[1] == _prediction( + model, root.episode(reverse=True), "bag" + )[1] + + +@pytest.mark.parametrize("mode", ["bag", "curved", "random"]) +def test_training_gradient_agrees_with_finite_difference(mode: str) -> None: + root = make_roots(split="train", seed=31003, per_family=1)[0] + model = HistoryHead.initialize(seed=11) + ep = root.episode() + target = root.truth() + _loss, grads = gradients(model, ep, target, mode=mode) + indices = ( + (root.initial_state, 0), + (0, 0), + (EVENTS.index(ep.events[0]), 0), + (0, 0), + (0,), + (EVENTS.index(ep.events[0]),), + ) + for array, grad, index in zip(model.weights, grads, indices, strict=True): + value = float(array[index]) + eps = 1e-5 + array[index] = value + eps + hi = gradients(model, ep, target, mode=mode)[0] + array[index] = value - eps + lo = gradients(model, ep, target, mode=mode)[0] + array[index] = value + assert grad[index] == pytest.approx((hi - lo) / (2 * eps), abs=2e-6) + + +def test_learned_pairwise_policy_and_scoring_custody() -> None: + training = make_roots(split="train", seed=31003, per_family=4) + evaluation = make_roots(split="eval", seed=61003, per_family=2) + models = {} + initial_sha = HistoryHead.initialize(41).digest() + for mode in TRAINED: + model, log = train(mode, roots=training, seed=41, updates=16) + assert log["trainable_parameters"] == 937 + assert log["initial32_loss"] > 0 + assert model.digest() != initial_sha + models[mode] = model + rows, scores = evaluate(models, roots=evaluation) + assert len(rows) == 8 + assert scores["all"]["exact_oracle"]["last_correct"] == 16 + assert scores["all"]["exact_oracle"]["both_orders_correct"] == 8 + assert scores["all"]["bag"]["both_orders_correct"] == 0 + assert scores["all"]["exact_oracle"]["verifier_calls"] == 32 + assert scores["heldout_mixed"]["exact_oracle"]["roots"] == 2 + observed_sets = {item["candidate_pool_sha256"] for r in rows for item in r["arms"].values()} + assert observed_sets == {_digest(CHOICES)} + assert all(r["truth"][0][1] != r["truth"][1][1] for r in rows) + assert all(row["evaluator_only"] for row in rows) + assert paired_contrasts(rows) == paired_contrasts(rows) + + +def test_deterministic_fit_and_transport_swap_does_not_change_public_event_stream() -> None: + roots = make_roots(split="train", seed=31003, per_family=2) + left, _ = train("curved", roots=roots, seed=7, updates=16) + right, _ = train("curved", roots=roots, seed=7, updates=16) + assert left.digest() == right.digest() + ep = roots[0].episode() + original = ep.public() + forward(left, ep, mode="curved", swap_transport=True) + assert original == ep.public() diff --git a/training/sgrt_holoarc_03/README.md b/training/sgrt_holoarc_03/README.md new file mode 100644 index 00000000..1f49ca08 --- /dev/null +++ b/training/sgrt_holoarc_03/README.md @@ -0,0 +1,139 @@ +# DG-SGRT-03: sequential storyworld evidence, same-set holonomy test + +**Stage:** CPU-only synthetic mechanism development, 2026-11-23. This is a +stacked follow-up to DG-SGRT-01/02 (draft DataGoblin PR #53), which reported +a negative three-seed learned candidate-ranking result. All older results +and frozen SRT/SGRT protocols remain unchanged. + +## Target question + +Can path-sensitive transport help a small learned recurrent policy revise +its decision when new evidence arrives **after** the preceding decision, +when candidate coverage, task families, verifier calls, and trainable +parameters are held fixed? + +A synthetic world has a four-bit public state. Fictional events such as +reversing a witness flag, rotating courier seals, and closing an archive +are deterministic noncommuting transformations of that state. Each root +has two episodes with identical initial state and the same two event +packets, presented AB and BA. Their final states deliberately differ. +A public episode exposes the initial state and events in order. The +environment-owned scorer alone computes the intermediate and final +correct labels with an independent exact interpreter. + +All policies receive exactly 16 legal action candidates (a forecast of +the next world state) at every step. Each policy predicts **once after +the first event**, keeps its prediction, then receives the second event +and predicts again. The simulator checks each prediction after the run; +its result is not fed into the policy. Thus all policies have identical +candidate multisets, four exact checker calls per paired root and two +recurrent visits per episode. Distinct root pairs, rather than paired +episode rows, are the unit of statistical inference. + +## Controls + +Five small NumPy heads have 937 trainable parameters each, the same +random initialization and root-pair ordering, the same 384 Adam updates, +and both intermediate and final supervised losses on the training split. + +| Arm | Mechanism | +|---|---| +| bag | Order-agnostic sum of event embeddings, exact alias negative control | +| direct | Ordinary learned two-step tanh recurrence with identity transport | +| flat | A commuting event-specific orthogonal transport | +| curved | Noncommuting event-specific holonomy produced by closed 12D spirographic loops | +| random | Independent orthogonal conjugates of flat transport, matching each event's eigenspectrum | + +For flat and curved, the per-event matrices have the same trace, +determinant, eigenangle multiset, orthogonality and Frobenius distance +from identity. Flat matrices use a shared orthogonal plane atlas and +commute across events. Curved matrices are Wilson products along closed +spirographic paths; their commutators are nonzero. Random control has +matched event spectra and can also be noncommuting, without spirographic +organization. This is a useful alternative when learned history matters +for reasons unrelated to the selected geometry. + +A sixth comparison, curved_transport_swap, uses the **same trained +curved weights** and preserves the chronological event embeddings but +swaps which event's transport operates at each step. Its per-root +transport multiset is unchanged. This tests sensitivity to event-to- +transport ordering, without changing candidate pools or checker calls. +The exact ordered simulator is the seventh comparison and ceiling. + +All learned modes share a 16D carried state and the same update: + + h0 = tanh(initial_table[public_initial_state]) + gt = sigmoid(gate_logits[public_event]) + ht = tanh(h(t-1) @ Wrec + event_table[event] + gt * (Qevent - I) @ h(t-1)) + logits = ht @ Wout + bias + +The bag control uses commutative accumulated evidence after the +first visit, making identical second-step logits for AB and BA. +Its residual gate is inactive; direct has an identity transport and +is the ordinary recurrent comparator. Because flat/curved/random apply +a frozen geometry with additional small-matrix operations, equality +of trainable parameters does not establish equal floating-point cost. +Record actual runtime before any model-architecture promotion. + +## Public split and default run + +- Training: 24 unique noncommuting lineage roots in each of three + families, 72 paired roots or 144 two-event episodes. +- Evaluation: 12 roots per family across all four families, including + 12 entirely held-out event-pair compositions; 48 pairs or 96 episodes. +- Each root is keyed by initial state and unordered event pair. Stable + SHA-256 bucketing separates train and evaluation within the first + three families. The held-out family uses different unordered event + pairs whose individual operations occur during training. +- No exact target or hidden evaluator state reaches the forward pass. +- Default optimizer seed 23; 384 paired-root updates; Adam LR 0.014; + two visits/episode; exact candidate pool size 16; four checks/root. +- Public generator/split seeds 31003 and 61003, recorded in source. + +### Run + + python -m pytest tests/unit/test_sgrt_history.py -q + ruff check src/datagoblin/training_gym/sgrt_history.py tests/unit/test_sgrt_history.py + python -m datagoblin.training_gym.sgrt_history --seed 23 --updates 384 --train-per-family 24 --eval-per-family 12 --out runs/dg-sgrt-03-public + +The workflow in .github/workflows/dg-sgrt-history.yml runs the same +commands, validates the geometry and oracle, then uploads the full +development report and scorer-owned individual rows. It needs NumPy +only, runs on the GitHub-hosted CPU, and never invokes Inky Mini, the +local GPU, paid APIs, or any trained Aleph checkpoint. + +## Measurement and claim boundaries + +The primary diagnostic is pair-level **both_orders_correct**: an arm +must predict the final state in both counterfactual orders for the +root to count. Report first-visit accuracy, final-visit accuracy, +order-distinguishing output count, and exact-oracle ceiling. +An order-blind bag model has an upper bound of one correct final +episode per paired root by construction. + +Use paired root bootstrap contrasts against direct recurrence. Break +out the held-out mixed family. Keep every failure and zero count. +Any positive curved result must also exceed the strongest random and +flat transport controls under a matched resource budget before +claiming value from the spirographic connection. + +The initial stage tests **frozen geometric priors** in a learned +recurrent head. It does not train the connection itself. The world's +event operations are known, finitely enumerable and much easier +than open-ended creative storyworld generation. The checker supplies +no online reward or corrective hint between the two decisions. +A prospective interactive follow-up can provide an action-dependent +second observation under controlled oracle custody after this baseline. + +## Stop / promotion rules + +Keep DG-SGRT-03 exploratory until paired root intervals and multiple +independent initialization seeds exist. A single public development +run cannot change the current HOLD decision on Aleph integration. +If curved transport loses to direct or random, retain that null. +If it wins, register independent family-disjoint sealed runs and a +matched-compute adaptive comparison before any real host sidecar. + +Proposer autonomy stops at a prediction. Only the fictional simulator +may change the world. No API credentials, actual trading, warfare, +deployment authority, model downloads, or production side effects. diff --git a/training/sgrt_holoarc_03/RESULTS.md b/training/sgrt_holoarc_03/RESULTS.md new file mode 100644 index 00000000..f082d0e8 --- /dev/null +++ b/training/sgrt_holoarc_03/RESULTS.md @@ -0,0 +1,108 @@ +# DG-SGRT-03: sequential history pilot result + +**Run:** 2026-11-23, CPU-only public synthetic development. +**GitHub Actions:** https://github.com/MoralityLabAI/DataGoblin/actions/runs/45105770458 +**PR:** https://github.com/MoralityLabAI/DataGoblin/pull/55 +**Result:** INSUFFICIENT LEARNED HEADROOM. Continue HOLD on Aleph architecture promotion. + +This experiment followed the negative three-seed DG-SGRT-02 candidate-coverage +study. It introduces chronological evidence between decisions, matched +candidate sets, and flat/noncommuting orthogonal transport. The two episodes +in each root present identical fictional evidence events in reverse order; +the exact interpreter guarantees their final states differ. + +## Protocol + +- Training: 72 unique lineage roots, 144 two-event episodes across three + composition families; fourth family withheld. Every model trained for + 384 paired-root Adam steps with seed 23 and an identical 937-parameter + tensor layout, initialization, loss, and example order. +- Evaluation: 48 independent roots, 96 episodes, including 12 roots from + completely withheld event-pair compositions. +- Fixed candidate multiset: the same 16 world-state forecasts at each + decision. One model prediction per observation, with independent + simulator checking after each episode. Four checks per paired root, + 192 for every arm. +- Primary paired-root measure: both reversed-order final forecasts + must be correct for a root to count. +- Supplementary: individual first/last step success, whether an arm + distinguishes AB and BA, root-paired bootstraps versus direct + recurrence and transport diagnostic invariants. + +## Geometry implementation checks + +| Invariant | Observed | +|---|---:| +| Maximum flat transport commutator Frobenius norm | 3.14018e-16 | +| Maximum curved transport commutator Frobenius norm | 5.54987 | +| Maximum flat/curved event trace mismatch | 1.77636e-15 | +| Maximum transport orthogonality error | 3.49010e-15 | + +The flat event transports commute while retaining the curved +transports' eventwise eigenangle spectrum. Geometry tests validate +this construction. They do not establish task utility. + +## Learned outcomes + +| Arm | Both orders correct / 48 | First-step correct / 96 | Final-step correct / 96 | +|---|---:|---:|---:| +| bag (order-invariant negative control) | 0 | 13 | 8 | +| direct learned recurrence | 0 | 19 | 7 | +| flat matched transport | 0 | 20 | 6 | +| curved HoloArc | 0 | 31 | 6 | +| random spectrally matched transport | 0 | 19 | 8 | +| curved with transports swapped between evidence steps | 0 | 23 | 9 | +| environment-owned exact simulator | 48 | 96 | 96 | + +All learned arms have zero exact paired-root success, giving a +degenerate [0,0]-percentage-point paired contrast against direct +recurrence. The test cannot rank architectures on the primary endpoint. +The curved head's 31 first-step successes may warrant further +engineering, but 6/96 final-step correct outcomes are at a +near-chance level for 16 legal states. + +The order-invariant bag mode produced identical final logits for AB +and BA by construction and correctly failed the paired criterion. +The exact simulator attained the 48/48 ceiling. That validates the +pairing and scorer. It also shows the candidate task's answer is +computable when the intended transitions are applied correctly. + +## Interpretation and next gate + +The two-step learned state update failed to carry enough +compositional information to evaluate transport chronology. At this +difficulty, a geometric advantage is unidentifiable: successful +holonomy readout, commutator fidelity, or phase shuffling cannot +substitute for task competence. + +Before another architectural comparison, run a separate +**headroom-calibration study** with a deliberately easier endpoint: + +1. Supervise exact single-event transitions with the same training + families, recording final-state accuracy before adding a second + event; check that held-out event-state pairs are still distinct. +2. Evaluate binary named-state queries (e.g. whether the archive + signal is active), registering query selection and balancing before + training. Include history-aliased AB/BA pairs whose correct + binary answers flip. +3. With sufficient base accuracy, restore multi-bit two-event + predictions. Compare ordinary learned recurrence against flat, + curved, and random transports at matched parameters, measured + FLOPs, and paired root custody before attempting an adaptive + storyworld experiment. + +Changes motivated by these public results must be labeled +development, with further held-out seeds and task families for any +confirmatory mechanism claim. The Aleph architecture remains +unchanged. The running local Inky Mini service was untouched. + +## Artifacts and replay + +The CI job uploads a short-lived artifact named +dg-sgrt-03-public-history-development, containing public_eval.jsonl, +scorer_only.jsonl and report.json. The public stream has 96 rows +and no simulator truth. The scorer-owned stream has 48 paired +root rows with exact targets, per-arm outcomes and receipts. + +The complete deterministic source and CLI remain in +src/datagoblin/training_gym/sgrt_history.py.