File size: 30,254 Bytes
fdcbc89
 
 
 
 
 
 
 
 
f317f35
 
bbb8ed2
8effdad
a436531
bbb8ed2
a436531
fdcbc89
 
 
26b9902
fdcbc89
 
 
 
 
 
 
 
 
 
 
 
 
 
a436531
bbb8ed2
 
fdcbc89
 
 
 
bbb8ed2
fdcbc89
 
 
 
a4589e7
fdcbc89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f317f35
fdcbc89
 
 
 
 
 
 
f317f35
 
fdcbc89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f317f35
fdcbc89
 
a436531
fdcbc89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbb8ed2
 
fdcbc89
a436531
 
fdcbc89
 
 
 
f317f35
 
 
 
fdcbc89
 
a436531
fdcbc89
 
 
 
 
 
 
f317f35
 
fdcbc89
 
 
a436531
fdcbc89
 
 
 
a436531
 
 
 
 
 
 
8effdad
 
 
 
fdcbc89
 
 
 
2624061
 
 
 
 
 
 
 
 
 
 
 
fdcbc89
 
 
 
 
 
 
 
 
 
 
2624061
 
fdcbc89
 
 
 
 
 
f317f35
fdcbc89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbb8ed2
fdcbc89
bbb8ed2
 
 
f317f35
 
 
 
 
 
 
 
 
 
 
 
 
bbb8ed2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdcbc89
 
26b9902
 
fdcbc89
 
26b9902
 
 
 
 
 
 
 
 
 
fdcbc89
 
7746322
 
 
 
 
f317f35
7746322
 
 
 
 
8dd9042
 
7746322
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a06c2e
 
 
 
 
 
 
 
7746322
 
 
f317f35
 
7746322
f317f35
 
 
7746322
 
 
 
 
f317f35
7746322
 
 
f317f35
 
7746322
 
 
 
 
fdcbc89
 
 
 
f317f35
6c9c630
 
 
a436531
 
 
 
 
 
 
 
 
7746322
f317f35
 
 
 
 
 
419a44e
fdcbc89
 
 
 
 
 
 
 
 
 
6c9c630
fdcbc89
a436531
 
f317f35
 
fdcbc89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26b9902
f317f35
 
a436531
 
 
 
 
 
f317f35
a436531
6c9c630
 
 
 
26b9902
 
7746322
 
fdcbc89
 
 
 
26b9902
 
 
 
 
 
 
 
bbb8ed2
 
26b9902
 
 
 
 
fdcbc89
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
"""Rebuild the public study artifacts from raw results with one command."""

import json
import re
from pathlib import Path
from statistics import median
from urllib.parse import quote

from .report_figures import build_figures
from .audit_report import findings
from .hybrid_results import hybrid_bound_text
from .flatness_progress import geometry_coverage
from .flatness_tables import checkpoint_table,flatness_ledger
from .readme_comparisons import comparison_sections,geometry_headlines
from .records import HORIZONS
from .run_inventory import inventory,matrix_markdown,status_lines
from .report_paper import write_paper
from .report_records import (
    METHODS, PAGES, STAGES, atomic_text, completed, describe_difference, example_runs, finite, fmt, study_snapshot,
    verdict_text,markdown_cell as _cell,markdown_table as _table,
)


def _method(run: dict) -> str:
    return METHODS.get(run.get("method"), run.get("method", "Unknown"))


def _stage(run: dict) -> str:
    return STAGES.get(run.get("stage"), run.get("stage", "Unknown"))


def _ledger_row(run: dict) -> list:
    return [
        _stage(run), _method(run), run.get("phase", "—"), run.get("seed", "—"),
        fmt(run.get("ratio")), fmt(run.get("tokens"), 0), fmt(run.get("dev_nll") if completed(run) else None, 4),
        fmt(run.get("dev_perplexity"), 4), fmt(run.get("test_nll"), 4), fmt(run.get("test_perplexity"), 4),
        fmt(run.get("tokens_per_sec"), 0), run["status"],
    ]


LEDGER_HEADERS = ["Stage", "Method", "Phase", "Seed", "Ratio", "Train tokens", "Dev NLL",
                  "Dev PPL", "Test NLL", "Test PPL", "Tokens/s", "Status"]


def _stage_summary(study: dict) -> str:
    return "\n\n".join(
        f"**{STAGES[stage]}.** {verdict_text(outcome,paired=True)}" for stage, outcome in study["stages"].items()
    )


def _pilot_summary(study):
    observed = []
    for stage, contrasts in study["pilot_comparisons"].items():
        if contrasts:
            numbers = ", ".join(f"{describe_difference(row['delta'])} against {METHODS[row['method']]}"
                                for row in contrasts)
            first = contrasts[0]
            observed.append(f"**{STAGES[stage]} development pilot.** At {first['tokens']:,} "
                            f"training targets, the third-order run recorded {numbers}. "
                            f"These are single-seed descriptions using {first['strength_basis']}.")
    return "\n\n".join(observed)


def _comparisons(study: dict) -> str:
    parts = []
    for stage, analysis in study["stages"].items():
        pairs = []
        summary = []
        for baseline, stats in analysis.get("comparisons", {}).items():
            name = METHODS.get(baseline, baseline)
            lo, hi = stats["median_ci"]
            summary.append([name, stats["wins"], stats["ties"], stats["losses"],
                            fmt(stats["median_delta"], 5), f"[{fmt(lo,5)}, {fmt(hi,5)}]",
                            fmt(stats["ci_coverage"], 4), fmt(stats["p_raw"], 5),
                            fmt(stats["p_holm"], 5)])
            for pair in stats["pairs"]:
                pairs.append([name, pair["seed"], fmt(pair["third_nll"], 5),
                              fmt(pair["baseline_nll"], 5), fmt(pair["delta"], 5)])
        if summary:
            parts.append(f"### {STAGES[stage]}\n\n" + _table(summary, [
                "Comparator", "Wins", "Ties", "Losses", "Median ΔNLL", "Marginal median interval",
                "Coverage", "Sign-test p", "Holm p"]) + "\n\n" + _table(pairs, [
                    "Comparator", "Seed", "Third-order NLL", "Comparator NLL", "ΔNLL"]))
        times = [[t["seed"], fmt(t["cutoff_seconds"], 1), _method({"method": m}),
                  fmt(o.get("train_seconds"), 1), fmt(o.get("tokens"), 0), fmt(o.get("dev_nll"), 5)]
                 for t in analysis.get("matched_time", []) for m, o in t.get("by_method", {}).items()
                 if isinstance(o, dict)]
        if times:
            parts.append(f"### {STAGES[stage]} at the shared training-time cutoff\n\n"
                         "Each row uses the latest fixed-window observation at or before the cutoff.\n\n" + _table(times, [
                "Seed", "Common cutoff (s)", "Method", "Recorded checkpoint (s)",
                "Training tokens", "Dev NLL"]))
        supplement = [[item["seed"],fmt(item["cutoff_seconds"],1),METHODS[m],fmt(point["clock_seconds"],1),
                       fmt(point["tokens"],0),fmt(point["dev_nll"],5)]
                      for item in analysis.get("matched_nonhost_time",[]) for m,point in item["by_method"].items()]
        if supplement:
            parts.append(f"### {STAGES[stage]} after subtracting host derivative calls\n\n"
                         "This supplementary clock excludes the measured host probe calls and their transfers. "
                         "The registered comparison above counts elapsed time with one GPU reserved.\n\n" +
                         _table(supplement,["Seed","Cutoff (s)","Method","Checkpoint (s)","Training tokens","Dev NLL"]))
    return "\n\n".join(parts)


def _run_learning(run: dict) -> str:
    """Use a trajectory only for a within-run observation; avoid causal attribution to a single run."""
    if run.get("error"):
        return f"The run recorded a failure. The run ledger contains the error and last metrics."
    series = [e for e in run["events"] if finite(e.get("dev_nll")) and finite(e.get("tokens"))]
    if len(series) >= 2 and series[0]["tokens"] < series[-1]["tokens"]:
        delta = series[-1]["dev_nll"] - series[0]["dev_nll"]
        return (f"On the fixed development windows, NLL changed by {delta:+.4f} nats per target token from "
                f"{series[0]['tokens']:,} to {series[-1]['tokens']:,} training targets. "
                "Attribution to the regularizer uses matched comparisons across seeds.")
    if completed(run) and finite(run.get("dev_nll")):
        return f"The observed development NLL is {fmt(run['dev_nll'], 4)} nats per target token."
    return "A development observation is pending."


def _sample(sample: dict) -> str:
    """Indent whole text blocks verbatim so model-generated Markdown is never executed."""
    def block(value):
        lines = str(value).splitlines() or [""]
        return "\n".join("    " + line for line in lines)
    segments = [("Prompt", sample.get("prompt", ""))]
    if sample.get("reference") is not None:
        segments.append(("Reference continuation", sample["reference"]))
    segments.append(("Model continuation", sample.get("continuation", "")))
    return "\n\n".join(f"**{title}**\n\n{block(body)}" for title, body in segments)


def _experiments(root, study):
    """Write all runs and samples, with one navigable index and brief evidence-linked learnings."""
    base = root / "reports" / "experiments"
    index = ["# Experiment ledger", "NLL is negative log-likelihood in nats per target token. "
             "A smaller value assigns more probability to the observed next tokens. Perplexity (PPL) is the "
             "exponential of the full-corpus NLL. Lower is better within a corpus and tokenizer. "
             "The ratio sets the pilot regularizer-gradient magnitude relative to cross-entropy.",
             "[Architecture, training algorithms, objectives and planned budgets](../planned-runs.md)",
             *status_lines(study),"[Status of every planned run](../planned-runs.md#current-evidence-and-remaining-runs)"]
    learnings = ["# Experimental learnings", _stage_summary(study),
                 "Independent random signs include mixed weight derivatives in the expected "
                 "penalty. The trace implementation motivating the gradient check converted its "
                 "estimate to a Python number. [Derivation and references](../literature-review.md)"]
    if study.get("scientific_audit"):
        source = "[Independent verification, passage exposure and scope of inference](../reviews/independent-scientific-audit.md)"
        index.append(source)
        learnings.append(source)
    if study["runs"]:
        rows = []
        planned = {r["id"]:r for r in study["run_inventory"]["fits"] if r["id"]}
        for run in study["runs"]:
            key = run["id"]
            link = "./" + quote(key, safe="") + "/experiment.md"
            rows.append([f"[{_cell(key)}]({link})", *_ledger_row(run)])
            raw_link = "../../../results/" + quote(key, safe="") + "/"
            material = [
                f"# {_stage(run)} · {_method(run)}",
                f"Run `{key}` · [raw records]({raw_link}) · [registered design](../../"
                + ("hybrid/" if run.get("phase") in {"hybrid","branch"} else "") + "preregistration.md)",
                _table([_ledger_row(run)], LEDGER_HEADERS),
                f"Training time is {fmt(run.get('train_seconds'), 1)} seconds. "
                f"Peak allocated GPU memory is {fmt(run.get('peak_vram_mb'), 1)} MiB. "
                f"Full-development token accuracy is {fmt(run.get('dev_accuracy') if completed(run) else None, 4)}. "
                f"Test token accuracy is {fmt(run.get('test_accuracy'), 4)}.",
                "[Design and hyperparameter rationale](../../planned-runs.md) · "
                f"[Saved configuration]({raw_link}config.json)",
            ]
            if key in planned:
                item = planned[key]
                material += [f"Training and development · {item['fit']}. Frozen test · {item['test']}. "
                             f"Checkpoint flatness · {item['geometry']}. "
                             "[Scheduled peers and controls](../../planned-runs.md#current-evidence-and-remaining-runs)"]
                if item["activity"]:
                    material.append(f"Recorded on {study['generated_at']} · {item['activity']}.")
            if run.get("flatness") or run.get("score_flatness"):
                material += ["## Checkpoint flatness",checkpoint_table(run["method"],run.get("flatness"),run.get("score_flatness")),
                             "The connection between width and better held-out prediction is unknown. "
                             "[Compare against every variant and baseline](../../flatness.md#every-variant-and-baseline)."]
            if run.get("failures"):
                material += ["## Recorded interruptions", _table(
                    [[failure["timestamp"],failure["error"]] for failure in run["failures"]],
                    ["Time (UTC)","Recorded exception"])]
            restarts = []
            for audit in run.get("restart_audits",[]):
                samples = audit["logged_replay_observations"]
                loss_diff = max(row["absolute_loss_delta"] for row in samples)
                grad_diff = max(row["absolute_gradient_norm_delta"] for row in samples)
                restarts.append(f"After the system restart, training resumed from update {audit['resume_checkpoint_step']:,} "
                                f"and replayed {audit['replayed_steps']} updates. Across {len(samples)} logged overlaps, "
                                f"the maximum absolute training NLL difference was {loss_diff:.4g} nats per target "
                                f"and the maximum difference in the unclipped gradient norm was {grad_diff:.4g}. "
                                f"[Replay measurements](../../../results/verification/{audit['source']})")
            if restarts:
                material += ["## Restart verification",*restarts]
            if run.get("precision_audit"):
                material += ["## Numerical diagnostic",run["precision_audit"]["reason"],
                             "[Precision amendment](../../amendments/adapter-precision.md)"]
            if finite(run.get("process_peak_rss_mib")):
                material.append(f"The process working-set high-water mark was {fmt(run['process_peak_rss_mib'],1)} MiB. "
                                "This OS measure includes earlier work in the same interpreter.")
            if run["samples"]:
                material += ["## Fixed-prompt generations",
                             *[_sample(sample) for sample in run["samples"]]]
            atomic_text(base / key / "experiment.md", "\n\n".join(material) + "\n")
            observation = _run_learning(run)
            if restarts:
                observation += " "+" ".join(restarts)
            if run.get("precision_audit"):
                observation = run["precision_audit"]["reason"]
            if run.get("failures"):
                observation += f" The run ledger records {len(run['failures'])} interrupted attempt(s)."
            atomic_text(base / key / "learnings.md", f"# Run learnings\n\n{observation}\n\n"
                        "[Experiment and source records](experiment.md)\n")
            learnings.append(f"- [{key}]({link}) — " + observation.replace("](../../../results/", "](../../results/"))
        index.append(_table(rows, ["Run", *LEDGER_HEADERS]))
    else:
        index.append("The first run record will populate this ledger.")
    atomic_text(base / "experiments.md", "\n\n".join(index) + "\n")
    atomic_text(base / "learnings.md", "\n\n".join(learnings) + "\n")


def _compact_table(study: dict) -> str:
    """Summarize like-for-like measured runs without selecting the strongest seed."""
    groups = {}
    for run in study["runs"]:
        if completed(run):
            key = (_stage(run), run.get("phase"), _method(run), run.get("ratio"), run.get("tokens"))
            groups.setdefault(key, []).append(run)
    rows = []
    for (stage, phase, method, ratio, tokens), runs in groups.items():
        def middle(metric):
            observed = [r[metric] for r in runs if finite(r.get(metric))]
            return fmt(median(observed), 4) if observed else "—"
        rows.append([stage, phase, method, fmt(ratio), fmt(tokens, 0), len(runs),
                     middle("dev_nll"), middle("dev_perplexity"), middle("test_nll"), middle("test_perplexity")])
    return _table(rows, ["Stage", "Phase", "Method", "Ratio", "Tokens/run", "Runs",
                         "Median dev NLL", "Median dev PPL", "Median test NLL", "Median test PPL"]) if rows else ""


def _dense_storage(study):
    """Scale a hypothetical dense tensor from archived coordinate counts and derivative dtypes."""
    examples = {"stories-pilot-s00-third-r03":("TinyStories · all decoder weights",4),
                "abstracts-pilot-s00-third-r03-fp64":("Pythia-410M · rank-eight QKV LoRA factors",8)}
    rows = []
    for r in study["runs"]:
        if r["id"] in examples and r.get("trainable_parameters"):
            label, size = examples[r["id"]]
            d = r["trainable_parameters"]
            rows.append([label,f"{d:,}",f"{d**3:.3g}",f"{d**3*size/10**18:.3g} EB at {size} bytes per entry"])
    return _table(rows,["Trainable coordinates","Weights","Dense ordered third partials","Hypothetical storage"]) if rows else "Awaiting archived coordinate counts."


def _experiment_milestones(study):
    """Track study completion independently of the direction or significance of its results."""
    finished = [r for r in study["runs"] if completed(r)]
    pilots = all(study["context"][stage]["selection"].get("ratios") and
                 {"initial", "unigram", "ce", "hessian_norm", "sham", "combined"} <=
                 {r["method"] for r in finished if r["stage"] == stage and r["seed"] == 0 and r["phase"] in {"pilot", "control"}}
                 for stage in STAGES)
    first_seed = all({"ce", "trace", "third"} <= {r["method"] for r in finished if r["stage"] == stage and
                     r["phase"] == "confirm" and r["seed"] == 1 and r["tokens"] == horizon}
                     for stage, horizon in HORIZONS.items())
    hybrid = study["hybrid"]
    tasks = [
        (pilots, "Finish both development searches and their single-seed trained and untrained controls. [Selection and controls](reports/planned-runs.md)"),
        (first_seed, "Complete the first full-budget AdamW, Hessian-trace and third-order comparison in both model families. [Run ledger](reports/experiments/experiments.md)"),
        (all(stage["complete"] for stage in study["stages"].values()), "Evaluate both frozen eight-seed primary test matrices. [Paired test results](reports/summary.md)"),
        (hybrid["completed_arms"] == 48 and hybrid["completed_trunks"] == 8,
         "Finish the late, curvature-dependent and replay experiments with all comparison arms. [Hybrid plan](reports/hybrid/preregistration.md) · [Width and prediction results](reports/hybrid/results.md)"),
        (all(c["complete"] == c["planned"] for c in geometry_coverage(study).values()),
         "Complete the common score-space measurement and each applicable weight-space measurement. [Flatness by checkpoint](reports/flatness.md)"),
        (bool(study.get("seed_sensitivity")), "Run the final seed-sensitivity analysis on the sealed results. [Across-seed variation](reports/seed-sensitivity.md)"),
    ]
    return "\n".join(f"- [{'x' if ready else ' '}] {description}" for ready, description in tasks)


def _update_sections(path,sections):
    """Replace only the named report sections, preserving the author's surrounding text."""
    if not path.exists():
        return
    content = path.read_text(encoding="utf-8-sig")
    for label,generated,required in sections:
        if not required and f"<!-- {label}:" not in content:
            continue
        pattern=f"<!-- {label}:START -->.*?<!-- {label}:END -->"
        if len(re.findall(pattern,content,re.DOTALL))!=1:
            raise ValueError(f"{path} requires exactly one pair of {label} markers")
        replacement=f"<!-- {label}:START -->\n\n"+generated.strip()+f"\n\n<!-- {label}:END -->"
        content=re.sub(pattern,lambda _:replacement,content,flags=re.DOTALL)
    atomic_text(path,content)


def _hybrid_report(root,study):
    """Report each observed width, censoring, matched fit and preregistered sign comparison."""
    data = study["hybrid"]
    headline = (f"TinyStories hybrid follow-up: {data['completed_arms']} of 48 full runs and "
                f"{data['completed_trunks']} of 8 shared checkpoints complete. "
                f"Width analysis status is “{data['status']}”. " + hybrid_bound_text(data)).strip()
    material = ["# Hybrid schedules on TinyStories",headline,
                "[Frozen protocol and decision rule](preregistration.md) · "
                "[Interactive measurement and run selector](../../docs/index.html#curves)",
                "Two-sided directional width is measured in the original Euclidean weight coordinates at a "
                "fixed increase of 0.1 nats per target. Each linked JSON contains all 32 rays and their brackets. "
                "A missing upper bound means that the search reached its maximum radius before crossing. "
                "The five shared-checkpoint arms reuse the trunk’s switch measurement and its recorded probe time."]
    widths = []
    for r in study["runs"]:
        for w in r.get("widths",{}).values():
            path = f"../../results/{r['id']}/width-{w['step']}.json"
            widths.append([r["seed"],_method(r),f"[{w['step']}]({path})",fmt(w["width"],5),
                           fmt(w["width_lower"],5),fmt(w["width_upper"],5),w["censored_rays"],
                           fmt(w["baseline_nll"],5),fmt(w["seconds"],2)])
    if widths:
        material += ["## Width observations",_table(widths,["Seed","Arm","Step","Width","Lower","Upper",
                       "Censored rays","Training probe NLL","Probe seconds"])]
        if any(finite(w["width"]) for r in study["runs"] for w in r.get("widths",{}).values()):
            material.append("![Median directional width by seed and training arm](../../docs/figures/hybrid_width.png)")
    arms = []
    for r in study["runs"]:
        if r.get("phase") not in {"hybrid","branch"} or not completed(r):
            continue
        url = f"../../results/{r['id']}/schedule.json"
        arms.append([r["seed"],_method(r),fmt(r["dev_nll"],6),fmt(r["dev_accuracy"],5),fmt(r["reference_rms"],5),
                     f"[{r['zero_steps']}]({url})",f"{r['final_third_lambda']:.6g}",fmt(r["tokens_per_sec"],0),
                     fmt(r["peak_vram_mb"],1),fmt(r["process_peak_rss_mib"],1)])
    if arms:
        material += ["## Full development and resource measurements",_table(arms,["Seed","Arm","Dev NLL","Accuracy",
                     "Reference RMS","Steps at zero λ₃","Final λ₃","Targets/s","Allocated GPU MiB","Process peak MiB"])]
    calibrations=[]
    for path in sorted((root/"results"/"hybrid"/"calibration").glob("seed-*.json")):
        cal=json.loads(path.read_text(encoding="utf-8"))
        calibrations.append([cal["seed"],len(cal["draws"]),f"{cal['delta']:.7g}",fmt(cal["calibration_seconds"],2),
                             f"[Per-draw gradient norms](../../results/hybrid/calibration/{path.name})"])
    if calibrations:
        material += ["## Stronger trace at the common checkpoint",
                     _table(calibrations,["Seed","Draws","Additional trace coefficient","Seconds","Calibration record"])]
    if data["pairs"]:
        material += ["## Adaptive minus comparator per seed","Positive Δwidth favors the adaptive schedule. "
                     "Negative ΔNLL favors its prediction. Comparable fit uses the frozen 0.02-nat training threshold.",
                     _table([[p["seed"],METHODS[p["comparator"]],fmt(p["delta"],6),
                              f"[{fmt(p['delta_lower'],6)}, {fmt(p['delta_upper'],6)}]",p["sign"],fmt(p["dev_nll_delta"],6),
                              fmt(p["train_probe_nll_delta"],6),"yes" if p["comparable_fit"] else "no"]
                             for p in data["pairs"]],["Seed","Comparator","Midpoint Δwidth gain","Search bounds","Resolved sign","Δdev NLL","Δtrain NLL","Comparable fit"]),
                     "A shared trunk cancels in the contrast. Open bounds reflect censoring. These are numerical "
                     "search brackets for the measured directions. Sampling uncertainty across seeds is a separate quantity."]
    for comparator,s in data["comparisons"].items():
        lo,hi = s["median_ci"]
        material.append(f"Against {METHODS[comparator]}, the median paired width difference is {fmt(s['median_delta'],6)}, "
                        f"interval [{fmt(lo,6)}, {fmt(hi,6)}], coverage {fmt(s['ci_coverage'],4)}. "
                        f"Wins/ties/losses: {s['wins']}/{s['ties']}/{s['losses']}. "
                        f"Nominal one-sided midpoint sign p = {fmt(s['p_raw'],5)}, Holm p = {fmt(s.get('p_holm'),5)}.")
    material += [f"The completed branches reused {data['shared_training_tokens_saved']:,} targets of optimization "
                 "compared with independently training each branch from initialization. The replay permutation "
                 "couples different seeds through their coefficient histories. The sign-test reference for this "
                 "comparison assumes independent fair signs under its null. Adjacent pairs reuse a donor's randomness. "
                 "Calibration of the replay p-value and median interval is unestablished. "
                 "All raw pairs are reported for inspection."]
    atomic_text(root/"reports"/"hybrid"/"results.md","\n\n".join(material)+"\n")
    return headline


def build_report(root: Path = Path(".")) -> dict:
    """Regenerate README results, PDF, experiment ledger, figures and the static dashboard."""
    root = Path(root).resolve()
    study = study_snapshot(root)
    _update_sections(root/"docs"/"third-derivative-penalty.md",[("DENSE",_dense_storage(study),False)])
    from .seed_sensitivity import render_seed_sensitivity
    sensitivity=render_seed_sensitivity(root,study)
    study["seed_sensitivity"]=sensitivity
    study["run_inventory"]=inventory(study)
    study["headline_flatness"]=geometry_headlines(study)
    from .progress import progress
    progress(root,study)
    timing=root/"results"/"feasibility"/"remaining-work.json"
    if timing.is_file():
        measured=json.loads(timing.read_text(encoding="utf-8"))
        if (measured["completed"],measured["planned"])==(study["run_inventory"]["done"],study["run_inventory"]["total"]):
            study["forecast"]=[measured["scenarios"][key]["total_hours"] for key in ("typical","slower")]
    hybrid = _hybrid_report(root,study)
    review = "reviews/independent-scientific-audit.md"
    audit = study["scientific_audit"]
    audit_prose = " ".join(audit[s] for s in ("stories","abstracts") if s in audit)
    if audit:
        record = json.loads((root/"results"/"analysis"/"scientific-audit.json").read_text(encoding="utf-8"))
        _update_sections(root/"reports"/review,[("FINDINGS",findings(record),True)])
    atomic_text(root/"reports"/"flatness.md",flatness_ledger(study))
    figures = build_figures(study, root / "docs" / "figures")
    study["figures"] = figures
    static = json.dumps(study, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
    atomic_text(root / "docs" / "study.json", static + "\n")
    _experiments(root, study)
    compact = _compact_table(study)
    comparisons = _comparisons(study)
    counts = len(study["runs"])
    done = sum(completed(run) for run in study["runs"])
    overview = f"Recorded {counts} runs, including {done} with a completed summary."
    documents = [f"[Interactive explorer]({PAGES})", "[Per-run ledger](experiments/experiments.md)", "[Final seed sensitivity](seed-sensitivity.md)",
                 "[Preregistration](preregistration.md)", "[Paper](paper.pdf)"]
    summary = ["# Study summary", overview, _stage_summary(study), hybrid+" [Hybrid outcomes](hybrid/results.md)",
               *status_lines(study),"[Status of every planned run](planned-runs.md#current-evidence-and-remaining-runs)", " · ".join(documents)]
    if audit:
        summary.insert(3,audit_prose+f" [Independent scientific audit]({review})")
    pilots = _pilot_summary(study)
    if pilots:
        summary.extend(["## Development observations", pilots])
    if compact:
        summary.extend(["## Measured scores", compact])
    if comparisons:
        summary.extend(["## Paired evidence", comparisons])
    for key, label in (("architecture", "Computation graph"), ("curves", "Development trajectories"),
                       ("paired", "Paired test differences")):
        if key in figures:
            summary.append(f"![{label}](../docs/figures/{figures[key]})")
    atomic_text(root / "reports" / "summary.md", "\n\n".join(summary) + "\n")
    badge = (f"[Explore the results]({PAGES}) · [Hugging Face explorer](https://huggingface.co/spaces/BurnyCoder/thirdloss-explorer) · "
             "[Hugging Face collection](https://huggingface.co/collections/BurnyCoder/third-derivatives-in-language-model-training-6b067fb7d5ae3eca49ebb378) · "
             "[Paper](reports/paper.pdf) · [Run ledger](reports/experiments/experiments.md)")
    opening,side_by_side=comparison_sections(study)
    if audit:
        opening += "\n\n"+audit_prose+f" [Independent scientific audit](reports/{review})"
    opening+="\n\n### Current and planned runs\n\n"+"\n\n".join(status_lines(study))+"\n\n"+(
             "[Finished, active and planned experiments](reports/planned-runs.md#current-evidence-and-remaining-runs) · "
             "[Live measurements](https://huggingface.co/spaces/BurnyCoder/thirdloss-explorer)")
    _update_sections(root/"reports"/"planned-runs.md",[("RUNS",matrix_markdown(study),False)])
    _update_sections(root/"reports"/"plan.md",[("STATUS","\n\n".join(["## Current evidence",*status_lines(study),
                     _stage_summary(study),hybrid+" [Hybrid results](hybrid/results.md)",
                     f"[Independent verification of the available evidence]({review})" if audit else "",
                     "[Execution matrix](planned-runs.md#current-evidence-and-remaining-runs) · [Flatness ledger](flatness.md)"]),False)])
    seed_status=("The final seed analysis is complete. It gives the across-seed spread and the range of medians "
                 "when each paired seed is omitted in turn." if sensitivity else
                 "Seed sensitivity is the final stage, after both primary test evaluations, all hybrid replications and checkpoint flatness.")
    side_by_side+="\n\n"+seed_status+" [Final seed-sensitivity report](reports/seed-sensitivity.md)"
    readme = [side_by_side,badge,overview,hybrid+" [Width measurements, scores and controls](reports/hybrid/results.md)",
              "[Full score table, strength search and per-seed test differences](reports/summary.md)"]
    if "hybrid_width" in figures:
        readme.append("![Directional width by TinyStories arm and seed](docs/figures/hybrid_width.png)")
    readme.append("![Parameter-space computation graph](docs/figures/architecture.png)")
    for key in ("paired", "curves"):
        if key in figures:
            readme.append(f"![{'Paired test differences' if key == 'paired' else 'Development NLL'}](docs/figures/{figures[key]})")
    examples=example_runs(study["runs"])
    if examples:
        readme.append("### Full generations by method")
        for stage,name in STAGES.items():
            links=[f"[{_method(r)}](reports/experiments/{r['id']}/experiment.md#fixed-prompt-generations)"
                   for r in examples if r["stage"]==stage]
            if links:
                readme.append(f"**{name}** · "+" · ".join(links))
    _update_sections(root/"README.md",[("RESULTS","\n\n".join(readme),True),("READOUT",opening,False),
                                      ("MILESTONES",_experiment_milestones(study),False)])
    # The collection's landing card shows the same tables with native Hub evidence links.
    hub_base="https://huggingface.co/BurnyCoder/thirdloss-study/blob/main/research/"
    hub_tables=re.sub(r"\]\(((?:reports|results)/)",lambda match:"]("+hub_base+match.group(1),
                      opening+"\n\n"+side_by_side)
    _update_sections(root/"docs"/"hub"/"archive.md",[("COMPARISONS",hub_tables,True)])
    write_paper(study, root / "reports" / "paper.pdf", root / "docs" / "figures", figures)
    return study