{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2c430a89",
   "metadata": {},
   "source": [
    "# The latent programme in one page\n",
    "\n",
    "`latent` is the sibling project this talk comes from: recurrent depth for **checked** proofs in\n",
    "Heyting and Peano arithmetic. Its results are recorded as nodes of the research map in\n",
    "`labyrinth/knowledge.json`. This page is generated from that file while the book is built, so it\n",
    "says what the map says, in the notation and typography of these notes ($R$ for the number of loops,\n",
    "which the map writes $r$ for the canary and $L$ for E3); the review notes of the statuses are put in\n",
    "plain words, and where a statement is made more exact than the map's wording, the end of the page\n",
    "says so."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a84637b1",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "import sys, pathlib, json, re\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",
    "K = json.loads((lib.LABYRINTH / \"knowledge.json\").read_text())\n",
    "nodes = {n[\"id\"]: n for n in K[\"nodes\"]}\n",
    "SOTA = json.loads((lib.LABYRINTH / \"sota.json\").read_text())\n",
    "\n",
    "\n",
    "def status(text):\n",
    "    \"\"\"A node's status in plain words: its first part ('established', 'measured', 'open', ...), whether\n",
    "    it is exploratory or descriptive, and whether it was independently re-checked (the map's review\n",
    "    notes in parentheses name internal roles and dates; only their meaning is kept).\"\"\"\n",
    "    head, _, note = (text or \"–\").partition(\" (\")\n",
    "    quals = [q for q in (\"exploratory\", \"descriptive\") if q in note]\n",
    "    if re.search(r\"unreviewed|not (yet )?(re-checked|refereed|reviewed)\", note):\n",
    "        quals.append(\"not independently re-checked\")\n",
    "    elif re.search(r\"independent|refereed|reviewed|audit|recount\", note):\n",
    "        quals.append(\"independently re-checked\")\n",
    "    shown.append(f\"{head} ({', '.join(quals)})\" if quals else head)\n",
    "    return shown[-1]\n",
    "\n",
    "\n",
    "shown = []                                      # every status shown on this page (checked at the end)\n",
    "\n",
    "_SUP = str.maketrans(\"0123456789-\", \"⁰¹²³⁴⁵⁶⁷⁸⁹⁻\")\n",
    "_REL = {\">=\": \"≥\", \"<=\": \"≤\", \"=\": \"=\"}\n",
    "\n",
    "\n",
    "def tidy(text):\n",
    "    \"\"\"Map text in the notes' notation and typography (DESIGN.md §5): R for the number of loops, powers of ten,\n",
    "    arrows and relations, ≈, en dashes in numeric ranges, the minus sign, ‖h₀‖, read-out, Campaign.\"\"\"\n",
    "    s = text or \"–\"\n",
    "    s = re.sub(r\"\\b[rR](>=|=)(\\d+) (\\d+)\\b\", lambda m: f\"R {_REL[m.group(1)]} {m.group(2)}: {m.group(3)}\", s)\n",
    "    s = re.sub(r\"\\b[rLR]\\s*(>=|<=|=)\\s*(?=\\d)\", lambda m: f\"R {_REL[m.group(1)]} \", s)\n",
    "    s = re.sub(r\"(\\d(?:\\.\\d+)?)e-(\\d+)\", lambda m: f\"{m.group(1)} × 10\" + (\"-\" + m.group(2)).translate(_SUP), s)\n",
    "    s = s.replace(\"->\", \" → \").replace(\">=\", \"≥\").replace(\"<=\", \"≤\").replace(\"  →  \", \" → \")\n",
    "    s = re.sub(r\"(\\d)\\.\\.(\\d)\", r\"\\1–\\2\", s)\n",
    "    s = re.sub(r\"~(?=\\d)\", \"≈\", s)\n",
    "    s = re.sub(r\"(?<![\\w.\\-])(\\d+(?:\\.\\d+)?)-(\\d+(?:\\.\\d+)?)(?![\\w\\-])\", r\"\\1–\\2\", s)\n",
    "    s = re.sub(r\"(?<![\\w)\\]])-(?=\\d)\", \"−\", s)\n",
    "    s = s.replace(\"||h0||=\", \"‖h₀‖ = \").replace(\"||h0||\", \"‖h₀‖\")\n",
    "    s = re.sub(r\"\\breadout\\b\", \"read-out\", s)\n",
    "    s = re.sub(r\"\\bcampaign (\\d)\", r\"Campaign \\1\", s)\n",
    "    return s\n",
    "\n",
    "\n",
    "# Made more exact than the map's wording (applied only while the map still has the old text; listed at the end).\n",
    "_e1 = json.loads((lib.RUNS / \"e1\" / \"routing\" / \"ar06-R3\" / \"routing.json\").read_text())\n",
    "_nw = [sum(_e1[\"embedding_share_norm_weighted\"][a:b]) / (b - a) for a, b in ((1, 36), (36, 72), (72, 108))]\n",
    "_share = f\"{100 * min(_nw):.1f}–{100 * max(_nw):.1f}%\"\n",
    "EXACT = [(\"only 2-3% norm-weighted\", f\"only {_share} norm-weighted\",\n",
    "          \"the norm-weighted embedding share per loop, computed from the routing probe\"),\n",
    "         (\"contributes only 2-3% of the mixture\", f\"contributes only {_share} of the mixture\",\n",
    "          \"the same share, in the answer to `q.embedding`\"),\n",
    "         (\"A second, independent run of PreNormLoop-0.6B with BOS\", \"A repeat run of PreNormLoop-0.6B with the same settings\",\n",
    "          \"the second PreNormLoop-0.6B run repeated the same settings\"),\n",
    "         (\"checked HA proofs, 192 fresh\", \"checked Heyting-arithmetic (HA) proofs, 192 fresh theorems\",\n",
    "          \"HA spelled out\")]\n",
    "applied = []\n",
    "\n",
    "\n",
    "def exact(text):\n",
    "    for old, new, why in EXACT:\n",
    "        if text and old in text:\n",
    "            text = text.replace(old, new)\n",
    "            applied.append(why)\n",
    "    return text\n",
    "\n",
    "\n",
    "def show(text):\n",
    "    return tidy(exact(text))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11269e16",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "src = nodes[\"src.latent\"]\n",
    "lib.md(f\"**{src['title']}.** {show(src['statement'])}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34a90913",
   "metadata": {},
   "source": [
    "## What latent established"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5c7d2c2",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "latent = [n for n in K[\"nodes\"] if n[\"id\"].startswith(\"l.\")]\n",
    "lib.md(lib.table([(f\"`{n['id']}`\", n[\"title\"], show(n[\"statement\"]), status(n.get(\"status\"))) for n in latent],\n",
    "                 [\"node\", \"finding\", \"what was measured\", \"status\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "adeb937c",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert {n[\"id\"] for n in latent} >= {\"l.c7forced\", \"l.gate\", \"l.canary\"}\n",
    "assert all(n.get(\"tier\") == \"T4\" for n in latent)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2be89f7d",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "dead = [n for n in K[\"nodes\"] if n[\"kind\"] == \"deadend\"]\n",
    "lib.md(\"**Dead ends.** \" + \" \".join(f\"*{n['title']}*: {show(n['statement'])} Lesson: {show(n['lesson'])}\" for n in dead))\n",
    "c7 = next(e for e in SOTA[\"entries\"] if e[\"id\"] == \"latent-c7\")\n",
    "lib.md(f\"**Best measured result in the latent regime** (`labyrinth/sota.json`): {show(c7['cls'])}: \"\n",
    "       f\"{show(c7['result'])}. Status: {status(c7['status'])}.\")\n",
    "lib.md(\"The two Campaign 7 lines measure different things: the row `l.c7forced` forces the number of passes for \"\n",
    "       \"every theorem (with adaptive checkpoints), while the best-result line compares methods at equal wall-clock \"\n",
    "       \"time on fresh theorems, so their depth-two numbers differ.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a7739e6",
   "metadata": {},
   "source": [
    "## The question it hands to ARLoop\n",
    "\n",
    "`latent` found that extra passes of a retrofitted recurrent model rarely helped checked proofs, and\n",
    "that learned stopping collapsed to a single pass. ARLoop claims that the **residual design**\n",
    "affects how much later passes are used. The map turns this into open questions and hunches. The\n",
    "hunches are speculation, never claims: tier T6, the lowest of the project's evidence scale\n",
    "({doc}`tests/tests`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb59b68c",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "qs = [nodes[q] for q in (\"q.canary\", \"q.proofs\", \"q.embedding\", \"q.extrap\", \"q.pairgsm8k\") if q in nodes]\n",
    "lib.md(lib.table([(f\"`{q['id']}`\", q[\"title\"], status(q.get(\"status\")), show(q.get(\"next\", \"–\")),\n",
    "                   show(q.get(\"answer\")) if q.get(\"answer\") else \"–\") for q in qs],\n",
    "                 [\"question\", \"\", \"status\", \"test\", \"answer\"]))\n",
    "hunches = [n for n in K[\"nodes\"] if n[\"kind\"] == \"hunch\"]\n",
    "lib.md(lib.table([(f\"`{h['id']}`\", h[\"title\"], show(h[\"statement\"]), status(h.get(\"status\"))) for h in hunches],\n",
    "                 [\"hunch (T6)\", \"\", \"statement\", \"status\"]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2221b968",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "answered = [n for n in K[\"nodes\"] if any(l.get(\"rel\") == \"answers\" for l in n.get(\"links\", []))]\n",
    "if answered:\n",
    "    lib.md(\"**Answered so far:**\\n\\n\" + \"\\n\".join(\n",
    "        f\"* `{n['id']}`: {show(n['statement'])} Status: {status(n.get('status'))}.\" for n in answered))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f3ca8787",
   "metadata": {},
   "source": [
    "The full research map, with every planned test cell of E1–E3 marked as established, contradicted\n",
    "or still open, is not published; a slide near the end of the talk summarises it: how many statements\n",
    "of each kind it holds, and the state of every test cell."
   ]
  },
  {
   "cell_type": "code",
   "id": "4f9ce89f",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "source": [
    "if applied:\n",
    "    lib.md(\"**Made more exact than the map's wording on this page:** \" + \"; \".join(dict.fromkeys(applied)) + \".\")\n"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b26db207",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "# the statuses on this page read in plain words: no internal role names or process notes\n",
    "assert shown and not any(re.search(r\"(?i)coordinator|referee|builder|pending|\\.md\\b\", s) for s in shown)\n",
    "# the typography pass leaves no ASCII forms of the rules it applies (checked on everything it touched)\n",
    "shown_text = [show(n.get(k)) for n in K[\"nodes\"] for k in (\"statement\", \"next\", \"answer\", \"lesson\") if n.get(k)]\n",
    "assert not any(re.search(r\"\\b[rL]\\s*(=|>=)\\s*\\d|->|>=|\\|\\|h0|\\breadout\\b|\\d\\.\\.\\d|(?<![\\w)\\]])-\\d\", t) for t in shown_text)\n",
    "assert 0.02 < min(_nw) < max(_nw) < 0.04"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
