Appendix: the helper module#
The notebooks share one Python module, book/seminar_lib.py. It is listed here in full so that
every number in the book can be traced to code: the configuration reader and parameter counts, the
replay of ARLoop’s routing schedule, the norm demo, the paper’s tables with their transcription
check, and the paired statistics of the experiments.
"""Shared helpers of the ARLoop seminar notes, imported by every notebook and listed in the appendix.
Everything two notebooks need is defined here once, so that every number in the book can be
traced to code printed in full:
* paths and rendering: `REPO`, `RUNS`, `rel()`, `md()`, `pending()`, `quote_check()`, and the number
formats shared with the digest: `signed()`, `pvalue()`, `pvalue_bound()`; `recheck_verdict()` reads
the verdict of an independent re-check note;
* the released models: `CHECKPOINTS` (pinned revisions, parameter counts from the Hugging Face API
as recorded in `source/SOURCE.md`), `config()` (the `config.json` files of the pinned revisions,
stored in `book/data/hf/`), `routing_parameters()` and `backbone_parameters()`;
* the routing schedule: `schedule()` replays the block commits and the sliding window of the
released forward pass for every effective sublayer (digest §2 and finding F6);
* the residual stream: `stream_norm_demo()` (PreNorm sum against softmax mixtures);
* the paper's tables as they appear in the digest, transcribed once from the LaTeX of v1 (`TAB1`,
`TAB2`, `TAB3`), and `check_transcription()`, which compares them with the LaTeX whenever
`source/latex/` is present (it is git-ignored because of the arXiv licence);
* paired statistics: `mcnemar_exact()`, `paired()` (the computation of
`experiments/e1_release/analyze.py`) and `paired_stratified()` (the one of
`experiments/e2_small/scripts/analyze.py`), so that the book can re-derive what those scripts
wrote;
* charts: `PALETTE`, `tint()`, `ramp()`, `figure()` and `style()`, one look for every chart, with the
colour meanings of the deck and the pages (`DESIGN.md`): ARLoop indigo, PreNorm gold, checked
cypress, a finding carmine, everything else neutral ink.
"""
from __future__ import annotations
import hashlib
import json
import math
import os
import random
import re
from pathlib import Path
import numpy as np
BOOK = Path(__file__).resolve().parent
REPO = BOOK.parent
# The result chapters read runs/; SEMINAR_RUNS_DIR points them at a mock tree when testing them.
RUNS = Path(os.environ.get("SEMINAR_RUNS_DIR", REPO / "runs"))
LABYRINTH = REPO / "labyrinth"
LATEX = REPO / "source" / "latex"
HF_DIR = BOOK / "data" / "hf"
DIGEST = REPO / "artifacts" / "mathematical" / "digest.md"
PROTOCOL = {e: REPO / "experiments" / d / "PROTOCOL.md"
for e, d in (("E1", "e1_release"), ("E2", "e2_small"), ("E3", "e3_pair"))}
# --------------------------------------------------------------------------------------------
# Rendering helpers (IPython is imported lazily, so the module also works in a plain script).
# --------------------------------------------------------------------------------------------
def rel(path) -> str:
"""A path relative to the repository root, for display (absolute if outside it)."""
path = Path(path).resolve()
return str(path.relative_to(REPO)) if path.is_relative_to(REPO) else str(path)
def md(text: str):
"""Display MyST markdown computed in a cell (rendered by myst-nb at build time)."""
from IPython.display import Markdown, display
display(Markdown(text))
def pending(title: str, body: str):
"""A visible 'pending' admonition: a result file is not there yet, so nothing is shown."""
md(f":::{{admonition}} Pending: {title}\n:class: warning\n{body}\n:::")
def note(title: str, body: str, cls: str = "note"):
md(f":::{{admonition}} {title}\n:class: {cls}\n{body}\n:::")
def table(rows, header) -> str:
"""A markdown table from a list of row tuples."""
out = ["| " + " | ".join(header) + " |", "|" + "---|" * len(header)]
out += ["| " + " | ".join(str(c) for c in r) + " |" for r in rows]
return "\n".join(out)
def quote_check(path, *snippets) -> bool:
"""True if every snippet occurs in the text file `path` (used to guard quoted protocol facts)."""
text = " ".join(Path(path).read_text().split())
return all(" ".join(s.split()) in text for s in snippets)
def sha256(path) -> str:
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def read_json(path):
path = Path(path)
return json.loads(path.read_text()) if path.exists() else None
MINUS = "−"
_SUPERSCRIPT = str.maketrans("0123456789-", "⁰¹²³⁴⁵⁶⁷⁸⁹⁻")
def signed(x: float, digits: int = 2) -> str:
"""A signed number with a typographic minus, as in the digest: +5.16, −0.45."""
return f"{x:+.{digits}f}".replace("-", MINUS)
def pvalue(p: float) -> str:
"""A p-value with two significant digits, as in the digest: 0.12, 0.0052, 6.5 × 10⁻⁵ (no-break
spaces around ×, so that a table cell never wraps inside the number)."""
if p >= 0.001:
return f"{p:.2g}"
m, e = f"{p:.1e}".split("e")
return f"{m} × 10{str(int(e)).translate(_SUPERSCRIPT)}"
def pvalue_bound(p: float) -> str:
"""An upper bound for p, rounded up to two significant digits (p ≤ bound): 1.13e-4 -> 1.2 × 10⁻⁴."""
e = math.floor(math.log10(p))
m = math.ceil(round(p / 10 ** (e - 1), 9)) / 10
if m >= 10:
m, e = m / 10, e + 1
if e >= -3:
return f"{m * 10 ** e:.{max(0, 1 - e)}f}"
return f"{m:.1f} × 10{str(e).translate(_SUPERSCRIPT)}"
def recheck_verdict(text: str) -> str | None:
"""The verdict of an independent re-check note (`runs/*/referee.md`, line 'Verdict: **...** (...)'):
the bold verdict in lower case, with those parenthetical details that state counts (such as
'0/32 in all 16 suites'); None if the note has no verdict line."""
m = re.search(r"Verdict: \*\*(.+?)\*\*\s*(?:\(([^)]*)\))?", text)
if not m:
return None
verdict = m.group(1).replace("ESTABLISHED", "established")
counts = [d.strip() for d in (m.group(2) or "").split(";") if re.search(r"\d+/\d+", d)]
return verdict + (f" ({'; '.join(counts)})" if counts else "")
# --------------------------------------------------------------------------------------------
# The released models
# --------------------------------------------------------------------------------------------
CHECKPOINTS = {
# Hugging Face repository, pinned revision, parameter count from the Hugging Face API
# (source/SOURCE.md, 2026-11-15) and SHA-256 of the config.json stored in book/data/hf/.
"ARLoop-0.6B": {"repo": "osunlp/ARLoop-0.6B",
"revision": "5cd28f3dbf0d46a7f82f9d34b62aca42ac0ab039",
"parameters": 583_138_944,
"config_sha256": "d4de7ddcfc27fc1a4d672339ebea7726d3b2085758ea1a1e5c59db4db3fbf365"},
"PreNormLoop-0.6B": {"repo": "osunlp/PreNormLoop-0.6B",
"revision": "e4ad59d0d03ab78f83d9f52b0c7d7267f372a151",
"parameters": 582_804_096,
"config_sha256": "1e0b2e41b5ca188cdbddc8c8313d7f2b84c49dbf9772c1ca6626be4efedc78ea"},
"ARLoop-1.2B": {"repo": "osunlp/ARLoop-1.2B",
"revision": "a29f310ac46646edf5c462425dc546b2ce7ea985",
"parameters": 1_208_655_360,
"config_sha256": "b442805d4d13e95ae050351e8e461836efb8303b1827373353164b2256995d59"},
}
def config(name: str) -> dict:
"""The config.json of a pinned checkpoint, after checking its SHA-256."""
path = HF_DIR / name / "config.json"
assert sha256(path) == CHECKPOINTS[name]["config_sha256"], f"{path} is not the pinned file"
return json.loads(path.read_text())
def effective_sublayers(cfg: dict) -> int:
"""2 sublayers (attention, FFN) per physical layer, looped `loop_count` times."""
return 2 * cfg["physical_layers"] * cfg["loop_count"]
def routing_vectors(cfg: dict) -> dict:
"""Depth-indexed routing parameters of ARLoop, each a vector of length hidden_size:
one query and one RMSNorm weight per effective sublayer, plus the read-out query and norm
(`attnres_queries`, `attnres_norms`, `final_attnres_query`, `final_attnres_norm`)."""
n = effective_sublayers(cfg)
return {"queries": n, "norms": n, "final query": 1, "final norm": 1}
def routing_parameters(cfg: dict) -> int:
return sum(routing_vectors(cfg).values()) * cfg["hidden_size"]
def backbone_parameters(cfg: dict) -> dict:
"""Parameters shared by ARLoop and PreNormLoop, by module, from the module list of the released
modeling code at the pinned revisions (`modeling_arloop.py`, `modeling_baseline.py`): tied token
embedding; one shared value embedding (vocab x kv_dim); per physical layer the projections
c_q, c_k, c_v, c_proj, the SwiGLU matrices fc (d -> 2I) and proj (I -> d) and two RMSNorm
weights; a value-embedding gate (32 -> kv heads) in every second layer; the final RMSNorm.
Q/K normalisation is parameter-free."""
d, V, L = cfg["hidden_size"], cfg["vocab_size"], cfg["physical_layers"]
kv = cfg["num_key_value_heads"] * cfg["head_dim"]
inter = cfg["intermediate_size"]
gated = [layer for layer in range(L) if layer % 2 == (L - 1) % 2]
return {
"token embedding (tied with the LM head)": V * d,
"shared value embedding": V * kv,
"attention projections": L * (d * d + 2 * d * kv + d * d),
"SwiGLU MLP": L * (d * 2 * inter + inter * d),
"RMSNorm weights in the blocks": L * 2 * d,
"value-embedding gates": len(gated) * 32 * cfg["num_key_value_heads"],
"final RMSNorm": d,
}
# --------------------------------------------------------------------------------------------
# The routing schedule: which residual sources each routing call reads
# --------------------------------------------------------------------------------------------
def schedule(cfg: dict, loops: int | None = None, embedding_in_first_block: bool = True) -> list:
"""Replay the bookkeeping of ARLoop's forward pass and return one record per routing call.
The rule is the one of the released code (digest §2): `blocks = [h0]`, `partial = h0` (finding
F6; `embedding_in_first_block=False` gives eq. (4) of the paper, whose first partial block is
empty); before each sublayer the router reads `blocks + [partial]`, cut to the embedding plus
the `sw_blocks` most recent entries when the list is longer than that; the partial block is
committed at the start of every effective layer l > 0 with l = 0 mod (block size / 2), after
the routing of that layer's attention sublayer and before its update; a last routing call
(the read-out query) produces the state passed to the final norm and the LM head.
Record fields: `call` (0, 1, ...: the code's order, 2l for attention and 2l + 1 for the FFN of
layer l), `layer` (0-based effective layer, None for the read-out), `loop` (1-based), `kind`
("attn", "ffn", "readout"), `ids` (indices into blocks + [partial]: 0 is the embedding, k the
committed block b_k, the last index the partial block), `labels` ("e", "b1", ..., "p") and
`terms` (what each source sums: "h0" and the 0-based calls whose update it contains).
"""
L = cfg["physical_layers"]
R = loops or cfg["loop_count"]
W = cfg["sw_blocks"]
per_block = cfg["attnres_block_size"] // 2 # layers per residual block
blocks = [("e", ("h0",))]
partial = ("h0",) if embedding_in_first_block else ()
calls = []
def read(kind, layer):
values = blocks + ([("p", partial)] if partial else [])
ids = list(range(len(values)))
if len(values) > W + 1:
ids = [ids[0], *ids[-W:]]
calls.append({"call": len(calls), "layer": layer,
"loop": None if layer is None else layer // L + 1, "kind": kind,
"ids": ids, "labels": [values[i][0] for i in ids],
"terms": [values[i][1] for i in ids], "committed": len(blocks) - 1})
for layer in range(L * R):
read("attn", layer)
if layer > 0 and layer % per_block == 0:
blocks.append((f"b{len(blocks)}", partial))
partial = ()
partial = partial + (2 * layer,)
read("ffn", layer)
partial = partial + (2 * layer + 1,)
read("readout", None)
return calls
def commit_layers(cfg: dict, loops: int | None = None) -> list:
"""Effective layers at whose start a residual block is committed."""
per_block = cfg["attnres_block_size"] // 2
n_layers = cfg["physical_layers"] * (loops or cfg["loop_count"])
return [layer for layer in range(1, n_layers) if layer % per_block == 0]
def describe_terms(terms) -> str:
"""'h0 + z[55..72]' style description of a source (z indexed by 0-based routing call)."""
parts = ["h0"] if "h0" in terms else []
zs = sorted(t for t in terms if t != "h0")
if zs:
parts.append(f"z[{zs[0]}]" if len(zs) == 1 else f"z[{zs[0]}..{zs[-1]}]")
return " + ".join(parts) if parts else "(empty)"
def query_rule(loop: int, trained: int, rule: str) -> int:
"""Which trained loop's queries a loop uses (1-based), as in experiments/e1_release/loopctl.py:
`repeat` reuses the last trained loop, `cycle` reuses loop ((k - 1) mod R_train) + 1."""
if loop <= trained:
return loop
return trained if rule == "repeat" else (loop - 1) % trained + 1
# --------------------------------------------------------------------------------------------
# Charts: one look for every figure of the notes (DESIGN.md, sections 2 and 4)
# --------------------------------------------------------------------------------------------
PALETTE = {
"ar": "#3F4FC4", # ARLoop, attention over depth (indigo)
"pn": "#A86F0C", # the PreNorm loop (gold)
"check": "#13703F", # checked or re-checked (cypress)
"err": "#B4232C", # a finding about the paper, a failure (carmine)
"neutral": "#5E6A61", # everything else: other models, controls, labels
"ink": "#111C16",
"rule": "#DCD8CC", # hairline grid
"axis": "#B8B3A6",
"paper": "#FBF9F3", # the notes' page colour
}
def tint(color: str, t: float) -> str:
"""`color` mixed with the page colour: t = 0 gives the page, t = 1 the colour itself."""
a = [int(color[i:i + 2], 16) for i in (1, 3, 5)]
b = [int(PALETTE["paper"][i:i + 2], 16) for i in (1, 3, 5)]
return "#" + "".join(f"{round(y + t * (x - y)):02X}" for x, y in zip(a, b))
def ramp(color: str, n: int, lightest: float = 0.3) -> list:
"""n shades of one hue from light to dark: more loops or more training is darker."""
return [tint(color, lightest + (1 - lightest) * k / max(n - 1, 1)) for k in range(n)]
def figure(*args, **kwargs):
"""`plt.subplots` on the page colour, with Inter for the labels when it is installed."""
import matplotlib.pyplot as plt
from matplotlib import font_manager
if any(f.name == "Inter" for f in font_manager.fontManager.ttflist):
plt.rcParams["font.family"] = ["Inter", "DejaVu Sans"]
return plt.subplots(*args, facecolor=PALETTE["paper"], **kwargs)
def style(ax, grid: str | None = "y"):
"""The notes' axes: page colour, no top or right spine, a hairline grid, muted ticks and labels."""
ax.set_facecolor(PALETTE["paper"])
for side in ("top", "right"):
ax.spines[side].set_visible(False)
for side in ("left", "bottom"):
ax.spines[side].set_color(PALETTE["axis"])
if grid:
ax.grid(axis=grid, color=PALETTE["rule"], lw=0.8)
ax.set_axisbelow(True)
ax.tick_params(colors=PALETTE["neutral"], labelsize=8.5)
ax.xaxis.label.set_color(PALETTE["neutral"])
ax.yaxis.label.set_color(PALETTE["neutral"])
ax.title.set_color(PALETTE["ink"])
return ax
# The residual stream: how large does it get?
# --------------------------------------------------------------------------------------------
def _softmax(x):
e = np.exp(x - x.max())
return e / e.sum()
def stream_norm_demo(cfg: dict, d: int | None = None, seed: int = 20261117, scale: float = 2.0) -> dict:
"""Norm of the state each routing call reads, s = 0, ..., n (n = number of effective sublayers;
call n is the read-out), when h0 and every update are unit vectors orthogonal to everything
before them.
* `prenorm[s]` = ||h0 + z_0 + ... + z_(s-1)||, the PreNorm stream; it equals sqrt(1 + s).
* `mixture[s]`: a softmax mixture with random scores over all sources {h0, z_0, ..., z_(s-1)}.
* `block[s]` and `bound[s]`: block attention residuals on the schedule of `cfg` (window, block
commits, F6) with random scores, and the largest norm among the sources that call reads.
"""
n = effective_sublayers(cfg)
d = d or cfg["hidden_size"]
rng = np.random.default_rng(seed)
basis, _ = np.linalg.qr(rng.standard_normal((d, n + 1))) # orthonormal columns
h0, Z = basis[:, 0], basis[:, 1:].T # Z[t] is the update produced after routing call t
prenorm = np.linalg.norm(np.vstack([h0, h0 + np.cumsum(Z, axis=0)]), axis=1)
mixture = np.empty(n + 1)
for s in range(n + 1):
sources = np.vstack([h0, Z[:s]])
mixture[s] = np.linalg.norm(_softmax(scale * rng.standard_normal(s + 1)) @ sources)
block, bound = np.empty(n + 1), np.empty(n + 1)
for rec in schedule(cfg):
vecs = np.array([sum((h0 if t == "h0" else Z[t]) for t in terms) for terms in rec["terms"]])
block[rec["call"]] = np.linalg.norm(_softmax(scale * rng.standard_normal(len(vecs))) @ vecs)
bound[rec["call"]] = np.linalg.norm(vecs, axis=1).max()
return {"prenorm": prenorm, "mixture": mixture, "block": block, "bound": bound}
# --------------------------------------------------------------------------------------------
# The paper's tables (v1), as they appear in the digest, transcribed from the LaTeX
# --------------------------------------------------------------------------------------------
# Table 1 (tables/results_comparison.tex): validation perplexity, 10M FineWeb-Edu tokens.
TAB1_COLS = [("140M", 1), ("140M", 3), ("140M", 5), ("370M", 1), ("370M", 3)]
TAB1 = {
"Sandwich-Norm": [18.98, 17.19, 16.59, 13.92, 12.97],
"DeepLoop": [18.72, 17.05, 16.52, 13.69, 12.78],
"Parcae w/o injection": [18.37, 16.60, 16.01, 13.55, 12.31],
"Parcae with injection": [18.37, 16.55, 15.96, 13.55, 12.30],
"PreNormLoop": [18.37, 16.91, 16.34, 13.55, 12.48],
"ARLoop": [18.26, 16.38, 15.84, 13.32, 12.17],
}
# Table 2 (tables/routing_granularity.tex): (scale, R) -> PPL (PreNorm, full, window) and
# downstream average (PreNorm, full, window).
TAB2 = {
("140M", 2): {"ppl": [17.48, 17.27, 17.30], "down": [42.22, 41.96, 42.27]},
("140M", 3): {"ppl": [16.91, 16.46, 16.38], "down": [42.72, 43.69, 43.09]},
("140M", 4): {"ppl": [16.59, 16.07, 16.03], "down": [43.27, 44.09, 43.73]},
("370M", 2): {"ppl": [12.83, 12.68, 12.55], "down": [48.98, 48.70, 49.25]},
("370M", 3): {"ppl": [12.48, 12.27, 12.17], "down": [49.29, 50.23, 50.67]},
("370M", 4): {"ppl": [12.27, 12.01, 11.99], "down": [50.19, 50.93, 50.76]},
}
TAB2_VARIANTS = ["PreNorm", "full history", "window"]
# Table 3 (tables/scaling_results.tex), the rows kept in the digest: loops (None = not looped),
# training FLOPs (1e21), tokens (T), then the eight benchmarks.
TAB3_COLS = ["loops", "FLOPs", "tokens"]
BENCHMARKS = ["ARC-C", "HellaSwag", "WinoGrande", "OBQA", "GSM8K", "MATH", "MBPP", "HumanEval"]
TAB3 = {
"Qwen3.5-2B": [None, 432, 36, 54.3, 67.5, 66.4, 37.8, 60.6, 35.8, 49.5, 32.9],
"Ouro-1.4B": [4, 259, 7.7, 59.9, 74.4, 70.5, 41.4, 78.2, 70.5, 68.3, 52.4],
"Huginn-3.5B": [32, 127, 0.8, 44.2, 68.0, 62.4, 40.0, 26.1, 14.1, 33.3, 20.7],
"PreNormLoop-0.6B": [3, 2, 0.18, 46.3, 60.6, 61.2, 39.8, 35.7, 20.9, 33.1, 17.6],
"ARLoop-0.6B": [3, 2, 0.18, 45.5, 62.5, 61.8, 40.8, 40.9, 26.3, 36.2, 20.1],
"ARLoop-1.2B": [3, 10, 0.5, 56.3, 71.5, 66.8, 45.5, 63.1, 37.8, 52.1, 33.1],
}
def scores(model: str) -> dict:
"""Benchmark -> score of a Table 3 row."""
return dict(zip(BENCHMARKS, TAB3[model][3:]))
def wins(a: str, b: str) -> list:
"""Benchmarks of Table 3 on which model a scores strictly higher than model b."""
sa, sb = scores(a), scores(b)
return [k for k in BENCHMARKS if sa[k] > sb[k]]
def _latex_rows(path: Path) -> list:
"""Numeric cells of each row of a LaTeX tabular (labels dropped), in order."""
body = path.read_text()
body = re.sub(r"%.*", "", body)
body = re.sub(r"\\(?:citep|cite|multirow|multicolumn|cmidrule|resizebox)(\[[^]]*\])?(\{[^}]*\})+", " ", body)
body = re.sub(r"\\textbf\{([^}]*)\}", r"\1", body)
body = re.sub(r"\\rowcolor\{[^}]*\}", " ", body)
body = body.replace("{", " ").replace("}", " ")
rows = []
for row in body.split("\\\\"):
cells = row.split("&")
if len(cells) < 3:
continue
nums = []
for cell in cells[1:]:
cell = cell.strip()
if re.fullmatch(r"-?\d+(\.\d+)?", cell):
nums.append(float(cell))
elif cell in ("None", "--", "–"):
nums.append(None)
if nums:
rows.append((" ".join(cells[0].split()), nums))
return rows
def check_transcription(latex_dir: Path = LATEX) -> dict | None:
"""Compare TAB1-TAB3 with the paper's LaTeX tables; None if the LaTeX is not present."""
if not (latex_dir / "tables").is_dir():
return None
report = {}
t1 = [nums for _, nums in _latex_rows(latex_dir / "tables" / "results_comparison.tex")]
report["Table 1"] = t1 == list(TAB1.values())
t2 = [nums for _, nums in _latex_rows(latex_dir / "tables" / "routing_granularity.tex")]
report["Table 2"] = [n[1:] for n in t2] == [v["ppl"] + v["down"] for v in TAB2.values()] and \
[int(n[0]) for n in t2] == [r for _, r in TAB2]
t3 = _latex_rows(latex_dir / "tables" / "scaling_results.tex")
names = {"Qwen3.5-2B": "Qwen3.5-2B", "Ouro-1.4B": "Ouro-1.4B", "Huginn-3.5B": "Huginn-3.5B",
"PreNormLoop-0.6B": "\\prenormSmallModel (Ours)", "ARLoop-0.6B": "\\recurrentSmallModel (Ours)",
"ARLoop-1.2B": "\\recurrentLargeModel (Ours)"}
# every row kept in the digest occurs in the LaTeX table (Huginn has two rows there: 0.18T, 0.8T)
report["Table 3"] = all([latex, TAB3[ours]] in [list(r) for r in t3] for ours, latex in names.items())
return report
# --------------------------------------------------------------------------------------------
# Paired statistics (same computation as experiments/e1_release/analyze.py)
# --------------------------------------------------------------------------------------------
def mcnemar_exact(only_a: int, only_b: int) -> float:
"""Exact two-sided McNemar test: binomial test on the discordant items."""
n, k = only_a + only_b, min(only_a, only_b)
if n == 0:
return 1.0
return min(1.0, 2 * sum(math.comb(n, i) for i in range(k + 1)) / 2 ** n)
def paired(a: dict, b: dict, seed: int = 20261115, B: int = 10000, bootstrap: bool = True) -> dict:
"""Accuracies, difference, discordant counts, exact McNemar p and (optionally) the paired
bootstrap 95% interval of analyze.py: B resamples of the n items with random.Random(seed),
interval [d[int(0.025 B)], d[int(0.975 B) - 1]] of the sorted resampled differences."""
ids = sorted(set(a) & set(b))
x, y = [a[i] for i in ids], [b[i] for i in ids]
n = len(ids)
oa = sum(1 for p, q in zip(x, y) if p > q)
ob = sum(1 for p, q in zip(x, y) if q > p)
out = {"n": n, "acc_a": sum(x) / n, "acc_b": sum(y) / n, "diff": (sum(x) - sum(y)) / n,
"only_a": oa, "only_b": ob, "mcnemar_p": mcnemar_exact(oa, ob)}
if bootstrap:
rng = random.Random(seed)
d = sorted(sum(x[i] - y[i] for i in (rng.randrange(n) for _ in range(n))) / n for _ in range(B))
out["ci95"] = [d[int(0.025 * B)], d[int(0.975 * B) - 1]]
return out
def paired_stratified(x: dict, y: dict, seeds, rng_seed: int = 20261115, resamples: int = 10000) -> dict:
"""The paired comparison of experiments/e2_small/scripts/analyze.py. Units are (seed, item)
keys with 0/1 values; returns the accuracy difference, per-seed count differences, discordant
counts, the exact McNemar p, a 95% bootstrap interval that resamples items within each seed
(interval [d[249], d[9749]] of 10,000 sorted draws) and the pre-registered candidate-effect
rule: the interval excludes 0 and all per-seed differences have the same non-zero sign."""
units = sorted(x)
assert units == sorted(y)
diff = {u: x[u] - y[u] for u in units}
n = len(units)
per_seed = {s: sum(v for u, v in diff.items() if u[0] == s) for s in seeds}
only_x = sum(1 for v in diff.values() if v > 0)
only_y = sum(1 for v in diff.values() if v < 0)
if only_x + only_y == 0:
ci = [0.0, 0.0]
else:
rng = random.Random(rng_seed)
strata = [[diff[u] for u in units if u[0] == s] for s in seeds]
draws = []
for _ in range(resamples):
total = 0
for values in strata:
m = len(values)
total += sum(values[rng.randrange(m)] for _ in range(m))
draws.append(total / n)
draws.sort()
ci = [draws[int(0.025 * resamples) - 1], draws[int(0.975 * resamples) - 1]]
signs = {(v > 0) - (v < 0) for v in per_seed.values()}
candidate = (ci[0] > 0 or ci[1] < 0) and len(signs) == 1 and 0 not in signs
return {"n": n, "acc_x": sum(x.values()) / n, "acc_y": sum(y.values()) / n,
"diff": sum(diff.values()) / n, "per_seed_count_diff": per_seed,
"only_x": only_x, "only_y": only_y, "mcnemar_p": mcnemar_exact(only_x, only_y),
"ci95": ci, "candidate_effect": candidate}
def samples_em(path) -> dict | None:
"""doc_id -> exact match (flexible-extract) from an lm-eval samples.jsonl written by run_lmeval.py."""
path = Path(path)
if not path.exists():
return None
rows = [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
if "flexible-extract" not in {r.get("filter") for r in rows}:
return None # analyze.py rejects runs without filter labels as well
return {r["doc_id"]: float(r["exact_match"]) for r in rows if r.get("filter") == "flexible-extract"}