{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "46f361d2",
   "metadata": {},
   "source": [
    "# E3: the matched pair, writing checked proofs\n",
    "\n",
    "The released ARLoop-0.6B and PreNormLoop-0.6B share data, tokeniser, backbone and training budget;\n",
    "only the residual path differs ({doc}`../mechanism/m2_parameters`). E3 fine-tunes both identically\n",
    "with the recipe of `latent`'s Campaign 4 and lets them write proofs that a pinned constructive\n",
    "checker verifies. The protocol (`experiments/e3_pair/PROTOCOL.md`) was written before any E3 data\n",
    "preparation, training or evaluation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a6e02d09",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "import sys, pathlib, re, json\n",
    "\n",
    "BOOK = next(p for p in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents] if (p / \"seminar_lib.py\").exists())\n",
    "sys.path.insert(0, str(BOOK))\n",
    "sys.dont_write_bytecode = True   # keep book/ free of __pycache__\n",
    "import seminar_lib as lib\n",
    "\n",
    "PROT = lib.PROTOCOL[\"E3\"]\n",
    "E3 = lib.RUNS / \"e3\"\n",
    "LOCAL = lib.REPO / \"experiments\" / \"e3_pair\" / \"results\"\n",
    "candidates = [E3 / \"results.json\", E3 / \"results\" / \"results.json\", LOCAL / \"results\" / \"results.json\", LOCAL / \"results.json\"]\n",
    "RESULTS = next((p for p in candidates if p.exists()), None)\n",
    "res = json.loads(RESULTS.read_text()) if RESULTS else None\n",
    "REFEREE = E3 / \"referee.md\"\n",
    "referee = REFEREE.read_text() if REFEREE.exists() else None\n",
    "REF = E3 / \"referee\" / \"e3_referee.json\"                  # the independent recount from the raw records\n",
    "ref = lib.read_json(REF)\n",
    "# the registered floor rule: \"If both bases accept <= 1 target in every suite, the run is floor-limited\"\n",
    "FLOOR = int(re.search(r\"accept <= (\\d+)\\s+target in every suite\", PROT.read_text()).group(1))\n",
    "FULL = 32                                                 # the development targets of a full suite\n",
    "RUN_NAME = re.compile(r\"^(arloop|prenorm)-(native3|random124)-s\\d+$\")\n",
    "\n",
    "\n",
    "def full_suites(evals):\n",
    "    \"\"\"(base, arm, L) -> proof summary of every full suite under `evals` (all 32 targets).\n",
    "\n",
    "    Smoke tests (directories `smoke-*`, 1 or 2 targets) carry the same run id, base, arm and L as\n",
    "    the full suites, so a summary is identified by its own fields and kept only if it covers all\n",
    "    targets. Two different full suites for one cell stop the build.\"\"\"\n",
    "    cells, skipped = {}, []\n",
    "    for path in sorted(evals.glob(\"*/proofs-L*-summary.json\")):\n",
    "        s = json.loads(path.read_text())\n",
    "        if s[\"targets\"] != FULL:\n",
    "            skipped.append(path)\n",
    "            continue\n",
    "        key = (s[\"base\"], s[\"arm\"], s[\"loops\"])\n",
    "        if key in cells and cells[key][1][\"proofs_sha256\"] != s[\"proofs_sha256\"]:\n",
    "            raise RuntimeError(f\"two different full suites for {key}: {cells[key][0]} and {path}\")\n",
    "        cells.setdefault(key, (path, s))\n",
    "    return cells, skipped"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "109a9f75",
   "metadata": {},
   "source": [
    "## The protocol in brief\n",
    "\n",
    "* **Arms** (2 bases × 2 arms = 4 fine-tuned checkpoints): `native3`, every update at $R = 3$ loops;\n",
    "  `random124`, each update draws $R$ from $\\{1, 2, 4\\}$ (latent's rule; the protocol and the code\n",
    "  write $L$ for the number of loops, a value forced per evaluation suite). ARLoop gets a bank of\n",
    "  routing queries and norms for a fourth loop, initialised as copies of loop 3's; it is trainable\n",
    "  only in `random124` ({doc}`../mechanism/m2_parameters`).\n",
    "* **Training**, identical for all four: LoRA of rank 32 on the attention and MLP matrices of the 18\n",
    "  physical blocks (one adapter per block, shared across loops), 512 updates of 16 sequences, one\n",
    "  seed (11), latent's Campaign-4 training corpus.\n",
    "* **Evaluation**: each checkpoint at forced $R \\in \\{1, 2, 3, 4\\}$, 16 suites; the 32 development\n",
    "  proof targets of Campaign 4; one greedy autonomous attempt per target, stopped at the first\n",
    "  malformed or rejected action; a proof counts only if the pinned Python checker replays it to a\n",
    "  kernel-checked QED. This is not a Lean check. The test split stays sealed.\n",
    "* **Comparisons**, fixed in advance: P1, ARLoop vs PreNorm, `native3`, $R = 3$ (primary); P2, the\n",
    "  same for `random124` at each $R$; P3, `random124` vs `native3` at $R = 4$ within each base.\n",
    "  Reading rules: a paired difference of at most 2 targets is \"no detectable difference\"; \"ARLoop\n",
    "  helps\" is a signal worth a confirmatory run only if ARLoop leads by at least 3 targets in P1 and\n",
    "  does not trail in `random124` at $R = 4$; if both bases accept at most 1 target in every suite,\n",
    "  the run is floor-limited and uninformative about the question. Tier T4, one seed. **[exp]**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ba2682d",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert lib.quote_check(PROT, \"`native3`: every update runs L = 3 loops.\",\n",
    "                       \"`random124`: each update draws L from {1, 2, 4}\",\n",
    "                       \"LoRA r = 32, alpha = 64\", \"**512 updates x effective batch 16**\",\n",
    "                       \"Grid: each of the 4 checkpoints at forced L in {1, 2, 3, 4} = 16 suites.\",\n",
    "                       \"the 32 C4 development proof targets\", \"This is not a Lean check.\",\n",
    "                       \"**The test split is not opened by E3**\",\n",
    "                       \"a paired difference of at most 2 targets is \\\"no detectable difference\\\"\",\n",
    "                       \"only if ARLoop leads by >= 3 targets in P1 and does not trail in `random124` at L = 4\",\n",
    "                       \"If both bases accept <= 1 target in every suite, the run is floor-limited and uninformative about the question\",\n",
    "                       \"Status: **discovery run, tier T4, one seed (11)**\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68b58a49",
   "metadata": {},
   "source": [
    "## Results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "60c5734f",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "if res is None:\n",
    "    lib.pending(\"E3 results\", \"No E3 results file yet (looked for `runs/e3/results.json`, \"\n",
    "                \"`runs/e3/results/results.json` and `experiments/e3_pair/results/`). Training of the four \"\n",
    "                \"checkpoints and the 16 evaluation suites run on WMI; this page shows no numbers until the \"\n",
    "                \"results arrive.\")\n",
    "else:\n",
    "    lib.md(f\"Read from `{lib.rel(RESULTS)}` (written by `experiments/e3_pair/analyze.py`); \"\n",
    "           f\"complete suites: {res['complete_suites']} of 16.\")\n",
    "    rows = []\n",
    "    for r in res[\"table\"]:\n",
    "        f = lambda v, spec: \"–\" if v is None else format(v, spec)\n",
    "        rows.append((r[\"base\"], r[\"arm\"], r[\"loops\"], \"–\" if r[\"accepted\"] is None else f\"{r['accepted']} / {r['targets']}\",\n",
    "                     f(r[\"wall_budget_limited\"], \"d\"), f(r[\"dev_ce_all\"], \".4f\"), f(r[\"dev_token_acc_all\"], \".4f\"),\n",
    "                     r[\"loop4_routing\"] or \"–\"))\n",
    "    lib.md(lib.table(rows, [\"base\", \"arm\", \"R\", \"proofs accepted\", \"wall-limited\", \"dev CE (nats/token)\",\n",
    "                            \"dev token accuracy\", \"loop-4 routing\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b0c590af",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if res is not None:\n",
    "    assert len(res[\"table\"]) == 16 and res[\"tier\"] == \"T4\"\n",
    "    assert len({(r[\"base\"], r[\"arm\"], r[\"loops\"]) for r in res[\"table\"]}) == 16      # one row per cell\n",
    "    done = [r for r in res[\"table\"] if r[\"accepted\"] is not None]\n",
    "    assert res[\"complete_suites\"] == len(done)\n",
    "    assert all(0 <= r[\"accepted\"] <= r[\"targets\"] == FULL for r in done)\n",
    "    assert res[\"floor_limited\"] == (len(done) == 16 and max(r[\"accepted\"] for r in done) <= FLOOR)\n",
    "    assert all(c[\"n\"] == FULL for c in res[\"comparisons\"].values() if c)              # P1 included\n",
    "    # every row is a full suite: compared with the proof summaries themselves, smoke tests excluded\n",
    "    if (LOCAL / \"evals\").is_dir():\n",
    "        cells, skipped = full_suites(LOCAL / \"evals\")\n",
    "        assert all(p.parent.name.startswith(\"smoke\") for p in skipped)\n",
    "        assert all(p.parent.name == s[\"run_id\"] and RUN_NAME.match(s[\"run_id\"]) for p, s in cells.values())\n",
    "        for r in done:\n",
    "            s = cells[(r[\"base\"], r[\"arm\"], r[\"loops\"])][1]\n",
    "            assert (r[\"accepted\"], r[\"targets\"], r[\"wall_budget_limited\"]) == (s[\"accepted\"], s[\"targets\"], s[\"wall_budget_limited\"])\n",
    "        if ref is not None:                       # the independent recount covers the same full suites\n",
    "            assert {(k.split(\"-\")[0], k.split(\"-\")[1], int(k.split(\"@\")[1])) for k in ref[\"suites\"]} == set(cells)\n",
    "            for k, v in ref[\"suites\"].items():\n",
    "                s = cells[(k.split(\"-\")[0], k.split(\"-\")[1], int(k.split(\"@\")[1]))][1]\n",
    "                assert v[\"slurm_job_id\"] == s[\"slurm_job_ids\"] and v[\"accepted\"] == s[\"accepted\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9556cdaa",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "if res is not None:\n",
    "    comps = {k: c for k, c in res[\"comparisons\"].items() if c}\n",
    "    if not comps:\n",
    "        lib.pending(\"E3 comparisons\", \"no comparison has both of its suites yet.\")\n",
    "    else:\n",
    "        # the floor rule takes precedence over the per-comparison rule (PROTOCOL.md, reading rules)\n",
    "        reading = (lambda c: \"uninformative (floor rule)\") if res[\"floor_limited\"] else (lambda c: c[\"reading\"])\n",
    "        def r_name(s):                          # E3's code writes L for the forced number of loops\n",
    "            return re.sub(r\"\\bL(\\d)\", r\"R = \\1\", s.replace(\"_\", \" \")).replace(\"@\", \" at R = \")\n",
    "        lib.md(lib.table([(r_name(k), f\"{r_name(c['a'])} vs {r_name(c['b'])}\", f\"{c['accepted_a']} / {c['accepted_b']}\",\n",
    "                           f\"{c['only_a']} / {c['only_b']}\", lib.pvalue(c[\"mcnemar_exact_p\"]), reading(c))\n",
    "                          for k, c in comps.items()],\n",
    "                         [\"comparison\", \"a vs b\", \"accepted, a / b\", \"only a / only b\", \"exact McNemar p\",\n",
    "                          \"reading (pre-registered)\"]))\n",
    "        p1 = res[\"comparisons\"].get(\"P1_native3_L3\")\n",
    "        if res[\"floor_limited\"]:\n",
    "            lib.md(f\"**Floor-limited:** both bases accept at most {FLOOR} target in every suite, so by the registered \"\n",
    "                   \"floor rule the comparisons, P1 included, are **uninformative** about the question. The \"\n",
    "                   \"pre-registered signal \\\"ARLoop helps\\\" is absent.\")\n",
    "        else:\n",
    "            lib.md(f\"Not floor-limited; pre-registered signal \\\"ARLoop helps\\\": \"\n",
    "                   f\"**{'yes' if res['arloop_helps_signal'] else 'no'}**\" + (\"\" if p1 else \" (P1 not yet available)\") + \".\")\n",
    "if ref is not None:\n",
    "    oracle, suites = ref[\"checks\"][\"oracle\"], ref[\"suites\"]\n",
    "    best = max(v[\"accepted\"] for v in suites.values())\n",
    "    lib.md((f\"No checkpoint proves any target: {best} of {oracle['targets']} in each of the {len(suites)} suites. \"\n",
    "            if best == 0 else f\"The best of the {len(suites)} suites accepts {best} of {oracle['targets']} targets. \") +\n",
    "           f\"The harness itself can accept a proof: the gold proof actions of the same {oracle['targets']} targets, \"\n",
    "           f\"fed through the same harness with the same budgets (the oracle check), are accepted on \"\n",
    "           f\"{oracle['accepted_recount']} of {oracle['targets']}. Counts from the independent recount \"\n",
    "           f\"(`{lib.rel(REF)}`). **[exp]**\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03574972",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if ref is not None:\n",
    "    assert len(suites) == 16 and all(v[\"n\"] == v[\"unique_ids\"] == oracle[\"targets\"] == 32 for v in suites.values())\n",
    "    assert oracle[\"accepted_recount\"] == oracle[\"accepted\"] == oracle[\"targets\"]\n",
    "    assert oracle[\"ids_equal_suite_ids\"] and oracle[\"budgets_equal\"] and ref[\"checks\"][\"same_32_ids_all_suites\"]\n",
    "    if res is not None and res[\"complete_suites\"] == 16:   # the recount agrees with the results table\n",
    "        assert sorted(r[\"accepted\"] for r in res[\"table\"]) == sorted(v[\"accepted\"] for v in suites.values())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c1f354fb",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if res is not None:\n",
    "    for k, c in res[\"comparisons\"].items():\n",
    "        if not c:\n",
    "            continue\n",
    "        assert c[\"difference\"] == c[\"accepted_a\"] - c[\"accepted_b\"] == c[\"only_a\"] - c[\"only_b\"]\n",
    "        assert abs(c[\"mcnemar_exact_p\"] - lib.mcnemar_exact(c[\"only_a\"], c[\"only_b\"])) < 1e-12\n",
    "        assert c[\"reading\"].startswith(\"no detectable\") == (abs(c[\"difference\"]) <= 2)\n",
    "    p1, p24 = res[\"comparisons\"].get(\"P1_native3_L3\"), res[\"comparisons\"].get(\"P2_random124_L4\")\n",
    "    assert res[\"arloop_helps_signal\"] == bool(p1 and p24 and p1[\"difference\"] >= 3 and p24[\"difference\"] >= 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eeed0bea",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "receipts = {}                                 # the training runs <base>-<arm>-s<seed>; nothing else\n",
    "for path in sorted(LOCAL.glob(\"runs/*/receipt.json\")) + sorted(E3.glob(\"**/receipt.json\")):\n",
    "    if RUN_NAME.match(path.parent.name):\n",
    "        r = json.loads(path.read_text())\n",
    "        if path.parent.name in receipts and receipts[path.parent.name] != r:\n",
    "            raise RuntimeError(f\"two different training receipts for {path.parent.name}\")\n",
    "        receipts[path.parent.name] = r\n",
    "if receipts:\n",
    "    rows = []\n",
    "    for name, r in receipts.items():\n",
    "        rows.append((f\"`{name}`\", r.get(\"state\", \"–\"), r.get(\"steps_completed\", \"–\"),\n",
    "                     \", \".join(f\"R = {k}: {v:,}\" for k, v in sorted(r[\"loops_histogram\"].items(), key=lambda kv: int(kv[0])))\n",
    "                     if isinstance(r.get(\"loops_histogram\"), dict) else \"–\",\n",
    "                     f\"{r['train_loss_first8_mean']:.3f} → {r['train_loss_last8_mean']:.3f}\" if \"train_loss_last8_mean\" in r else \"–\",\n",
    "                     r.get(\"loop4_routing\", \"–\"), f\"`{r['adapter_sha256'][:12]}…`\" if r.get(\"adapter_sha256\") else \"–\"))\n",
    "    lib.md(\"**Training receipts** (as found):\\n\\n\" +\n",
    "           lib.table(rows, [\"run\", \"state\", \"updates\", \"loops drawn\", \"train loss, first 8 → last 8 updates\",\n",
    "                            \"loop-4 routing\", \"adapter SHA-256\"]))\n",
    "if referee:\n",
    "    lib.note(\"Independent re-check\", f\"`{lib.rel(REFEREE)}`: a separate script recounted every suite from the \"\n",
    "             \"raw records and checked the pairing of the arms, the provenance of the code and the test split. \"\n",
    "             f\"Verdict: **{lib.recheck_verdict(referee) or 'see the note'}**.\", \"important\")\n",
    "elif res is not None:\n",
    "    lib.note(\"Not yet re-checked\", \"These numbers come straight from the run files; the independent re-check \"\n",
    "             \"(`runs/e3/referee.md`) is not there yet.\", \"warning\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bee70482",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if receipts:\n",
    "    assert len(receipts) == 4 and all(r.get(\"steps_completed\") == 512 for r in receipts.values())\n",
    "if referee:\n",
    "    assert lib.recheck_verdict(referee) == \"established as T4 evidence: floor-limited (0/32 in all 16 suites)\"\n",
    "    assert lib.quote_check(REFEREE, \"(written for this check) run on WMI over the raw records\",\n",
    "                           \"**Recount of the pre-registered metric.**\", \"**Pairing.**\", \"**Provenance.**\",\n",
    "                           \"**Test split.**\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3-explore-md",
   "metadata": {},
   "source": [
    "## Exploratory, post hoc: how far the failed attempts get\n",
    "\n",
    "With every suite at zero, the registered comparisons are uninformative. Two descriptive measures were\n",
    "added after ARLoop `native3`'s suites had been seen at 0/32, and before any PreNorm or `random124`\n",
    "suite ran (amendment in `experiments/e3_pair/STATUS.md`):\n",
    "\n",
    "* the number of actions accepted before an attempt fails;\n",
    "* whether one action, generated after the gold prefix of a proof, is valid, on 64 development rows of\n",
    "  Campaign 4.\n",
    "\n",
    "The numbers below are the independent recount from the raw records\n",
    "(`runs/e3/referee/e3_referee.json`). They only generate hypotheses: one seed, 32 targets, and the\n",
    "cells of different $R$ share the same 64 rows. **[exp]**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e3-explore-code",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "if ref is None:\n",
    "    lib.pending(\"E3 exploratory measures\", \"`runs/e3/referee/e3_referee.json` is not there yet.\")\n",
    "else:\n",
    "    sx = ref[\"suites\"]\n",
    "    assert len(sx) == 16 and all(v[\"n\"] == 32 and v[\"accepted\"] == 0 for v in sx.values())\n",
    "    rows = []\n",
    "    for arm in (\"native3\", \"random124\"):\n",
    "        for L in (1, 2, 3, 4):\n",
    "            a, b = sx[f\"arloop-{arm}-s11@{L}\"], sx[f\"prenorm-{arm}-s11@{L}\"]\n",
    "            sa, sb = ref[\"steps\"][f\"arloop-{arm}-s11@{L}\"], ref[\"steps\"][f\"prenorm-{arm}-s11@{L}\"]\n",
    "            pa, ps = ref[\"pairs\"][f\"actions:{arm}@{L}\"], ref[\"pairs\"][f\"steps:{arm}@{L}\"]\n",
    "            rows.append((arm, L, f\"{a['mean_accepted_actions']:.2f} / {b['mean_accepted_actions']:.2f}\",\n",
    "                         f\"{pa['a_gt_b']} / {pa['a_lt_b']}\", lib.pvalue(pa[\"sign_p\"]),\n",
    "                         f\"{sa['valid']} / {sb['valid']} of {sa['n']}\", lib.pvalue(ps[\"mcnemar_p\"])))\n",
    "    lib.md(lib.table(rows, [\"arm\", \"R\", \"accepted actions per attempt, ARLoop / PreNorm\",\n",
    "                            \"targets longer: ARLoop / PreNorm\", \"sign test p\",\n",
    "                            \"single-step valid, ARLoop / PreNorm\", \"exact McNemar p\"]))\n",
    "    reuse = \"the name '<x>' is already in use; choose a fresh name.\"\n",
    "    allre = {b: [k.split('-s11@')[0].split('-', 1)[1] + ' R = ' + k.split('@')[1] for k, v in sx.items()\n",
    "                 if k.startswith(b) and v['error_classes'].get(reuse, 0) == v['n']] for b in ('arloop', 'prenorm')}\n",
    "    collapsed = {k for k, v in sx.items() if v[\"status\"].get(\"malformed_or_truncated\", 0) == v[\"n\"]}\n",
    "    cells = [(arm, L) for arm in (\"native3\", \"random124\") for L in (1, 2, 3, 4)\n",
    "             if not {f\"arloop-{arm}-s11@{L}\", f\"prenorm-{arm}-s11@{L}\"} & collapsed]\n",
    "    further = [(arm, L) for arm, L in cells if L != 3]\n",
    "    at3 = [(arm, L) for arm, L in cells if L == 3]\n",
    "    p_further = max(ref[\"pairs\"][f\"actions:{arm}@{L}\"][\"sign_p\"] for arm, L in further)\n",
    "    p_at3 = min(ref[\"pairs\"][f\"actions:{arm}@{L}\"][\"sign_p\"] for arm, L in at3)\n",
    "    lib.md(\"How attempts end (native checker messages): a reused variable name during the opening `intro` run, \"\n",
    "           \"the wrong hypothesis at the first `cases`, or a result that does not match the goal. All 32 attempts \"\n",
    "           f\"end by name reuse in {len(allre['prenorm'])} PreNorm cells ({', '.join(allre['prenorm'])}) and in \"\n",
    "           f\"{len(allre['arloop'])} ARLoop cells.\\n\\n\"\n",
    "           \"The `native3` checkpoints collapse at R = 1 and 2: every attempt ends in a malformed or truncated \"\n",
    "           \"action, as below the trained depth in E1.3. In the \"\n",
    "           f\"{len(further)} other cells with R ≠ 3, ARLoop's attempt is the longer one on more targets (sign test \"\n",
    "           f\"p ≤ {lib.pvalue_bound(p_further)}); at R = 3 neither base is clearly ahead (p ≥ {lib.pvalue(p_at3)}). \"\n",
    "           \"This pattern is a hypothesis, not a result: a confirmatory run would have to fix the measure in \"\n",
    "           \"advance and use targets not seen so far (a proposal is in `experiments/e3_pair/CONFIRM-PROPOSAL.md`).\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1bf4d730",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "if ref is not None:\n",
    "    assert collapsed == {f\"{b}-native3-s11@{L}\" for b in (\"arloop\", \"prenorm\") for L in (1, 2)}\n",
    "    assert len(further) == 4 and len(at3) == 2 and p_further < 1e-3 < 0.05 < p_at3\n",
    "    assert all(ref[\"pairs\"][f\"actions:{arm}@{L}\"][\"a_gt_b\"] > ref[\"pairs\"][f\"actions:{arm}@{L}\"][\"a_lt_b\"]\n",
    "               for arm, L in further)\n",
    "    assert len(allre[\"prenorm\"]) == 4 and not allre[\"arloop\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "436ae5d3",
   "metadata": {},
   "source": [
    "## Why this test\n",
    "\n",
    "In `latent`, a retrofitted recurrent Qwen model gained little from a second pass on checked\n",
    "proofs, and its learned stopping rule collapsed to one pass ({doc}`../latent`). One of the\n",
    "project's hunches is that choosing the next tactic needs earlier goal structure more than deeper\n",
    "computation, and that selective access to earlier depths could help where PreNorm overwrites.\n",
    "E3 is the cleanest available test of that hunch: two released models that differ only in the\n",
    "residual path, fine-tuned identically, and scored by a proof checker rather than by a proxy metric.\n",
    "With 32 targets and one seed it can find a signal worth a confirmatory run, not establish an effect.\n",
    "Stage 1a trains the same pair for longer ({doc}`stage1`)."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
