BurnyCoder commited on
Commit
2a5c21d
·
verified ·
1 Parent(s): dedcddc

Publish the preregistered paper and explorer before numerical experiments

Browse files
Files changed (49) hide show
  1. .gitattributes +1 -0
  2. research/.env.example +3 -0
  3. research/.python-version +1 -0
  4. research/AGENTS.md +5 -0
  5. research/README.md +44 -0
  6. research/docs/data.md +23 -0
  7. research/docs/explorer.css +101 -0
  8. research/docs/explorer.js +350 -0
  9. research/docs/figures/architecture.png +0 -0
  10. research/docs/index.html +106 -0
  11. research/docs/runbook.md +38 -0
  12. research/docs/study.json +1 -0
  13. research/pyproject.toml +32 -0
  14. research/reports/experiments/experiments.md +7 -0
  15. research/reports/experiments/learnings.md +7 -0
  16. research/reports/literature-review.md +23 -0
  17. research/reports/paper.pdf +0 -0
  18. research/reports/plan.md +3 -0
  19. research/reports/planned-runs.md +17 -0
  20. research/reports/preregistration.md +22 -0
  21. research/reports/progress.md +19 -0
  22. research/reports/reviews/methodology.md +23 -0
  23. research/reports/state-of-the-art-review.md +9 -0
  24. research/reports/summary.md +11 -0
  25. research/src/thirdloss/__init__.py +1 -0
  26. research/src/thirdloss/analysis.py +188 -0
  27. research/src/thirdloss/cli.py +103 -0
  28. research/src/thirdloss/data.py +301 -0
  29. research/src/thirdloss/evaluation.py +90 -0
  30. research/src/thirdloss/models.py +158 -0
  31. research/src/thirdloss/objectives.py +89 -0
  32. research/src/thirdloss/overlap.py +134 -0
  33. research/src/thirdloss/penalties.py +52 -0
  34. research/src/thirdloss/progress.py +40 -0
  35. research/src/thirdloss/records.py +84 -0
  36. research/src/thirdloss/release.py +87 -0
  37. research/src/thirdloss/report_figures.py +141 -0
  38. research/src/thirdloss/report_paper.py +331 -0
  39. research/src/thirdloss/report_records.py +215 -0
  40. research/src/thirdloss/reporting.py +255 -0
  41. research/src/thirdloss/study.py +174 -0
  42. research/src/thirdloss/train.py +200 -0
  43. research/src/thirdloss/windows.py +49 -0
  44. research/tests/test_analysis.py +171 -0
  45. research/tests/test_data.py +128 -0
  46. research/tests/test_derivatives.py +183 -0
  47. research/tests/test_reporting.py +44 -0
  48. research/tests/test_training.py +87 -0
  49. research/uv.lock +1039 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ research/reports/paper.pdf filter=lfs diff=lfs merge=lfs -text
research/.env.example ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Copy to .env to override the default ./storage directory for large data and weights.
2
+ THIRDLOSS_STORAGE=./storage
3
+ # HF_TOKEN can be supplied by the existing interactive Hugging Face login.
research/.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.12
research/AGENTS.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Research conventions
2
+
3
+ Follow the published preregistration, preserve exact split and checkpoint provenance, and qualify claims by their direct evidence. Make data or analysis changes explicit in the experiment history. Hold the test sets until the registered comparisons are frozen. Pin reproducible dependencies with uv and keep credentials, raw corpora and optimizer checkpoints out of Git. The paper alone carries the AI statement.
4
+
5
+ Publish the source and tests before the first run. Each completed training or evaluation updates raw records, study reports, checkpoint cards and the public explorer. Use one review pass for scientific, correctness and maintenance risks and retain negative results. [Protocol](reports/preregistration.md) · [Planned runs](reports/planned-runs.md)
research/README.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Third derivatives in language-model training
2
+
3
+ Does a language model predict unseen tokens better when training penalizes rapid changes in the curvature of its loss? This project compares ordinary AdamW, Hessian-trace regularization, and a penalty on every third partial derivative of token cross-entropy with respect to the trainable weights. Its two experiments cover full-weight training on short stories and low-rank adaptation on research abstracts. The primary evidence is held-out loss at equal training tokens.
4
+
5
+ ## Flat minima, Hessians and third derivatives in earlier work
6
+
7
+ | Setting | What the researchers used the derivatives for | Original papers and projects |
8
+ |---|---|---|
9
+ | Origin of flat-minimum search | Hochreiter and Schmidhuber searched for connected regions of weights where training error changes little. Their journal paper describes a search algorithm using second derivatives. | [Original NeurIPS paper, 1994](https://proceedings.neurips.cc/paper/1994/hash/01882513d5fa7c329e940dda99b12147-Abstract.html) · [Flat Minima, Neural Computation, 1997](https://people.idsia.ch/~juergen/fm/) |
10
+ | Hessians in language models | Sophia uses stochastic curvature estimates to precondition GPT training updates. Liu et al. measure Hessian trace and study downstream behavior of language models. Liu, Yu and Lin explicitly add trace to the objective in WikiText-2 LSTM and GRU experiments. | [Sophia paper](https://arxiv.org/pdf/2305.14342) · [Sophia code](https://github.com/Liuhong99/Sophia) · [Language-model flatness study](https://proceedings.mlr.press/v202/liu23ao.html) · [Explicit Hessian penalty, §5.2](https://arxiv.org/pdf/2208.05924) |
11
+ | Hessians outside language modeling | Layerwise Hessian-trace penalties have been tested in image classification. Reparameterization studies explain why a curvature measurement alone cannot establish predictive generalization. | [Sankar et al.](https://arxiv.org/pdf/2012.03801) · [Dinh et al.](https://proceedings.mlr.press/v70/dinh17b.html) |
12
+ | Third derivatives in language models | Yang et al. approximate third derivatives of the **training loss with respect to weights** to predict what happens when training batches are reordered. McGee et al. fit a cubic along a fine-tuning update to select a step size. Zhang and Wang test cubic corrections along hidden-activation interventions in a frozen model and report failures for large perturbations. | [FUT++, §5.1 and Appendix A.1](https://arxiv.org/pdf/2505.22042) · [Step selection, Appendix C.1.1](https://arxiv.org/pdf/2610.02190#page=28) · [Activation patching, §4 and supplement](https://arxiv.org/pdf/2606.09899) |
13
+ | Third derivatives outside LLMs | Wolinski projects third derivatives of the **weight-space loss** to regularize a local optimization model. Lellmann et al. study third **spatial** derivatives of terrain surfaces. Duchon gives the general squared-derivative roughness formulation. | [Projected parameter derivatives](https://arxiv.org/pdf/2312.03885) · [Third-order terrain reconstruction](https://www.lellmann.net/work/_media/lellmann_ssvm13.pdf) · [Spline roughness](https://doi.org/10.1007/BFb0086566) |
14
+
15
+ These papers motivate a distinct experiment here: putting the squared norm of the **third derivative of next-token loss with respect to trainable weights** directly in the training objective. The reviewed studies leave its effect on held-out next-token loss open.
16
+
17
+ The third-order term measures how the Hessian changes as weights move. Two independent random sign vectors estimate its squared Frobenius norm. Differentiating the estimate gives the optimizer a fourth-derivative contribution. This combines an order-three roughness density with matrix-free norm estimation. [Duchon](https://doi.org/10.1007/BFb0086566) · [Bujanović and Kressner](https://arxiv.org/pdf/2004.06433) · [Hessian comparator](https://arxiv.org/pdf/2208.05924)
18
+
19
+ **Study record.** The protocol and run matrix precede model execution. Experiments, scientific conclusions, and generated examples will be recorded from raw artifacts here. [Preregistration](reports/preregistration.md) · [Run matrix](reports/planned-runs.md) · [Literature](reports/literature-review.md) · [State of the art](reports/state-of-the-art-review.md) · [Progress](reports/progress.md)
20
+
21
+ <!-- RESULTS:START -->
22
+ [Explore the results](https://burnycoder.github.io/llm-training-with-penalizing-rapid-changes-of-curvature-of-its-loss/) · [Paper](reports/paper.pdf) · [Run ledger](reports/experiments/experiments.md)
23
+
24
+ Recorded 0 runs, including 0 with a completed summary.
25
+
26
+ **TinyStories.** Awaiting paired test results (0 of 8 full-horizon training triplets).
27
+
28
+ **Research abstracts.** Awaiting paired test results (0 of 8 full-horizon training triplets).
29
+
30
+ ![Parameter-space computation graph](docs/figures/architecture.png)
31
+ <!-- RESULTS:END -->
32
+
33
+ ## Reproduce the study
34
+
35
+ Use Python 3.12, uv, and an NVIDIA GPU for the full study. Install with `uv sync --locked`, run `uv run pytest -q`, then use `uv run thirdloss study`. In another terminal run `uv run thirdloss dashboard` for live accuracy and loss. Regenerate the paper, plots and score tables with `uv run thirdloss report`. [Setup, checkpoints and CLI](docs/runbook.md) · [Document splits](docs/data.md) · [Model collection](https://huggingface.co/collections/BurnyCoder/third-derivatives-in-language-model-training-6b067fb7d5ae3eca49ebb378)
36
+
37
+ The pipeline pins the source texts, splits by document, learns the stories tokenizer using training documents, and freezes the evaluation definition. Identical initializations and document orders pair the competing objectives. The smaller model trains all weights. The pretrained model trains only attention adapters. Examine both improvement and deterioration across seeds and both computational budgets. [TinyStories](https://arxiv.org/pdf/2305.07759) · [Pythia](https://huggingface.co/EleutherAI/pythia-410m) · [Common Pile](https://huggingface.co/datasets/common-pile/arxiv_abstracts_filtered) · [LoRA](https://arxiv.org/pdf/2106.09685)
38
+
39
+ ## Milestones
40
+
41
+ - Publish the protocol, references and analysis decisions.
42
+ - Verify the scalar objective and its training gradient on analytical functions and a small Transformer.
43
+ - Train the pilot, publish throughput and establish feasibility on the local GPU.
44
+ - Complete controls, development selection, paired confirmations and a reproducible report.
research/docs/data.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Corpus preparation
2
+
3
+ The public entry point `thirdloss.data.prepare(stage, root)` creates a self-contained `stories` or `abstracts` stage directory under the selected data root. A repeat call verifies its checksums and recovers damaged output. The original source cache lives alongside the prepared stages. The Hub client uses an immutable revision. A public HTTPS fallback checks the same upstream object identity and size before accepting the bytes. [Hub download API](https://huggingface.co/docs/huggingface_hub/package_reference/file_download)
4
+
5
+ ## Cohorts
6
+
7
+ | Stage | Source and assignment |
8
+ |---|---|
9
+ | Stories | Take the first 160,000 rows of the source training split in physical parquet row order. Assign a story to development when the integer encoded by the first 16 hex digits of its normalized SHA-256 hash is divisible by 50. Use all rows from the official validation parquet as candidate test documents. Source row IDs remain stable across re-runs. [Pinned input files](https://huggingface.co/datasets/roneneldan/TinyStories/tree/f54c09fd23315a6f9c86f9dc80f725de7d8f9c64/data) · [Arrow streaming reader](https://arrow.apache.org/docs/python/generated/pyarrow.parquet.ParquetFile.html) |
10
+ | Abstracts | Scan both compressed JSONL shards. Use the source `created` timestamp to select first submissions in January through April 2024 for training, May for development and June for testing. Group versions using the base arXiv identifier and retain the first source record per ID. Log how often the identifier month differs from the creation month. The corpus stores the abstract available at collection time, which can include revisions after submission. [Pinned abstracts](https://huggingface.co/datasets/common-pile/arxiv_abstracts_filtered/tree/dc1ceab4755eb037ec61e49cf1350dab7ceee6e7) · [arXiv identifier scheme](https://info.arxiv.org/help/arxiv_identifier.html) · [Upstream first-version timestamp example](https://arxiv.org/abs/0704.0001) |
11
+
12
+ ## Overlap audit
13
+
14
+ Hash Unicode NFKC, case-folded, whitespace-collapsed text. Retain the earliest exact copy within each split with priority given to test, then development, then training. Train the tokenizer on the original retained text after trimming outer whitespace. For cross-split near copies, form sets of five consecutive Unicode word tokens. Short documents form one shingle. Punctuation-only documents retain a normalized whole-text key.
15
+
16
+ The audit excludes any lower-priority document that reaches Jaccard similarity 4/5 against a retained higher-priority document. To identify candidates, order shingles by their reference-split document frequency, then lexically. With n shingles, index the first floor(n/5)+1. Every pair meeting the cutoff must share a prefix term under this common ordering. Verify candidates by exact set intersection. Evaluation references with the earliest source index break a match tie. Every exclusion has an auditable reason and matched ID. This procedure detects all cross-split copies meeting the stated whole-document shingle criterion. Paraphrases, snippets copied inside a longer document, and lower-similarity boilerplate can survive. Near matches within a single split can also survive and affect its diversity. [Xiao et al., §2.2](https://archives.iw3c2.org/www2008/papers/pdf/p131-xiaoA.pdf)
17
+
18
+ ## Token and evidence files
19
+
20
+ - Stories use byte-level BPE with a complete byte alphabet, one end-of-text symbol, 4,096 entries, and all retained training documents. Abstracts reuse the exact tokenizer bytes of the base model. The manifest separates the largest usable tokenizer ID plus one from Pythia’s padded output-head width. [BPE trainer](https://huggingface.co/docs/tokenizers/en/api/trainers) · [Pinned base checkpoint](https://huggingface.co/EleutherAI/pythia-410m/tree/9879c9b5f8bea9051dcb0e68dff21493d67e9d4f)
21
+ - Each split is a contiguous little-endian uint16 file ordered by source row, with one appended EOS per document and no injected BOS. The model can see previous documents in a packed window across EOS boundaries. Context and next-target shifting belong to the training/evaluation code. An example file opens with `numpy.memmap(stage_dir / "train.bin", dtype="<u2", mode="r")`.
22
+ - `documents.jsonl` gives each retained document’s source ID, normalized content hash, starting token, and length including EOS. Abstracts additionally include the submitted timestamp. `rejections.jsonl` lists rejected document IDs and reasons. These two files contain metadata rather than copies of source documents.
23
+ - `manifest.json` records split counts, audit counts, source revisions, source and output SHA-256 hashes, encoding settings and vocabulary dimensions. The stage-local lock serializes preparation. A temporary build promotes verified outputs atomically one file at a time and publishes this manifest last.
research/docs/explorer.css ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ color-scheme: light;
3
+ --paper: #fbfcf8;
4
+ --ink: #263733;
5
+ --muted: #52635c;
6
+ --rule: #cdd9d0;
7
+ --teal: #006d5c;
8
+ --tint: #e8f1e9;
9
+ font: 16px/1.53 system-ui, -apple-system, "Segoe UI", sans-serif;
10
+ }
11
+ *, *::before, *::after { box-sizing: border-box; }
12
+ html { scroll-behavior: smooth; scroll-padding-top: 1.5rem; }
13
+ body { margin: 0; background: var(--paper); color: var(--ink); }
14
+ a { color: var(--teal); text-underline-offset: .22em; }
15
+ a:hover { color: #09382f; }
16
+ :focus-visible { outline: 3px solid #e28941; outline-offset: 3px; }
17
+ .skip { position: absolute; transform: translateY(-130%); background: white; padding: .6rem; z-index: 4; }
18
+ .skip:focus { transform: none; }
19
+ .rail, main, footer { width: min(1120px, calc(100% - 64px)); margin: 0 auto; }
20
+ header { border-bottom: 1px solid var(--rule); background: #f4f7f0; }
21
+ .rail { display: flex; align-items: center; gap: 2rem; min-height: 64px; }
22
+ .signature { font: italic 33px/1 Georgia, serif; color: var(--ink); text-decoration: none; }
23
+ .signature sup { font: 16px Georgia, serif; vertical-align: super; }
24
+ nav { display: flex; flex-wrap: wrap; gap: 1.5rem; }
25
+ nav a, .source { color: var(--muted); font-size: .86rem; font-weight: 560; text-decoration: none; }
26
+ nav a:hover, .source:hover { text-decoration: underline; }
27
+ .source { margin-left: auto; }
28
+ .intro { display: grid; grid-template-columns: minmax(0, 3fr) minmax(200px, 1fr); align-items: end; gap: 7%; padding: 3.6rem 0 2.2rem; }
29
+ h1, h2, h3, p { margin: 0; }
30
+ h1, h2 { font-family: Georgia, "Times New Roman", serif; font-weight: normal; }
31
+ h1 { font-size: clamp(2.5rem, 5.7vw, 4.65rem); line-height: 1.02; letter-spacing: -.055em; }
32
+ .intro p, .prose { max-width: 77ch; color: var(--muted); }
33
+ .intro p { font-size: 1.06rem; margin: 1.25rem 0 .75rem; }
34
+ .protocol, .section-title a, .method-links a, .sample-controls a { font-size: .9rem; font-weight: 600; }
35
+ .summary { border-left: 2px solid #75a290; padding-left: 1.45rem; display: grid; gap: 1.05rem; }
36
+ .summary div { display: flex; flex-direction: column; }
37
+ .summary span, .curve-tools label, .filters label, .sample-controls label { font-size: .79rem; color: var(--muted); }
38
+ .summary strong { font: 1.65rem/1.12 Georgia, serif; font-variant-numeric: tabular-nums; }
39
+ .feed { font-size: .8rem; color: var(--muted); border-block: 1px solid var(--rule); padding: .64rem 0; }
40
+ .feed::before { content: ""; display: inline-block; vertical-align: .04em; width: .5rem; height: .5rem; background: #8c9389; border-radius: 100%; margin-right: .55rem; }
41
+ .feed.live::before { background: #21855d; }
42
+ main > section:not(.intro) { margin-top: 3rem; }
43
+ .section-title { display: flex; align-items: baseline; justify-content: space-between; gap: .8rem; }
44
+ h2 { font-size: clamp(2rem, 3.8vw, 2.8rem); line-height: 1.12; letter-spacing: -.045em; }
45
+ .section-title p { font-size: .87rem; color: var(--muted); }
46
+ .filters, .curve-tools, .sample-controls { display: flex; flex-wrap: wrap; gap: 1rem; align-items: end; }
47
+ .filters { margin: 1.15rem 0; }
48
+ label { display: inline-flex; flex-direction: column; gap: .25rem; }
49
+ select { display: block; min-width: 0; max-width: 100%; padding: .5rem 1.8rem .5rem .65rem; font: inherit; font-size: .9rem; color: var(--ink); background: white; border: 1px solid #afc0b4; border-radius: 4px; }
50
+ .run-filter { min-width: 12rem; max-width: 100%; }
51
+ .curve-panel { background: white; border: 1px solid var(--rule); padding: 1.2rem 1.4rem 1rem; border-radius: 6px; }
52
+ .curve-tools { justify-content: space-between; margin-bottom: .45rem; }
53
+ .chart-frame { height: clamp(245px, 30vw, 345px); position: relative; }
54
+ #chart { display: block; width: 100%; height: 100%; }
55
+ .chart-empty { pointer-events: none; position: absolute; inset: 0; margin: auto; height: fit-content; text-align: center; padding: 1.5em; color: var(--muted); }
56
+ #point { display: block; font-size: .82rem; min-height: 1.4em; color: var(--muted); font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
57
+ .legend { display: flex; flex-wrap: wrap; column-gap: 1.1rem; row-gap: .3rem; padding-top: .65rem; font-size: .8rem; }
58
+ .legend span { display: inline-flex; align-items: center; gap: .35rem; }
59
+ .legend i { width: 17px; height: 3px; }
60
+ .curve-note { margin-top: .55rem; font-size: .75rem; color: var(--muted); }
61
+ .run-ledger, .table-wrap { margin-top: 1rem; }
62
+ .run-ledger summary { cursor: pointer; color: var(--teal); font-weight: 600; }
63
+ .table-wrap { max-width: 100%; overflow-x: auto; }
64
+ table { width: 100%; border-collapse: collapse; font-size: .83rem; font-variant-numeric: tabular-nums; text-align: left; }
65
+ th, td { padding: .55rem .65rem; border-bottom: 1px solid var(--rule); vertical-align: top; }
66
+ th { color: var(--muted); font-size: .74rem; background: #edf2eb; font-weight: 600; }
67
+ td { white-space: nowrap; }
68
+ .prose { margin: .8rem 0 1rem; }
69
+ .verdict, .prompt { padding: .85rem 1rem; border-left: 3px solid #6f9d87; background: var(--tint); }
70
+ #stats details { margin: .8rem 0; }
71
+ .sample-controls { justify-content: space-between; margin: 1rem 0; }
72
+ .sample-controls label { max-width: 100%; }
73
+ .empty { color: var(--muted); padding: .85rem 0; }
74
+ .sample-pair { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-top: .7rem; }
75
+ .sample-pair article { border: 1px solid var(--rule); padding: 1rem; border-radius: 5px; background: white; }
76
+ .sample-pair article:last-child { background: #f2f7f1; }
77
+ #sample-view h3 { font: 650 .85rem/1.3 system-ui, sans-serif; color: var(--teal); margin-bottom: .42rem; }
78
+ #sample-view p { white-space: pre-wrap; overflow-wrap: anywhere; font: 1.05rem/1.5 Georgia, serif; }
79
+ .architecture { display: block; width: 100%; height: auto; background: white; border: 1px solid var(--rule); }
80
+ .method-links { display: flex; flex-wrap: wrap; gap: 1rem; margin-top: .7rem; }
81
+ footer { display: flex; justify-content: space-between; gap: 1rem; border-top: 1px solid var(--rule); margin-top: 3rem; padding: 1rem 0 2rem; font-size: .8rem; color: var(--muted); }
82
+ .sr { position: absolute; width: 1px; height: 1px; clip-path: inset(50%); overflow: hidden; }
83
+ [hidden] { display: none !important; }
84
+ @media (max-width: 650px) {
85
+ .rail, main, footer { width: calc(100% - 32px); }
86
+ .rail { gap: .8rem; min-height: 52px; }
87
+ nav { gap: .7rem; }
88
+ nav a, .source { font-size: .74rem; }
89
+ .intro { display: block; padding: 2.3rem 0 1.2rem; }
90
+ .summary { border-left: 0; border-top: 1px solid var(--rule); padding: .85rem 0 0; margin: 1.1rem 0 0; display: flex; justify-content: space-between; gap: .5rem; }
91
+ .summary span { font-size: .68rem; }
92
+ .summary strong { font-size: 1.3rem; }
93
+ .filters { gap: .5rem; }
94
+ .run-filter { min-width: 0; flex: 1; }
95
+ .curve-panel { padding: .75rem .65rem; }
96
+ .curve-tools { gap: .5rem; }
97
+ .curve-tools label { max-width: 48%; }
98
+ .sample-pair { grid-template-columns: 1fr; }
99
+ .section-title { flex-wrap: wrap; }
100
+ }
101
+ @media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } }
research/docs/explorer.js ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The same read-only snapshot feeds GitHub Pages and the local training server.
2
+ // Browser APIs: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D
3
+ "use strict";
4
+ const element = id => document.getElementById(id);
5
+ const repository = "https://github.com/BurnyCoder/llm-training-with-penalizing-rapid-changes-of-curvature-of-its-loss";
6
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(location.hostname) ||
7
+ new URL(location.href).searchParams.get("live") === "1";
8
+ const metrics = {
9
+ dev_nll: ["Development NLL", "nats / target token"], loss: ["Training NLL", "nats / target token"],
10
+ dev_accuracy: ["Development accuracy", "% correct"], accuracy: ["Training accuracy", "% correct"],
11
+ penalty: ["Weighted active penalty", "weighted loss contribution"],
12
+ raw_third: ["Third-derivative norm estimate", "squared Frobenius estimate"],
13
+ raw_trace: ["Hessian trace estimate", "signed trace estimate"],
14
+ raw_hessian_norm: ["Squared Hessian norm estimate", "squared Frobenius estimate"],
15
+ };
16
+ const axes = {tokens: "training target tokens", train_seconds: "training seconds", step: "optimizer steps"};
17
+ const numeric = value => typeof value === "number" && Number.isFinite(value);
18
+ const number = (value, digits = 3) => numeric(value) ? value.toLocaleString("en-US", {
19
+ minimumFractionDigits: digits, maximumFractionDigits: digits,
20
+ }) : "—";
21
+ const compact = value => numeric(value) ? new Intl.NumberFormat("en-US", {
22
+ notation: "compact", maximumFractionDigits: 2,
23
+ }).format(value) : "—";
24
+ const isComplete = run => ["complete", "completed", "finished", "evaluated", "success"].includes(run.status);
25
+ let study = {runs: [], stages: {}, method_names: {}, colors: {}, stage_names: {}};
26
+ let filteredRuns = [];
27
+ let sampleEntries = [];
28
+ let curves = [];
29
+ let points = [];
30
+ let inspected = -1;
31
+
32
+ function node(tag, value) {
33
+ const result = document.createElement(tag);
34
+ if (value !== undefined) result.textContent = value;
35
+ return result;
36
+ }
37
+
38
+ function options(select, choices, previous) {
39
+ const entries = choices.map(([value, name]) => {
40
+ const option = node("option", name);
41
+ option.value = value;
42
+ return option;
43
+ });
44
+ select.replaceChildren(...entries);
45
+ if (choices.some(([key]) => key === previous)) select.value = previous;
46
+ }
47
+
48
+ function methodName(method) { return study.method_names[method] || method || "—"; }
49
+ function stageName(stage) { return study.stage_names[stage] || stage; }
50
+ function methodColor(method) { return study.colors[method] || "#56665c"; }
51
+
52
+ function rebuildFilters() {
53
+ const stage = element("stage").value;
54
+ const selected = study.runs.filter(run => run.stage === stage);
55
+ const phases = [...new Set(selected.map(run => run.phase).filter(Boolean))].sort();
56
+ options(element("phase"), [["", "All phases"], ...phases.map(p => [p, p])], element("phase").value);
57
+ const phase = element("phase").value;
58
+ const inPhase = phase ? selected.filter(run => run.phase === phase) : selected;
59
+ options(element("run"), [["", "All runs"], ...inPhase.map(run => [run.id, run.id])], element("run").value);
60
+ const id = element("run").value;
61
+ filteredRuns = id ? inPhase.filter(run => run.id === id) : inPhase;
62
+ }
63
+
64
+ function showTotals() {
65
+ element("runs-count").textContent = number(study.runs.filter(isComplete).length, 0);
66
+ for (const [field, target] of [["tokens", "tokens-count"], ["train_seconds", "hours-count"]]) {
67
+ const values = study.runs.map(run => run[field]).filter(numeric);
68
+ const total = values.reduce((a, b) => a + b, 0);
69
+ element(target).textContent = values.length ? (field === "tokens" ? compact(total) : number(total / 3600, 2) + " h") : "—";
70
+ if (values.length) element(target).title = number(total, 0) + (field === "tokens" ? " training tokens" : " seconds");
71
+ }
72
+ }
73
+
74
+ function showLedger() {
75
+ const body = element("ledger");
76
+ body.replaceChildren();
77
+ for (const run of filteredRuns) {
78
+ const tr = node("tr");
79
+ const first = node("td");
80
+ const link = node("a", run.id);
81
+ link.href = repository + "/tree/main/results/" + encodeURIComponent(run.id);
82
+ first.append(link);
83
+ tr.append(first);
84
+ for (const value of [methodName(run.method), run.seed ?? "—", number(run.ratio, 3),
85
+ number(run.tokens, 0), number(run.dev_nll, 4), number(run.test_nll, 4),
86
+ number(run.tokens_per_sec, 0), number(run.peak_vram_mb, 0), run.status]) {
87
+ tr.append(node("td", value));
88
+ }
89
+ body.append(tr);
90
+ }
91
+ element("ledger-count").textContent = "(" + filteredRuns.length + ")";
92
+ if (!filteredRuns.length) {
93
+ const cell = node("td", "Awaiting a run in this selection.");
94
+ cell.colSpan = 10;
95
+ const row = node("tr");
96
+ row.append(cell);
97
+ body.append(row);
98
+ }
99
+ }
100
+
101
+ function collectCurves() {
102
+ const metric = element("metric").value;
103
+ const axis = element("axis").value;
104
+ const percent = metric.endsWith("accuracy") ? 100 : 1;
105
+ curves = filteredRuns.map(run => {
106
+ const values = (run.events || []).filter(e => numeric(e[metric]) && numeric(e[axis]))
107
+ .map(e => ({x: e[axis], y: e[metric] * percent, run}));
108
+ return {run, values};
109
+ }).filter(series => series.values.length);
110
+ const legend = element("legend");
111
+ legend.replaceChildren();
112
+ for (const method of [...new Set(curves.map(s => s.run.method))]) {
113
+ const item = node("span");
114
+ const stroke = node("i");
115
+ stroke.style.backgroundColor = methodColor(method);
116
+ item.append(stroke, document.createTextNode(methodName(method)));
117
+ legend.append(item);
118
+ }
119
+ inspected = -1;
120
+ element("point").textContent = "";
121
+ draw();
122
+ }
123
+
124
+ function draw() {
125
+ const canvas = element("chart");
126
+ const bounds = canvas.getBoundingClientRect();
127
+ const w = Math.max(100, bounds.width);
128
+ const h = Math.max(100, bounds.height);
129
+ const scale = Math.min(window.devicePixelRatio || 1, 3);
130
+ canvas.width = Math.round(w * scale);
131
+ canvas.height = Math.round(h * scale);
132
+ const ctx = canvas.getContext("2d");
133
+ ctx.scale(scale, scale);
134
+ const frame = {left: w < 480 ? 49 : 62, right: w - 13, top: 28, bottom: h - 49};
135
+ const all = curves.flatMap(s => s.values);
136
+ points = [];
137
+ element("chart-empty").hidden = all.length > 0;
138
+ element("chart-empty").textContent = "The selected measurement will appear after its first logged observation.";
139
+ if (!all.length) return;
140
+ const metric = element("metric").value;
141
+ const axis = element("axis").value;
142
+ let low = Infinity, high = -Infinity, maxX = 0;
143
+ for (const point of all) {
144
+ low = Math.min(low, point.y);
145
+ high = Math.max(high, point.y);
146
+ maxX = Math.max(maxX, point.x);
147
+ }
148
+ if (metric.endsWith("accuracy")) {
149
+ low = 0; high = 100;
150
+ } else {
151
+ const pad = (high - low || Math.max(Math.abs(high) * .1, .01)) * .09;
152
+ low -= pad; high += pad;
153
+ }
154
+ maxX = maxX || 1;
155
+ const positionX = value => frame.left + (frame.right - frame.left) * value / maxX;
156
+ const positionY = value => frame.bottom - (frame.bottom - frame.top) * (value - low) / (high - low);
157
+ const tick = value => Math.abs(value) >= 10000 || (value !== 0 && Math.abs(value) < .001) ?
158
+ value.toExponential(1) : Number(value.toPrecision(4)).toLocaleString("en-US");
159
+ ctx.font = "11px system-ui, sans-serif";
160
+ ctx.lineWidth = 1;
161
+ ctx.fillStyle = "#52635c";
162
+ ctx.textAlign = "left";
163
+ ctx.fillText(metrics[metric][1], frame.left, 13);
164
+ for (let i = 0; i <= 4; i++) {
165
+ const yValue = low + (high - low) * i / 4;
166
+ const y = positionY(yValue);
167
+ ctx.strokeStyle = "#dce6de";
168
+ ctx.beginPath(); ctx.moveTo(frame.left, y); ctx.lineTo(frame.right, y); ctx.stroke();
169
+ ctx.textAlign = "right";
170
+ ctx.fillText(tick(yValue), frame.left - 7, y + 3);
171
+ const xValue = maxX * i / 4;
172
+ ctx.textAlign = i === 4 ? "right" : i === 0 ? "left" : "center";
173
+ ctx.fillText(compact(xValue), positionX(xValue), frame.bottom + 18);
174
+ }
175
+ ctx.textAlign = "center";
176
+ ctx.fillText(axes[axis], (frame.left + frame.right) / 2, h - 6);
177
+ for (const series of curves) {
178
+ const color = methodColor(series.run.method);
179
+ ctx.strokeStyle = color; ctx.fillStyle = color; ctx.lineWidth = 1.65;
180
+ ctx.globalAlpha = curves.length > 10 ? .58 : .92;
181
+ ctx.beginPath();
182
+ series.values.forEach((value, i) => {
183
+ const px = positionX(value.x), py = positionY(value.y);
184
+ points.push({...value, px, py});
185
+ if (i) ctx.lineTo(px, py); else ctx.moveTo(px, py);
186
+ });
187
+ ctx.stroke();
188
+ if (series.values.length <= 60) {
189
+ for (const value of series.values) {
190
+ ctx.beginPath(); ctx.arc(positionX(value.x), positionY(value.y), 2.4, 0, Math.PI * 2); ctx.fill();
191
+ }
192
+ }
193
+ }
194
+ ctx.globalAlpha = 1;
195
+ if (inspected >= 0 && points[inspected]) {
196
+ const p = points[inspected];
197
+ ctx.fillStyle = "white"; ctx.strokeStyle = methodColor(p.run.method); ctx.lineWidth = 2.3;
198
+ ctx.beginPath(); ctx.arc(p.px, p.py, 4.7, 0, Math.PI * 2); ctx.fill(); ctx.stroke();
199
+ element("point").textContent = p.run.id + " · " + number(p.x, axis === "train_seconds" ? 1 : 0) +
200
+ " " + axes[axis] + " · " + number(p.y, 4) + " " + metrics[metric][1];
201
+ }
202
+ }
203
+
204
+ function table(headers, rows) {
205
+ const wrapper = node("div");
206
+ wrapper.className = "table-wrap";
207
+ const result = node("table");
208
+ const head = node("thead"), top = node("tr"), body = node("tbody");
209
+ headers.forEach(title => top.append(node("th", title)));
210
+ head.append(top); result.append(head);
211
+ for (const values of rows) {
212
+ const row = node("tr");
213
+ values.forEach(value => row.append(node("td", value)));
214
+ body.append(row);
215
+ }
216
+ result.append(body); wrapper.append(result);
217
+ return wrapper;
218
+ }
219
+
220
+ function showEvidence() {
221
+ const stage = element("stage").value;
222
+ const outcome = study.stages[stage] || {};
223
+ element("evidence-stage").textContent = stageName(stage);
224
+ const verdicts = {
225
+ confirmed: "The third-order objective beat both baselines under the registered rule.",
226
+ inconclusive: "The completed stage did not establish superiority over both baselines.",
227
+ adverse: "A median paired interval favors at least one baseline.",
228
+ invalid: "The registered analysis flagged incompatible run records.",
229
+ };
230
+ element("verdict").textContent = verdicts[outcome.status] ||
231
+ "Awaiting paired test results. Full-horizon training triplets: " +
232
+ (outcome.n_complete_seeds || 0) + " of " + (outcome.n_expected_seeds || 8) + ".";
233
+ const target = element("stats");
234
+ target.replaceChildren();
235
+ const pilots = (study.pilot_comparisons || {})[stage] || [];
236
+ if (pilots.length) {
237
+ const heading = node("details");
238
+ heading.append(node("summary", "Single-seed development comparisons"));
239
+ heading.append(table(["Comparator", "Training tokens", "Third-order dev NLL", "Comparator dev NLL", "ΔNLL", "Strengths"],
240
+ pilots.map(p => [methodName(p.method), number(p.tokens, 0), number(p.third_nll, 5),
241
+ number(p.baseline_nll, 5), number(p.delta, 5), p.strength_basis])));
242
+ target.append(heading);
243
+ }
244
+ const entries = Object.entries(outcome.comparisons || {});
245
+ if (entries.length) {
246
+ target.append(table(["Comparator", "Wins / ties / losses", "Median ΔNLL", "Median interval", "Coverage", "Holm p"],
247
+ entries.map(([baseline, s]) => [methodName(baseline), [s.wins, s.ties, s.losses].join(" / "),
248
+ number(s.median_delta, 5), (s.median_ci || []).map(x => number(x, 5)).join(" to "),
249
+ number(s.ci_coverage * 100, 2) + "%", number(s.p_holm, 5)])));
250
+ const details = node("details");
251
+ details.append(node("summary", "Individual paired differences"));
252
+ details.append(table(["Comparator", "Seed", "Third-order NLL", "Comparator NLL", "ΔNLL"],
253
+ entries.flatMap(([baseline, s]) => s.pairs.map(p => [methodName(baseline), p.seed,
254
+ number(p.third_nll, 5), number(p.baseline_nll, 5), number(p.delta, 5)]))));
255
+ target.append(details);
256
+ }
257
+ if ((outcome.matched_time || []).length) {
258
+ const details = node("details");
259
+ details.append(node("summary", "Development loss at matched training time"));
260
+ details.append(table(["Seed", "Cutoff (s)", "Method", "Checkpoint (s)", "Training tokens", "Dev NLL"],
261
+ outcome.matched_time.flatMap(t => Object.entries(t.by_method || {}).filter(([, m]) => m)
262
+ .map(([name, m]) => [t.seed, number(t.cutoff_seconds, 1), methodName(name),
263
+ number(m.train_seconds, 1), number(m.tokens, 0), number(m.dev_nll, 5)]))));
264
+ target.append(details);
265
+ }
266
+ }
267
+
268
+ function showSample() {
269
+ const entry = sampleEntries.find(s => s.id === element("sample").value);
270
+ element("sample-view").hidden = !entry;
271
+ if (!entry) return;
272
+ const s = entry.sample;
273
+ element("prompt-text").textContent = s.prompt ?? "";
274
+ element("reference-text").textContent = s.reference ?? "No reference continuation was recorded for this prompt.";
275
+ element("generated-text").textContent = s.continuation ?? "";
276
+ element("raw-sample").href = repository + "/blob/main/results/" + encodeURIComponent(entry.run.id) + "/samples.jsonl";
277
+ }
278
+
279
+ function showOutputs() {
280
+ sampleEntries = filteredRuns.flatMap(run => (run.samples || []).map((sample, index) => ({
281
+ id: run.id + "/" + index, name: run.id + " · sample " + (index + 1), sample, run,
282
+ })));
283
+ const menu = element("sample");
284
+ options(menu, sampleEntries.map(s => [s.id, s.name]), menu.value);
285
+ element("sample-controls").hidden = !sampleEntries.length;
286
+ element("samples-empty").hidden = sampleEntries.length > 0;
287
+ element("samples-empty").textContent = "Awaiting an archived continuation in the selected runs.";
288
+ showSample();
289
+ }
290
+
291
+ function render() {
292
+ rebuildFilters(); showTotals(); showLedger(); collectCurves(); showEvidence(); showOutputs();
293
+ }
294
+
295
+ async function getData(url) {
296
+ const response = await fetch(url, {cache: "no-store"});
297
+ if (!response.ok) throw new Error("HTTP " + response.status);
298
+ const result = await response.json();
299
+ if (!Array.isArray(result.runs) || !result.stages) throw new Error("Unrecognized study record");
300
+ return result;
301
+ }
302
+
303
+ async function refresh() {
304
+ let live = false;
305
+ const status = element("feed-status");
306
+ try {
307
+ if (local) {
308
+ try { study = await getData("/live.json"); live = true; }
309
+ catch { study = await getData("study.json"); }
310
+ } else study = await getData("study.json");
311
+ render();
312
+ const stamp = new Date(study.generated_at);
313
+ const asOf = Number.isNaN(stamp.valueOf()) ? "time unavailable" :
314
+ stamp.toLocaleString(undefined, {dateStyle: "medium", timeStyle: "medium"});
315
+ status.textContent = (live ? "Live local metrics" : "Published results") + " · Updated " + asOf;
316
+ status.classList.toggle("live", live);
317
+ } catch (error) {
318
+ status.classList.remove("live");
319
+ status.textContent = "Ledger temporarily unavailable. " + error.message + ". Retrying automatically.";
320
+ if (!study.runs.length) render();
321
+ } finally { window.setTimeout(refresh, local ? 10000 : 60000); }
322
+ }
323
+
324
+ for (const id of ["stage", "phase", "run"]) element(id).addEventListener("change", render);
325
+ for (const id of ["axis", "metric"]) element(id).addEventListener("change", collectCurves);
326
+ element("sample").addEventListener("change", showSample);
327
+ const canvas = element("chart");
328
+ new ResizeObserver(draw).observe(element("chart").parentElement);
329
+ canvas.addEventListener("pointermove", e => {
330
+ const box = canvas.getBoundingClientRect();
331
+ const x = e.clientX - box.left, y = e.clientY - box.top;
332
+ let nearest = -1, distance = 25 * 25;
333
+ points.forEach((point, i) => {
334
+ const d = (point.px - x) ** 2 + (point.py - y) ** 2;
335
+ if (d < distance) { nearest = i; distance = d; }
336
+ });
337
+ if (nearest !== inspected) {
338
+ inspected = nearest;
339
+ if (nearest < 0) element("point").textContent = "";
340
+ draw();
341
+ }
342
+ });
343
+ canvas.addEventListener("keydown", e => {
344
+ if (points.length && ["ArrowRight", "ArrowLeft"].includes(e.key)) {
345
+ e.preventDefault();
346
+ inspected = (Math.max(0, inspected + (e.key === "ArrowRight" ? 1 : -1))) % points.length;
347
+ draw();
348
+ }
349
+ });
350
+ refresh();
research/docs/figures/architecture.png ADDED
research/docs/index.html ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta name="color-scheme" content="light">
7
+ <meta name="description" content="Training curves, paired comparisons and generated text from the third-derivative language-model study.">
8
+ <title>Third derivatives in language-model training</title>
9
+ <link rel="stylesheet" href="explorer.css">
10
+ <script src="explorer.js" defer></script>
11
+ </head>
12
+ <body>
13
+ <a class="skip" href="#curves">Skip to training curves</a>
14
+ <header>
15
+ <div class="rail">
16
+ <a class="signature" href="#top" aria-label="Study overview">∂<sup>3</sup></a>
17
+ <nav aria-label="Study sections">
18
+ <a href="#curves">Training</a><a href="#evidence">Evidence</a><a href="#outputs">Outputs</a><a href="#method">Method</a>
19
+ </nav>
20
+ <a class="source" href="https://github.com/BurnyCoder/llm-training-with-penalizing-rapid-changes-of-curvature-of-its-loss">Repository ↗</a>
21
+ </div>
22
+ </header>
23
+ <main id="top">
24
+ <section class="intro">
25
+ <div>
26
+ <h1>Third derivatives in<br>language-model training</h1>
27
+ <p>Does penalizing changes in loss curvature improve next-token predictions? Compare ordinary training, Hessian-trace regularization, and a third-derivative penalty at equal training tokens.</p>
28
+ <a class="protocol" href="https://github.com/BurnyCoder/llm-training-with-penalizing-rapid-changes-of-curvature-of-its-loss/blob/main/reports/preregistration.md">Read the preregistration <span aria-hidden="true">↗</span></a>
29
+ </div>
30
+ <div class="summary" aria-label="Study totals">
31
+ <div><span>Completed runs</span><strong id="runs-count">—</strong></div>
32
+ <div><span>Training tokens logged</span><strong id="tokens-count">—</strong></div>
33
+ <div><span>Recorded training time</span><strong id="hours-count">—</strong></div>
34
+ </div>
35
+ </section>
36
+ <div id="feed-status" class="feed" role="status">Loading the study ledger…</div>
37
+
38
+ <section id="curves">
39
+ <div class="section-title"><h2>Training curves</h2><p>One trajectory per run</p></div>
40
+ <div class="filters">
41
+ <label>Stage<select id="stage"><option value="stories">TinyStories</option><option value="abstracts">Research abstracts</option></select></label>
42
+ <label>Phase<select id="phase"><option value="">All phases</option></select></label>
43
+ <label class="run-filter">Run<select id="run"><option value="">All runs</option></select></label>
44
+ </div>
45
+ <div class="curve-panel">
46
+ <div class="curve-tools">
47
+ <label>Measurement<select id="metric">
48
+ <option value="dev_nll">Development NLL</option><option value="loss">Training NLL</option>
49
+ <option value="dev_accuracy">Development accuracy</option><option value="accuracy">Training accuracy</option>
50
+ <option value="penalty">Weighted active penalty</option><option value="raw_third">Third-derivative norm estimate</option>
51
+ <option value="raw_trace">Hessian trace estimate</option><option value="raw_hessian_norm">Squared Hessian norm estimate</option>
52
+ </select></label>
53
+ <label>Horizontal axis<select id="axis"><option value="tokens">Training tokens</option><option value="train_seconds">Training time</option><option value="step">Optimizer steps</option></select></label>
54
+ </div>
55
+ <div class="chart-frame">
56
+ <canvas id="chart" tabindex="0" aria-label="Training curve. Focus and use left and right arrows to inspect points."></canvas>
57
+ <p id="chart-empty" class="chart-empty" hidden></p>
58
+ </div>
59
+ <output id="point" aria-live="polite"></output>
60
+ <div id="legend" class="legend"></div>
61
+ <p class="curve-note">Development curves use fixed probe windows. Completed-run tables show full development scores. The raw run logs retain every observation.</p>
62
+ </div>
63
+ <details class="run-ledger"><summary>Run ledger <span id="ledger-count"></span></summary>
64
+ <div class="table-wrap">
65
+ <table><caption class="sr">Measurements from runs matching the filters</caption><thead><tr>
66
+ <th>Run</th><th>Method</th><th>Seed</th><th>Ratio</th><th>Tokens</th><th>Dev NLL</th><th>Test NLL</th><th>Tokens/s</th><th>Peak MiB</th><th>Status</th>
67
+ </tr></thead><tbody id="ledger"></tbody></table>
68
+ </div>
69
+ </details>
70
+ </section>
71
+
72
+ <section id="evidence">
73
+ <div class="section-title"><h2>Paired evidence</h2><p id="evidence-stage"></p></div>
74
+ <p class="prose">The registered comparison uses held-out loss at equal training tokens. A negative difference favors the third-order objective. Both baseline comparisons must pass the corrected sign tests.</p>
75
+ <div id="verdict" class="verdict"></div>
76
+ <div id="stats"></div>
77
+ </section>
78
+ <section id="outputs">
79
+ <div class="section-title"><h2>Output examples</h2><p>Fixed development prompts</p></div>
80
+ <div id="sample-controls" class="sample-controls" hidden>
81
+ <label>Archived sample<select id="sample"></select></label>
82
+ <a id="raw-sample" href="#">Raw generation ↗</a>
83
+ </div>
84
+ <p id="samples-empty" class="empty"></p>
85
+ <div id="sample-view" hidden>
86
+ <div class="prompt"><h3>Prompt</h3><p id="prompt-text"></p></div>
87
+ <div class="sample-pair">
88
+ <article><h3>Reference continuation</h3><p id="reference-text"></p></article>
89
+ <article><h3>Model continuation</h3><p id="generated-text"></p></article>
90
+ </div>
91
+ </div>
92
+ </section>
93
+ <section id="method">
94
+ <div class="section-title"><h2>Method</h2><a href="https://github.com/BurnyCoder/llm-training-with-penalizing-rapid-changes-of-curvature-of-its-loss/blob/main/reports/paper.pdf">Read the paper ↗</a></div>
95
+ <p class="prose">The Hessian describes local loss curvature. Its derivative describes how that curvature changes as weights move. Two independent random sign vectors estimate the squared size of all third partial derivatives, including interactions between weights.</p>
96
+ <img class="architecture" src="figures/architecture.png" alt="TinyStories full-weight training and Pythia QKV adaptation feed next-token cross-entropy, a Hessian contraction, a third derivative and the regularized objective." loading="lazy">
97
+ <div class="method-links">
98
+ <a href="https://doi.org/10.1007/BFb0086566">Derivative roughness ↗</a>
99
+ <a href="https://arxiv.org/pdf/2208.05924">Hessian baseline ↗</a>
100
+ <a href="https://arxiv.org/pdf/2004.06433">Random probe estimator ↗</a>
101
+ </div>
102
+ </section>
103
+ </main>
104
+ <footer><span>Libor “Burny” Burian</span><a href="study.json">Download displayed records</a></footer>
105
+ </body>
106
+ </html>
research/docs/runbook.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reproducing the study
2
+
3
+ Install Python 3.12 and [uv](https://docs.astral.sh/uv/). The lock targets Windows AMD64 and Linux x86_64 with an NVIDIA driver supporting the CUDA 13.2 PyTorch wheel. The default scratch model and adapter math use float32. Make a project-local environment and install all locked dependencies with `uv sync --locked`. Copy `.env.example` to `.env` and optionally set `THIRDLOSS_STORAGE` to a directory with room for corpora, CUDA checkpoints and Hub downloads. Use the existing GitHub CLI and Hugging Face login for publication.
4
+
5
+ ```sh
6
+ uv run pytest -q
7
+ uv run thirdloss prepare --stage stories
8
+ uv run thirdloss train --stage stories --method third --phase pilot --seed 0 --ratio 0.03
9
+ uv run thirdloss dashboard --port 8765
10
+ ```
11
+
12
+ In another terminal, open the printed dashboard URL. The public explorer reads the last published results. The local dashboard reads running records. Accuracy is top-one token accuracy and NLL is in nats per target token. The training-time column excludes data preparation, checks, validation, checkpoint serialization and publication.
13
+
14
+ Run `uv run thirdloss study` to execute both stages, select strengths on development data, freeze all confirmatory checkpoints, and evaluate them. The owner's publishing workflow uses `uv run thirdloss study --publish`. This uploads fitted coordinates after each run and the study record after each training/evaluation. A local clone can omit the publishing flag. Repeating the same command resumes the last saved optimization step and skips completed runs. Checkpoints include optimizer state, random state and data cursor. The corpus manifests and run configuration must match. [Data and leakage checks](data.md) · [Preregistered run matrix](../reports/planned-runs.md)
15
+
16
+ Use `uv run thirdloss report` to regenerate the README results, PDF, figures, experiment notes, progress and explorer from `results/`. Use `uv run thirdloss progress` for current status. `uv run thirdloss evaluate RUN_ID` verifies the registered weight digest and test split before scoring a frozen run. Both tokenizers are stored alongside their stage data. Full untruncated generated token IDs, prompts, reference continuations and outputs are in each run's `samples.jsonl`. Timestamped session logs are stored locally under `logs/`.
17
+
18
+ ## Load a published checkpoint
19
+
20
+ All models are indexed in the [Hugging Face collection](https://huggingface.co/collections/BurnyCoder/third-derivatives-in-language-model-training-6b067fb7d5ae3eca49ebb378). The run name identifies its objective, phase, seed and penalty strength. Replace the example run name with the desired published checkpoint. Run from a clone with the locked environment.
21
+
22
+ ```python
23
+ from pathlib import Path
24
+ from huggingface_hub import snapshot_download
25
+ from safetensors.torch import load_file
26
+ from tokenizers import Tokenizer
27
+ from thirdloss.models import StoryTransformer
28
+
29
+ run_id = "stories-pilot-s00-third-r03"
30
+ snapshot = snapshot_download("BurnyCoder/thirdloss-stories", allow_patterns=f"runs/{run_id}/*")
31
+ folder = Path(snapshot) / "runs" / run_id
32
+ model = StoryTransformer()
33
+ model.load_state_dict(load_file(str(folder / "model.safetensors")))
34
+ model.eval()
35
+ tokenizer = Tokenizer.from_file(str(folder / "tokenizer.json"))
36
+ ```
37
+
38
+ For adapter snapshots use `AutoModelForCausalLM.from_pretrained("EleutherAI/pythia-410m", revision="9879c9b5f8bea9051dcb0e68dff21493d67e9d4f")` and load the adapter directory with `PeftModel.from_pretrained(base, folder)`. The published stage repo is `BurnyCoder/thirdloss-pythia-410m-adapters`. [PEFT](https://huggingface.co/docs/peft/en/package_reference/lora)
research/docs/study.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"generated_at":"2026-11-25T06:42:52+00:00","runs":[],"stages":{"stories":{"stage":"stories","status":"pending","complete":false,"success":null,"n_expected_seeds":8,"n_complete_seeds":0,"missing":[],"comparisons":{},"matched_time":[],"reason":"Awaiting confirmatory runs."},"abstracts":{"stage":"abstracts","status":"pending","complete":false,"success":null,"n_expected_seeds":8,"n_complete_seeds":0,"missing":[],"comparisons":{},"matched_time":[],"reason":"Awaiting confirmatory runs."}},"method_names":{"ce":"Ordinary AdamW","trace":"Hessian trace","third":"Third derivative","hessian_norm":"Squared Hessian norm","sham":"Randomized gradient signs","combined":"Trace + third derivative","initial":"Initial checkpoint","unigram":"Unigram"},"stage_names":{"stories":"TinyStories","abstracts":"Research abstracts"},"colors":{"ce":"#374d67","trace":"#ac582a","third":"#007166","hessian_norm":"#64569c","sham":"#ac3c66","combined":"#3974a2","initial":"#674e35","unigram":"#73736c"},"context":{"stories":{"datasets":{},"selection":{},"feasibility":{}},"abstracts":{"datasets":{},"selection":{},"feasibility":{}}},"pilot_comparisons":{"stories":[],"abstracts":[]},"figures":{"architecture":"architecture.png"}}
research/pyproject.toml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "thirdloss"
3
+ version = "0.1.0"
4
+ description = "Preregistered parameter-derivative experiments for causal language models"
5
+ requires-python = ">=3.12,<3.13"
6
+ dependencies = [
7
+ "torch==2.15.0", "numpy>=2", "transformers>=5.24,<6", "peft>=0.22,<1",
8
+ "huggingface-hub>=1", "tokenizers>=0.22", "safetensors>=0.5",
9
+ "pyarrow>=20", "filelock>=3", "httpx>=0.27", "python-dotenv>=1",
10
+ "matplotlib>=3.10", "reportlab>=4", "scipy>=1.14",
11
+ ]
12
+
13
+ [project.scripts]
14
+ thirdloss = "thirdloss.cli:main"
15
+
16
+ [build-system]
17
+ requires = ["hatchling"]
18
+ build-backend = "hatchling.build"
19
+
20
+ [dependency-groups]
21
+ dev = ["pytest>=8", "pypdf>=5"]
22
+
23
+ [tool.uv]
24
+ environments = ["sys_platform == 'win32' and platform_machine == 'AMD64'", "sys_platform == 'linux' and platform_machine == 'x86_64'"]
25
+
26
+ [tool.uv.sources]
27
+ torch = { index = "pytorch-cu132" }
28
+
29
+ [[tool.uv.index]]
30
+ name = "pytorch-cu132"
31
+ url = "https://download.pytorch.org/whl/cu132"
32
+ explicit = true
research/reports/experiments/experiments.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Experiment ledger
2
+
3
+ NLL is negative log-likelihood in nats per target token. A smaller value assigns more probability to the observed next tokens. The ratio sets the pilot regularizer-gradient magnitude relative to cross-entropy.
4
+
5
+ [Architecture, training algorithms, objectives and planned budgets](../planned-runs.md)
6
+
7
+ The first run record will populate this ledger.
research/reports/experiments/learnings.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Experimental learnings
2
+
3
+ **TinyStories.** Awaiting paired test results (0 of 8 full-horizon training triplets).
4
+
5
+ **Research abstracts.** Awaiting paired test results (0 of 8 full-horizon training triplets).
6
+
7
+ 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)
research/reports/literature-review.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Literature review
2
+
3
+ **Question.** Does explicitly discouraging variation of the parameter Hessian improve out-of-sample next-token predictions? The search covered parameter-Hessian penalties, high-order derivative regularization, tensor norm estimation, automatic differentiation, compact LM benchmarks and public implementations. Input derivatives, optimizer approximations, and parameter-loss derivatives answer different questions.
4
+
5
+ | Source | What it establishes | Decision for this study |
6
+ |---|---|---|
7
+ | [Duchon, 1977, pp. 85–87](https://doi.org/10.1007/BFb0086566) | Integrating sums of squared derivatives gives rotation-invariant roughness functionals. | Apply the local order-three density at training weights. Spline interpolation theorems do not carry over to neural training. |
8
+ | [Lellmann, Morel and Schönlieb](https://www.lellmann.net/work/_media/lellmann_ssvm13.pdf) | Third-order regularizers for reconstructing surfaces use mixed partials. Isotropic smoothing can erase features on their elevation data. | Compare predictive loss independently of any reduction in curvature variation. Their total-variation penalty has a different power and integration domain. |
9
+ | [Liu, Yu and Lin, equations 9–12 and §5.2](https://arxiv.org/pdf/2208.05924) | The paper defines cross-entropy plus a signed Hessian trace and reports WikiText-2 LSTM and GRU experiments. Algorithm 1 uses dense Rademacher probes. The language experiments use the sparsified variant. | Adapt the dense equation to causal Transformers. Published recurrent-model scores are external results. |
10
+ | [Authors’ trace implementation](https://github.com/Dean-lyc/Hessian-Regularization/blob/7d18787b06ba3e7912bf841ea9ebe4505a6191b3/hess.py#L87-L98) | In this public code path the trace is converted to a Python number. Adding it to cross-entropy cannot transmit its parameter gradient. | Test optimizer motion and the penalty gradient. The observation concerns this released implementation path. |
11
+ | [Bujanović and Kressner, especially §3](https://arxiv.org/pdf/2004.06433) | Products of independent sign vectors support unbiased trace estimation with structured probes. The randomness has different concentration properties than a full independent probe. | Unfold the order-three tensor along one index, apply a rank-one probe and square the resulting vector norm. Preserve independent probes and log stochastic variability. |
12
+ | [Wolinski, ECML PKDD](https://ecmlpkdd-storage.s3.eu-central-1.amazonaws.com/preprints/2025/research/preprint_ecml_pkdd_2025_research_332.pdf) | Grouped directional derivatives make higher-order parameter information accessible for optimization. | Compute directional contractions but use their magnitude as a term in the training objective. |
13
+ | [Liu et al., ICML 2023](https://proceedings.mlr.press/v202/liu23ao.html) | Language-model runs can have similar pretraining losses and different downstream behavior. | Limit the main claim to within-domain next-token prediction. |
14
+ | [Dinh et al.](https://proceedings.mlr.press/v70/dinh17b.html) | Reparameterization can alter local geometry while preserving the predictor. | Interpret geometry in the fixed training coordinates. Compare methods within each model stage. |
15
+ | [Eldan and Li](https://arxiv.org/pdf/2305.07759) | Synthetic English stories allow small causal models to exhibit meaningful language behavior. | Use full-weight pretraining with fixed-prompt, uncurated continuations. |
16
+ | [Pythia](https://arxiv.org/pdf/2304.01373), [LoRA](https://arxiv.org/pdf/2106.09685), [Common Pile](https://huggingface.co/datasets/common-pile/arxiv_abstracts_filtered) | An open pretrained decoder, low-rank adaptation and a dated abstracts collection support a second-domain experiment. | Restrict derivatives to the trained QKV adapters. Use first-submission months after the Pythia release. |
17
+ | [Bouthillier et al.](https://proceedings.mlsys.org/paper_files/paper/2021/hash/0184b0cd3cfb185989f858a1d9f5c1eb-Abstract.html), [Lones](https://arxiv.org/abs/2108.02497), [NeurIPS checklist](https://neurips.cc/public/guides/PaperChecklist) | Evaluation needs explicit variability, data isolation, reporting and reproducibility. | Pair seeds, fix the estimand and tuning budget, and report individual runs and both comparisons. |
18
+
19
+ ### Third derivatives with respect to language-model weights
20
+
21
+ Yang et al. use a third weight derivative of minibatch training loss in a Taylor expansion of the Adam update. Their FUT++ method takes finite differences of approximate Hessians at successive reference checkpoints. They compare predictions for reordered batches against actual retraining of a 636-million-parameter LLaMA-style model on WikiText-103. Those measurements use the reference training trajectory. Our regularizer samples directions independently in weight space to estimate a squared norm over all mixed third partials. [Yang et al., §5.1 and Table 1](https://arxiv.org/pdf/2505.22042#page=6) · [Appendix A.1, equations 14–15](https://arxiv.org/pdf/2505.22042#page=15)
22
+
23
+ McGee et al. derive a cubic model using a directional slope and two symmetric function evaluations along an optimizer step. In their language-model fine-tuning runs, GRPO supplies the slope and a separate reward-minus-KL score supplies the function evaluations. The fitted cubic combines these quantities to select a step size. Interpreting its coefficient as one objective's directional third derivative requires the slope and function values to come from that same objective. [McGee, Bergou and Dutta, §2](https://arxiv.org/pdf/2610.02190) · [Implementation, Appendix C.1.1](https://arxiv.org/pdf/2610.02190#page=28)
research/reports/paper.pdf ADDED
Binary file (131 Bytes). View file
 
research/reports/plan.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Research plan
2
+
3
+ The accepted design is preserved in the [preregistration](preregistration.md) and [run matrix](planned-runs.md). Work proceeds from public registration to source and test publication, analytical verification, development pilots, secondary controls, paired full-budget confirmations, sealed evaluation and reporting. Publish code, raw summaries, model cards and figures throughout. The live dashboard tracks development metrics and exposes checkpoint progress. The paper and interactive explorer will report positive, negative and inconclusive outcomes from the same raw results.
research/reports/planned-runs.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Planned runs
2
+
3
+ | Stage | Trainable coordinates | Data | Confirmatory target tokens | Effective windows per update |
4
+ |---|---|---|---:|---:|
5
+ | stories | Four causal blocks, width 192, four heads, gated SiLU MLP width 512, tied embeddings and 4,096 tokens | TinyStories | 16,777,216 | 32 |
6
+ | abstracts | Pythia-410M with rank-eight QKV LoRA in every block, scale alpha 16 | 2024 arXiv abstracts | 524,288 | 8 |
7
+
8
+ AdamW peaks at 0.0003 for stories and 0.0001 for adapters, with betas 0.9 and 0.95, weight decay 0.1 on matrices, gradient norm clip 1, 5% warmup and cosine decay to 10% of peak. Use full-precision parameter derivatives and eager attention. Physical microbatching can change to fit GPU memory while preserving the effective batch and two-window derivative estimate. Data order and optimizer settings are paired. These are experimental design choices.
9
+
10
+ | Phase | Seed | Arms and budget |
11
+ |---|---:|---|
12
+ | Untrained controls | 0 | Evaluate initial checkpoint and training-token unigram on development text. |
13
+ | Pilot and development | 0 | Run third-order 3% first. Run ordinary AdamW and both derivative baselines on the same initial one-eighth of the stage horizon. Complete the equal 1%, 3%, 10% grid for trace and third order. Measure cost before confirmatory training. |
14
+ | Secondary controls | 0 | Squared Hessian norm at 3%, sign-scrambled third-order update, combined selected trace and third order. Use the development horizon and report them as pilot comparisons. |
15
+ | Confirmation | 1–8 | Ordinary, signed trace, and third order at the selected strength, each at the full stage horizon. |
16
+
17
+ Evaluate seed-paired final test predictions only when the stage has all planned confirmatory checkpoints. Preserve every development candidate. The one-week allocation prioritizes the two registered stages and their controls. The first 14 hours target a real one-seed pilot with its untrained controls. [Protocol](preregistration.md)
research/reports/preregistration.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Preregistration
2
+
3
+ Libor “Burny” Burian · 25 November 2026 · initial protocol before model tests, inference, or training.
4
+
5
+ ## Hypothesis and estimand
6
+
7
+ At equal target-token counts, third-order regularization lowers held-out negative log-likelihood per valid target token against both cross-entropy alone and signed Hessian-trace regularization. Full-weight pretraining is primary. Adapter training is a separately reported replication. Use each final scheduled checkpoint. The population for seed-level inference is repeated initialization, data order and probe randomness on the frozen corpus.
8
+
9
+ Let L be unregularized minibatch mean cross-entropy, H its parameter Hessian and T its third derivative. For independent iid unnormalized Rademacher vectors u and v, r[k] = sum(i,j) T[i,j,k] u[i] v[j]. Taking the expectation of the squared vector norm leaves only terms with matching i and j, hence E||r||² = sum(i,j,k) T[i,j,k]². Differentiate this nonnegative estimate through r. It targets the expected squared norm of the **two-window minibatch** tensor. Fix the sample size because squaring and averaging over documents do not commute. With independent Bernoulli gates of probability 1/8, multiplying active penalties by eight preserves their expectation before optimizer clipping. [Rank-one probes](https://arxiv.org/pdf/2004.06433)
10
+
11
+ ## Design and isolation
12
+
13
+ - Stories use up to the first 160,000 source training records, a deterministic approximately 2% document-hash development split, and the original official validation documents as a sealed test. Abstracts use base arXiv identifiers first submitted in January–April 2024 for training, May for development and June for testing. Drop empty texts, exact normalized duplicates, and audit near duplicates using word shingles. Keep evaluation documents in preference to training duplicates. Tokenize after splitting. Record revisions, counts, checksums, parameters and residual contamination limitations.
14
+ - Use 128 prediction targets per window. Freeze a train-only 4,096-token BPE for stories. Use the pretrained tokenizer for abstracts. Match initial parameters, order, effective batch, learning schedule, gate draws and token horizon within a stage. Draw two windows from the current batch for each active update and use independent RNG streams for probes and sham signs. Report all prompts and continuations. Evaluate development during training.
15
+ - Use pilot seed 0. Calibrate strength on 16 training batches at its shared initialization using the median ratio of ordinary gradient norm to unweighted penalty-gradient norm. Try ratios 0.01, 0.03 and 0.10 equally for the Hessian and third-order arms. Select lowest development NLL at the common development horizon with smaller ratio on a tie. Freeze coefficients before any confirmatory test. Combined uses the separately selected coefficients. Sham uses the selected third-order coefficient. Squared-Hessian control uses the same calibration rule.
16
+ - Use eight matched confirmatory seeds 1–8 per stage. Test the final checkpoints after each stage’s complete confirmatory training matrix is frozen. A stage-level one-sided exact paired sign test asks whether the probability of a lower NLL exceeds one half, excluding ties. Holm-adjust the two primary p-values at 0.05. Both must pass for success. Report individual paired deltas (third minus comparator), their median and distribution-free order-statistic interval with coverage of at least 95%. A stage with a missing pair is descriptive until completed. A reliably worse comparator difference contradicts the directional claim for that comparison. Mixed or imprecise results remain inconclusive.
17
+ - Secondary outcomes are token accuracy, perplexity from corpus NLL, matched elapsed-training-time development NLL, token throughput, peak allocated VRAM, penalty values, and fixed-prompt continuations. Use the latest recorded checkpoint at or before the shortest final training time for each seed. Do not select by test NLL. Interpret the two stages separately because tokenization and trainable coordinates differ.
18
+ - Report numerical failures, retries, stalled learning, and protocol amendments with dates and commits. An implementation defect triggers revalidation and rerunning affected arms. A time or memory limitation is a reported feasibility outcome. Any budget revision is explicitly exploratory unless separately preregistered before testing. Preserve the requested confirmatory horizons.
19
+
20
+ ## Checks and reporting
21
+
22
+ The quartic objective must give penalty 576x² and gradient 1152x. The pure mixed cubic xyz must average to six. Verify a tiny float64 Transformer against dense third partials, finite differences of the penalty, and a real update. Check that the signed trace retains gradients, sham signs preserve magnitudes, ordinary training is identical for a zero coefficient, and a resumed run recovers the uninterrupted data and probe streams. Record GPU throughput and memory before opening either test. [Hessian paper](https://arxiv.org/pdf/2208.05924) · [Reference code](https://github.com/Dean-lyc/Hessian-Regularization/blob/7d18787b06ba3e7912bf841ea9ebe4505a6191b3/hess.py#L87-L98) · [Analysis principles](https://arxiv.org/abs/2108.02497)
research/reports/progress.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Study progress
2
+
3
+ Updated 2026-11-25T06:42:52+00:00.
4
+
5
+ 0 training/control records and 0 final evaluations are complete. This is 0.0% of 120 planned model milestones.
6
+
7
+ ## Current record
8
+
9
+ **stories** has 0 completed runs. The next milestone is determined by the run matrix.
10
+
11
+ Statistical status: pending. Awaiting confirmatory runs.
12
+
13
+ **abstracts** has 0 completed runs. The next milestone is determined by the run matrix.
14
+
15
+ Statistical status: pending. Awaiting confirmatory runs.
16
+
17
+ ## Monitoring
18
+
19
+ Inspect runs lasting over 10, 30 and 60 minutes at 5, 15 and 30 minute intervals respectively. The live dashboard refreshes between those checks. [Study design](plan.md) · [Run matrix](planned-runs.md) · [Experiment ledger](experiments/experiments.md)
research/reports/reviews/methodology.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pre-execution scientific review
2
+
3
+ The preregistration tests a claim about held-out next-token prediction within two fixed stage-specific protocols. This review records failure modes and diagnostic checks before the first model run. Empirical conclusions require the recorded final evaluations. [Registered estimand and comparisons](../preregistration.md)
4
+
5
+ ## Mathematical target
6
+
7
+ The third tensor is the derivative of **unregularized mean token cross-entropy** in the trainable coordinate system. Keeping two independent sign probes fixed through all differentiations yields a vector contraction. Its squared length is unbiased for the squared Frobenius norm conditional on that particular minibatch. A shared probe leaves cross terms. Checking the mixed cubic by enumerating the two sign vectors exposes this error, whereas a single-coordinate quartic catches a detached fourth derivative. The dense reference uses three nested forward Jacobians and central differences of the dense contraction. [Rank-one norm estimation](https://arxiv.org/pdf/2004.06433) · [PyTorch gradient checks](https://docs.pytorch.org/docs/stable/notes/gradcheck.html)
8
+
9
+ Squaring after averaging across documents makes the objective depend on the probe-window batch size. Ordinary gradient accumulation can preserve token cross-entropy while changing this penalty. The two probe windows must share one graph and keep the same target count. The physical CE microbatch can vary independently. [Registered batch definition](../preregistration.md)
10
+
11
+ ## Interpretation of the intervention
12
+
13
+ Signed Hessian trace and squared tensor norm differ in both derivative order and scalar aggregation. The squared-Hessian control helps distinguish these changes. Coordinatewise randomization of the penalty-gradient signs preserves the absolute values of its entries before addition, clipping and AdamW. It will generally change their relationship to the ordinary gradient and the optimizer's moments. A comparison supports a contribution from directional information under this optimizer. An independent conclusion about the origin of generalization would require further interventions. [Hessian comparator](https://arxiv.org/pdf/2208.05924) · [Reparameterization example](https://proceedings.mlr.press/v70/dinh17b.html)
14
+
15
+ In the adapter stage, the derivatives are in the two low-rank factors. Factor rescaling can leave their product unchanged while changing derivatives in the factor coordinates. Treat an adapter result as a replication of the training recipe in that parameterization. The change of corpus and checkpoint precludes isolating model scale as the sole cause of a stage difference. [LoRA](https://arxiv.org/pdf/2106.09685)
16
+
17
+ The inverse gate-probability multiplier restores the expected sampled penalty gradient before clipping. Clipping and adaptive moment normalization are nonlinear, so the resulting parameter update need not be an unbiased estimate of an update under dense regularization. Report instability and the relationship between the penalty gradient and the ordinary gradient where recorded. [Derivation and gating schedule](../preregistration.md)
18
+
19
+ ## Inference and leakage
20
+
21
+ Use the paired seed as the independent unit. Report individual NLL differences alongside the sign count. The one-sided sign test conditional on non-ties assesses win probability. A few large adverse effects can therefore coexist with many small wins. Show median effects and exact binomial order-statistic intervals, with the achieved coverage exposed because discreteness can make them conservative. Holm adjustment covers the two primary hypotheses within a stage. The elapsed-training-time comparison uses the last recorded evaluation on the same fixed development windows at or before each seed's common cutoff. It reports the time gap for each arm. The full development split measures final validation performance. [Sign test](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binomtest.html) · [Distribution-free quantile intervals](https://nvlpubs.nist.gov/nistpubs/TechnicalNotes/NIST.TN.2119.pdf) · [Holm procedure](https://stat.ethz.ch/R-manual/R-devel/library/stats/html/p.adjust.html)
22
+
23
+ The report withholds primary deltas and p-values until it has all final equal-token records. The evaluator must also freeze the entire checkpoint set before scoring. Hash the evaluation split and frozen set, and retain every dev candidate and each through-training stopping decision. Corpus cleaning can miss paraphrases or boilerplate even after exact and shingle matching. A later source timestamp reduces one route of pretraining overlap while leaving coincidental or previously circulated text possible. Report corpus provenance and review all split audits. [Benchmark variability](https://proceedings.mlsys.org/paper_files/paper/2021/hash/0184b0cd3cfb185989f858a1d9f5c1eb-Abstract.html) · [Evaluation pitfalls](https://arxiv.org/abs/2108.02497)
research/reports/state-of-the-art-review.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Comparison with existing methods
2
+
3
+ The nearest published language experiment found in this review is Hessian-trace training of recurrent models. Its scalar regularizer measures signed curvature along coordinates. A Hessian with changing entries can have constant trace. Squared Frobenius penalties on the Hessian and on its derivative therefore supply important controls. [Hessian objective and experiments](https://arxiv.org/pdf/2208.05924)
4
+
5
+ Noise stability optimization approximates a Hessian penalty by perturbing weights symmetrically and has been studied on multimodal pretraining and chain-of-thought fine-tuning. Expansion through a third-order term in an optimizer or perturbation formula is a different intervention from adding the squared third derivative to the training loss. [Zhang, Li and Ju](https://arxiv.org/pdf/2306.08553)
6
+
7
+ Stochastic Taylor derivative estimators address higher-order differential operators in applications such as physics-informed learning. Their authors discuss limits when differentiating network parameters. We use ordinary compositional parameter autograd and test its fourth-order contribution directly. [Shi et al.](https://arxiv.org/pdf/2412.00088) · [PyTorch autograd](https://docs.pytorch.org/docs/stable/generated/torch.autograd.grad.html)
8
+
9
+ The contribution under test is the particular parameter-space objective in causal LM pretraining and adaptation, with equal-token, method-matched and direction-randomized comparisons. The norm, the sketch and low-rank adaptation each have precedents. The literature reviewed here does not establish a predictive benefit for this combination. [Local roughness](https://doi.org/10.1007/BFb0086566) · [Norm estimation](https://arxiv.org/pdf/2004.06433)
research/reports/summary.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Study summary
2
+
3
+ Recorded 0 runs, including 0 with a completed summary.
4
+
5
+ **TinyStories.** Awaiting paired test results (0 of 8 full-horizon training triplets).
6
+
7
+ **Research abstracts.** Awaiting paired test results (0 of 8 full-horizon training triplets).
8
+
9
+ [Interactive explorer](https://burnycoder.github.io/llm-training-with-penalizing-rapid-changes-of-curvature-of-its-loss/) · [Per-run ledger](experiments/experiments.md) · [Preregistration](preregistration.md) · [Paper](paper.pdf)
10
+
11
+ ![Computation graph](../docs/figures/architecture.png)
research/src/thirdloss/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Experiments on parameter-space third derivatives of causal language-model loss."""
research/src/thirdloss/analysis.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Registered comparisons for third-derivative training on a fixed test corpus.
2
+
3
+ Seeds are independent experimental units. Positive deltas mean worse prediction for the
4
+ third-order method. The module consumes ordinary JSON-compatible result records so the
5
+ CLI, static report, and interactive explorer can share the same inference.
6
+ """
7
+
8
+ from math import comb, isfinite
9
+ from statistics import median
10
+
11
+
12
+ _METHODS = ("ce", "trace", "third")
13
+ _SEEDS = range(1, 9)
14
+ _HORIZON = {"stories": 2**24, "abstracts": 2**19}
15
+
16
+
17
+ def _number(value):
18
+ """Reject missing, boolean and nonfinite values before constructing measures or plots."""
19
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and isfinite(value)
20
+
21
+
22
+ def _comparison(records, baseline):
23
+ """Apply the registered paired sign test and symmetric distribution-free median interval."""
24
+ pairs = []
25
+ for seed in _SEEDS:
26
+ third = records[seed, "third"]["test_nll"]
27
+ other = records[seed, baseline]["test_nll"]
28
+ pairs.append({"seed": seed, "third_nll": third, "baseline_nll": other, "delta": third - other})
29
+
30
+ ordered = sorted(pair["delta"] for pair in pairs)
31
+ wins = sum(d < 0 for d in ordered)
32
+ losses = sum(d > 0 for d in ordered)
33
+ discordant = wins + losses
34
+ # Exact upper binomial tail under fair signs conditional on discordant pairs.
35
+ # https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binomtest.html
36
+ p_raw = sum(comb(discordant, k) for k in range(wins, discordant + 1)) / 2**discordant
37
+
38
+ # If m is a continuous population median, #{observations < m} has Bin(n, 1/2) law.
39
+ # Choose the narrowest symmetric order-statistic interval meeting the registered level.
40
+ # Equations 29–30: https://nvlpubs.nist.gov/nistpubs/TechnicalNotes/NIST.TN.2119.pdf
41
+ n = len(ordered)
42
+ rank = 0
43
+ discarded = 0
44
+ coverage = 1.0
45
+ for k in range(n // 2):
46
+ discarded += comb(n, k)
47
+ candidate = 1 - 2 * discarded / 2**n
48
+ if candidate < 0.95:
49
+ break
50
+ rank, coverage = k + 1, candidate
51
+ # The registered eight pairs admit a finite interval; expose unbounded ends for small n.
52
+ interval = [ordered[rank - 1], ordered[-rank]] if rank else [None, None]
53
+ return {
54
+ "pairs": pairs, "median_delta": median(ordered), "median_ci": interval,
55
+ "ci_coverage": coverage, "wins": wins, "ties": n - discordant, "losses": losses,
56
+ "p_raw": p_raw,
57
+ }
58
+
59
+
60
+ def _time_match(seed, records):
61
+ """Look backward from the shortest complete training run to actual validation evaluations."""
62
+ runs = {method: records[seed, method] for method in _METHODS}
63
+ if any(not _number(run.get("train_seconds")) or run["train_seconds"] <= 0 for run in runs.values()):
64
+ return None
65
+ cutoff = min(run["train_seconds"] for run in runs.values())
66
+ # Production logs evaluate fixed windows at each diagnostic, including the final step.
67
+ # Older homogeneous result files have a single dev_nll field for the same population.
68
+ fixed_windows = any("matched_dev_nll" in run for run in runs.values())
69
+ summary_field = "matched_dev_nll" if fixed_windows else "dev_nll"
70
+ matched = {}
71
+ for method, run in runs.items():
72
+ events = list(run.get("events") or [])
73
+ final = run.get("status") not in {"configured", "in progress", "training", "failed"}
74
+ if final and _number(run.get(summary_field)):
75
+ events.append({
76
+ "tokens": run["tokens"], "train_seconds": run["train_seconds"],
77
+ "dev_nll": run[summary_field],
78
+ })
79
+ eligible = [
80
+ event for event in events
81
+ if _number(event.get("train_seconds")) and 0 <= event["train_seconds"] <= cutoff
82
+ and _number(event.get("dev_nll")) and event["dev_nll"] >= 0
83
+ and _number(event.get("tokens")) and event["tokens"] >= 0
84
+ ]
85
+ if not eligible:
86
+ return None
87
+ # max() takes the first equal timestamp, giving a real event priority over its summary.
88
+ event = max(eligible, key=lambda x: x["train_seconds"])
89
+ matched[method] = {key: event[key] for key in ("tokens", "train_seconds", "dev_nll")}
90
+ matched[method]["staleness_seconds"] = cutoff - event["train_seconds"]
91
+ return {"seed": seed, "cutoff_seconds": cutoff, "by_method": matched}
92
+
93
+
94
+ def _inconsistency(records):
95
+ """Check optional provenance as an all-or-none contract within a completed scored matrix."""
96
+ for field in ("freeze_id", "test_manifest_sha256", "test_tokens"):
97
+ values = {row.get(field) for row in records.values()}
98
+ if len(values) > 1:
99
+ return f"The stage has inconsistent {field} values across final checkpoints."
100
+ for method in ("trace", "third"):
101
+ ratios = {records[seed, method].get("ratio") for seed in _SEEDS}
102
+ if len(ratios) > 1:
103
+ return f"The frozen {method} regularization ratio changes across seeds."
104
+ return None
105
+
106
+
107
+ def analyze_stage(summaries: list[dict], stage: str) -> dict:
108
+ """Analyze the fixed three-arm matrix after every registered checkpoint has a final score.
109
+
110
+ Partial matrices expose progress and eligible elapsed-time development comparisons.
111
+ Duplicate rows or incompatible provenance invalidate inference for that stage.
112
+ """
113
+ horizon = _HORIZON[stage]
114
+ result = {
115
+ "stage": stage, "status": "pending", "complete": False, "success": None,
116
+ "n_expected_seeds": len(_SEEDS), "n_complete_seeds": 0, "missing": [],
117
+ "comparisons": {}, "matched_time": [], "reason": "Awaiting confirmatory runs.",
118
+ }
119
+ records = {}
120
+ for row in summaries:
121
+ seed, method = row.get("seed"), row.get("method")
122
+ if (row.get("stage") != stage or row.get("phase") != "confirm" or method not in _METHODS
123
+ or type(seed) is not int or seed not in _SEEDS):
124
+ continue
125
+ key = (seed, method)
126
+ if key in records:
127
+ result.update(status="invalid", reason=f"Duplicate final-run records for seed {seed}, {method}.")
128
+ return result
129
+ if row.get("target_tokens") is not None and row["target_tokens"] != horizon:
130
+ result.update(status="invalid", reason=f"The configured {method} budget differs from registration.")
131
+ return result
132
+ records[key] = row
133
+ if not records:
134
+ return result
135
+
136
+ for seed in _SEEDS:
137
+ missing_methods = [
138
+ method for method in _METHODS if records.get((seed, method), {}).get("tokens") != horizon
139
+ ]
140
+ if missing_methods:
141
+ result["missing"].extend(f"Seed {seed} {method} full horizon" for method in missing_methods)
142
+ else:
143
+ result["n_complete_seeds"] += 1
144
+ timing = _time_match(seed, records)
145
+ if timing is not None:
146
+ result["matched_time"].append(timing)
147
+ if result["missing"]:
148
+ result.update(status="incomplete", reason=f"All checkpoints must reach {horizon:,} target tokens.")
149
+ return result
150
+
151
+ # Inspect the test scores only after establishing complete training coverage.
152
+ for (seed, method), row in records.items():
153
+ score = row.get("test_nll")
154
+ if score is None:
155
+ result["missing"].append(f"Seed {seed} {method} final test score")
156
+ elif not _number(score) or score < 0:
157
+ result.update(status="invalid", reason=f"Invalid test NLL for seed {seed}, {method}.")
158
+ return result
159
+ if result["missing"]:
160
+ result.update(status="incomplete", reason="Awaiting the complete frozen set of final test scores.")
161
+ return result
162
+ issue = _inconsistency(records)
163
+ if issue:
164
+ result.update(status="invalid", reason=issue)
165
+ return result
166
+
167
+ comparisons = {baseline: _comparison(records, baseline) for baseline in ("ce", "trace")}
168
+ # Holm step-down: adjusted p-values are monotone in raw-p rank; ties receive equal values.
169
+ # https://stat.ethz.ch/R-manual/R-devel/library/stats/html/p.adjust.html
170
+ running_max = 0.0
171
+ for index, stats in enumerate(sorted(comparisons.values(), key=lambda item: item["p_raw"])):
172
+ running_max = max(running_max, stats["p_raw"] * (len(comparisons) - index))
173
+ stats["p_holm"] = min(1.0, running_max)
174
+ if stats["p_holm"] <= 0.05:
175
+ stats["interpretation"] = "improved"
176
+ elif stats["median_ci"][0] > 0:
177
+ stats["interpretation"] = "adverse"
178
+ else:
179
+ stats["interpretation"] = "inconclusive"
180
+ success = all(stats["p_holm"] <= 0.05 for stats in comparisons.values())
181
+ if success:
182
+ status, reason = "confirmed", "Both registered superiority comparisons passed."
183
+ elif any(stats["interpretation"] == "adverse" for stats in comparisons.values()):
184
+ status, reason = "adverse", "A median-difference interval favors a baseline."
185
+ else:
186
+ status, reason = "inconclusive", "The registered two-comparison superiority criterion was unmet."
187
+ result.update(status=status, complete=True, success=success, comparisons=comparisons, reason=reason)
188
+ return result
research/src/thirdloss/cli.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """User-facing commands for one arm, the full research pipeline, and a live local explorer."""
2
+
3
+ import argparse
4
+ import json
5
+ from functools import partial
6
+ from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
7
+ from pathlib import Path
8
+
9
+ from .records import HORIZONS, METHODS, storage_root
10
+
11
+
12
+ def dashboard(project, port):
13
+ """Serve the same Pages application locally with a live view of atomically recorded events."""
14
+ from .report_records import study_snapshot
15
+
16
+ class Handler(SimpleHTTPRequestHandler):
17
+ def do_GET(self):
18
+ if self.path.split("?",1)[0] == "/live.json":
19
+ data = json.dumps(study_snapshot(project),ensure_ascii=False,allow_nan=False).encode()
20
+ self.send_response(200)
21
+ self.send_header("Content-Type","application/json; charset=utf-8")
22
+ self.send_header("Cache-Control","no-store")
23
+ self.send_header("Content-Length",str(len(data)))
24
+ self.end_headers()
25
+ self.wfile.write(data)
26
+ else:
27
+ super().do_GET()
28
+ server = ThreadingHTTPServer(("127.0.0.1",port),partial(Handler,directory=str(project/"docs")))
29
+ print(f"Live study dashboard http://127.0.0.1:{port}/",flush=True)
30
+ server.serve_forever()
31
+
32
+
33
+ def parser():
34
+ p = argparse.ArgumentParser(description=__doc__)
35
+ p.add_argument("--project",type=Path,default=Path.cwd())
36
+ parsers = p.add_subparsers(dest="action",required=True)
37
+ for action in ("prepare","train","study","freeze","evaluate","report","dashboard","publish","progress"):
38
+ sub = parsers.add_parser(action)
39
+ if action in {"prepare","study"}:
40
+ sub.add_argument("--stage",choices=(*HORIZONS,"both"),default="both")
41
+ if action in {"train","freeze"}:
42
+ sub.add_argument("--stage",choices=HORIZONS,required=True)
43
+ if action in {"train","study","evaluate"}:
44
+ sub.add_argument("--device",default="cuda")
45
+ if action=="train":
46
+ sub.add_argument("--method",choices=(*METHODS,"unigram","initial"),required=True)
47
+ sub.add_argument("--phase",choices=("pilot","control","confirm","smoke"),default="pilot")
48
+ sub.add_argument("--seed",type=int,default=0)
49
+ sub.add_argument("--ratio",type=float,default=0.03)
50
+ sub.add_argument("--microbatch",type=int)
51
+ if action in {"train","study","evaluate"}:
52
+ sub.add_argument("--publish",action="store_true",help="Publish results to the configured project accounts")
53
+ if action=="evaluate":
54
+ sub.add_argument("run_id")
55
+ if action=="dashboard":
56
+ sub.add_argument("--port",type=int,default=8765)
57
+ if action=="publish":
58
+ sub.add_argument("--message",default="Update third-derivative study records")
59
+ return p
60
+
61
+
62
+ def main(argv=None):
63
+ args = parser().parse_args(argv)
64
+ project = args.project.resolve()
65
+ storage = storage_root(project)
66
+ if args.action=="dashboard":
67
+ return dashboard(project,args.port)
68
+ if args.action in {"report","progress","publish"}:
69
+ from .progress import progress
70
+ if args.action == "progress":
71
+ print(progress(project))
72
+ return
73
+ from .reporting import build_report
74
+ build_report(project)
75
+ progress(project)
76
+ if args.action == "publish":
77
+ from .release import publish_snapshot
78
+ print(publish_snapshot(project,args.message))
79
+ return
80
+ from .study import evaluate_one,freeze,milestone,prepare_stage,run_study
81
+ if args.action=="freeze":
82
+ print(freeze(project,storage,args.stage)["freeze_id"])
83
+ return
84
+ stages = list(HORIZONS) if getattr(args,"stage",None)=="both" else [getattr(args,"stage",None)]
85
+ if args.action=="prepare":
86
+ for stage in stages:
87
+ prepare_stage(project,storage,stage)
88
+ return
89
+ from .records import setup_device
90
+ device = setup_device(args.device)
91
+ if args.action=="study":
92
+ run_study(project,storage,stages,device,args.publish)
93
+ return
94
+ if args.action=="evaluate":
95
+ summary = evaluate_one(project,storage,args.run_id,device)
96
+ else:
97
+ from .train import run_one
98
+ summary = run_one(project,storage,args.stage,args.method,args.phase,args.seed,args.ratio,device,args.microbatch)
99
+ milestone(project,storage,summary,args.publish)
100
+
101
+
102
+ if __name__=="__main__":
103
+ main()
research/src/thirdloss/data.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prepare versioned, leakage-audited token streams for both causal LM experiments."""
2
+
3
+ import gzip
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import re
8
+ import shutil
9
+ import time
10
+ import urllib.request
11
+ from collections import Counter
12
+ from datetime import datetime, timezone
13
+ from itertools import batched, islice
14
+ from pathlib import Path
15
+ from tempfile import TemporaryDirectory
16
+
17
+ import httpx
18
+ import numpy as np
19
+ import pyarrow.parquet as pq
20
+ from filelock import FileLock
21
+ from huggingface_hub import constants, hf_hub_download, hf_hub_url
22
+ from tokenizers import Tokenizer, decoders, models, pre_tokenizers, trainers
23
+
24
+ from .overlap import Document, clean_splits
25
+
26
+
27
+ STORY_REPO = "roneneldan/TinyStories"
28
+ STORY_REVISION = "f54c09fd23315a6f9c86f9dc80f725de7d8f9c64"
29
+ ABSTRACT_REPO = "common-pile/arxiv_abstracts_filtered"
30
+ ABSTRACT_REVISION = "dc1ceab4755eb037ec61e49cf1350dab7ceee6e7"
31
+ PYTHIA_REPO = "EleutherAI/pythia-410m"
32
+ PYTHIA_REVISION = "9879c9b5f8bea9051dcb0e68dff21493d67e9d4f"
33
+ STORY_LIMIT = 160_000
34
+ STORY_VOCAB = 4096
35
+ EOS = "<|endoftext|>"
36
+ FORMAT = "thirdloss-packed-v1"
37
+
38
+ # Object IDs and byte lengths come from the pinned HF tree APIs documented in docs/data.md.
39
+ # Large files use LFS SHA-256. The tokenizer uses the Git blob identifier at this release.
40
+ FILES = {
41
+ "story_train": ("data/train-00000-of-00004-2d5a1467fff1081b.parquet", 248731111,
42
+ "77cf780cebe52b6e83e3a2ac84bc56d8059363113e41d17a023f1d8b2ed0fc0b"),
43
+ "story_test": ("data/validation-00000-of-00001-869c898b519ad725.parquet", 9989127,
44
+ "33406a6206554cfc279c29c11f4df51528af487aa1a602b075566fc83c49dcab"),
45
+ "abstract_0": ("arxiv-abstracts-dolma-0000.json.gz", 892766221,
46
+ "2aa4dba7c362a977853619239655f073205346978931d6ad070026c7dfa1c4d2"),
47
+ "abstract_1": ("arxiv-abstracts-dolma-0001.json.gz", 235616002,
48
+ "451ff8bbc867360d66ddca2794459377d1cc56f91b2243587857f8ded982af36"),
49
+ "pythia_tokenizer": ("tokenizer.json", 2113710, "f74dfbfab8f97770a87769c739fb080c21c8bacc"),
50
+ }
51
+
52
+
53
+ def _log(message: str) -> None:
54
+ """Make long stream/audit phases visible to the command-line run log."""
55
+ stamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
56
+ print(f"{stamp} [prepare] {message}", flush=True)
57
+
58
+
59
+ def _sha256(path: Path) -> str:
60
+ """Hash bytes incrementally to avoid holding upstream archives in memory."""
61
+ with path.open("rb") as stream:
62
+ return hashlib.file_digest(stream, "sha256").hexdigest()
63
+
64
+
65
+ def _verify_source(path: Path, size: int, expected: str) -> str:
66
+ """Authenticate each input against the immutable upstream object identifier."""
67
+ if path.stat().st_size != size:
68
+ raise ValueError(f"Unexpected byte count for {path.name}")
69
+ sha = _sha256(path)
70
+ if len(expected) == 40:
71
+ git = hashlib.sha1(f"blob {size}\0".encode("ascii"), usedforsecurity=False)
72
+ with path.open("rb") as stream:
73
+ for block in iter(lambda: stream.read(1024 * 1024), b""):
74
+ git.update(block)
75
+ actual = git.hexdigest()
76
+ else:
77
+ actual = sha
78
+ if actual != expected:
79
+ raise ValueError(f"Content hash differs from pinned revision for {path.name}")
80
+ return sha
81
+
82
+
83
+ def _source(root: Path, repo: str, revision: str, key: str, kind: str = "dataset") -> tuple[Path, dict]:
84
+ """Download from the pinned Hub revision, with a verified public HTTPS fallback."""
85
+ name, size, oid = FILES[key]
86
+ fallback = root / "_sources" / "https" / revision / name
87
+ options = dict(repo_id=repo, filename=name, revision=revision, repo_type=kind)
88
+ _log(f"resolving {repo}@{revision[:9]}/{name}")
89
+ if fallback.is_file():
90
+ try:
91
+ digest = _verify_source(fallback, size, oid)
92
+ return fallback, dict(repo=repo, revision=revision, file=name, bytes=size, sha256=digest)
93
+ except ValueError:
94
+ _log(f"refreshing damaged fallback for {name}")
95
+ try:
96
+ path = Path(hf_hub_download(**options, cache_dir=root / "_sources" / "hub"))
97
+ digest = _verify_source(path, size, oid)
98
+ except (OSError, RuntimeError, ValueError, httpx.HTTPError) as error:
99
+ if constants.HF_HUB_OFFLINE:
100
+ raise
101
+ _log(f"Hub transport failed ({type(error).__name__}); verifying public HTTPS copy")
102
+ # A nonce requests a fresh signed object URL on networks that cache stale redirects.
103
+ url = hf_hub_url(**options) + f"?download=true&attempt={int(time.time())}"
104
+ fallback.parent.mkdir(parents=True, exist_ok=True)
105
+ with TemporaryDirectory(dir=fallback.parent, prefix=".download-") as directory:
106
+ partial = Path(directory) / "download"
107
+ request = urllib.request.Request(url, headers={"User-Agent": "thirdloss-data/1"})
108
+ with urllib.request.urlopen(request, timeout=120) as response, partial.open("wb") as target:
109
+ shutil.copyfileobj(response, target, length=4 * 1024 * 1024)
110
+ digest = _verify_source(partial, size, oid)
111
+ os.replace(partial, fallback)
112
+ path = fallback
113
+ return path, dict(repo=repo, revision=revision, file=name, bytes=size, sha256=digest)
114
+
115
+
116
+ def _texts(path: Path):
117
+ """Stream Arrow record batches in physical row order and keep only the text column."""
118
+ with pq.ParquetFile(path) as table:
119
+ for batch in table.iter_batches(batch_size=2048, columns=["text"]):
120
+ yield from batch.column(0).to_pylist()
121
+
122
+
123
+ def _story_documents(root: Path) -> tuple[dict, list, dict]:
124
+ """Assign the first registered source rows before deduplication and tokenizer fitting."""
125
+ train, train_meta = _source(root, STORY_REPO, STORY_REVISION, "story_train")
126
+ test, test_meta = _source(root, STORY_REPO, STORY_REVISION, "story_test")
127
+ docs = {"train": [], "dev": [], "test": []}
128
+ for row, text in enumerate(islice(_texts(train), STORY_LIMIT)):
129
+ doc = Document.make(f"train:{row}", text or "")
130
+ # A content hash makes equivalent stories receive the same development assignment.
131
+ split = "dev" if int(doc.digest[:16], 16) % 50 == 0 else "train"
132
+ docs[split].append(doc)
133
+ if len(docs["train"]) + len(docs["dev"]) != STORY_LIMIT:
134
+ raise ValueError("Pinned first training shard does not cover the registered prefix")
135
+ for row, text in enumerate(_texts(test)):
136
+ docs["test"].append(Document.make(f"validation:{row}", text or ""))
137
+ return docs, [train_meta, test_meta], dict(training_prefix=STORY_LIMIT, dev_hash_modulus=50)
138
+
139
+
140
+ def _abstract_id(value: str, submitted: str) -> tuple[str, str] | None:
141
+ """Split by the source's creation timestamp, grouping all versions of a paper."""
142
+ month = str(submitted)[:7]
143
+ if not re.fullmatch(r"2024-0[1-6]", month):
144
+ return None
145
+ match = re.fullmatch(r"(?:arXiv:)?(\d{4}\.\d{5})(?:v[1-9]\d*)?", str(value).strip())
146
+ if not match:
147
+ raise ValueError(f"Unrecognized modern arXiv identifier {value!r} with submission date {submitted!r}")
148
+ split = "train" if month <= "2024-04" else ("dev" if month == "2024-05" else "test")
149
+ return match[1], split
150
+
151
+
152
+ def _abstract_documents(root: Path) -> tuple[dict, list, dict]:
153
+ """Read both Common Pile shards, grouping versions of each base paper identifier."""
154
+ docs = {"train": [], "dev": [], "test": []}
155
+ seen_ids, sources = set(), []
156
+ counts = Counter()
157
+ for key in ("abstract_0", "abstract_1"):
158
+ path, meta = _source(root, ABSTRACT_REPO, ABSTRACT_REVISION, key)
159
+ sources.append(meta)
160
+ with gzip.open(path, "rb") as stream:
161
+ for line in stream:
162
+ record = json.loads(line)
163
+ counts["total_source_rows"] += 1
164
+ parsed = _abstract_id(record["id"], record["created"])
165
+ if parsed is None:
166
+ continue
167
+ identifier, split = parsed
168
+ if identifier in seen_ids:
169
+ counts["repeated_base_id"] += 1
170
+ continue
171
+ seen_ids.add(identifier)
172
+ submitted = str(record["created"])
173
+ # arXiv assigns IDs at announcement; retain date-boundary disagreements for audit.
174
+ if identifier[:4] != submitted[2:4] + submitted[5:7]:
175
+ counts["identifier_month_differs_from_created"] += 1
176
+ docs[split].append(Document.make(identifier, record["text"] or "", submitted))
177
+ _log(f"scanned {meta['file']}, {len(seen_ids):,} eligible paper IDs so far")
178
+ return docs, sources, dict(counts)
179
+
180
+
181
+ def _tokenizer(stage: str, train: list[Document], root: Path, output: Path, sources: list) -> Tokenizer:
182
+ """Only accepted training documents may fit the scratch BPE. Preserve the adapter tokenizer."""
183
+ if stage == "abstracts":
184
+ path, metadata = _source(root, PYTHIA_REPO, PYTHIA_REVISION, "pythia_tokenizer", "model")
185
+ sources.append(metadata)
186
+ shutil.copyfile(path, output)
187
+ return Tokenizer.from_file(str(output))
188
+ tokenizer = Tokenizer(models.BPE())
189
+ tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
190
+ tokenizer.decoder = decoders.ByteLevel()
191
+ trainer = trainers.BpeTrainer(vocab_size=STORY_VOCAB, initial_alphabet=sorted(pre_tokenizers.ByteLevel.alphabet()),
192
+ special_tokens=[EOS], show_progress=False)
193
+ _log(f"fitting {STORY_VOCAB:,}-token byte BPE on {len(train):,} retained training documents")
194
+ tokenizer.train_from_iterator((doc.text for doc in train), trainer=trainer, length=len(train))
195
+ if tokenizer.get_vocab_size() != STORY_VOCAB:
196
+ raise ValueError("Training text did not support the registered BPE vocabulary size")
197
+ tokenizer.save(str(output))
198
+ return tokenizer
199
+
200
+
201
+ def _write_line(stream, record: dict) -> None:
202
+ """Use a stable machine-readable row for each document decision."""
203
+ stream.write(json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n")
204
+
205
+
206
+ def _pack(directory: Path, splits: dict, tokenizer: Tokenizer, eos: int) -> dict:
207
+ """Save little-endian IDs and byte-addressable membership records for reproducible slicing."""
208
+ metadata = {}
209
+ with (directory / "documents.jsonl").open("w", encoding="utf-8", newline="\n") as members:
210
+ for split, documents in splits.items():
211
+ path = directory / f"{split}.bin"
212
+ offset = 0
213
+ with path.open("wb") as stream:
214
+ for block in batched(documents, 256):
215
+ encodings = tokenizer.encode_batch([doc.text for doc in block], add_special_tokens=False)
216
+ flat = []
217
+ for doc, encoding in zip(block, encodings, strict=True):
218
+ ids = encoding.ids
219
+ size = len(ids) + 1
220
+ member = dict(split=split, id=doc.source_id, sha256=doc.digest,
221
+ start_token=offset, tokens=size)
222
+ if doc.submitted:
223
+ member["submitted"] = doc.submitted
224
+ _write_line(members, member)
225
+ flat.extend(ids)
226
+ flat.append(eos)
227
+ offset += size
228
+ np.asarray(flat, dtype="<u2").tofile(stream)
229
+ metadata[split] = dict(documents=len(documents), tokens=offset, bytes=path.stat().st_size,
230
+ sha256=_sha256(path))
231
+ _log(f"packed {split}: {len(documents):,} documents, {offset:,} tokens")
232
+ return metadata
233
+
234
+
235
+ def _existing(directory: Path) -> dict | None:
236
+ """Only return a completed preparation if its byte-level evidence is still intact."""
237
+ marker = directory / "manifest.json"
238
+ if not marker.is_file():
239
+ return None
240
+ try:
241
+ manifest = json.loads(marker.read_text(encoding="utf-8"))
242
+ if manifest["format"] != FORMAT or manifest["stage"] != directory.name:
243
+ return None
244
+ for name in ("tokenizer.json", "train.bin", "dev.bin", "test.bin", "documents.jsonl", "rejections.jsonl"):
245
+ path = directory / name
246
+ if not path.is_file() or _sha256(path) != manifest["artifacts"][name]["sha256"]:
247
+ return None
248
+ return manifest
249
+ except (KeyError, ValueError, TypeError):
250
+ return None
251
+
252
+
253
+ def prepare(stage: str, root: Path) -> dict:
254
+ """Create or verify an entire stage, publishing the manifest after all content checks pass."""
255
+ if stage not in ("stories", "abstracts"):
256
+ raise ValueError("stage must be 'stories' or 'abstracts'")
257
+ root = Path(root)
258
+ root.mkdir(parents=True, exist_ok=True)
259
+ output = root / stage
260
+ with FileLock(str(root / f".{stage}.prepare.lock")):
261
+ existing = _existing(output)
262
+ if existing is not None:
263
+ return existing
264
+ with TemporaryDirectory(dir=root, prefix=f".prepare-{stage}-") as directory:
265
+ staged = Path(directory)
266
+ load = _story_documents if stage == "stories" else _abstract_documents
267
+ raw, sources, selection = load(root)
268
+ splits, audit, rejected = clean_splits(raw, _log)
269
+ if not all(splits.values()):
270
+ raise ValueError(f"Empty split after {stage} corpus filtering: {audit}")
271
+ with (staged / "rejections.jsonl").open("w", encoding="utf-8", newline="\n") as records:
272
+ for item in rejected:
273
+ _write_line(records, item)
274
+ tokenizer = _tokenizer(stage, splits["train"], root, staged / "tokenizer.json", sources)
275
+ vocab = tokenizer.get_vocab(with_added_tokens=True)
276
+ vocab_size = max(vocab.values()) + 1
277
+ eos = tokenizer.token_to_id(EOS)
278
+ if eos is None or vocab_size > 65536:
279
+ raise ValueError("The tokenizer must have an EOS ID and fit in uint16")
280
+ packed = _pack(staged, splits, tokenizer, eos)
281
+ files = {f"{split}.bin": dict(bytes=values["bytes"], sha256=values["sha256"])
282
+ for split, values in packed.items()}
283
+ for name in ("tokenizer.json", "documents.jsonl", "rejections.jsonl"):
284
+ path = staged / name
285
+ files[name] = dict(bytes=path.stat().st_size, sha256=_sha256(path))
286
+ manifest = dict(format=FORMAT, stage=stage, sources=sources, selection=selection, audit=audit,
287
+ overlap=dict(words=5, jaccard_at_least="4/5", priority=["test", "dev", "train"],
288
+ coverage="All retained cross-split document pairs at this threshold"),
289
+ dtype="<u2", packing="one appended EOS per document, no added BOS",
290
+ eos_id=eos, vocab_size=vocab_size, tokenizer_entries=len(vocab),
291
+ model_vocab_size=50304 if stage == "abstracts" else vocab_size,
292
+ token_counts={s: v["tokens"] for s, v in packed.items()},
293
+ splits=packed, artifacts=files)
294
+ (staged / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n",
295
+ encoding="utf-8", newline="\n")
296
+ output.mkdir(exist_ok=True)
297
+ # Atomic per-file publication, with the manifest as the final commit marker.
298
+ (output / "manifest.json").unlink(missing_ok=True)
299
+ for name in (*files, "manifest.json"):
300
+ os.replace(staged / name, output / name)
301
+ return manifest
research/src/thirdloss/evaluation.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Token-weighted NLL, exact token accuracy, and uncurated paired development continuations."""
2
+
3
+ import math
4
+ import numpy as np
5
+ import torch
6
+ from tokenizers import Tokenizer
7
+
8
+ from .models import logits_of, token_nll
9
+ from .records import CONTEXT
10
+
11
+
12
+ @torch.no_grad()
13
+ def score(model, path, device, batch_size, limit_windows=None, unigram=None):
14
+ """Score each packed target once, including a final short window, with a fixed context grid."""
15
+ tokens = np.memmap(path, mode="r", dtype="<u2")
16
+ n = len(tokens) - 1
17
+ if n < 1:
18
+ raise ValueError("Empty evaluation split")
19
+ full, tail = divmod(n, CONTEXT)
20
+ indices = np.arange(full)
21
+ if limit_windows is not None and full > limit_windows:
22
+ indices = np.linspace(0, full-1, limit_windows, dtype=np.int64)
23
+ tail = 0
24
+ total_loss, correct, count = 0.0, 0, 0
25
+ if model is not None:
26
+ model.eval()
27
+
28
+ def batch_score(ids):
29
+ target = ids[:, 1:]
30
+ if unigram is not None:
31
+ return (-np.log(unigram[target])).sum(dtype=np.float64).item(), int((target == unigram.argmax()).sum())
32
+ seq = torch.from_numpy(ids.astype(np.int64)).to(device)
33
+ logits = logits_of(model, seq[:, :-1])
34
+ losses = token_nll(logits, seq[:, 1:])
35
+ return losses.sum(dtype=torch.float64).item(), (logits.argmax(-1) == seq[:, 1:]).sum().item()
36
+
37
+ for start in range(0, len(indices), batch_size):
38
+ offsets = indices[start:start+batch_size, None] * CONTEXT + np.arange(CONTEXT+1)
39
+ loss, hits = batch_score(tokens[offsets])
40
+ total_loss, correct, count = total_loss+loss, correct+hits, count+offsets.shape[0]*CONTEXT
41
+ if tail:
42
+ loss, hits = batch_score(np.asarray(tokens[full*CONTEXT:])[None, :])
43
+ total_loss, correct, count = total_loss+loss, correct+hits, count+tail
44
+ nll = total_loss/count
45
+ return {"nll": nll, "accuracy": correct/count, "tokens": count, "perplexity": math.exp(nll)}
46
+
47
+
48
+ def unigram_distribution(train, size):
49
+ """Laplace smoothing puts mass on the same output vocabulary as the neural decoder."""
50
+ tokens = np.memmap(train, mode="r", dtype="<u2")
51
+ counts = np.ones(size, dtype=np.float64)
52
+ for block in range(0, len(tokens), 1_000_000):
53
+ counts += np.bincount(tokens[block:block+1_000_000], minlength=size)
54
+ return counts/counts.sum()
55
+
56
+
57
+ @torch.no_grad()
58
+ def sample_outputs(model, directory, manifest, device, recorder, *, unigram=None):
59
+ """Use the first three eligible development documents and fixed sampling randomness."""
60
+ tokenizer = Tokenizer.from_file(str(directory/"tokenizer.json"))
61
+ tokens = np.memmap(directory/"dev.bin", mode="r", dtype="<u2")
62
+ eos = manifest["eos_id"]
63
+ start, emitted = 0, 0
64
+ for stop in np.flatnonzero(tokens[:200_000] == eos):
65
+ doc = tokens[start:stop].astype(np.int64).tolist()
66
+ start = stop+1
67
+ if len(doc) < 56:
68
+ continue
69
+ prefix, reference = doc[:16], doc[16:56]
70
+ generated = []
71
+ rng = torch.Generator(device=device).manual_seed(7401+emitted)
72
+ for _ in range(40):
73
+ if unigram is None:
74
+ seq = torch.tensor([prefix+generated], device=device)
75
+ logits = logits_of(model, seq[:, -CONTEXT:])[0, -1]
76
+ probabilities = (logits/0.8).softmax(-1)
77
+ else:
78
+ probabilities = torch.as_tensor(unigram, device=device)
79
+ next_token = torch.multinomial(probabilities, 1, generator=rng).item()
80
+ generated.append(next_token)
81
+ if next_token == eos:
82
+ break
83
+ recorder.emit({"split":"dev", "prompt":tokenizer.decode(prefix),
84
+ "reference":tokenizer.decode(reference), "continuation":tokenizer.decode(generated),
85
+ "prompt_ids":prefix, "generated_ids":generated, "tokens":len(generated),
86
+ "sampling_seed":7401+emitted, "temperature":0.8 if unigram is None else 1.0},
87
+ "samples.jsonl")
88
+ emitted += 1
89
+ if emitted == 3:
90
+ break
research/src/thirdloss/models.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Both study models use eager, differentiable attention on genuine next-token inputs.
2
+
3
+ The stories decoder uses RMSNorm, rotary attention and a gated SiLU MLP as in
4
+ https://arxiv.org/abs/2302.13971. The adapter stage uses the public Pythia weights
5
+ and PEFT LoRA (https://arxiv.org/abs/2106.09685).
6
+ """
7
+
8
+ from dataclasses import asdict, dataclass
9
+ from pathlib import Path
10
+
11
+ import torch
12
+ from torch import nn
13
+ from torch.nn import functional as F
14
+
15
+ PYTHIA = "EleutherAI/pythia-410m"
16
+ REVISION = "9879c9b5f8bea9051dcb0e68dff21493d67e9d4f"
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class StoryConfig:
21
+ vocab_size: int = 4096
22
+ width: int = 192
23
+ heads: int = 4
24
+ layers: int = 4
25
+ hidden: int = 512
26
+ context: int = 128
27
+
28
+
29
+ class RMSNorm(nn.Module):
30
+ """RMS-normalize the final dimension using differentiable elementary operations."""
31
+
32
+ def __init__(self, width):
33
+ super().__init__()
34
+ self.weight = nn.Parameter(torch.ones(width))
35
+
36
+ def forward(self, x):
37
+ return self.weight * x * torch.rsqrt(x.square().mean(dim=-1, keepdim=True) + 1e-5)
38
+
39
+
40
+ class Block(nn.Module):
41
+ """Pre-normalized causal self-attention and gated feedforward residual branches."""
42
+
43
+ def __init__(self, c):
44
+ super().__init__()
45
+ self.heads = c.heads
46
+ self.head_width = c.width // c.heads
47
+ if c.width % c.heads or self.head_width % 2:
48
+ raise ValueError("Rotary attention requires an even head width")
49
+ self.attn_norm, self.mlp_norm = RMSNorm(c.width), RMSNorm(c.width)
50
+ self.qkv = nn.Linear(c.width, 3 * c.width, bias=False)
51
+ self.out = nn.Linear(c.width, c.width, bias=False)
52
+ self.gate_up = nn.Linear(c.width, 2 * c.hidden, bias=False)
53
+ self.down = nn.Linear(c.hidden, c.width, bias=False)
54
+ positions = torch.arange(c.context)[:, None]
55
+ angles = positions / 10000 ** (torch.arange(0, self.head_width, 2) / self.head_width)
56
+ self.register_buffer("cos", angles.cos(), persistent=False)
57
+ self.register_buffer("sin", angles.sin(), persistent=False)
58
+ self.register_buffer("allowed", torch.ones(c.context, c.context, dtype=torch.bool).tril(),
59
+ persistent=False)
60
+
61
+ def rotate(self, x):
62
+ """Rotate pairs of coordinates by a deterministic position-dependent phase."""
63
+ n = x.shape[-2]
64
+ a, b = x[..., ::2], x[..., 1::2]
65
+ return torch.stack((a*self.cos[:n] - b*self.sin[:n], a*self.sin[:n] + b*self.cos[:n]),
66
+ dim=-1).flatten(-2)
67
+
68
+ def forward(self, x):
69
+ batch, length, width = x.shape
70
+ q, k, v = self.qkv(self.attn_norm(x)).reshape(
71
+ batch, length, 3, self.heads, self.head_width).permute(2, 0, 3, 1, 4)
72
+ scores = self.rotate(q) @ self.rotate(k).transpose(-1, -2) * self.head_width**-0.5
73
+ weights = scores.masked_fill(~self.allowed[:length, :length], float("-inf")).softmax(-1)
74
+ attended = (weights @ v).transpose(1, 2).reshape(batch, length, width)
75
+ x = x + self.out(attended)
76
+ gate, up = self.gate_up(self.mlp_norm(x)).chunk(2, dim=-1)
77
+ return x + self.down((gate * gate.sigmoid()) * up)
78
+
79
+
80
+ class StoryTransformer(nn.Module):
81
+ """Small causal decoder with one shared input/output embedding parameter."""
82
+
83
+ def __init__(self, config=None):
84
+ super().__init__()
85
+ self.config = config or StoryConfig()
86
+ c = self.config
87
+ self.embedding = nn.Embedding(c.vocab_size, c.width)
88
+ self.blocks = nn.Sequential(*(Block(c) for _ in range(c.layers)))
89
+ self.norm = RMSNorm(c.width)
90
+ for layer in self.modules():
91
+ if isinstance(layer, (nn.Linear, nn.Embedding)):
92
+ nn.init.normal_(layer.weight, std=0.02)
93
+
94
+ def forward(self, ids):
95
+ return F.linear(self.norm(self.blocks(self.embedding(ids))), self.embedding.weight)
96
+
97
+
98
+ class PrimitiveLayerNorm(nn.Module):
99
+ """Evaluate the pretrained LayerNorm formula with primitives supporting fourth derivatives."""
100
+
101
+ def __init__(self, original):
102
+ super().__init__()
103
+ self.weight, self.bias, self.eps = original.weight, original.bias, original.eps
104
+
105
+ def forward(self, x):
106
+ centered = x - x.mean(-1, keepdim=True)
107
+ return centered * torch.rsqrt(centered.square().mean(-1, keepdim=True) + self.eps) * self.weight + self.bias
108
+
109
+
110
+ def build_model(stage, seed, device, storage):
111
+ """Build the same initialization across paired arms, with frozen Pythia backbone weights."""
112
+ torch.manual_seed(seed)
113
+ if stage == "stories":
114
+ return StoryTransformer().to(device)
115
+ from peft import LoraConfig, TaskType, get_peft_model
116
+ from transformers import AutoModelForCausalLM
117
+
118
+ base = AutoModelForCausalLM.from_pretrained(PYTHIA, revision=REVISION, dtype=torch.float32,
119
+ attn_implementation="eager", cache_dir=str(storage / "hub"))
120
+ base.config.use_cache = False
121
+ for parent in list(base.modules()):
122
+ for name, child in list(parent.named_children()):
123
+ if isinstance(child, nn.LayerNorm):
124
+ setattr(parent, name, PrimitiveLayerNorm(child))
125
+ lora = LoraConfig(task_type=TaskType.CAUSAL_LM, r=8, lora_alpha=16,
126
+ target_modules=["query_key_value"], lora_dropout=0.0, bias="none")
127
+ return get_peft_model(base, lora).to(device)
128
+
129
+
130
+ def logits_of(model, ids):
131
+ """Normalize native stories tensors and Transformers CausalLMOutput to [B,T,V]."""
132
+ out = model(ids)
133
+ return out if isinstance(out, torch.Tensor) else out.logits
134
+
135
+
136
+ def token_nll(logits, targets):
137
+ """Elementwise stable next-token NLL, exposing all derivative orders in the log partition."""
138
+ observed = logits.gather(-1, targets.unsqueeze(-1)).squeeze(-1)
139
+ return torch.logsumexp(logits, -1) - observed
140
+
141
+
142
+ def token_loss(logits, targets):
143
+ return token_nll(logits, targets).mean()
144
+
145
+
146
+ def export_weights(model, path: Path):
147
+ """Write a portable safetensors snapshot of exactly the fitted coordinates."""
148
+ import json
149
+ from safetensors.torch import save_file
150
+
151
+ path.mkdir(parents=True, exist_ok=True)
152
+ if isinstance(model, StoryTransformer):
153
+ save_file({n: p.detach().cpu().contiguous() for n, p in model.named_parameters()},
154
+ str(path / "model.safetensors"))
155
+ (path / "config.json").write_text(json.dumps(asdict(model.config), indent=2), encoding="utf-8")
156
+ return path / "model.safetensors"
157
+ model.save_pretrained(path, safe_serialization=True)
158
+ return path / "adapter_model.safetensors"
research/src/thirdloss/objectives.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ordinary CE, probe gradients and fair train-only calibration on identical initial weights."""
2
+
3
+ import statistics
4
+ import torch
5
+
6
+ from .models import build_model, logits_of, token_loss, token_nll
7
+ from .penalties import estimate, partials, random_signs
8
+ from .records import BATCHES, read_json, sha256, write_json
9
+ from .windows import TrainingWindows, generator, probe_rows
10
+
11
+
12
+ def ce_backward(model, inputs, targets, microbatch):
13
+ """Accumulate the global token-mean CE despite physical microbatching."""
14
+ total_loss = torch.zeros((), device=inputs.device)
15
+ hits = torch.zeros((), device=inputs.device, dtype=torch.long)
16
+ for start in range(0, len(inputs), microbatch):
17
+ x, y = inputs[start:start+microbatch], targets[start:start+microbatch]
18
+ logits = logits_of(model, x)
19
+ contribution = token_nll(logits, y).sum() / targets.numel()
20
+ contribution.backward()
21
+ total_loss += contribution.detach()
22
+ hits += (logits.detach().argmax(-1) == y).sum()
23
+ return total_loss, hits / targets.numel()
24
+
25
+
26
+ def vector_norm(values):
27
+ return torch.linalg.vector_norm(torch.stack([torch.linalg.vector_norm(x.detach()) for x in values]))
28
+
29
+
30
+ def probe_gradient(model, parameters, inputs, targets, kind, seed, step):
31
+ """Differentiate the sampled penalty, including the fourth-order contraction."""
32
+ rng = generator(inputs.device, seed, step, 827)
33
+ rows = probe_rows(seed, step, len(inputs))
34
+ base = token_loss(logits_of(model, inputs[rows]), targets[rows])
35
+ value = estimate(base, parameters, kind, generator=rng)
36
+ return value.detach(), partials(value, parameters, create_graph=False)
37
+
38
+
39
+ def calibrate(project, storage, stage, kind, device, microbatch):
40
+ """Fix unit-strength scales for all seeds using only training data at pilot initialization."""
41
+ path = project / "results" / "calibration" / f"{stage}-{kind}.json"
42
+ data = storage / "data" / stage
43
+ fingerprint = sha256(data/"manifest.json")
44
+ if path.exists():
45
+ existing = read_json(path)
46
+ if existing["data_manifest_sha256"] != fingerprint:
47
+ raise ValueError(f"Calibration data changed for {stage}")
48
+ return existing["unit_lambda"]
49
+ model = build_model(stage, 0, device, storage)
50
+ parameters = tuple(p for p in model.parameters() if p.requires_grad)
51
+ windows = TrainingWindows(data/"train.bin", 6247, BATCHES[stage])
52
+ rows = []
53
+ for step in range(16):
54
+ inputs, targets = windows.get(step, device)
55
+ model.zero_grad(set_to_none=True)
56
+ ce_backward(model, inputs, targets, microbatch)
57
+ ce_norm = vector_norm(p.grad for p in parameters if p.grad is not None).item()
58
+ model.zero_grad(set_to_none=True)
59
+ value, grads = probe_gradient(model, parameters, inputs, targets, kind, 6247, step)
60
+ norm = vector_norm(grads).item()
61
+ if not (0 < norm < float("inf") and 0 < ce_norm < float("inf")):
62
+ raise FloatingPointError(f"Nonfinite or zero {kind} calibration norm at draw {step}: {norm}")
63
+ rows.append({"draw":step, "ce_grad_norm":ce_norm, "penalty_grad_norm":norm,
64
+ "value":value.item(), "norm_ratio":ce_norm/norm})
65
+ del grads
66
+ result = statistics.median(row["norm_ratio"] for row in rows)
67
+ write_json(path, {"stage":stage, "kind":kind, "data_manifest_sha256":fingerprint,
68
+ "unit_lambda":result, "draws":rows})
69
+ return result
70
+
71
+
72
+ def add_penalty(model, parameters, inputs, targets, coefficients, method, seed, step):
73
+ """Add the gated derivative contribution to already-accumulated CE gradients."""
74
+ telemetry = {}
75
+ for kind, weight in coefficients.items():
76
+ if not weight:
77
+ continue
78
+ value, grads = probe_gradient(model, parameters, inputs, targets, kind, seed, step)
79
+ raw_norm = vector_norm(grads).item()
80
+ if method == "sham":
81
+ signs = random_signs(parameters, generator(inputs.device, seed, step, 839))
82
+ grads = tuple(g * sign for g, sign in zip(grads, signs, strict=True))
83
+ with torch.no_grad():
84
+ for param, grad in zip(parameters, grads, strict=True):
85
+ if param.grad is None:
86
+ param.grad = torch.zeros_like(param)
87
+ param.grad.add_(grad, alpha=8*weight)
88
+ telemetry[kind] = {"estimate":value.item(), "raw_grad_norm":raw_norm, "lambda":weight}
89
+ return telemetry
research/src/thirdloss/overlap.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Split documents before tokenization, using exact hashes and verified shingle overlap."""
2
+
3
+ import hashlib
4
+ import re
5
+ import unicodedata
6
+ from collections import Counter, defaultdict
7
+ from dataclasses import dataclass
8
+ from typing import Callable
9
+
10
+
11
+ def canonical(text: str) -> str:
12
+ """Make whitespace, case and Unicode compatibility variants equal for leakage checks."""
13
+ return " ".join(unicodedata.normalize("NFKC", text).casefold().split())
14
+
15
+
16
+ def content_hash(text: str) -> str:
17
+ """Use a stable identity across processes, files and operating systems."""
18
+ return hashlib.sha256(canonical(text).encode("utf-8")).hexdigest()
19
+
20
+
21
+ @dataclass(frozen=True, slots=True)
22
+ class Document:
23
+ """Preserve the source text for tokenization and its normalized identity for audits."""
24
+
25
+ source_id: str
26
+ text: str
27
+ digest: str
28
+ submitted: str = ""
29
+
30
+ @classmethod
31
+ def make(cls, source_id: str, text: str, submitted: str = "") -> "Document":
32
+ return cls(source_id, text.strip(), content_hash(text), submitted)
33
+
34
+
35
+ def shingles(text: str) -> set[str]:
36
+ """Use distinct five-word runs and one whole-text key for very short documents."""
37
+ words = re.findall(r"\w+", canonical(text))
38
+ if len(words) < 5:
39
+ return {" ".join(words) if words else canonical(text)}
40
+ return {" ".join(words[i:i + 5]) for i in range(len(words) - 4)}
41
+
42
+
43
+ def prefix_size(size: int) -> int:
44
+ """At 4/5 Jaccard, at most floor(size/5) items may be outside the intersection."""
45
+ return size // 5 + 1
46
+
47
+
48
+ class ShingleIndex:
49
+ """Index a higher-priority split using the lossless prefix filtering lemma.
50
+
51
+ For Jaccard >= 4/5 the overlap must cover at least 4/5 of each set. Under
52
+ a common term order, its first shared term falls in both indexed prefixes.
53
+ Full set comparison verifies all candidates. See Xiao et al., section 2.2:
54
+ https://archives.iw3c2.org/www2008/papers/pdf/p131-xiaoA.pdf
55
+ """
56
+
57
+ def __init__(self, documents: list[Document]) -> None:
58
+ self.documents = documents
59
+ self.frequency = Counter()
60
+ self.postings = defaultdict(list)
61
+ self.lengths = []
62
+ # A rare-first order reduces overlap from generic story openings.
63
+ for doc in documents:
64
+ self.frequency.update(shingles(doc.text))
65
+ for index, doc in enumerate(documents):
66
+ terms = shingles(doc.text)
67
+ self.lengths.append(len(terms))
68
+ for term in self._prefix(terms):
69
+ self.postings[term].append(index)
70
+
71
+ def _prefix(self, terms: set[str]) -> list[str]:
72
+ """Unknown terms sort first and cannot appear in any reference posting."""
73
+ known = [term for term in terms if term in self.frequency]
74
+ count = prefix_size(len(terms)) - (len(terms) - len(known))
75
+ if count <= 0:
76
+ return []
77
+ known.sort(key=lambda term: (self.frequency[term], term))
78
+ return known[:count]
79
+
80
+ def match(self, terms: set[str]) -> Document | None:
81
+ """Return the earliest source match; exact integer arithmetic decides the cutoff."""
82
+ candidates = set()
83
+ for term in self._prefix(terms):
84
+ candidates.update(self.postings.get(term, ()))
85
+ for index in sorted(candidates):
86
+ n, m = len(terms), self.lengths[index]
87
+ if 5 * min(n, m) < 4 * max(n, m):
88
+ continue
89
+ doc = self.documents[index]
90
+ common = len(terms.intersection(shingles(doc.text)))
91
+ if 5 * common >= 4 * (n + m - common):
92
+ return doc
93
+ return None
94
+
95
+
96
+ def clean_splits(raw: dict[str, list[Document]], log: Callable[[str], None]) -> tuple[dict, dict, list]:
97
+ """Protect test, then dev, then train; retain an audit trail without publishing text."""
98
+ retained: dict[str, list[Document]] = {}
99
+ seen: dict[str, tuple[str, str]] = {}
100
+ protected: list[tuple[str, ShingleIndex]] = []
101
+ rejections = []
102
+ summary = {}
103
+ for split in ("test", "dev", "train"):
104
+ retained[split] = []
105
+ reasons = Counter()
106
+ for row, doc in enumerate(raw[split]):
107
+ if row and row % 25000 == 0:
108
+ log(f"audited {row:,}/{len(raw[split]):,} {split} documents")
109
+ reason, other_split, other_id = "", "", ""
110
+ if not canonical(doc.text):
111
+ reason = "empty"
112
+ elif doc.digest in seen:
113
+ reason = "exact"
114
+ other_split, other_id = seen[doc.digest]
115
+ elif protected:
116
+ terms = shingles(doc.text)
117
+ for name, reference in protected:
118
+ match = reference.match(terms)
119
+ if match is not None:
120
+ reason, other_split, other_id = "near", name, match.source_id
121
+ break
122
+ if reason:
123
+ reasons[reason] += 1
124
+ rejections.append(dict(split=split, source_id=doc.source_id, sha256=doc.digest,
125
+ reason=reason, reference_split=other_split, reference_id=other_id))
126
+ else:
127
+ seen[doc.digest] = (split, doc.source_id)
128
+ retained[split].append(doc)
129
+ summary[split] = dict(input=len(raw[split]), kept=len(retained[split]),
130
+ exact=reasons["exact"], cross_split_near=reasons["near"], empty=reasons["empty"])
131
+ log(f"{split} overlap audit {summary[split]}")
132
+ if split != "train":
133
+ protected.append((split, ShingleIndex(retained[split])))
134
+ return retained, summary, rejections
research/src/thirdloss/penalties.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parameter-space derivative penalties following the equations in reports/preregistration.md.
2
+
3
+ The rank-one trace identity is developed in https://arxiv.org/pdf/2004.06433.
4
+ Keep every derivative differentiable until the outer training gradient is taken.
5
+ """
6
+
7
+ import torch
8
+
9
+
10
+ def random_signs(parameters, generator=None):
11
+ """Draw independent signs in each parameter's coordinates, fixed during differentiation."""
12
+ return tuple(torch.empty_like(p).bernoulli_(0.5, generator=generator).mul_(2).sub_(1)
13
+ for p in parameters)
14
+
15
+
16
+ def partials(value, parameters, *, create_graph=True):
17
+ """Differentiate a scalar, including structurally constant or unused coordinates."""
18
+ if not value.requires_grad:
19
+ return tuple(torch.zeros_like(p) for p in parameters)
20
+ values = torch.autograd.grad(value, parameters, create_graph=create_graph,
21
+ allow_unused=True, retain_graph=True)
22
+ return tuple(torch.zeros_like(p) if g is None else g for p, g in zip(parameters, values, strict=True))
23
+
24
+
25
+ def inner(left, right):
26
+ """Contract parameter-shaped tuples without flattening/copying a whole model."""
27
+ return torch.stack([(a * b).sum() for a, b in zip(left, right, strict=True)]).sum()
28
+
29
+
30
+ def estimate(loss, parameters, kind, u=None, v=None, generator=None):
31
+ """Return one differentiable estimate of trace(H), ||H||² or ||D³loss||².
32
+
33
+ The repeated probe in the trace and the independent second probe for D³ implement
34
+ two distinct expectations. H is always the Hessian of the unregularized loss.
35
+ """
36
+ parameters = tuple(parameters)
37
+ if not parameters or kind not in {"trace", "hessian_norm", "third"}:
38
+ raise ValueError(f"Expected trainable parameters and a derivative penalty, received {kind!r}")
39
+ u = random_signs(parameters, generator) if u is None else tuple(x.detach() for x in u)
40
+ gradient = partials(loss, parameters)
41
+ hu = partials(inner(gradient, u), parameters)
42
+ if kind == "trace":
43
+ value = inner(hu, u)
44
+ elif kind == "hessian_norm":
45
+ value = inner(hu, hu)
46
+ else:
47
+ v = random_signs(parameters, generator) if v is None else tuple(x.detach() for x in v)
48
+ third_vector = partials(inner(hu, v), parameters)
49
+ value = inner(third_vector, third_vector)
50
+ # A constant cubic tensor still needs an explicitly verifiable zero training gradient.
51
+ anchor = torch.stack([p.reshape(-1)[0] for p in parameters]).sum() * 0
52
+ return value + anchor
research/src/thirdloss/progress.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compute study progress and throughput-based remaining confirmation time from result files."""
2
+
3
+ from .records import HORIZONS, read_json, time_now
4
+ from .report_records import atomic_text, study_snapshot
5
+
6
+
7
+ def progress(project):
8
+ study = study_snapshot(project)
9
+ runs = [r for r in study["runs"] if r.get("phase")!="smoke"]
10
+ done = [r for r in runs if r["status"] in {"complete","evaluated"}]
11
+ tests = [r for r in done if "test_nll" in r]
12
+ # Each stage has seven development candidates, two free controls, three ablations,
13
+ # three arms times eight confirmed seeds and the same number of test evaluations.
14
+ total = len(HORIZONS) * (7+2+3+2*3*8)
15
+ lines = ["# Study progress",f"Updated {time_now()}.",f"{len(done)} training/control records and "
16
+ f"{len(tests)} final evaluations are complete. This is {(len(done)+len(tests))/total:.1%} "
17
+ f"of {total} planned model milestones.", "## Current record"]
18
+ for stage,horizon in HORIZONS.items():
19
+ rows = [r for r in done if r.get("stage")==stage]
20
+ live = [r for r in runs if r.get("stage")==stage and r not in done]
21
+ status = ", ".join(f"{r['id']} ({r['status']}, {r.get('tokens',0):,} targets)" for r in live)
22
+ lines.append(f"**{stage}** has {len(rows)} completed runs. "
23
+ + (f"Current records: {status}." if live else "The next milestone is determined by the run matrix."))
24
+ path = project/"results"/"feasibility"/f"{stage}.json"
25
+ if path.exists():
26
+ spec = read_json(path)
27
+ remaining = 0.0
28
+ for arm in spec["arms"]:
29
+ completed = sum(r.get("tokens",0) for r in rows if r.get("phase")=="confirm" and r["method"]==arm["method"])
30
+ remaining += max(0,8*horizon-completed)/arm["tokens_per_sec"]/3600
31
+ lines.append(f"Pilot rates project {remaining:.2f} remaining confirmation GPU-hours, "
32
+ "excluding validation, exports and uploads.")
33
+ outcome = study["stages"][stage]
34
+ lines.append(f"Statistical status: {outcome['status']}. {outcome['reason']}")
35
+ lines += ["## Monitoring","Inspect runs lasting over 10, 30 and 60 minutes at 5, 15 and 30 minute intervals "
36
+ "respectively. The live dashboard refreshes between those checks. "
37
+ "[Study design](plan.md) · [Run matrix](planned-runs.md) · [Experiment ledger](experiments/experiments.md)"]
38
+ body = "\n\n".join(lines)+"\n"
39
+ atomic_text(project/"reports"/"progress.md",body)
40
+ return body
research/src/thirdloss/records.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Durable run identities, atomic JSON/checkpoint writes, and timestamped experiment records."""
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+
9
+ from dotenv import load_dotenv
10
+
11
+ HORIZONS = {"stories": 2**24, "abstracts": 2**19}
12
+ BATCHES = {"stories": 32, "abstracts": 8}
13
+ METHODS = ("ce", "trace", "third", "hessian_norm", "sham", "combined")
14
+ RATIOS = (0.01, 0.03, 0.10)
15
+ CONTEXT = 128
16
+
17
+
18
+ def time_now():
19
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
20
+
21
+
22
+ def storage_root(project):
23
+ load_dotenv(project / ".env")
24
+ root = Path(os.environ.get("THIRDLOSS_STORAGE", "storage")).expanduser()
25
+ return (project / root).resolve()
26
+
27
+
28
+ def sha256(path):
29
+ with Path(path).open("rb") as stream:
30
+ return hashlib.file_digest(stream, "sha256").hexdigest()
31
+
32
+
33
+ def read_json(path):
34
+ return json.loads(Path(path).read_text(encoding="utf-8-sig"))
35
+
36
+
37
+ def write_json(path, value):
38
+ """Atomic replacement leaves the preceding durable version intact after interruption."""
39
+ path = Path(path)
40
+ path.parent.mkdir(parents=True, exist_ok=True)
41
+ tmp = path.with_suffix(path.suffix + ".partial")
42
+ tmp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n", encoding="utf-8")
43
+ tmp.replace(path)
44
+
45
+
46
+ def json_lines(path):
47
+ if not path.exists():
48
+ return []
49
+ with path.open(encoding="utf-8") as stream:
50
+ return [json.loads(line) for line in stream if line.strip()]
51
+
52
+
53
+ class Recorder:
54
+ """Mirror every metric and complete generation to the terminal and a timestamped log."""
55
+
56
+ def __init__(self, project, run_id):
57
+ self.directory = project / "results" / run_id
58
+ self.directory.mkdir(parents=True, exist_ok=True)
59
+ logs = project / "logs"
60
+ logs.mkdir(exist_ok=True)
61
+ self.log = logs / f"{run_id}-{datetime.now(timezone.utc):%Y%m%dT%H%M%S%fZ}.jsonl"
62
+
63
+ def emit(self, record, filename="events.jsonl"):
64
+ row = {"timestamp": time_now(), **record}
65
+ line = json.dumps(row, ensure_ascii=True, allow_nan=False)
66
+ for path in (self.directory / filename, self.log):
67
+ with path.open("a", encoding="utf-8") as stream:
68
+ stream.write(line + "\n")
69
+ print(line, flush=True)
70
+
71
+
72
+ def run_name(stage, method, phase, seed, ratio):
73
+ return f"{stage}-{phase}-s{seed:02d}-{method}-r{round(ratio * 100):02d}"
74
+
75
+
76
+ def setup_device(requested):
77
+ """Enable CUDA when available and keep the parameter differentiation path in FP32."""
78
+ import torch
79
+ device = torch.device(requested)
80
+ if device.type == "cuda" and not torch.cuda.is_available():
81
+ raise RuntimeError("The requested CUDA device is unavailable in this PyTorch installation")
82
+ if device.type == "cuda":
83
+ torch.set_float32_matmul_precision("highest")
84
+ return device
research/src/thirdloss/release.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Publish the explicitly requested study artifacts using existing Git and Hugging Face logins."""
2
+
3
+ import subprocess
4
+ from pathlib import Path
5
+
6
+ from huggingface_hub import HfApi
7
+
8
+ from .records import read_json, sha256, write_json
9
+
10
+ OWNER = "BurnyCoder"
11
+ STUDY_HUB = f"{OWNER}/thirdloss-study"
12
+ COLLECTION = f"{OWNER}/third-derivatives-in-language-model-training-6b067fb7d5ae3eca49ebb378"
13
+ GITHUB = "https://github.com/BurnyCoder/llm-training-with-penalizing-rapid-changes-of-curvature-of-its-loss"
14
+ STAGE_HUB = {"stories":f"{OWNER}/thirdloss-stories", "abstracts":f"{OWNER}/thirdloss-pythia-410m-adapters"}
15
+
16
+
17
+ def publish_snapshot(project, message):
18
+ """Commit only curated public study outputs, then mirror tracked research files to the Hub."""
19
+ def git(*args):
20
+ return subprocess.run(["git",*args],cwd=project,check=True,capture_output=True,text=True).stdout.strip()
21
+ if git("branch","--show-current") != "main":
22
+ raise ValueError("Publish study snapshots from the merged main branch")
23
+ public = [name for name in ("README.md","reports","docs","results") if (project/name).exists()]
24
+ git("add","--",*public)
25
+ if git("diff","--cached","--name-only"):
26
+ git("commit","-m",message,"--",*public)
27
+ git("push","origin","main")
28
+ # Allowlist tracked files, excluding the dataset bytes, .env, logs and local environments.
29
+ from huggingface_hub import CommitOperationAdd
30
+ tracked = git("ls-files").splitlines()
31
+ api = HfApi()
32
+ operations = [CommitOperationAdd(path_in_repo="research/"+name, path_or_fileobj=project/name)
33
+ for name in tracked if (project/name).is_file()
34
+ and (name in {"README.md","uv.lock","pyproject.toml",".env.example",".python-version","AGENTS.md"}
35
+ or name.startswith(("src/","tests/","reports/","docs/","results/")))]
36
+ # A full mirror is appropriate for the first publication. Subsequent commits transfer changes only.
37
+ cursor = project / ".cache" / "hub-mirror.json"
38
+ previous = read_json(cursor) if cursor.exists() else {}
39
+ hashes = {op.path_in_repo:sha256(op.path_or_fileobj) for op in operations}
40
+ changed = [op for op in operations if hashes[op.path_in_repo]!=previous.get(op.path_in_repo)]
41
+ if changed:
42
+ api.create_commit(repo_id=STUDY_HUB,operations=changed,commit_message=message)
43
+ write_json(cursor,hashes)
44
+ card = ("---\nlanguage: [en]\ntags: [scientific-research, causal-language-modeling]\n---\n"
45
+ "# Third derivatives in language-model training\n\n"
46
+ "This repository preserves the preregistration, exact source, raw observations and generated reports. "
47
+ "The primary comparison is final test NLL over paired training seeds at equal token counts. "
48
+ "Read the [current study summary](research/reports/summary.md), [paper](research/reports/paper.pdf), "
49
+ f"[GitHub project]({GITHUB}), or [collection of checkpoints](https://huggingface.co/collections/{COLLECTION}).\n")
50
+ api.upload_file(repo_id=STUDY_HUB,path_or_fileobj=card.encode(),path_in_repo="README.md",
51
+ commit_message="Describe the research archive and evidence")
52
+ return git("rev-parse","HEAD")
53
+
54
+
55
+ def publish_weights(project, storage, summary):
56
+ """Store each fitted checkpoint in a distinct reproducible run directory in the collection."""
57
+ if "weights_sha256" not in summary:
58
+ return
59
+ stage, run_id = summary["stage"], summary["id"]
60
+ repo = STAGE_HUB[stage]
61
+ api = HfApi()
62
+ api.create_repo(repo,exist_ok=True)
63
+ api.add_collection_item(COLLECTION,repo,"model",exists_ok=True)
64
+ folder = storage/"checkpoints"/run_id/"export"
65
+ if sha256(folder/summary["weights_name"]) != summary["weights_sha256"]:
66
+ raise ValueError(f"Checkpoint integrity failure for {run_id}")
67
+ prior = "EleutherAI/pythia-410m" if stage=="abstracts" else "Random initialization"
68
+ card = (f"# {run_id}\n\n"
69
+ f"Research checkpoint for {stage} using the {summary['method']} objective. Base: {prior}. "
70
+ f"The run processed {summary['tokens']:,} training targets. Full development NLL was "
71
+ f"{summary['dev_nll']:.6f} nats per target. "
72
+ + (f"Sealed test NLL was {summary['test_nll']:.6f}. " if "test_nll" in summary else "")
73
+ + f"See the [protocol]({GITHUB}/blob/main/reports/preregistration.md) and "
74
+ f"[machine-readable results]({GITHUB}/tree/main/results/{run_id}). "
75
+ f"Use the pinned base and loading instructions in [the guide]({GITHUB}/blob/main/docs/runbook.md).\n")
76
+ (folder/"README.md").write_text(card,encoding="utf-8")
77
+ write_json(folder/"training_summary.json",summary)
78
+ api.upload_folder(repo_id=repo,folder_path=folder,path_in_repo="runs/"+run_id,
79
+ commit_message=f"Publish {run_id} training and evaluation artifacts")
80
+ description = ("Full-weight research checkpoints" if stage=="stories" else "LoRA adapters for EleutherAI/pythia-410m")
81
+ index = (f"---\nlanguage: [en]\npipeline_tag: text-generation\n"
82
+ + ("base_model: EleutherAI/pythia-410m\nlibrary_name: peft\n" if stage=="abstracts" else "library_name: pytorch\n")
83
+ + f"---\n# Third-derivative study · {stage}\n\n{description} are stored under "
84
+ f"[runs](https://huggingface.co/{repo}/tree/main/runs). Each directory includes its model card, "
85
+ f"weights, tokenizer and machine-readable scores. [Study and reproduction guide]({GITHUB})\n")
86
+ api.upload_file(repo_id=repo,path_or_fileobj=index.encode(),path_in_repo="README.md",
87
+ commit_message=f"Index {stage} checkpoint collection")
research/src/thirdloss/report_figures.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Publication figures from the same raw-run snapshot served by the interactive explorer."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from tempfile import NamedTemporaryFile
6
+
7
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
8
+ from matplotlib.figure import Figure
9
+ from matplotlib.patches import FancyBboxPatch
10
+
11
+ from .report_records import COLORS, METHODS, STAGES, finite
12
+
13
+ INK = "#263735"
14
+ GRID = "#dbe2df"
15
+
16
+
17
+ def _save(figure: Figure, path: Path) -> None:
18
+ """Write a stable PNG atomically for Pages and the ReportLab paper."""
19
+ FigureCanvasAgg(figure)
20
+ with NamedTemporaryFile(dir=path.parent, suffix=".png", delete=False) as handle:
21
+ temp = Path(handle.name)
22
+ try:
23
+ figure.savefig(temp, format="png", dpi=170, bbox_inches="tight", facecolor="white")
24
+ os.replace(temp, path)
25
+ finally:
26
+ temp.unlink(missing_ok=True)
27
+ figure.clear()
28
+
29
+
30
+ def architecture(path: Path) -> None:
31
+ """Draw the mathematical computation graph and the trainable coordinate choice."""
32
+ fig = Figure(figsize=(10.2, 3.2))
33
+ ax = fig.subplots()
34
+ ax.set(xlim=(0, 10), ylim=(0, 3.25))
35
+ ax.axis("off")
36
+
37
+ def box(x, y, w, h, line1, line2, fill):
38
+ ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.02,rounding_size=0.1",
39
+ facecolor=fill, edgecolor="#afc7c0", linewidth=1.1))
40
+ ax.text(x + w / 2, y + h * 0.63, line1, ha="center", va="center",
41
+ color=INK, fontsize=9.6, fontweight="semibold")
42
+ ax.text(x + w / 2, y + h * 0.29, line2, ha="center", va="center", color=INK, fontsize=8.5)
43
+
44
+ def arrow(start, end):
45
+ ax.annotate("", xy=end, xytext=start, arrowprops={"arrowstyle": "-|>", "color": "#506c65",
46
+ "lw": 1.25, "shrinkA": 1, "shrinkB": 2})
47
+
48
+ box(0.06, 2.12, 2.01, 0.77, "TinyStories", "all decoder weights", "#e7f2ef")
49
+ box(0.06, 0.42, 2.01, 0.77, "Research abstracts", "Pythia QKV adapters", "#e7f2ef")
50
+ box(2.65, 1.27, 1.85, 0.77, "Next-token loss", "cross-entropy L", "#f0f3f1")
51
+ box(5.15, 2.12, 2.0, 0.77, "Hessian contraction", "independent signs u, v", "#f6ede6")
52
+ box(7.84, 2.12, 2.0, 0.77, "Third derivative", "r = grad(uᵀ H v)", "#e7f2ef")
53
+ box(7.84, 0.42, 2.0, 0.77, "Training objective", "L + weighted ‖r‖²", "#d9eee8")
54
+ arrow((2.08, 2.48), (2.65, 1.83))
55
+ arrow((2.08, 0.80), (2.65, 1.47))
56
+ arrow((4.51, 1.84), (5.14, 2.47))
57
+ arrow((7.17, 2.5), (7.82, 2.5))
58
+ arrow((8.84, 2.08), (8.84, 1.2))
59
+ arrow((4.51, 1.43), (7.80, 0.73))
60
+ ax.text(5.8, 0.5, "AdamW differentiates the complete objective",
61
+ fontsize=8, color="#526863", ha="center")
62
+ _save(fig, path)
63
+
64
+
65
+ def _axes_style(ax, xlabel, ylabel):
66
+ """Give each scale its units and never imply a zero baseline for a difference plot."""
67
+ ax.set_xlabel(xlabel, fontsize=9)
68
+ ax.set_ylabel(ylabel, fontsize=9)
69
+ ax.grid(axis="y", color=GRID, linewidth=0.6)
70
+ ax.set_axisbelow(True)
71
+ ax.spines[["top", "right"]].set_visible(False)
72
+ ax.spines[["left", "bottom"]].set_color("#91a09c")
73
+ ax.tick_params(labelsize=8, color="#91a09c")
74
+
75
+
76
+ def _curves(study, path) -> bool:
77
+ """Draw actual development measurements in stage/phase panels, preserving run identity."""
78
+ groups = {}
79
+ for run in study["runs"]:
80
+ points = [(e["tokens"], e["dev_nll"]) for e in run["events"]
81
+ if finite(e.get("tokens")) and finite(e.get("dev_nll"))]
82
+ if points:
83
+ groups.setdefault((run.get("stage"), run.get("phase")), []).append((run, points))
84
+ if not groups:
85
+ return False
86
+ fig = Figure(figsize=(8, 2.8 * len(groups)), layout="constrained")
87
+ axes = fig.subplots(len(groups), 1, squeeze=False).ravel()
88
+ for ax, ((stage, phase), series) in zip(axes, groups.items()):
89
+ labels = set()
90
+ for run, points in series:
91
+ method = run.get("method")
92
+ label = METHODS.get(method, method) if method not in labels else "_nolegend_"
93
+ labels.add(method)
94
+ tokens, losses = zip(*points)
95
+ ax.plot(tokens, losses, color=COLORS.get(method, "#777"), marker=".",
96
+ markersize=3, linewidth=1, alpha=0.78, label=label)
97
+ _axes_style(ax, "Training target tokens", "Development NLL (nats/token)")
98
+ ax.set_title(f"{STAGES.get(stage, stage)} / {phase}", loc="left", fontsize=11, color=INK)
99
+ ax.legend(loc="best", fontsize=7, frameon=False, ncol=2)
100
+ _save(fig, path)
101
+ return True
102
+
103
+
104
+ def _paired(study, path) -> bool:
105
+ """Show every seed and the median interval for each registered comparison."""
106
+ rows = [(stage, baseline, stats) for stage, outcome in study["stages"].items()
107
+ for baseline, stats in outcome.get("comparisons", {}).items() if stats.get("pairs")]
108
+ if not rows:
109
+ return False
110
+ fig = Figure(figsize=(8.5, 1.5 + 0.72 * len(rows)), layout="constrained")
111
+ ax = fig.subplots()
112
+ axis_labels = []
113
+ for index, (stage, baseline, stats) in enumerate(rows):
114
+ axis_labels.append(f"{STAGES[stage]} / {METHODS[baseline]}")
115
+ pairs = stats["pairs"]
116
+ y = [index + (k - (len(pairs) - 1) / 2) * 0.036 for k in range(len(pairs))]
117
+ ax.scatter([pair["delta"] for pair in pairs], y, color=COLORS["third"], s=21, zorder=2)
118
+ lo, hi = stats["median_ci"]
119
+ if finite(lo) and finite(hi):
120
+ ax.hlines(index + 0.22, lo, hi, color=INK, linewidth=1.5)
121
+ ax.scatter([stats["median_delta"]], [index + 0.22], color=INK, marker="D", s=25, zorder=3)
122
+ ax.axvline(0, color="#677572", linewidth=0.8, linestyle="--")
123
+ ax.set_yticks(range(len(rows)), axis_labels)
124
+ _axes_style(ax, "Test NLL difference, third-order minus baseline (nats/token)", "")
125
+ ax.set_title("Paired seeds and median intervals", loc="left", fontsize=11, color=INK)
126
+ _save(fig, path)
127
+ return True
128
+
129
+
130
+ def build_figures(study: dict, directory: Path) -> dict:
131
+ """Emit the architecture always and measured plots only when observations exist."""
132
+ directory.mkdir(parents=True, exist_ok=True)
133
+ architecture(directory / "architecture.png")
134
+ products = {"architecture": "architecture.png"}
135
+ for key, draw in (("curves", _curves), ("paired", _paired)):
136
+ file = directory / f"{key}.png"
137
+ if draw(study, file):
138
+ products[key] = file.name
139
+ else:
140
+ file.unlink(missing_ok=True)
141
+ return products
research/src/thirdloss/report_paper.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typeset the preregistered study and current evidence using ReportLab Platypus.
2
+
3
+ Flowables permit a protocol-only manuscript to expand as complete seed pairs appear.
4
+ Renderer reference: https://docs.reportlab.com/reportlab/userguide/ch5_platypus/
5
+ """
6
+
7
+ import os
8
+ from datetime import datetime
9
+ from pathlib import Path
10
+ from statistics import median
11
+ from tempfile import NamedTemporaryFile
12
+ from xml.sax.saxutils import escape, quoteattr
13
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
14
+
15
+ from matplotlib import get_data_path
16
+ from reportlab.lib import colors
17
+ from reportlab.lib.enums import TA_LEFT
18
+ from reportlab.lib.pagesizes import A4
19
+ from reportlab.lib.styles import ParagraphStyle
20
+ from reportlab.pdfbase import pdfmetrics
21
+ from reportlab.pdfbase.ttfonts import TTFont
22
+ from reportlab.platypus import (
23
+ Image, KeepTogether, LongTable, PageBreak, Paragraph, SimpleDocTemplate, Spacer, TableStyle,
24
+ )
25
+
26
+ from .report_records import METHODS, REPOSITORY, STAGES, completed, describe_difference, finite, fmt, verdict_text
27
+
28
+ REFERENCES = {
29
+ "roughness": ("Duchon, Splines minimizing rotation-invariant semi-norms in Sobolev spaces",
30
+ "https://doi.org/10.1007/BFb0086566"),
31
+ "trace": ("Liu, Yu and Lin, Regularizing deep neural networks with stochastic estimators of Hessian trace",
32
+ "https://arxiv.org/pdf/2208.05924"),
33
+ "sketch": ("Bujanović and Kressner, Norm and trace estimation with random rank-one vectors",
34
+ "https://arxiv.org/pdf/2004.06433"),
35
+ "stories": ("Eldan and Li, TinyStories", "https://arxiv.org/pdf/2305.07759"),
36
+ "pythia": ("Biderman et al., Pythia", "https://arxiv.org/pdf/2304.01373"),
37
+ "lora": ("Hu et al., Low-rank adaptation of large language models", "https://arxiv.org/pdf/2106.09685"),
38
+ "abstracts": ("Common Pile, Filtered arXiv abstracts", "https://huggingface.co/datasets/common-pile/arxiv_abstracts_filtered"),
39
+ "seeds": ("Bouthillier et al., Accounting for variance in machine learning benchmarks",
40
+ "https://proceedings.mlsys.org/paper_files/paper/2021/hash/0184b0cd3cfb185989f858a1d9f5c1eb-Abstract.html"),
41
+ "coordinates": ("Dinh et al., Sharp minima can generalize for deep nets",
42
+ "https://proceedings.mlr.press/v70/dinh17b.html"),
43
+ }
44
+ TEAL = "#006c60"
45
+ INK = "#263735"
46
+ MUTED = "#4b5e59"
47
+
48
+
49
+ def _link(url, label):
50
+ return f"<link href={quoteattr(url)} color='{TEAL}'><u>{escape(str(label))}</u></link>"
51
+
52
+
53
+ def _cite(key):
54
+ label, url = REFERENCES[key]
55
+ return _link(url, label.split(",")[0] if key != "trace" else "Liu, Yu and Lin")
56
+
57
+
58
+ def _styles():
59
+ """Use embedded Unicode fonts shipped with Matplotlib on every supported machine."""
60
+ fonts = Path(get_data_path()) / "fonts" / "ttf"
61
+ for name, file in (("PaperSans", "DejaVuSans.ttf"), ("PaperBold", "DejaVuSans-Bold.ttf"),
62
+ ("PaperSerif", "DejaVuSerif.ttf")):
63
+ if name not in pdfmetrics.getRegisteredFontNames():
64
+ pdfmetrics.registerFont(TTFont(name, str(fonts / file)))
65
+ pdfmetrics.registerFontFamily("PaperSans", normal="PaperSans", bold="PaperBold",
66
+ italic="PaperSans", boldItalic="PaperBold")
67
+ base = dict(fontName="PaperSans", fontSize=9.0, leading=14, textColor=colors.HexColor(INK),
68
+ alignment=TA_LEFT, spaceAfter=7, splitLongWords=True)
69
+ styles = {"body": ParagraphStyle("body", **base)}
70
+ for name, changes in {
71
+ "title": dict(fontName="PaperSerif", fontSize=25, leading=30, spaceAfter=9, keepWithNext=True),
72
+ "heading": dict(fontName="PaperSerif", fontSize=15, leading=20, spaceBefore=8, spaceAfter=6, keepWithNext=True),
73
+ "subheading": dict(fontName="PaperBold", fontSize=10.4, leading=14, spaceBefore=6, keepWithNext=True),
74
+ "byline": dict(fontSize=9.5, leading=15, textColor=colors.HexColor(TEAL), spaceAfter=13),
75
+ "caption": dict(fontSize=7.8, leading=11.2, textColor=colors.HexColor(MUTED), spaceAfter=7),
76
+ "cell": dict(fontSize=7.45, leading=10.4, spaceAfter=0),
77
+ "headcell": dict(fontName="PaperBold", fontSize=7.3, leading=10.4, textColor=colors.white, spaceAfter=0),
78
+ "equation": dict(fontName="PaperSerif", fontSize=12.4, leading=19, leftIndent=9,
79
+ spaceBefore=3, spaceAfter=9),
80
+ }.items():
81
+ styles[name] = ParagraphStyle(name, parent=styles["body"], **changes)
82
+ return styles
83
+
84
+
85
+ def _grid(styles, headers, rows, widths):
86
+ """Repeat the column labels if the growing experiment table spans multiple pages."""
87
+ def line(cells, style):
88
+ return [Paragraph(escape(str(cell)), styles[style]) for cell in cells]
89
+ table = LongTable([line(headers, "headcell"), *[line(r, "cell") for r in rows]],
90
+ colWidths=widths, repeatRows=1, hAlign="LEFT", splitByRow=True)
91
+ table.setStyle(TableStyle([
92
+ ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#34504a")),
93
+ ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f0f5f2")]),
94
+ ("VALIGN", (0, 0), (-1, -1), "TOP"),
95
+ ("LEFTPADDING", (0, 0), (-1, -1), 5), ("RIGHTPADDING", (0, 0), (-1, -1), 5),
96
+ ("TOPPADDING", (0, 0), (-1, -1), 4.5), ("BOTTOMPADDING", (0, 0), (-1, -1), 4.5),
97
+ ]))
98
+ return table
99
+
100
+
101
+ def _figure(path, max_width=477, max_height=240):
102
+ image = Image(str(path))
103
+ scale = min(max_width / image.imageWidth, max_height / image.imageHeight)
104
+ image.drawWidth = image.imageWidth * scale
105
+ image.drawHeight = image.imageHeight * scale
106
+ image.hAlign = "LEFT"
107
+ return image
108
+
109
+
110
+ def _score_rows(study):
111
+ """Separate tuning strengths and token horizons before any descriptive aggregation."""
112
+ groups = {}
113
+ for run in study["runs"]:
114
+ if completed(run):
115
+ key = (run.get("stage"), run.get("phase"), run.get("method"),
116
+ run.get("ratio"), run.get("tokens"))
117
+ groups.setdefault(key, []).append(run)
118
+ rows = []
119
+ for (stage, phase, method, ratio, tokens), runs in groups.items():
120
+ def middle(key):
121
+ values = [r[key] for r in runs if finite(r.get(key))]
122
+ return fmt(median(values), 4) if values else "—"
123
+ rows.append([STAGES.get(stage, stage), phase, METHODS.get(method, method),
124
+ fmt(ratio), len(runs), fmt(tokens, 0), middle("dev_nll"), middle("test_nll")])
125
+ return rows
126
+
127
+
128
+ def write_paper(study: dict, output: Path, figure_dir: Path, figures: dict) -> None:
129
+ """Create the dated paper, with pretraining and adaptation interpreted separately."""
130
+ styles = _styles()
131
+ flow = []
132
+
133
+ def p(markup, style="body"):
134
+ flow.append(Paragraph(markup, styles[style]))
135
+
136
+ try:
137
+ local_time = datetime.fromisoformat(study["generated_at"]).astimezone(ZoneInfo("Europe/Berlin"))
138
+ except ZoneInfoNotFoundError:
139
+ local_time = datetime.fromisoformat(study["generated_at"]).astimezone()
140
+ rendered = local_time.strftime("%d %B %Y")
141
+ p("Third-derivative regularization for causal language models", "title")
142
+ p(f"Libor “Burny” Burian &nbsp;·&nbsp; {rendered}", "byline")
143
+ p("Abstract", "heading")
144
+ p("We study whether a language model improves its predictions when training penalizes "
145
+ "variation in the curvature of its next-token loss. Independent random signs produce "
146
+ "a differentiable estimate of the squared norm of all third partial derivatives in "
147
+ "the trainable coordinates. Two matched interventions compare this objective with "
148
+ "ordinary AdamW and a signed Hessian-trace penalty. " +
149
+ " ".join(f"{STAGES[s]}: {escape(verdict_text(outcome))}" for s, outcome in study["stages"].items()))
150
+ p("Motivation and related work", "heading")
151
+ p("A Hessian gives a local quadratic description of loss. Two nearby sets of weights "
152
+ "can share its trace while individual curvature components vary. Summing squared "
153
+ "third partials assigns a nonnegative cost to that variation in the chosen coordinates. "
154
+ "The proposed local density adapts an order-three spline roughness measure. The "
155
+ "published signed-trace language experiments studied recurrent language models. "
156
+ f"{_cite('roughness')} · {_cite('trace')} · {_cite('coordinates')}")
157
+ p("The estimator and its update", "heading")
158
+ p("J(θ) = L(θ) + λ · ‖D³L(θ)‖²<sub>F</sub>", "equation")
159
+ p("For independent Rademacher vectors u and v, form r = ∇(uᵀHv). Squaring and summing "
160
+ "its coordinates, then averaging over probes, cancels every cross term with unmatched "
161
+ "indices. The expectation is the squared Frobenius norm of the minibatch third derivative. "
162
+ "The gradient through r supplies a fourth-derivative contraction to AdamW. The "
163
+ "derivative minibatch contains two windows. A Bernoulli gate samples one eighth of "
164
+ "updates and multiplies the active contribution by eight. "
165
+ f"{_cite('sketch')} · {_link(REPOSITORY + '/blob/main/reports/preregistration.md', 'Preregistration')}")
166
+ flow.append(KeepTogether([_figure(figure_dir / figures["architecture"], max_height=140),
167
+ Paragraph("Figure 1. Trainable coordinate sets and the stochastic "
168
+ "regularization path.", styles["caption"])]))
169
+ flow.append(PageBreak())
170
+ p("Experimental design", "heading")
171
+ p("Full-weight pretraining uses a four-block causal Transformer with width 192, four heads, "
172
+ "a gated 512-wide MLP, tied embeddings and 128 targets per window. Stories use a "
173
+ "train-only vocabulary of 4,096 tokens. The adapter stage freezes Pythia-410M and trains "
174
+ "rank-eight attention QKV adapters with scale alpha 16. The first-submission timestamp "
175
+ "sets the split within 2024, grouping versions by base arXiv identifier. January through April supply training text, May supplies "
176
+ "development text, and June supplies the held-out test. "
177
+ f"{_cite('stories')} · {_cite('pythia')} · {_cite('lora')} · {_cite('abstracts')}")
178
+ p("The confirmatory horizons are 16,777,216 target tokens for stories and 524,288 for "
179
+ "abstracts. Within a stage, each seed pairs starting weights, text order and optimizer "
180
+ "schedule. The pilot calibrates penalty gradients on training data and selects strength "
181
+ "at equal development horizons. The squared-Hessian, sign-randomized and combined arms "
182
+ "test derivative order, gradient direction and incremental benefit. Initial checkpoints "
183
+ "and token unigrams supply untrained references. "
184
+ f"{_link(REPOSITORY + '/blob/main/reports/planned-runs.md', 'Run matrix')}")
185
+ p("Normalize and deduplicate whole documents before fitting the stories tokenizer. Prioritize "
186
+ "evaluation records when removing overlaps, and audit word-shingle similarity between "
187
+ "splits. Pack documents with an end-of-sequence token. Full evaluation counts each valid "
188
+ "target once. During training, the development curve uses a fixed subset of windows. "
189
+ f"{_link(REPOSITORY + '/blob/main/docs/data.md', 'Data preparation and overlap audit')}")
190
+ data_rows = [[STAGES[stage], name, fmt(split.get("documents"), 0), fmt(split.get("tokens"), 0)]
191
+ for stage, context in study["context"].items()
192
+ for name, split in context["datasets"].get("splits", {}).items()]
193
+ if data_rows:
194
+ flow.append(_grid(styles, ["Corpus", "Split", "Retained documents", "Packed tokens"],
195
+ data_rows, [112, 90, 132, 141]))
196
+ p("Packed-token counts include document separators. The number of valid next-token "
197
+ "targets is recorded separately during evaluation.", "caption")
198
+ p("Statistical analysis", "heading")
199
+ p("Corpus negative log-likelihood sums token losses and divides by the valid target count. "
200
+ "For each baseline, paired differences subtract baseline NLL from third-order NLL at the "
201
+ "same token budget. The registered stage decision requires both one-sided exact paired "
202
+ "sign tests to pass Holm correction at 0.05 across eight seed pairs. Ties are removed "
203
+ "from sign-test denominators. A distribution-free order-statistic interval quantifies "
204
+ "uncertainty in the median paired difference. Equal-time analyses use the latest logged "
205
+ "development checkpoint within the shortest final training time of that seed triple. "
206
+ f"{_cite('seeds')} · {_link(REPOSITORY + '/blob/main/reports/preregistration.md', 'Decision rule')}")
207
+ p("Results", "heading")
208
+ run_count = len(study["runs"])
209
+ done_count = sum(completed(run) for run in study["runs"])
210
+ p(f"The ledger contains {run_count} runs and {done_count} completed summaries. "
211
+ f"{_link(REPOSITORY + '/tree/main/results', 'Raw records')} · "
212
+ f"{_link(REPOSITORY + '/blob/main/reports/experiments/experiments.md', 'Per-run ledger')}")
213
+ for stage, outcome in study["stages"].items():
214
+ p(f"<b>{STAGES[stage]}.</b> {escape(verdict_text(outcome))}")
215
+ context = study["context"][stage]
216
+ selected = context["selection"].get("ratios", {})
217
+ if selected:
218
+ p(f"Development selected trace ratio {fmt(selected.get('trace'))} and third-order "
219
+ f"ratio {fmt(selected.get('third'))}. "
220
+ f"{_link(REPOSITORY + '/blob/main/results/selection/' + stage + '.json', 'All candidate scores')}")
221
+ hours = context["feasibility"].get("projected_confirm_training_hours")
222
+ if finite(hours):
223
+ p(f"The selected-arm pilot speeds project {hours:.2f} training hours for this full "
224
+ "confirmatory stage. This estimate covers optimization time. "
225
+ f"{_link(REPOSITORY + '/blob/main/results/feasibility/' + stage + '.json', 'Measured timing basis')}")
226
+ pilots = study["pilot_comparisons"][stage]
227
+ if pilots:
228
+ changes = ", ".join(f"{describe_difference(row['delta'])} against "
229
+ f"{METHODS[row['method']]}" for row in pilots)
230
+ p(f"In the development pilot at {pilots[0]['tokens']:,} training targets, third-order "
231
+ f"training recorded {changes}. The comparison uses one seed and "
232
+ f"{pilots[0]['strength_basis']}.")
233
+ evaluated = _score_rows(study)
234
+ if evaluated:
235
+ p("Scores across methods", "subheading")
236
+ flow.append(_grid(styles, ["Corpus", "Phase", "Method", "Ratio", "Runs", "Tokens/run", "Dev NLL", "Test NLL"],
237
+ evaluated, [60, 53, 105, 36, 34, 69, 58, 60]))
238
+ p("Table 1. Medians over available completed runs sharing corpus, method, development "
239
+ "strength and token horizon. NLL is in nats per target token. Dashes mark missing "
240
+ "observations. The paired seed analyses use individual final test scores.", "caption")
241
+ for key, caption in (("curves", "Development NLL by logged token count. Each line is a run; "
242
+ "panels separate training stages and phases."),
243
+ ("paired", "Individual differences in test NLL. Diamonds mark median "
244
+ "differences and horizontal segments show their registered intervals.")):
245
+ if key in figures:
246
+ flow.append(KeepTogether([_figure(figure_dir / figures[key]),
247
+ Paragraph(caption, styles["caption"])]))
248
+ p("Discussion and limitations", "heading")
249
+ p("Predictive utility requires lower held-out loss against both baselines. A reduction in "
250
+ "the derivative estimate alone describes local geometry. Parameterization changes its "
251
+ "magnitude, including the low-rank factorization used for abstracts. The estimate targets "
252
+ "expected two-window minibatch roughness. The small datasets, limited seed count and "
253
+ "two tokenization schemes bound the interpretation. More tokens per GPU hour can change "
254
+ "the practical ranking. "
255
+ f"{_cite('coordinates')} · {_link(REPOSITORY + '/blob/main/reports/preregistration.md', 'Scope of inference')}")
256
+ p("Conclusion", "heading")
257
+ if all(outcome.get("complete") for outcome in study["stages"].values()):
258
+ confirmed = [STAGES[s] for s, outcome in study["stages"].items() if outcome.get("success")]
259
+ if confirmed:
260
+ p("The registered dual-baseline criterion was met in " + " and ".join(confirmed) +
261
+ ". The observed gain applies to the reported data, trainable coordinates and token horizons.")
262
+ else:
263
+ p("Neither stage established the registered dual-baseline improvement. The paired "
264
+ "effects and uncertainty intervals quantify the range compatible with these data.")
265
+ else:
266
+ p("The outstanding paired evaluations determine which claims can be made about prediction quality "
267
+ "at the registered horizons. The run ledger preserves every available observation and implementation failure.")
268
+ pair_rows = [[STAGES[stage], METHODS.get(base, base), pair["seed"],
269
+ fmt(pair["third_nll"], 5), fmt(pair["baseline_nll"], 5), fmt(pair["delta"], 5)]
270
+ for stage, outcome in study["stages"].items()
271
+ for base, stats in outcome.get("comparisons", {}).items() for pair in stats["pairs"]]
272
+ if pair_rows:
273
+ p("Appendix · Paired effects", "heading")
274
+ flow.append(_grid(styles, ["Corpus", "Baseline", "Seed", "Third NLL", "Baseline NLL", "ΔNLL"],
275
+ pair_rows, [85, 110, 40, 78, 82, 80]))
276
+ for stage, outcome in study["stages"].items():
277
+ for base, stats in outcome.get("comparisons", {}).items():
278
+ lo, hi = stats["median_ci"]
279
+ p(f"{STAGES[stage]} / {METHODS[base]}: median ΔNLL {fmt(stats['median_delta'], 5)}, "
280
+ f"interval [{fmt(lo,5)}, {fmt(hi,5)}] at achieved coverage {fmt(stats['ci_coverage'],4)}. "
281
+ f"Holm-adjusted p = {fmt(stats['p_holm'], 5)}.", "caption")
282
+ has_examples = any(run["samples"] for run in study["runs"])
283
+ if has_examples:
284
+ p("Appendix · Output examples", "heading")
285
+ p("For each stage and method, the first saved sample in run-ID order is shown in excerpt. "
286
+ "The experiment ledger contains every full saved continuation and its corresponding "
287
+ f"reference when recorded. {_link(REPOSITORY + '/tree/main/reports/experiments', 'All outputs')}")
288
+ seen = set()
289
+ for run in study["runs"]:
290
+ key = (run.get("stage"), run.get("method"))
291
+ if not run["samples"] or key in seen:
292
+ continue
293
+ seen.add(key)
294
+ sample = run["samples"][0]
295
+ p(f"{STAGES.get(key[0], key[0])} · {METHODS.get(key[1], key[1])}", "subheading")
296
+ for field, name in (("prompt", "Prompt"), ("reference", "Reference"), ("continuation", "Prediction")):
297
+ if sample.get(field) is not None:
298
+ value = str(sample[field])
299
+ excerpt = value[:420] + (" […]" if len(value) > 420 else "")
300
+ p(f"<b>{name}.</b> {escape(excerpt)}", "caption")
301
+ p("References and reproducibility", "heading")
302
+ for title, url in REFERENCES.values():
303
+ p(_link(url, title), "caption")
304
+ p(f"Rebuild tables, figures, the explorer and this paper with <b>uv run thirdloss report</b>. "
305
+ f"{_link(REPOSITORY, 'Code and versioned protocol')}", "caption")
306
+ p("AI statement", "subheading")
307
+ p("Codex wrote the codebase and paper from the exact specification provided by a human. "
308
+ "Human cleanup and rewriting are in progress.", "caption")
309
+
310
+ def footer(canvas, doc):
311
+ canvas.saveState()
312
+ canvas.setStrokeColor(colors.HexColor("#ccd8d3"))
313
+ canvas.line(doc.leftMargin, 40, A4[0] - doc.rightMargin, 40)
314
+ canvas.setFillColor(colors.HexColor(MUTED))
315
+ canvas.setFont("PaperSans", 7.4)
316
+ canvas.drawString(doc.leftMargin, 27, "THIRD-DERIVATIVE REGULARIZATION")
317
+ canvas.drawRightString(A4[0] - doc.rightMargin, 27, str(doc.page))
318
+ canvas.restoreState()
319
+
320
+ output.parent.mkdir(parents=True, exist_ok=True)
321
+ with NamedTemporaryFile(dir=output.parent, suffix=".pdf", delete=False) as handle:
322
+ tmp = Path(handle.name)
323
+ try:
324
+ document = SimpleDocTemplate(str(tmp), pagesize=A4, leftMargin=49, rightMargin=49,
325
+ topMargin=43, bottomMargin=54,
326
+ title="Third-derivative regularization for causal language models",
327
+ author="Libor “Burny” Burian")
328
+ document.build(flow, onFirstPage=footer, onLaterPages=footer)
329
+ os.replace(tmp, output)
330
+ finally:
331
+ tmp.unlink(missing_ok=True)
research/src/thirdloss/report_records.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read the run ledger shared by the paper, live dashboard and static explorer."""
2
+
3
+ import json
4
+ import math
5
+ import os
6
+ import re
7
+ from datetime import datetime, timezone
8
+ from pathlib import Path
9
+ from tempfile import NamedTemporaryFile
10
+
11
+ from .analysis import analyze_stage
12
+
13
+
14
+ REPOSITORY = "https://github.com/BurnyCoder/llm-training-with-penalizing-rapid-changes-of-curvature-of-its-loss"
15
+ PAGES = "https://burnycoder.github.io/llm-training-with-penalizing-rapid-changes-of-curvature-of-its-loss/"
16
+ STAGES = {"stories": "TinyStories", "abstracts": "Research abstracts"}
17
+ METHODS = {
18
+ "ce": "Ordinary AdamW",
19
+ "trace": "Hessian trace",
20
+ "third": "Third derivative",
21
+ "hessian_norm": "Squared Hessian norm",
22
+ "sham": "Randomized gradient signs",
23
+ "combined": "Trace + third derivative",
24
+ "initial": "Initial checkpoint",
25
+ "unigram": "Unigram",
26
+ }
27
+ COLORS = {
28
+ "ce": "#374d67", "trace": "#ac582a", "third": "#007166",
29
+ "hessian_norm": "#64569c", "sham": "#ac3c66", "combined": "#3974a2",
30
+ "initial": "#674e35", "unigram": "#73736c",
31
+ }
32
+ FIELDS = (
33
+ "id", "stage", "method", "phase", "seed", "ratio", "tokens", "steps",
34
+ "train_seconds", "tokens_per_sec", "peak_vram_mb", "dev_nll", "dev_accuracy",
35
+ "test_nll", "test_accuracy", "status", "target_tokens", "budget", "parameters",
36
+ "trainable_parameters", "lambda", "coefficients", "device", "learning_rate",
37
+ "batch_size", "architecture", "commit", "dataset_revision", "data_hash",
38
+ "freeze_id", "test_manifest_sha256", "test_tokens", "data_manifest_sha256",
39
+ "token_budget", "batch_windows", "microbatch", "context", "weights_sha256", "dev_tokens",
40
+ "git_revision", "gpu", "torch", "matched_dev_nll", "finished_at",
41
+ )
42
+ EVENT_FIELDS = (
43
+ "step", "tokens", "train_seconds", "loss", "accuracy", "penalty", "dev_nll",
44
+ "dev_accuracy", "timestamp", "status", "peak_vram_mb",
45
+ )
46
+
47
+
48
+ def atomic_text(path: Path, text: str) -> None:
49
+ """Replace a complete UTF-8 artifact so a local dashboard never reads half a report."""
50
+ path.parent.mkdir(parents=True, exist_ok=True)
51
+ if path.exists() and path.read_text(encoding="utf-8") == text:
52
+ return
53
+ with NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", dir=path.parent,
54
+ delete=False, suffix=".tmp") as handle:
55
+ handle.write(text)
56
+ name = handle.name
57
+ try:
58
+ os.replace(name, path)
59
+ finally:
60
+ Path(name).unlink(missing_ok=True)
61
+
62
+
63
+ def read_json(path: Path) -> dict:
64
+ """Small summaries and configurations are atomically produced by the trainer."""
65
+ if not path.exists():
66
+ return {}
67
+ with path.open(encoding="utf-8-sig") as stream:
68
+ value = json.load(stream)
69
+ if not isinstance(value, dict):
70
+ raise ValueError(f"Expected a JSON object in {path}")
71
+ return value
72
+
73
+
74
+ def read_lines(path: Path) -> list[dict]:
75
+ """Ignore a concurrent partial trailing write, but surface damaged complete records."""
76
+ if not path.exists():
77
+ return []
78
+ records = []
79
+ with path.open("rb") as stream:
80
+ for number, line in enumerate(stream, 1):
81
+ if not line.strip():
82
+ continue
83
+ try:
84
+ record = json.loads(line)
85
+ except (ValueError, UnicodeDecodeError) as exc:
86
+ if not line.endswith(b"\n"):
87
+ break
88
+ raise ValueError(f"Unreadable JSON record {path}:{number}") from exc
89
+ if not isinstance(record, dict):
90
+ raise ValueError(f"Expected a JSON object at {path}:{number}")
91
+ records.append(record)
92
+ return records
93
+
94
+
95
+ def finite(value) -> bool:
96
+ """Exclude missing values, booleans and nonfinite numbers from graphs and summaries."""
97
+ return isinstance(value, (float, int)) and not isinstance(value, bool) and math.isfinite(value)
98
+
99
+
100
+ def fmt(value, digits: int = 3) -> str:
101
+ """Use a visible missing-value marker instead of completing an unobserved measurement."""
102
+ return f"{value:,.{digits}f}" if finite(value) else "—"
103
+
104
+
105
+ def run_record(folder: Path) -> dict:
106
+ """Join configuration, events and final summary with explicit completion state."""
107
+ config = read_json(folder / "config.json")
108
+ summary = read_json(folder / "summary.json")
109
+ last_error = read_json(folder / "failure.json")
110
+ events = read_lines(folder / "events.jsonl")
111
+ record = {key: config[key] for key in FIELDS if key in config}
112
+ # Calibration can fail before the trainer writes the final configuration.
113
+ identity = re.fullmatch(r"(stories|abstracts)-(\w+)-s(\d+)-(\w+)-r(\d+)", folder.name)
114
+ if identity and not config:
115
+ stage, phase, seed, method, ratio = identity.groups()
116
+ record.update(stage=stage, phase=phase, seed=int(seed), method=method, ratio=int(ratio) / 100)
117
+ for event in events:
118
+ for key in ("tokens", "train_seconds", "peak_vram_mb", "dev_nll", "dev_accuracy", "status"):
119
+ if event.get(key) is not None:
120
+ record[key] = event[key]
121
+ if event.get("step") is not None:
122
+ record["steps"] = event["step"]
123
+ record.update({key: summary[key] for key in FIELDS if key in summary})
124
+ if "token_budget" in record:
125
+ record["target_tokens"] = record["token_budget"]
126
+ record["id"] = folder.name
127
+ if last_error and not summary:
128
+ record["status"] = "failed"
129
+ record["error"] = str(last_error.get("error", "Recorded failure"))
130
+ else:
131
+ record.setdefault("status", "complete" if summary else "in progress" if events else "configured")
132
+ record["events"] = []
133
+ for event in events:
134
+ row = {k: event[k] for k in EVENT_FIELDS if event.get(k) is not None}
135
+ for kind, details in (event.get("derivatives") or {}).items():
136
+ if isinstance(details, dict) and finite(details.get("estimate")):
137
+ row["raw_" + kind] = details["estimate"]
138
+ record["events"].append(row)
139
+ record["samples"] = read_lines(folder / "samples.jsonl")
140
+ return record
141
+
142
+
143
+ def display_events(events: list[dict], maximum: int = 240) -> list[dict]:
144
+ """Thin evenly by log index for display, keeping both endpoints and every validation event."""
145
+ if len(events) <= maximum:
146
+ return events
147
+ keep = {round(i * (len(events) - 1) / (maximum - 1)) for i in range(maximum)}
148
+ keep.update(i for i, event in enumerate(events) if finite(event.get("dev_nll")))
149
+ return [events[i] for i in sorted(keep)]
150
+
151
+
152
+ def pilot_differences(runs: list[dict], stage: str, selection: dict) -> list[dict]:
153
+ """Compare one reserved seed at an identical observed horizon; keep the tuning status explicit."""
154
+ ratios = selection.get("ratios", {})
155
+ desired = {"ce": 0.0, "trace": ratios.get("trace", 0.03), "third": ratios.get("third", 0.03),
156
+ "hessian_norm": 0.03, "sham": ratios.get("third", 0.03), "combined": ratios.get("third", 0.03)}
157
+ by_method = {r["method"]: r for r in runs if r.get("stage") == stage and r.get("phase") == "pilot"
158
+ and r.get("seed") == 0 and completed(r) and finite(r.get("dev_nll"))
159
+ and r.get("method") in desired and r.get("ratio") == desired[r["method"]]}
160
+ third = by_method.get("third")
161
+ if not third:
162
+ return []
163
+ return [{"method": method, "third_id": third["id"], "comparison_id": other["id"],
164
+ "tokens": third["tokens"], "delta": third["dev_nll"] - other["dev_nll"],
165
+ "third_nll": third["dev_nll"], "baseline_nll": other["dev_nll"],
166
+ "strength_basis": "selected on development" if ratios else "initial pilot strengths"}
167
+ for method, other in by_method.items() if method != "third" and other.get("tokens") == third.get("tokens")]
168
+
169
+
170
+ def study_snapshot(root: Path = Path(".")) -> dict:
171
+ """Return a JSON-ready live view. Inference uses full logs before display thinning."""
172
+ directory = Path(root) / "results"
173
+ runs = []
174
+ for folder in sorted(directory.glob("*")):
175
+ if folder.is_dir() and any((folder / f).is_file() for f in ("config.json", "summary.json", "failure.json")):
176
+ runs.append(run_record(folder))
177
+ stages = {stage: analyze_stage(runs, stage) for stage in STAGES}
178
+ for run in runs:
179
+ run["events_total"] = len(run["events"])
180
+ run["events"] = display_events(run["events"])
181
+ context = {stage: {key: read_json(directory / key / f"{stage}.json")
182
+ for key in ("datasets", "selection", "feasibility")} for stage in STAGES}
183
+ pilots = {s: pilot_differences(runs, s, context[s]["selection"]) for s in STAGES}
184
+ return {
185
+ "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
186
+ "runs": runs, "stages": stages, "method_names": METHODS, "stage_names": STAGES,
187
+ "colors": COLORS, "context": context, "pilot_comparisons": pilots,
188
+ }
189
+
190
+
191
+ def completed(run: dict) -> bool:
192
+ return run.get("status", "").lower() in {"complete", "completed", "finished", "evaluated", "success"}
193
+
194
+
195
+ def describe_difference(delta) -> str:
196
+ if delta == 0:
197
+ return "identical development NLL"
198
+ direction = "lower" if delta < 0 else "higher"
199
+ return f"{abs(delta):.5f} nats per target token {direction}"
200
+
201
+
202
+ def verdict_text(result: dict) -> str:
203
+ """Use the analysis contract to distinguish an incomplete matrix from an inconclusive trial."""
204
+ status = result.get("status")
205
+ count = result.get("n_complete_seeds", 0)
206
+ goal = result.get("n_expected_seeds", 8)
207
+ if status == "confirmed":
208
+ return "Third-order training improved test NLL over both baselines under the registered decision rule."
209
+ if status == "inconclusive":
210
+ return "The completed stage did not establish an improvement over both baselines under the registered decision rule."
211
+ if status == "adverse":
212
+ return "The median test-loss difference favored at least one baseline across its full uncertainty interval."
213
+ if status == "invalid":
214
+ return f"The stage records require review. {result.get('reason') or 'See the analysis ledger.'}"
215
+ return f"Awaiting paired test results ({count} of {goal} full-horizon training triplets)."
research/src/thirdloss/reporting.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rebuild the public study artifacts from raw results with one command."""
2
+
3
+ import json
4
+ import re
5
+ from pathlib import Path
6
+ from statistics import median
7
+ from urllib.parse import quote
8
+
9
+ from .report_figures import build_figures
10
+ from .report_paper import write_paper
11
+ from .report_records import (
12
+ METHODS, PAGES, STAGES, atomic_text, completed, describe_difference, finite, fmt, study_snapshot,
13
+ verdict_text,
14
+ )
15
+
16
+
17
+ def _cell(value) -> str:
18
+ """Keep arbitrary run annotations and identifiers inside one Markdown table cell."""
19
+ return str(value).replace("|", "\\|").replace("\n", " ")
20
+
21
+
22
+ def _table(rows: list[list], headings: list[str]) -> str:
23
+ def row(values):
24
+ return "| " + " | ".join(_cell(v) for v in values) + " |"
25
+ return "\n".join([row(headings), row(["---"] * len(headings)), *(row(v) for v in rows)])
26
+
27
+
28
+ def _method(run: dict) -> str:
29
+ return METHODS.get(run.get("method"), run.get("method", "Unknown"))
30
+
31
+
32
+ def _stage(run: dict) -> str:
33
+ return STAGES.get(run.get("stage"), run.get("stage", "Unknown"))
34
+
35
+
36
+ def _ledger_row(run: dict) -> list:
37
+ return [
38
+ _stage(run), _method(run), run.get("phase", "—"), run.get("seed", "—"),
39
+ fmt(run.get("ratio")), fmt(run.get("tokens"), 0), fmt(run.get("dev_nll"), 4),
40
+ fmt(run.get("test_nll"), 4), fmt(run.get("tokens_per_sec"), 0), run["status"],
41
+ ]
42
+
43
+
44
+ LEDGER_HEADERS = ["Stage", "Method", "Phase", "Seed", "Ratio", "Train tokens", "Dev NLL",
45
+ "Test NLL", "Tokens/s", "Status"]
46
+
47
+
48
+ def _stage_summary(study: dict) -> str:
49
+ return "\n\n".join(
50
+ f"**{STAGES[stage]}.** {verdict_text(outcome)}" for stage, outcome in study["stages"].items()
51
+ )
52
+
53
+
54
+ def _pilot_summary(study):
55
+ observed = []
56
+ for stage, contrasts in study["pilot_comparisons"].items():
57
+ if contrasts:
58
+ numbers = ", ".join(f"{describe_difference(row['delta'])} against {METHODS[row['method']]}"
59
+ for row in contrasts)
60
+ first = contrasts[0]
61
+ observed.append(f"**{STAGES[stage]} development pilot.** At {first['tokens']:,} "
62
+ f"training targets, the third-order run recorded {numbers}. "
63
+ f"These are single-seed descriptions using {first['strength_basis']}.")
64
+ return "\n\n".join(observed)
65
+
66
+
67
+ def _comparisons(study: dict) -> str:
68
+ parts = []
69
+ for stage, analysis in study["stages"].items():
70
+ pairs = []
71
+ summary = []
72
+ for baseline, stats in analysis.get("comparisons", {}).items():
73
+ name = METHODS.get(baseline, baseline)
74
+ lo, hi = stats["median_ci"]
75
+ summary.append([name, stats["wins"], stats["ties"], stats["losses"],
76
+ fmt(stats["median_delta"], 5), f"[{fmt(lo,5)}, {fmt(hi,5)}]",
77
+ fmt(stats["ci_coverage"], 4), fmt(stats["p_raw"], 5),
78
+ fmt(stats["p_holm"], 5)])
79
+ for pair in stats["pairs"]:
80
+ pairs.append([name, pair["seed"], fmt(pair["third_nll"], 5),
81
+ fmt(pair["baseline_nll"], 5), fmt(pair["delta"], 5)])
82
+ if summary:
83
+ parts.append(f"### {STAGES[stage]}\n\n" + _table(summary, [
84
+ "Comparator", "Wins", "Ties", "Losses", "Median ΔNLL", "Median interval",
85
+ "Coverage", "Sign-test p", "Holm p"]) + "\n\n" + _table(pairs, [
86
+ "Comparator", "Seed", "Third-order NLL", "Comparator NLL", "ΔNLL"]))
87
+ times = [[t["seed"], fmt(t["cutoff_seconds"], 1), _method({"method": m}),
88
+ fmt(o.get("train_seconds"), 1), fmt(o.get("tokens"), 0), fmt(o.get("dev_nll"), 5)]
89
+ for t in analysis.get("matched_time", []) for m, o in t.get("by_method", {}).items()
90
+ if isinstance(o, dict)]
91
+ if times:
92
+ parts.append(f"### {STAGES[stage]} at equal training time\n\n" + _table(times, [
93
+ "Seed", "Common cutoff (s)", "Method", "Recorded checkpoint (s)",
94
+ "Training tokens", "Dev NLL"]))
95
+ return "\n\n".join(parts)
96
+
97
+
98
+ def _run_learning(run: dict) -> str:
99
+ """Use a trajectory only for a within-run observation; avoid causal attribution to a single run."""
100
+ if run.get("error"):
101
+ return f"The run recorded a failure. The run ledger contains the error and last metrics."
102
+ series = [e for e in run["events"] if finite(e.get("dev_nll")) and finite(e.get("tokens"))]
103
+ if len(series) >= 2 and series[0]["tokens"] < series[-1]["tokens"]:
104
+ delta = series[-1]["dev_nll"] - series[0]["dev_nll"]
105
+ return (f"Development NLL changed by {delta:+.4f} nats per target token from "
106
+ f"{series[0]['tokens']:,} to {series[-1]['tokens']:,} training targets. "
107
+ "Attribution to the regularizer uses matched comparisons across seeds.")
108
+ if finite(run.get("dev_nll")):
109
+ return f"The observed development NLL is {fmt(run['dev_nll'], 4)} nats per target token."
110
+ return "A development observation is pending."
111
+
112
+
113
+ def _sample(sample: dict) -> str:
114
+ """Indent whole text blocks verbatim so model-generated Markdown is never executed."""
115
+ def block(value):
116
+ lines = str(value).splitlines() or [""]
117
+ return "\n".join(" " + line for line in lines)
118
+ segments = [("Prompt", sample.get("prompt", ""))]
119
+ if sample.get("reference") is not None:
120
+ segments.append(("Reference continuation", sample["reference"]))
121
+ segments.append(("Model continuation", sample.get("continuation", "")))
122
+ return "\n\n".join(f"**{title}**\n\n{block(body)}" for title, body in segments)
123
+
124
+
125
+ def _experiments(root, study):
126
+ """Write all runs and samples, with one navigable index and brief evidence-linked learnings."""
127
+ base = root / "reports" / "experiments"
128
+ index = ["# Experiment ledger", "NLL is negative log-likelihood in nats per target token. "
129
+ "A smaller value assigns more probability to the observed next tokens. "
130
+ "The ratio sets the pilot regularizer-gradient magnitude relative to cross-entropy.",
131
+ "[Architecture, training algorithms, objectives and planned budgets](../planned-runs.md)"]
132
+ learnings = ["# Experimental learnings", _stage_summary(study),
133
+ "Independent random signs include mixed weight derivatives in the expected "
134
+ "penalty. The trace implementation motivating the gradient check converted its "
135
+ "estimate to a Python number. [Derivation and references](../literature-review.md)"]
136
+ if study["runs"]:
137
+ rows = []
138
+ for run in study["runs"]:
139
+ key = run["id"]
140
+ link = "./" + quote(key, safe="") + "/experiment.md"
141
+ rows.append([f"[{_cell(key)}]({link})", *_ledger_row(run)])
142
+ raw_link = "../../../results/" + quote(key, safe="") + "/"
143
+ material = [
144
+ f"# {_stage(run)} · {_method(run)}",
145
+ f"Run `{key}` · [raw records]({raw_link}) · [registered design](../../preregistration.md)",
146
+ _table([_ledger_row(run)], LEDGER_HEADERS),
147
+ f"Training time is {fmt(run.get('train_seconds'), 1)} seconds. "
148
+ f"Peak allocated GPU memory is {fmt(run.get('peak_vram_mb'), 1)} MiB. "
149
+ f"Development token accuracy is {fmt(run.get('dev_accuracy'), 4)}. "
150
+ f"Test token accuracy is {fmt(run.get('test_accuracy'), 4)}.",
151
+ "[Design and hyperparameter rationale](../../planned-runs.md) · "
152
+ f"[Saved configuration]({raw_link}config.json)",
153
+ ]
154
+ if run.get("error"):
155
+ material += ["## Recorded failure", _sample({"prompt": "Error", "continuation": run["error"]})]
156
+ if run["samples"]:
157
+ material += ["## Fixed-prompt generations",
158
+ *[_sample(sample) for sample in run["samples"]]]
159
+ atomic_text(base / key / "experiment.md", "\n\n".join(material) + "\n")
160
+ observation = _run_learning(run)
161
+ atomic_text(base / key / "learnings.md", f"# Run learnings\n\n{observation}\n\n"
162
+ "[Experiment and source records](experiment.md)\n")
163
+ learnings.append(f"- [{key}]({link}) — {observation}")
164
+ index.append(_table(rows, ["Run", *LEDGER_HEADERS]))
165
+ else:
166
+ index.append("The first run record will populate this ledger.")
167
+ atomic_text(base / "experiments.md", "\n\n".join(index) + "\n")
168
+ atomic_text(base / "learnings.md", "\n\n".join(learnings) + "\n")
169
+
170
+
171
+ def _compact_table(study: dict) -> str:
172
+ """Summarize like-for-like measured runs without selecting the strongest seed."""
173
+ groups = {}
174
+ for run in study["runs"]:
175
+ if completed(run):
176
+ key = (_stage(run), run.get("phase"), _method(run), run.get("ratio"), run.get("tokens"))
177
+ groups.setdefault(key, []).append(run)
178
+ rows = []
179
+ for (stage, phase, method, ratio, tokens), runs in groups.items():
180
+ def middle(metric):
181
+ observed = [r[metric] for r in runs if finite(r.get(metric))]
182
+ return fmt(median(observed), 4) if observed else "—"
183
+ rows.append([stage, phase, method, fmt(ratio), fmt(tokens, 0), len(runs),
184
+ middle("dev_nll"), middle("test_nll")])
185
+ return _table(rows, ["Stage", "Phase", "Method", "Ratio", "Tokens/run", "Runs",
186
+ "Median dev NLL", "Median test NLL"]) if rows else ""
187
+
188
+
189
+ def _update_readme(root: Path, body: str) -> None:
190
+ """Preserve all hand-authored material, including edits made between report builds."""
191
+ path = root / "README.md"
192
+ if not path.exists():
193
+ return
194
+ before = path.read_text(encoding="utf-8-sig")
195
+ pattern = r"<!-- RESULTS:START -->.*?<!-- RESULTS:END -->"
196
+ if len(re.findall(pattern, before, re.DOTALL)) != 1:
197
+ raise ValueError(f"{path} requires exactly one pair of results markers")
198
+ replacement = "<!-- RESULTS:START -->\n" + body.strip() + "\n<!-- RESULTS:END -->"
199
+ atomic_text(path, re.sub(pattern, lambda _: replacement, before, flags=re.DOTALL))
200
+
201
+
202
+ def build_report(root: Path = Path(".")) -> dict:
203
+ """Regenerate README results, PDF, experiment ledger, figures and the static dashboard."""
204
+ root = Path(root).resolve()
205
+ study = study_snapshot(root)
206
+ figures = build_figures(study, root / "docs" / "figures")
207
+ study["figures"] = figures
208
+ static = json.dumps(study, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
209
+ atomic_text(root / "docs" / "study.json", static + "\n")
210
+ _experiments(root, study)
211
+ compact = _compact_table(study)
212
+ comparisons = _comparisons(study)
213
+ counts = len(study["runs"])
214
+ done = sum(completed(run) for run in study["runs"])
215
+ overview = f"Recorded {counts} runs, including {done} with a completed summary."
216
+ documents = [f"[Interactive explorer]({PAGES})", "[Per-run ledger](experiments/experiments.md)",
217
+ "[Preregistration](preregistration.md)", "[Paper](paper.pdf)"]
218
+ summary = ["# Study summary", overview, _stage_summary(study), " · ".join(documents)]
219
+ pilots = _pilot_summary(study)
220
+ if pilots:
221
+ summary.extend(["## Development observations", pilots])
222
+ if compact:
223
+ summary.extend(["## Measured scores", compact])
224
+ if comparisons:
225
+ summary.extend(["## Paired evidence", comparisons])
226
+ for key, label in (("architecture", "Computation graph"), ("curves", "Development trajectories"),
227
+ ("paired", "Paired test differences")):
228
+ if key in figures:
229
+ summary.append(f"![{label}](../docs/figures/{figures[key]})")
230
+ atomic_text(root / "reports" / "summary.md", "\n\n".join(summary) + "\n")
231
+ badge = f"[Explore the results]({PAGES}) · [Paper](reports/paper.pdf) · [Run ledger](reports/experiments/experiments.md)"
232
+ readme = [badge, overview, _stage_summary(study)]
233
+ if pilots:
234
+ readme.append(pilots)
235
+ if compact:
236
+ readme.extend(["### Measured scores", compact])
237
+ readme.append("![Parameter-space computation graph](docs/figures/architecture.png)")
238
+ for key in ("paired", "curves"):
239
+ if key in figures:
240
+ readme.append(f"![{'Paired test differences' if key == 'paired' else 'Development NLL'}](docs/figures/{figures[key]})")
241
+ seen = set()
242
+ panels = []
243
+ for run in study["runs"]:
244
+ key = (run.get("stage"), run.get("method"))
245
+ if not run["samples"] or key in seen:
246
+ continue
247
+ seen.add(key)
248
+ panels.append(f"<details><summary>{_stage(run)} · {_method(run)}</summary>\n\n"
249
+ + _sample(run["samples"][0]) + "\n\n</details>")
250
+ if panels:
251
+ readme += ["### Recorded predictions", "First archived sample in run-ID order per "
252
+ "stage and method. [All continuations](reports/experiments/experiments.md)", *panels]
253
+ _update_readme(root, "\n\n".join(readme))
254
+ write_paper(study, root / "reports" / "paper.pdf", root / "docs" / "figures", figures)
255
+ return study
research/src/thirdloss/study.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sequence prospective pilots, blinded model selection, sealed evaluation and releases."""
2
+
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+
7
+ from huggingface_hub import hf_hub_download
8
+ from safetensors.torch import load_file
9
+
10
+ from .data import prepare
11
+ from .evaluation import score
12
+ from .models import build_model
13
+ from .records import HORIZONS, RATIOS, read_json, run_name, sha256, time_now, write_json
14
+ from .release import STAGE_HUB, publish_snapshot, publish_weights
15
+ from .train import run_one
16
+
17
+
18
+ def prepare_stage(project, storage, stage):
19
+ manifest = prepare(stage,storage/"data")
20
+ write_json(project/"results"/"datasets"/f"{stage}.json",manifest)
21
+ return manifest
22
+
23
+
24
+ def select(project, stage):
25
+ """Lock selection using the six equal-horizon full-development scores."""
26
+ candidates = {}
27
+ for kind in ("trace","third"):
28
+ candidates[kind] = []
29
+ for ratio in RATIOS:
30
+ path = project/"results"/run_name(stage,kind,"pilot",0,ratio)/"summary.json"
31
+ row = read_json(path)
32
+ if row["tokens"] != HORIZONS[stage]//8:
33
+ raise ValueError("All pilot candidates must finish the same development horizon")
34
+ candidates[kind].append({"ratio":ratio,"nll":row["dev_nll"],"run":row["id"]})
35
+ result = {"stage":stage,"candidates":candidates,"ratios":{
36
+ kind:min(rows,key=lambda x:(x["nll"],x["ratio"]))["ratio"] for kind,rows in candidates.items()}}
37
+ path = project/"results"/"selection"/f"{stage}.json"
38
+ if path.exists() and read_json(path)!=result:
39
+ raise ValueError("Development scores changed after the stage selection was locked")
40
+ write_json(path,result)
41
+ return result["ratios"]
42
+
43
+
44
+ def weights_file(storage, summary):
45
+ """Verify local snapshot or retrieve the same digest from the published collection."""
46
+ run_id = summary["id"]
47
+ filename = summary["weights_name"]
48
+ path = storage/"checkpoints"/run_id/"export"/filename
49
+ if not path.is_file():
50
+ path = Path(hf_hub_download(STAGE_HUB[summary["stage"]],f"runs/{run_id}/{filename}",
51
+ cache_dir=str(storage/"hub")))
52
+ if sha256(path)!=summary["weights_sha256"]:
53
+ raise ValueError(f"Weights for {run_id} differ from their registered checksum")
54
+ return path
55
+
56
+
57
+ def freeze(project, storage, stage):
58
+ """Bind all 24 finished checkpoints, split, and selected coefficients before opening test bytes."""
59
+ selection = read_json(project/"results"/"selection"/f"{stage}.json")["ratios"]
60
+ split = read_json(storage/"data"/stage/"manifest.json")["splits"]["test"]
61
+ frozen = {"stage":stage,"ratios":selection,"test_sha256":split["sha256"],"runs":{}}
62
+ for seed in range(1,9):
63
+ for method in ("ce","trace","third"):
64
+ name = run_name(stage,method,"confirm",seed,selection.get(method,0))
65
+ summary = read_json(project/"results"/name/"summary.json")
66
+ if summary["tokens"]!=HORIZONS[stage] or summary["status"]!="complete":
67
+ raise ValueError(f"Incomplete registered checkpoint {name}")
68
+ if summary["data_manifest_sha256"]!=sha256(storage/"data"/stage/"manifest.json"):
69
+ raise ValueError(f"Different corpus for {name}")
70
+ weights_file(storage,summary)
71
+ frozen["runs"][name] = summary["weights_sha256"]
72
+ frozen["freeze_id"] = hashlib.sha256(json.dumps(frozen,sort_keys=True).encode()).hexdigest()
73
+ path = project/"results"/"freeze"/f"{stage}.json"
74
+ if path.exists() and read_json(path)!=frozen:
75
+ raise ValueError("A sealed checkpoint or dataset changed")
76
+ write_json(path,frozen)
77
+ return frozen
78
+
79
+
80
+ def evaluate_one(project, storage, run_id, device):
81
+ path = project/"results"/run_id/"summary.json"
82
+ summary = read_json(path)
83
+ stage = summary["stage"]
84
+ sealed = read_json(project/"results"/"freeze"/f"{stage}.json")
85
+ data = storage/"data"/stage
86
+ if sealed["runs"].get(run_id)!=summary.get("weights_sha256") or run_id not in sealed["runs"]:
87
+ raise ValueError("Evaluation requires a checkpoint present in the stage freeze")
88
+ weights = weights_file(storage,summary)
89
+ if "test_nll" in summary:
90
+ if summary["freeze_id"]!=sealed["freeze_id"]:
91
+ raise ValueError("Existing evaluation uses a different freeze")
92
+ return summary
93
+ if sha256(data/"test.bin") != sealed["test_sha256"]:
94
+ raise ValueError("Test stream differs from the frozen manifest")
95
+ model = build_model(stage,summary["seed"],device,storage)
96
+ state = load_file(str(weights),device="cpu")
97
+ if stage=="stories":
98
+ model.load_state_dict(state,strict=True)
99
+ else:
100
+ from peft import get_peft_model_state_dict,set_peft_model_state_dict
101
+ if set(state)!=set(get_peft_model_state_dict(model)):
102
+ raise ValueError("Adapter payload does not match the pinned backbone and target modules")
103
+ set_peft_model_state_dict(model,state)
104
+ stats = score(model,data/"test.bin",device,summary["microbatch"])
105
+ summary.update(test_nll=stats["nll"],test_accuracy=stats["accuracy"],test_tokens=stats["tokens"],
106
+ test_manifest_sha256=sealed["test_sha256"],freeze_id=sealed["freeze_id"],
107
+ evaluated_at=time_now())
108
+ write_json(path,summary)
109
+ return summary
110
+
111
+
112
+ def milestone(project,storage,summary,publish):
113
+ from .reporting import build_report
114
+ from .progress import progress
115
+ path = project/"results"/summary["id"]/"summary.json"
116
+ marker = storage/"releases"/(summary["id"]+".json")
117
+ fingerprint = sha256(path)
118
+ if publish and marker.exists() and read_json(marker)["summary_sha256"]==fingerprint:
119
+ return
120
+ build_report(project)
121
+ progress(project)
122
+ if publish:
123
+ publish_weights(project,storage,summary)
124
+ label = "evaluation" if "test_nll" in summary else "development"
125
+ revision = publish_snapshot(project,f"Record {label} results for {summary['id']}")
126
+ write_json(marker,{"summary_sha256":fingerprint,"git_revision":revision})
127
+
128
+
129
+ def feasibility(project, stage):
130
+ """Project training-only cost from actual per-arm pilot timing before using test data."""
131
+ selected = read_json(project/"results"/"selection"/f"{stage}.json")["ratios"]
132
+ rows = []
133
+ for method in ("third","ce","trace"):
134
+ row = read_json(project/"results"/run_name(stage,method,"pilot",0,selected.get(method,0))/"summary.json")
135
+ rows.append({"method":method,"pilot_run":row["id"],"tokens_per_sec":row["tokens_per_sec"],
136
+ "peak_vram_mb":row["peak_vram_mb"],"projected_confirm_hours":
137
+ 8*HORIZONS[stage]/row["tokens_per_sec"]/3600})
138
+ hours = sum(r["projected_confirm_hours"] for r in rows)
139
+ result = {"stage":stage,"arms":rows,"projected_confirm_training_hours":hours,
140
+ "basis":"Pilot training time. Data, calibration, evaluation, checkpoint and upload overhead are additional."}
141
+ write_json(project/"results"/"feasibility"/f"{stage}.json",result)
142
+ return result
143
+
144
+
145
+ def run_study(project,storage,stages,device,publish):
146
+ """Retry-safe complete study. Cached milestones allow continuation after reboot or network loss."""
147
+ def run(stage,method,phase,seed,ratio):
148
+ row = run_one(project,storage,stage,method,phase,seed,ratio,device)
149
+ milestone(project,storage,row,publish)
150
+ return row
151
+ for stage in stages:
152
+ prepare_stage(project,storage,stage)
153
+ run(stage,"third","pilot",0,0.03)
154
+ for method in ("initial","unigram"):
155
+ run(stage,method,"control",0,0)
156
+ run(stage,"ce","pilot",0,0)
157
+ for method in ("trace","third"):
158
+ for ratio in RATIOS:
159
+ run(stage,method,"pilot",0,ratio)
160
+ selected = select(project,stage)
161
+ feasibility(project,stage)
162
+ for method,ratio in (("hessian_norm",0.03),("sham",selected["third"]),("combined",selected["third"])):
163
+ run(stage,method,"pilot",0,ratio)
164
+ for stage in stages:
165
+ selected = select(project,stage)
166
+ for seed in range(1,9):
167
+ for method in ("third","ce","trace"):
168
+ run(stage,method,"confirm",seed,selected.get(method,0))
169
+ sealed = freeze(project,storage,stage)
170
+ if publish:
171
+ publish_snapshot(project,f"Freeze all {stage} confirmatory checkpoints before test evaluation")
172
+ for run_id in sealed["runs"]:
173
+ row = evaluate_one(project,storage,run_id,device)
174
+ milestone(project,storage,row,publish)
research/src/thirdloss/train.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Time, train, checkpoint and export one fully specified arm of the registered experiment."""
2
+
3
+ import math
4
+ import os
5
+ import platform
6
+ import shutil
7
+ import subprocess
8
+ import time
9
+ from pathlib import Path
10
+
11
+ import torch
12
+ from filelock import FileLock
13
+
14
+ from .evaluation import sample_outputs, score, unigram_distribution
15
+ from .models import build_model, export_weights
16
+ from .objectives import add_penalty, calibrate, ce_backward
17
+ from .records import (BATCHES, CONTEXT, HORIZONS, RATIOS, Recorder, json_lines, read_json,
18
+ run_name, sha256, time_now, write_json)
19
+ from .windows import TrainingWindows, gate
20
+
21
+
22
+ def scientific_config(stage, method, phase, seed, ratio):
23
+ """Validate identities so pilots, confirmations and smoke tests cannot be mixed in analysis."""
24
+ if stage not in HORIZONS or phase not in {"pilot", "confirm", "control", "smoke"}:
25
+ raise ValueError("Unknown study stage or phase")
26
+ if phase == "confirm" and (seed not in range(1,9) or method not in {"ce","trace","third"}):
27
+ raise ValueError("Confirmation uses seeds 1–8 and the three primary arms")
28
+ if phase in {"control", "pilot"} and seed != 0:
29
+ raise ValueError("Development and control runs use the reserved pilot seed")
30
+ if method in {"ce","initial","unigram"}:
31
+ ratio = 0.0
32
+ elif ratio not in RATIOS:
33
+ raise ValueError(f"Unregistered penalty strength {ratio}")
34
+ budget = HORIZONS[stage] if phase == "confirm" else HORIZONS[stage]//8
35
+ if phase == "smoke":
36
+ budget = CONTEXT * BATCHES[stage] * 8
37
+ if method in {"unigram","initial"}:
38
+ budget = 0
39
+ return {"id":run_name(stage, method, phase, seed, ratio), "stage":stage, "method":method,
40
+ "phase":phase, "seed":seed, "ratio":ratio, "token_budget":budget,
41
+ "batch_windows":BATCHES[stage], "context":CONTEXT}
42
+
43
+
44
+ def learning_rate(stage, step, steps):
45
+ peak = 3e-4 if stage == "stories" else 1e-4
46
+ warm = max(1, round(0.05*steps))
47
+ if step < warm:
48
+ return peak * (step+1)/warm
49
+ progress = (step-warm+1) / max(1, steps-warm)
50
+ return peak * (0.1+0.9*0.5*(1+math.cos(math.pi*progress)))
51
+
52
+
53
+ def chosen_coefficients(project, storage, config, device, microbatch):
54
+ method, ratio, stage = (config[k] for k in ("method","ratio","stage"))
55
+ if method in {"ce","initial","unigram"}:
56
+ return {}
57
+ if method == "combined":
58
+ selected = read_json(project/"results"/"selection"/f"{stage}.json")["ratios"]
59
+ kinds = {"trace":selected["trace"], "third":selected["third"]}
60
+ else:
61
+ kinds = {"third" if method == "sham" else method: ratio}
62
+ return {kind: scale*calibrate(project,storage,stage,kind,device,microbatch) for kind,scale in kinds.items()}
63
+
64
+
65
+ def save_state(path, model, optimizer, step, elapsed, config):
66
+ """Atomically persist optimizer, trainable weights, all stochastic state and next data step."""
67
+ state = {"weights":{n:p.detach() for n,p in model.named_parameters() if p.requires_grad},
68
+ "optimizer":optimizer.state_dict(), "next_step":step, "train_seconds":elapsed,
69
+ "config":config, "cpu_rng":torch.get_rng_state(),
70
+ "cuda_rng":torch.cuda.get_rng_state() if next(model.parameters()).is_cuda else None}
71
+ temp = path.with_suffix(".partial")
72
+ torch.save(state, temp)
73
+ os.replace(temp,path)
74
+
75
+
76
+ def restore_state(path, model, optimizer, config, recorder, device):
77
+ """Recover the last committed checkpoint and ignore telemetry from interrupted later steps."""
78
+ if not path.exists():
79
+ return 0, 0.0
80
+ state = torch.load(path, map_location="cpu", weights_only=True)
81
+ if state["config"] != config:
82
+ raise ValueError("Resume configuration differs from saved scientific settings")
83
+ model.load_state_dict(state["weights"], strict=False)
84
+ optimizer.load_state_dict(state["optimizer"])
85
+ torch.set_rng_state(state["cpu_rng"])
86
+ if state["cuda_rng"] is not None:
87
+ torch.cuda.set_rng_state(state["cuda_rng"], device)
88
+ step = state["next_step"]
89
+ path = recorder.directory/"events.jsonl"
90
+ if path.exists():
91
+ import json
92
+ rows = [r for r in json_lines(path) if r.get("step", 0) <= step]
93
+ temp = path.with_suffix(".partial")
94
+ temp.write_text("".join(json.dumps(r)+"\n" for r in rows), encoding="utf-8")
95
+ temp.replace(path)
96
+ return step, state["train_seconds"]
97
+
98
+
99
+ def run_one(project, storage, stage, method, phase, seed, ratio, device, microbatch=None):
100
+ config = scientific_config(stage,method,phase,seed,ratio)
101
+ microbatch = microbatch or (32 if stage == "stories" else 2)
102
+ if microbatch < 1:
103
+ raise ValueError("A physical batch must contain at least one window")
104
+ recorder = Recorder(project, config["id"])
105
+ locks = storage / "locks"
106
+ locks.mkdir(parents=True, exist_ok=True)
107
+ with FileLock(str(locks/(config["id"]+".lock"))):
108
+ try:
109
+ return _run(project, storage, config, recorder, device, microbatch)
110
+ except Exception as exc:
111
+ write_json(recorder.directory/"failure.json", {"timestamp":time_now(), "error":repr(exc)})
112
+ raise
113
+
114
+
115
+ def _run(project, storage, config, recorder, device, microbatch):
116
+ stage, method, seed, budget = (config[k] for k in ("stage","method","seed","token_budget"))
117
+ data = storage/"data"/stage
118
+ manifest = read_json(data/"manifest.json")
119
+ config["data_manifest_sha256"] = sha256(data/"manifest.json")
120
+ config["microbatch"] = microbatch
121
+ config["coefficients"] = chosen_coefficients(project,storage,config,device,microbatch)
122
+ output = recorder.directory
123
+ if (output/"config.json").exists() and read_json(output/"config.json") != config:
124
+ raise ValueError(f"Existing run configuration conflicts with {config['id']}")
125
+ write_json(output/"config.json",config)
126
+ summary_path = output/"summary.json"
127
+ if summary_path.exists():
128
+ return read_json(summary_path)
129
+ ckpt = storage/"checkpoints"/config["id"]
130
+ ckpt.mkdir(parents=True,exist_ok=True)
131
+ if device.type == "cuda":
132
+ torch.cuda.empty_cache()
133
+ torch.cuda.reset_peak_memory_stats(device)
134
+ model = None if method == "unigram" else build_model(stage,seed,device,storage)
135
+ parameters = tuple(p for p in model.parameters() if p.requires_grad) if model is not None else ()
136
+ summary = {**config, "device":str(device), "torch":str(torch.__version__), "platform":platform.platform(),
137
+ "gpu":torch.cuda.get_device_name(device) if device.type=="cuda" else None,
138
+ "git_revision":subprocess.check_output(["git","rev-parse","HEAD"],cwd=project,text=True).strip(),
139
+ "trainable_parameters":sum(p.numel() for p in parameters)}
140
+ batch = BATCHES[stage]
141
+ steps = budget//(batch*CONTEXT)
142
+ elapsed = 0.0
143
+ if budget:
144
+ windows = TrainingWindows(data/"train.bin",seed,batch)
145
+ groups = [{"params":[p for p in parameters if p.ndim>1],"weight_decay":0.1},
146
+ {"params":[p for p in parameters if p.ndim<=1],"weight_decay":0.0}]
147
+ optimizer = torch.optim.AdamW(groups,lr=1e-4,betas=(0.9,0.95),fused=(device.type=="cuda"))
148
+ start,elapsed = restore_state(ckpt/"latest.pt",model,optimizer,config,recorder,device)
149
+ # Match elapsed-time comparisons with periodic fixed development windows in every arm.
150
+ interval = min(128,max(1,steps//16))
151
+ for step in range(start,steps):
152
+ model.train()
153
+ tic = time.perf_counter()
154
+ inputs,targets = windows.get(step,device)
155
+ optimizer.zero_grad(set_to_none=True)
156
+ base,accuracy = ce_backward(model,inputs,targets,microbatch)
157
+ active = bool(config["coefficients"]) and gate(seed,step)
158
+ terms = add_penalty(model,parameters,inputs,targets,config["coefficients"],method,seed,step) if active else {}
159
+ norm = torch.nn.utils.clip_grad_norm_(parameters,1.0,error_if_nonfinite=True)
160
+ lr = learning_rate(stage,step,steps)
161
+ for group in optimizer.param_groups:
162
+ group["lr"] = lr
163
+ optimizer.step()
164
+ if device.type == "cuda":
165
+ torch.cuda.synchronize(device)
166
+ elapsed += time.perf_counter()-tic
167
+ done = step+1
168
+ if done % 8 == 0 or active or done == 1 or done % interval == 0 or done == steps:
169
+ row = {"step":done, "tokens":done*batch*CONTEXT, "train_seconds":elapsed, "loss":base.item(),
170
+ "accuracy":accuracy.item(), "lr":lr, "gradient_norm":norm.item(),"derivatives":terms}
171
+ if terms:
172
+ row["penalty"] = sum(8*t["lambda"]*t["estimate"] for t in terms.values())
173
+ if done%interval == 0 or done==steps:
174
+ metrics = score(model,data/"dev.bin",device,microbatch,limit_windows=64)
175
+ row.update(dev_nll=metrics["nll"],dev_accuracy=metrics["accuracy"])
176
+ recorder.emit(row)
177
+ if done%interval == 0 or done==steps:
178
+ save_state(ckpt/"latest.pt",model,optimizer,done,elapsed,config)
179
+ del optimizer
180
+ dist = unigram_distribution(data/"train.bin",4096 if stage=="stories" else 50304) if method=="unigram" else None
181
+ validation = score(model,data/"dev.bin",device,microbatch,unigram=dist)
182
+ # A rerun after final-checkpoint interruption writes each documented sample exactly once.
183
+ sample_path = output/"samples.jsonl"
184
+ if sample_path.exists():
185
+ sample_path.unlink()
186
+ sample_outputs(model,data,manifest,device,recorder,unigram=dist)
187
+ if budget:
188
+ weights = export_weights(model,ckpt/"export")
189
+ shutil.copy2(data/"tokenizer.json", ckpt/"export"/"tokenizer.json")
190
+ summary.update(weights_sha256=sha256(weights),weights_name=weights.name)
191
+ summary["matched_dev_nll"] = next(e["dev_nll"] for e in reversed(json_lines(output/"events.jsonl"))
192
+ if "dev_nll" in e)
193
+ summary.update(tokens=budget,steps=steps,train_seconds=elapsed,tokens_per_sec=budget/elapsed if elapsed else 0,
194
+ peak_vram_mb=torch.cuda.max_memory_allocated(device)/2**20 if device.type=="cuda" else 0,
195
+ dev_nll=validation["nll"],dev_accuracy=validation["accuracy"],dev_tokens=validation["tokens"],
196
+ finished_at=time_now(),status="complete")
197
+ write_json(summary_path,summary)
198
+ (output/"failure.json").unlink(missing_ok=True)
199
+ print(f"Completed {config['id']} development NLL {summary['dev_nll']:.6f}",flush=True)
200
+ return summary
research/src/thirdloss/windows.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic packed-token windows with epoch permutations and independent probe streams."""
2
+
3
+ import numpy as np
4
+ import torch
5
+
6
+ from .records import CONTEXT
7
+
8
+
9
+ class TrainingWindows:
10
+ """Random-access batches let a checkpoint store the next step as its data cursor."""
11
+
12
+ def __init__(self, filename, seed, batch_size):
13
+ self.tokens = np.memmap(filename, mode="r", dtype="<u2")
14
+ self.count = (len(self.tokens) - 1) // CONTEXT
15
+ self.seed, self.batch_size = seed, batch_size
16
+ self.epoch, self.order = -1, None
17
+ if self.count < batch_size:
18
+ raise ValueError(f"{filename} contains too few complete training windows")
19
+
20
+ def get(self, step, device):
21
+ cursor = step * self.batch_size
22
+ remaining = self.batch_size
23
+ chunks = []
24
+ while remaining:
25
+ epoch, start = divmod(cursor, self.count)
26
+ if epoch != self.epoch:
27
+ self.epoch = epoch
28
+ self.order = np.random.default_rng([self.seed, epoch, 101]).permutation(self.count)
29
+ take = min(remaining, self.count - start)
30
+ chunks.append(self.order[start:start+take])
31
+ cursor += take
32
+ remaining -= take
33
+ offsets = np.concatenate(chunks)[:, None] * CONTEXT + np.arange(CONTEXT+1)
34
+ packed = torch.from_numpy(self.tokens[offsets].astype(np.int64)).to(device)
35
+ return packed[:, :-1], packed[:, 1:]
36
+
37
+
38
+ def gate(seed, step):
39
+ """Stateless gates are identical across arms and survive process restarts."""
40
+ return np.random.default_rng([seed, step, 811]).integers(8) == 0
41
+
42
+
43
+ def probe_rows(seed, step, size):
44
+ return np.random.default_rng([seed, step, 821]).choice(size, 2, replace=False).tolist()
45
+
46
+
47
+ def generator(device, seed, step, stream):
48
+ value = int(np.random.SeedSequence([seed, step, stream]).generate_state(1, dtype=np.uint64)[0])
49
+ return torch.Generator(device=device).manual_seed(value)
research/tests/test_analysis.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Use deliberately synthetic summaries to test the registered inference and visibility rules."""
2
+
3
+ import math
4
+
5
+ import pytest
6
+
7
+ from thirdloss.analysis import analyze_stage
8
+
9
+
10
+ METHODS = ("ce", "trace", "third")
11
+ STORY_TOKENS = 16_777_216
12
+
13
+
14
+ def complete_matrix():
15
+ """Every registered seed has the same tiny improvement in this artificial fixture."""
16
+ return [
17
+ {
18
+ "id": f"stories-{method}-{seed}", "stage": "stories", "phase": "confirm",
19
+ "seed": seed, "method": method, "tokens": STORY_TOKENS,
20
+ "test_nll": 1.0 if method == "third" else 1.5,
21
+ "freeze_id": "fixture-matrix", "test_manifest_sha256": "fixture-test-corpus",
22
+ }
23
+ for seed in range(1, 9)
24
+ for method in METHODS
25
+ ]
26
+
27
+
28
+ def test_wins_require_both_registered_exact_sign_tests():
29
+ """The two equally small p-values have the same adjusted p-value under step-down Holm."""
30
+ result = analyze_stage(complete_matrix(), "stories")
31
+ assert result["complete"] and result["success"]
32
+ assert result["n_complete_seeds"] == 8
33
+ for stats in result["comparisons"].values():
34
+ assert [p["seed"] for p in stats["pairs"]] == list(range(1, 9))
35
+ assert stats["wins"] == 8 and stats["ties"] == 0 and stats["losses"] == 0
36
+ assert stats["median_delta"] == -0.5
37
+ assert stats["median_ci"] == [-0.5, -0.5]
38
+ assert stats["ci_coverage"] == 254 / 256
39
+ assert stats["p_raw"] == 1 / 256
40
+ assert stats["p_holm"] == 2 / 256
41
+
42
+
43
+ def test_second_comparator_failure_and_ties_count_separately():
44
+ """Declaring a win against ordinary AdamW alone would violate the registered conjunction."""
45
+ rows = complete_matrix()
46
+ for row in rows:
47
+ if row["method"] == "trace":
48
+ row["test_nll"] = 1.0 if row["seed"] % 2 else 0.5
49
+ result = analyze_stage(rows, "stories")
50
+ assert result["complete"] and result["success"] is False
51
+ trace = result["comparisons"]["trace"]
52
+ assert trace["wins"] == 0 and trace["ties"] == 4 and trace["losses"] == 4
53
+ assert trace["p_raw"] == 1
54
+ assert result["comparisons"]["ce"]["p_holm"] == 2 / 256
55
+
56
+
57
+ def test_holm_step_down_tie_handling_and_exact_boundary():
58
+ """Seven wins can pass the second Holm threshold once the first comparator passes."""
59
+ rows = complete_matrix()
60
+ for row in rows:
61
+ if row["seed"] == 8 and row["method"] == "trace":
62
+ row["test_nll"] = 0.5
63
+ result = analyze_stage(rows, "stories")
64
+ assert result["success"] is True
65
+ assert result["comparisons"]["trace"]["p_holm"] == 9 / 256
66
+
67
+
68
+ def test_all_ties_are_reported_with_unit_p_value():
69
+ """A zero number of discordant pairs supplies no direction for a sign test."""
70
+ rows = complete_matrix()
71
+ for row in rows:
72
+ row["test_nll"] = 1.0
73
+ result = analyze_stage(rows, "stories")
74
+ assert result["success"] is False
75
+ assert result["comparisons"]["ce"]["p_raw"] == 1
76
+ assert result["comparisons"]["trace"]["ties"] == 8
77
+
78
+
79
+ @pytest.mark.parametrize("defect", ["missing", "no score", "duplicate", "unequal tokens",
80
+ "all short", "wrong configured budget", "nonfinite",
81
+ "mixed freeze", "mixed corpus"])
82
+ def test_partial_or_mismatched_results_never_unlock_primary_inference(defect):
83
+ """In particular, identical truncated budgets cannot form a full-budget confirmation."""
84
+ rows = complete_matrix()
85
+ if defect == "missing":
86
+ rows.pop()
87
+ elif defect == "no score":
88
+ rows[-1].pop("test_nll")
89
+ elif defect == "duplicate":
90
+ rows.append(dict(rows[-1], id="another-checkpoint-for-same-seed"))
91
+ elif defect == "unequal tokens":
92
+ rows[-1]["tokens"] -= 128
93
+ elif defect == "all short":
94
+ for row in rows:
95
+ row["tokens"] //= 8
96
+ elif defect == "wrong configured budget":
97
+ rows[0]["target_tokens"] = STORY_TOKENS * 2
98
+ elif defect == "nonfinite":
99
+ rows[-1]["test_nll"] = math.nan
100
+ elif defect == "mixed freeze":
101
+ rows[-1]["freeze_id"] = "another-set"
102
+ elif defect == "mixed corpus":
103
+ rows[-1]["test_manifest_sha256"] = "another-corpus"
104
+ result = analyze_stage(rows, "stories")
105
+ assert result["success"] is None and not result["complete"]
106
+ assert result["comparisons"] == {}
107
+ assert result["status"] in {"invalid", "incomplete"}
108
+
109
+
110
+ def test_adverse_effect_reported_separately_from_uncertainty():
111
+ """A strictly positive exact interval favors the comparison in the stated sign convention."""
112
+ rows = complete_matrix()
113
+ for row in rows:
114
+ if row["method"] == "trace":
115
+ row["test_nll"] = 0.25
116
+ result = analyze_stage(rows, "stories")
117
+ assert result["status"] == "adverse"
118
+ assert result["comparisons"]["trace"]["interpretation"] == "adverse"
119
+
120
+
121
+ def test_exploratory_arms_and_other_stages_do_not_enter_paired_matrix():
122
+ """Unrelated validation sweeps cannot increase the number of independent seeds."""
123
+ rows = complete_matrix()
124
+ extras = [
125
+ dict(rows[0], phase="pilot", test_nll=0.1),
126
+ dict(rows[0], stage="abstracts", tokens=524_288),
127
+ dict(rows[0], method="hessian_norm", test_nll=0.1),
128
+ ]
129
+ assert analyze_stage(rows + extras, "stories") == analyze_stage(rows, "stories")
130
+ assert analyze_stage([], "stories")["status"] == "pending"
131
+
132
+
133
+ def test_elapsed_time_uses_latest_actual_validation_before_shared_cutoff():
134
+ """Faster methods can process more tokens within the common time allowance."""
135
+ rows = complete_matrix()
136
+ for row in rows:
137
+ seconds = {"ce": 10.0, "trace": 15.0, "third": 20.0}[row["method"]]
138
+ row.update(train_seconds=seconds, dev_nll=1.0)
139
+ row["events"] = [
140
+ {"train_seconds": 9.0, "tokens": 80, "dev_nll": 2.2},
141
+ {"train_seconds": 5.0, "tokens": 48, "dev_nll": 2.8},
142
+ {"train_seconds": 9.9, "tokens": 96, "loss": 1.8}, # training-only record
143
+ {"train_seconds": 12.0, "tokens": 120, "dev_nll": 1.6},
144
+ ]
145
+ groups = analyze_stage(rows, "stories")["matched_time"]
146
+ assert [g["seed"] for g in groups] == list(range(1, 9))
147
+ first = groups[0]
148
+ assert first["cutoff_seconds"] == 10.0
149
+ assert first["by_method"]["ce"]["dev_nll"] == 1.0 # eligible final checkpoint
150
+ assert first["by_method"]["trace"]["dev_nll"] == 2.2
151
+ assert first["by_method"]["third"]["tokens"] == 80
152
+
153
+
154
+ def test_time_matched_comparison_uses_one_validation_population_across_methods():
155
+ """Whole-split NLL cannot replace a fixed-window diagnostic in another run."""
156
+ rows = complete_matrix()
157
+ for row in rows:
158
+ row.update(train_seconds=10.0, dev_nll=90.0)
159
+ row["events"] = [{"train_seconds": 5.0, "tokens": 48, "dev_nll": 8.0}]
160
+ if row["method"] == "ce":
161
+ # The actual diagnostic at the final clock takes priority over a summary.
162
+ row["matched_dev_nll"] = 3.0
163
+ row["events"].append({"train_seconds": 10.0, "tokens": 96, "dev_nll": 2.0})
164
+ elif row["method"] == "third":
165
+ row["matched_dev_nll"] = 5.0
166
+ by_method = analyze_stage(rows, "stories")["matched_time"][0]["by_method"]
167
+ assert by_method["ce"]["dev_nll"] == 2.0
168
+ assert by_method["ce"]["tokens"] == 96
169
+ assert by_method["trace"]["dev_nll"] == 8.0
170
+ assert by_method["trace"]["staleness_seconds"] == 5.0
171
+ assert by_method["third"]["dev_nll"] == 5.0
research/tests/test_data.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline corpus fixtures exercise the split and tokenizer logic through its public API."""
2
+
3
+ import gzip
4
+ import json
5
+ import random
6
+
7
+ import numpy as np
8
+ import pyarrow as pa
9
+ import pyarrow.parquet as pq
10
+ from tokenizers import Tokenizer
11
+
12
+ from thirdloss import data
13
+ from thirdloss.overlap import Document, ShingleIndex, clean_splits, content_hash, shingles
14
+
15
+
16
+ def test_exact_and_edited_documents_respect_split_priority():
17
+ original = " ".join(f"w{i}" for i in range(75))
18
+ changed = original.replace("w39", "revised")
19
+ raw = {
20
+ "test": [Document.make("t", original)],
21
+ "dev": [Document.make("d", changed), Document.make("d2", "Development only.")],
22
+ "train": [Document.make("a", " \t" + original.upper()), Document.make("b", changed),
23
+ Document.make("c", "Development only."), Document.make("d", "Fresh words."),
24
+ Document.make("empty", " \t\n")],
25
+ }
26
+ clean, counts, rejected = clean_splits(raw, lambda _: None)
27
+ assert [doc.source_id for doc in clean["train"]] == ["d"]
28
+ assert [doc.source_id for doc in clean["dev"]] == ["d2"]
29
+ assert counts["train"] == dict(input=5, kept=1, exact=2, cross_split_near=1, empty=1)
30
+ assert [(row["source_id"], row["reference_split"]) for row in rejected if row["reason"] == "near"] == [
31
+ ("d", "test"), ("b", "test")
32
+ ]
33
+
34
+
35
+ def test_prefix_candidates_match_exhaustive_jaccard_including_boundary():
36
+ # A short exact-threshold pair exercises integer rounding in both the length and prefix filters.
37
+ prefix = "one two three four five six seven eight"
38
+ docs = [Document.make("boundary", prefix + " nine")]
39
+ assert ShingleIndex(docs).match(shingles(prefix)) == docs[0]
40
+ generator = random.Random(1903)
41
+ queries = []
42
+ for i in range(24):
43
+ words = [f"w{j}" for j in generator.sample(range(800), 85)]
44
+ docs.append(Document.make(str(i), " ".join(words)))
45
+ for edits in range(0, 7):
46
+ probe = words.copy()
47
+ for idx in generator.sample(range(len(words)), edits):
48
+ probe[idx] = "changed"
49
+ queries.append(shingles(" ".join(probe)))
50
+ index = ShingleIndex(docs)
51
+ references = [(doc, shingles(doc.text)) for doc in docs]
52
+ for query in queries:
53
+ brute = next((doc for doc, terms in references
54
+ if 5 * len(terms & query) >= 4 * len(terms | query)), None)
55
+ assert index.match(query) == brute
56
+
57
+
58
+ def test_abstract_submission_month_and_base_id_grouping(monkeypatch, tmp_path):
59
+ rows = [
60
+ [("2312.12345", "2023-12-31", "old"), ("2405.00001v1", "2024-04-30", "April"),
61
+ ("2405.00002", "2024-05-01", "May")],
62
+ [("2405.00001v2", "2024-04-30", "same ID revised"), ("2407.00001", "2024-06-30", "June"),
63
+ ("2407.00002", "2024-07-01", "July")],
64
+ ]
65
+ for i, batch in enumerate(rows):
66
+ with gzip.open(tmp_path / str(i), "wt", encoding="utf-8") as writer:
67
+ for identifier, submitted, text in batch:
68
+ writer.write(json.dumps(dict(id=identifier, created=submitted, added="2025-01-01", text=text)) + "\n")
69
+ def source(root, repo, revision, key):
70
+ return tmp_path / key[-1], {"file": key}
71
+ monkeypatch.setattr(data, "_source", source)
72
+ docs, sources, audit = data._abstract_documents(tmp_path)
73
+ assert {split: [doc.text for doc in entries] for split, entries in docs.items()} == {
74
+ "train": ["April"], "dev": ["May"], "test": ["June"],
75
+ }
76
+ assert [doc.source_id for doc in docs["train"]] == ["2405.00001"]
77
+ assert audit["repeated_base_id"] == 1
78
+ assert audit["identifier_month_differs_from_created"] == 2
79
+ assert len(sources) == 2
80
+
81
+
82
+ def test_prepare_from_parquet_proves_train_only_fit_packing_and_repair(monkeypatch, tmp_path):
83
+ # Each document uses its own words. Both retained splits therefore survive the overlap audit.
84
+ texts = []
85
+ train_count = dev_count = 0
86
+ while train_count < 30 or dev_count < 2:
87
+ i = len(texts)
88
+ text = " ".join(f"document{i}word{j}" for j in range(12))
89
+ texts.append(text)
90
+ if int(content_hash(text)[:16], 16) % 50:
91
+ train_count += 1
92
+ else:
93
+ dev_count += 1
94
+ heldout = " ".join(f"heldout{j}" for j in range(30))
95
+ pq.write_table(pa.table({"text": texts}), tmp_path / "source-train.parquet")
96
+ pq.write_table(pa.table({"text": [heldout]}), tmp_path / "source-test.parquet")
97
+ def source(root, repo, revision, key):
98
+ path = tmp_path / f"source-{key.split('_')[1]}.parquet"
99
+ return path, {"file": path.name}
100
+ monkeypatch.setattr(data, "_source", source)
101
+ monkeypatch.setattr(data, "STORY_LIMIT", len(texts))
102
+ monkeypatch.setattr(data, "STORY_VOCAB", 280)
103
+ original = data._tokenizer
104
+ observed = []
105
+ def find_training_docs(stage, train, root, output, sources):
106
+ observed.extend(doc.text for doc in train)
107
+ return original(stage, train, root, output, sources)
108
+ monkeypatch.setattr(data, "_tokenizer", find_training_docs)
109
+ manifest = data.prepare("stories", tmp_path)
110
+ assert set(observed) == {text for text in texts if int(content_hash(text)[:16], 16) % 50}
111
+ assert manifest["vocab_size"] == 280
112
+ folder = tmp_path / "stories"
113
+ tokenizer = Tokenizer.from_file(str(folder / "tokenizer.json"))
114
+ assert tokenizer.decode(tokenizer.encode("Hello, café 🦉").ids) == "Hello, café 🦉"
115
+ streams = {s: np.fromfile(folder / f"{s}.bin", dtype="<u2") for s in ("train", "dev", "test")}
116
+ for line in (folder / "documents.jsonl").read_text(encoding="utf-8").splitlines():
117
+ entry = json.loads(line)
118
+ row = int(entry["id"].split(":")[1])
119
+ text = heldout if entry["split"] == "test" else texts[row]
120
+ start = entry["start_token"]
121
+ end = start + entry["tokens"]
122
+ expected = tokenizer.encode(text, add_special_tokens=False).ids + [manifest["eos_id"]]
123
+ assert streams[entry["split"]][start:end].tolist() == expected
124
+ assert data.prepare("stories", tmp_path) == manifest
125
+ (folder / "test.bin").write_bytes(b"corrupt")
126
+ repaired = data.prepare("stories", tmp_path)
127
+ assert repaired["artifacts"]["test.bin"]["sha256"] == manifest["artifacts"]["test.bin"]["sha256"]
128
+ assert repaired["token_counts"] == {s: len(ids) for s, ids in streams.items()}
research/tests/test_derivatives.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Numerical oracles for the implemented parameter-space penalties.
2
+
3
+ The dense reference uses forward-mode transforms, whereas training contracts reverse-mode
4
+ derivatives. Reference for composable Jacobians: https://docs.pytorch.org/docs/stable/func.html
5
+ """
6
+
7
+ from itertools import product
8
+ from math import sqrt
9
+
10
+ import pytest
11
+ import torch
12
+ from torch.func import jacfwd
13
+
14
+ from thirdloss.penalties import estimate
15
+
16
+
17
+ @pytest.fixture(scope="module", autouse=True)
18
+ def small_cpu_tensors():
19
+ """Keep the tiny reference calculations deterministic and inexpensive on a CPU."""
20
+ previous = torch.get_num_threads()
21
+ torch.set_num_threads(1)
22
+ yield
23
+ torch.set_num_threads(previous)
24
+
25
+
26
+ def test_quartic_penalty_retains_fourth_derivative():
27
+ """A detached numerical penalty would pass the value check and fail the gradient check."""
28
+ x = torch.tensor(-0.375, dtype=torch.float64, requires_grad=True)
29
+ one = torch.ones_like(x)
30
+ penalty = estimate(x**4, (x,), "third", u=(one,), v=(-one,))
31
+ torch.testing.assert_close(penalty, 576 * x.square())
32
+ gradient, = torch.autograd.grad(penalty, x)
33
+ torch.testing.assert_close(gradient, 1152 * x)
34
+
35
+
36
+ def test_mixed_cubic_exactly_averages_to_tensor_norm():
37
+ """The xyz tensor has six unit entries at permutations of three distinct indices."""
38
+ x = torch.tensor([0.3, -0.5, 0.7], dtype=torch.float64, requires_grad=True)
39
+ signs = [x.new_tensor(s) for s in product((-1, 1), repeat=3)]
40
+ values = [
41
+ estimate(x[0] * x[1] * x[2], (x,), "third", u=(u,), v=(v,)).detach()
42
+ for u, v in product(signs, repeat=2)
43
+ ]
44
+ torch.testing.assert_close(torch.stack(values).mean(), x.new_tensor(6.0))
45
+
46
+
47
+ def test_random_probe_generator_gives_independent_directions():
48
+ """Reusing a probe for xyz always gives 12, twice the registered expectation."""
49
+ x = torch.ones(3, dtype=torch.float64, requires_grad=True)
50
+ generator = torch.Generator().manual_seed(307)
51
+ values = [
52
+ estimate(x[0] * x[1] * x[2], (x,), "third", generator=generator).item()
53
+ for _ in range(256)
54
+ ]
55
+ # Each scalar draw is 4 or 12, with probability 1/4 of 12 under independent signs.
56
+ assert set(values) == {4.0, 12.0}
57
+ assert abs(sum(values) / len(values) - 6.0) < 1.0
58
+
59
+
60
+ @pytest.mark.parametrize("kind", ["third", "trace", "hessian_norm"])
61
+ def test_penalty_supports_linear_loss_and_unused_coordinates(kind):
62
+ """Constant and unused derivatives contribute zero while ordinary training stays live."""
63
+ x = torch.tensor(0.7, dtype=torch.float64, requires_grad=True)
64
+ unused = torch.tensor(-0.1, dtype=torch.float64, requires_grad=True)
65
+ ones = (torch.ones_like(x), torch.ones_like(unused))
66
+ loss = 3 * x
67
+ penalty = estimate(loss, (x, unused), kind, u=ones, v=ones)
68
+ torch.testing.assert_close(penalty, x.new_zeros(()))
69
+ gx, gu = torch.autograd.grad(loss + penalty, (x, unused), allow_unused=True)
70
+ torch.testing.assert_close(gx, x.new_tensor(3.0))
71
+ assert gu is None or gu.item() == 0
72
+
73
+
74
+ def test_quadratic_has_curvature_and_zero_third_derivative():
75
+ """The third-order term must vanish even when the Hessian is arbitrarily steep."""
76
+ x = torch.tensor(0.3, dtype=torch.float64, requires_grad=True)
77
+ one = (torch.ones_like(x),)
78
+ penalty = estimate(10_000 * x.square(), (x,), "third", u=one, v=one)
79
+ torch.testing.assert_close(penalty, x.new_zeros(()))
80
+
81
+
82
+ def test_signed_hessian_trace_and_squared_norm_have_correct_gradients():
83
+ """Concave curvature distinguishes the signed literature baseline from its square."""
84
+ x = torch.tensor(0.2, dtype=torch.float64, requires_grad=True)
85
+ one = (torch.ones_like(x),)
86
+ hessian = 3 * x - 10
87
+ trace = estimate((x**3 - 10 * x.square()) / 2, (x,), "trace", u=one)
88
+ squared = estimate((x**3 - 10 * x.square()) / 2, (x,), "hessian_norm", u=one)
89
+ torch.testing.assert_close(trace, hessian)
90
+ torch.testing.assert_close(squared, hessian.square())
91
+ torch.testing.assert_close(torch.autograd.grad(trace, x)[0], x.new_tensor(3.0))
92
+ torch.testing.assert_close(torch.autograd.grad(squared, x)[0], 6 * hessian)
93
+
94
+
95
+ def tiny_causal_loss(theta):
96
+ """A one-block decoder fixture with active coefficients in attention, MLP and head.
97
+
98
+ Fixed input embeddings and held-fixed weights isolate a three-coordinate parameter
99
+ subspace. The causal mask and trainable operations use smooth, deterministic math.
100
+ """
101
+ embeddings = theta.new_tensor([[0.7, -0.6], [0.2, 1.0], [-0.9, 0.5]])
102
+ hidden = embeddings[[0, 1, 2]]
103
+ query = hidden @ (theta.new_tensor([[1.0, 0.2], [-0.1, 0.8]])
104
+ + theta[0] * theta.new_tensor([[0.4, -0.2], [0.3, 0.6]]))
105
+ key = hidden @ theta.new_tensor([[0.7, -0.4], [0.1, 0.9]])
106
+ scores = query @ key.T / sqrt(hidden.size(-1))
107
+ future = torch.ones_like(scores, dtype=torch.bool).triu(diagonal=1)
108
+ attention = scores.masked_fill(future, float("-inf")).softmax(dim=-1)
109
+ hidden = hidden + attention @ hidden
110
+ expansion = hidden @ theta.new_tensor([[1.0, 0.2], [-0.5, 0.7]])
111
+ hidden = hidden + torch.tanh(expansion * (0.8 + theta[1]))
112
+ hidden = hidden * (hidden.square().mean(dim=-1, keepdim=True) + 1e-4).rsqrt()
113
+ outputs = embeddings.T + theta[2] * theta.new_tensor([[0.2, 0.5, -0.4], [0.8, -0.3, 0.6]])
114
+ logits = hidden @ outputs
115
+ targets = torch.tensor([1, 2, 0], dtype=torch.long, device=theta.device)
116
+ target_logits = logits.gather(1, targets[:, None]).squeeze(1)
117
+ return (logits.logsumexp(dim=-1) - target_logits).mean()
118
+
119
+
120
+ def test_tiny_transformer_against_dense_tensor_and_finite_differences():
121
+ """Compare a contracted third derivative and its parameter gradient to independent oracles."""
122
+ theta = torch.tensor([0.19, -0.37, 0.22], dtype=torch.float64, requires_grad=True)
123
+ u = theta.new_tensor([-1.0, 1.0, 1.0])
124
+ v = theta.new_tensor([1.0, -1.0, 1.0])
125
+ dense_third = jacfwd(jacfwd(jacfwd(tiny_causal_loss)))
126
+
127
+ def reference(point):
128
+ """Contract explicitly materialized partials in this small verification subspace."""
129
+ tensor = dense_third(point)
130
+ vector = torch.einsum("ijk,j,k->i", tensor, u, v)
131
+ return vector.square().sum()
132
+
133
+ point = theta.detach()
134
+ penalty = estimate(tiny_causal_loss(theta), (theta,), "third", u=(u,), v=(v,))
135
+ torch.testing.assert_close(penalty.detach(), reference(point), rtol=2e-9, atol=1e-11)
136
+ gradient, = torch.autograd.grad(penalty, theta)
137
+ # Central-difference the independent dense-AD scalar. Vary one parameter at a time.
138
+ step = 2e-5
139
+ basis = torch.eye(point.numel(), dtype=point.dtype)
140
+ numerical = torch.stack([
141
+ (reference(point + step * e) - reference(point - step * e)) / (2 * step)
142
+ for e in basis
143
+ ])
144
+ assert numerical.norm() > 1e-5
145
+ torch.testing.assert_close(gradient, numerical, rtol=3e-5, atol=1e-8)
146
+
147
+
148
+ def test_actual_adamw_update_responds_to_the_third_order_term():
149
+ """The registered penalty reverses this ordinary gradient; detaching restores the CE step."""
150
+ def updated(strength, detach=False):
151
+ """Use AdamW itself, including its moment normalization."""
152
+ x = torch.nn.Parameter(torch.tensor(0.25, dtype=torch.float64))
153
+ optimizer = torch.optim.AdamW([x], lr=0.01, weight_decay=0)
154
+ loss = x**4 - x
155
+ one = (torch.ones_like(x),)
156
+ penalty = estimate(loss, (x,), "third", u=one, v=one)
157
+ (loss + strength * (penalty.detach() if detach else penalty)).backward()
158
+ optimizer.step()
159
+ return x.detach()
160
+
161
+ ordinary = updated(0)
162
+ assert updated(0.01).item() < 0.25 < ordinary.item()
163
+ torch.testing.assert_close(updated(0.01, detach=True), ordinary, rtol=0, atol=0)
164
+
165
+
166
+ def test_production_story_model_exposes_full_weight_penalty_gradient():
167
+ """Exercise all trainable coordinates through the same scratch-model entry point as training."""
168
+ from thirdloss.models import StoryConfig, StoryTransformer, token_loss
169
+
170
+ with torch.random.fork_rng(devices=[]):
171
+ torch.manual_seed(42)
172
+ config = StoryConfig(vocab_size=7, width=8, heads=2, layers=1, hidden=12, context=4)
173
+ model = StoryTransformer(config).double().eval()
174
+ ids = torch.tensor([[2, 4, 1, 5], [3, 6, 2, 1]])
175
+ targets = torch.tensor([[4, 1, 5, 6], [6, 2, 1, 0]])
176
+ loss = token_loss(model(ids), targets)
177
+ weights = tuple(model.parameters())
178
+ penalty = estimate(loss, weights, "third", generator=torch.Generator().manual_seed(7))
179
+ augmented = torch.autograd.grad(loss + 0.01 * penalty, weights)
180
+ plain = torch.autograd.grad(token_loss(model(ids), targets), weights)
181
+ assert penalty.isfinite() and penalty > 0
182
+ assert all(gradient.isfinite().all() for gradient in augmented)
183
+ assert any(not torch.allclose(a, b, atol=1e-10, rtol=1e-9) for a, b in zip(augmented, plain))
research/tests/test_reporting.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Check that the public progress views, paper and live feed share the same real records."""
2
+
3
+ import json
4
+
5
+ from pypdf import PdfReader
6
+
7
+ from thirdloss.reporting import build_report, study_snapshot
8
+
9
+
10
+ def test_snapshot_keeps_full_score_and_trace_semantics(tmp_path):
11
+ """Distinguish raw derivative size, weighted training contribution and full validation."""
12
+ run = tmp_path / "results" / "stories-pilot-s00-third-r03"
13
+ run.mkdir(parents=True)
14
+ config = {"stage": "stories", "phase": "pilot", "seed": 0, "method": "third", "token_budget": 4096}
15
+ (run / "config.json").write_text(json.dumps(config), encoding="utf-8")
16
+ event = {"step": 1, "tokens": 4096, "loss": 3.2, "penalty": 0.03, "dev_nll": 4.0,
17
+ "derivatives": {"third": {"estimate": 7.0}}, "train_seconds": 1.0}
18
+ (run / "events.jsonl").write_bytes(json.dumps(event).encode() + b'\n{"step":')
19
+ (run / "summary.json").write_text('{"dev_nll":3.9,"status":"complete"}', encoding="utf-8")
20
+ record = study_snapshot(tmp_path)["runs"][0]
21
+ assert record["dev_nll"] == 3.9
22
+ assert record["target_tokens"] == record["tokens"] == 4096
23
+ assert record["events"][0]["raw_third"] == 7.0
24
+ assert record["events"][0]["penalty"] == 0.03
25
+ assert record["events_total"] == 1
26
+
27
+
28
+ def test_report_before_first_run_keeps_readme_and_emits_protocol_paper(tmp_path):
29
+ """A fresh checkout supports an explicit, illustrated preregistration-only publication."""
30
+ readme = tmp_path / "README.md"
31
+ readme.write_text("# Intro\n\nRelated work.\n\n<!-- RESULTS:START -->\n"
32
+ "<!-- RESULTS:END -->\n\n## Reproduction\n", encoding="utf-8")
33
+ study = build_report(tmp_path)
34
+ assert not study["runs"]
35
+ assert (tmp_path / "docs" / "figures" / "architecture.png").is_file()
36
+ assert not (tmp_path / "docs" / "figures" / "paired.png").exists()
37
+ assert "Related work." in readme.read_text(encoding="utf-8")
38
+ assert "## Reproduction" in readme.read_text(encoding="utf-8")
39
+ assert "AI statement" not in readme.read_text(encoding="utf-8")
40
+ reader = PdfReader(tmp_path / "reports" / "paper.pdf")
41
+ text = " ".join(page.extract_text() for page in reader.pages)
42
+ assert "AI statement" in text
43
+ assert "Awaiting paired test results" in text
44
+ assert "Libor" in text
research/tests/test_training.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify paired data, sham updates, and exact restart of the actual training loop."""
2
+
3
+ import subprocess
4
+
5
+ import numpy as np
6
+ import torch
7
+ from safetensors.torch import load_file
8
+
9
+ from thirdloss import train
10
+ from thirdloss.models import StoryConfig, StoryTransformer
11
+ from thirdloss.objectives import add_penalty
12
+ from thirdloss.records import read_json, write_json
13
+ from thirdloss.windows import TrainingWindows, gate, generator
14
+
15
+
16
+ def small_model(stage, seed, device, storage):
17
+ torch.manual_seed(seed)
18
+ return StoryTransformer(StoryConfig(vocab_size=7,width=8,heads=2,layers=1,hidden=12)).to(device)
19
+
20
+
21
+ def test_randomized_control_preserves_coordinate_magnitudes_and_zero_is_noop():
22
+ model = small_model("stories",0,"cpu",None)
23
+ params = tuple(model.parameters())
24
+ x = torch.tensor([[2,3,4,0],[1,3,2,1],[4,2,5,0]])
25
+ y = (x+1)%7
26
+ for p in params:
27
+ p.grad = torch.zeros_like(p)
28
+ add_penalty(model,params,x,y,{"third":0.0},"third",3,1)
29
+ assert all(p.grad.count_nonzero()==0 for p in params)
30
+ add_penalty(model,params,x,y,{"third":0.01},"third",3,1)
31
+ actual = torch.cat([p.grad.flatten() for p in params])
32
+ model.zero_grad(set_to_none=True)
33
+ add_penalty(model,params,x,y,{"third":0.01},"sham",3,1)
34
+ sham = torch.cat([p.grad.flatten() for p in params])
35
+ torch.testing.assert_close(actual.abs(),sham.abs(),rtol=0,atol=0)
36
+ assert torch.any(actual*sham < 0)
37
+
38
+
39
+ def test_step_recovery_matches_uninterrupted_weights(tmp_path,monkeypatch):
40
+ """Crash just after a committed checkpoint, then restart through the public runner."""
41
+ project = tmp_path/"project"
42
+ project.mkdir()
43
+ subprocess.run(["git","init","-q"],cwd=project,check=True)
44
+ subprocess.run(["git","-c","user.name=Test","-c","user.email=test@example.invalid",
45
+ "commit","--allow-empty","-qm","fixture"],cwd=project,check=True)
46
+ root = tmp_path/"store"
47
+ directory = root/"data"/"stories"
48
+ directory.mkdir(parents=True)
49
+ rng = np.random.default_rng(42)
50
+ for split in ("train","dev"):
51
+ rng.integers(0,7,size=7000,dtype=np.uint16).tofile(directory/f"{split}.bin")
52
+ write_json(directory/"manifest.json",{"eos_id":0})
53
+ (directory/"tokenizer.json").write_text("{}",encoding="utf-8")
54
+ monkeypatch.setattr(train,"build_model",small_model)
55
+ monkeypatch.setattr(train,"sample_outputs",lambda *a,**k:None)
56
+ monkeypatch.setattr(train,"chosen_coefficients",lambda *a:{"third":1e-13})
57
+ saved = train.save_state
58
+ seed = next(s for s in range(100) if any(gate(s,i) for i in range(2,8)))
59
+
60
+ def interrupt(*args):
61
+ saved(*args)
62
+ if args[3] == 2:
63
+ raise RuntimeError("intentional restart fixture")
64
+
65
+ prior_threads = torch.get_num_threads()
66
+ torch.set_num_threads(1)
67
+ try:
68
+ monkeypatch.setattr(train,"save_state",interrupt)
69
+ import pytest
70
+ with pytest.raises(RuntimeError,match="intentional restart"):
71
+ train.run_one(project,root,"stories","third","smoke",seed,0.03,torch.device("cpu"))
72
+ monkeypatch.setattr(train,"save_state",saved)
73
+ resumed = train.run_one(project,root,"stories","third","smoke",seed,0.03,torch.device("cpu"))
74
+ import shutil
75
+ reference = tmp_path/"reference"
76
+ shutil.copytree(project/".git",reference/".git")
77
+ store2 = tmp_path/"store2"
78
+ shutil.copytree(root/"data",store2/"data")
79
+ normal = train.run_one(reference,store2,"stories","third","smoke",seed,0.03,torch.device("cpu"))
80
+ for path, other in [(root,store2)]:
81
+ rel = f"checkpoints/{normal['id']}/export/model.safetensors"
82
+ first, second = load_file(str(path/rel)),load_file(str(other/rel))
83
+ for name in first:
84
+ torch.testing.assert_close(first[name],second[name],rtol=0,atol=0)
85
+ assert normal["dev_nll"]==resumed["dev_nll"]
86
+ finally:
87
+ torch.set_num_threads(prior_threads)
research/uv.lock ADDED
@@ -0,0 +1,1039 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = 1
2
+ revision = 5
3
+ requires-python = "==3.12.*"
4
+ resolution-markers = [
5
+ "platform_machine == 'AMD64' and sys_platform == 'win32'",
6
+ "platform_machine == 'x86_64' and sys_platform == 'linux'",
7
+ ]
8
+ supported-markers = [
9
+ "platform_machine == 'AMD64' and sys_platform == 'win32'",
10
+ "platform_machine == 'x86_64' and sys_platform == 'linux'",
11
+ ]
12
+
13
+ [[package]]
14
+ name = "accelerate"
15
+ version = "1.16.0"
16
+ source = { registry = "https://pypi.org/simple" }
17
+ dependencies = [
18
+ { name = "huggingface-hub" },
19
+ { name = "numpy" },
20
+ { name = "packaging" },
21
+ { name = "psutil" },
22
+ { name = "pyyaml" },
23
+ { name = "safetensors" },
24
+ { name = "torch" },
25
+ ]
26
+ sdist = { url = "https://files.pythonhosted.org/packages/62/dd/14c28a3918ae4d3e40d87e2edcb8737731e52c57f28f0980bb780f50dad6/accelerate-1.16.0.tar.gz", hash = "sha256:43c446b9affb145220946a63fe32e14e968fcfca645d25b5f1f3fdbc375657ae", size = 424969, upload-time = "2026-11-16T21:00:38.494Z" }
27
+ wheels = [
28
+ { url = "https://files.pythonhosted.org/packages/29/8e/d77aa769cf76472ede10e73e5c27ed22587ff12091fdd7408bc390f41af7/accelerate-1.16.0-py3-none-any.whl", hash = "sha256:180885b6d7b05a19dc2dd6f722c5ce930f615e81e9e5f79d3ca910ddb9e6859e", size = 389390, upload-time = "2026-11-16T21:00:36.979Z" },
29
+ ]
30
+
31
+ [[package]]
32
+ name = "annotated-doc"
33
+ version = "0.0.7"
34
+ source = { registry = "https://pypi.org/simple" }
35
+ sdist = { url = "https://files.pythonhosted.org/packages/0b/7d/bdbf3062e5dae31da8b3de1e3269110beb93d268df4a7f6d22b167c6cee0/annotated_doc-0.0.7.tar.gz", hash = "sha256:0a30ef8f5322a4173720ae6712dc9a5e58f5a19868f3f167b4b5778db066c2b5", size = 10764, upload-time = "2026-11-18T11:06:55.181Z" }
36
+ wheels = [
37
+ { url = "https://files.pythonhosted.org/packages/5e/b1/9530d6bee606979d54501adcc767d958a38929827f11a524b0d93429d2ad/annotated_doc-0.0.7-py3-none-any.whl", hash = "sha256:6bc31bbbec6dfaaedc1676dbc11dbda96fe22a2b5c400e9ebad113fec44a9dc6", size = 5286, upload-time = "2026-11-18T11:06:54.096Z" },
38
+ ]
39
+
40
+ [[package]]
41
+ name = "annotated-types"
42
+ version = "0.8.0"
43
+ source = { registry = "https://pypi.org/simple" }
44
+ sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" }
45
+ wheels = [
46
+ { url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" },
47
+ ]
48
+
49
+ [[package]]
50
+ name = "anyio"
51
+ version = "4.16.0"
52
+ source = { registry = "https://pypi.org/simple" }
53
+ dependencies = [
54
+ { name = "idna" },
55
+ { name = "typing-extensions" },
56
+ ]
57
+ sdist = { url = "https://files.pythonhosted.org/packages/a1/98/7e457a3b014976887a050561955c0b76e1e7e2d6e27b78ecef2ef80518f2/anyio-4.16.0.tar.gz", hash = "sha256:59bb03251907983d1603d27c3087ddb1e93299ea2163adcdba37899a4fb12ffb", size = 310971, upload-time = "2026-11-01T11:20:07.282Z" }
58
+ wheels = [
59
+ { url = "https://files.pythonhosted.org/packages/a9/16/7757fb84c819accc7d7e9af5291b261e4abb8627ee040f99e7d35ef2457a/anyio-4.16.0-py3-none-any.whl", hash = "sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026", size = 134521, upload-time = "2026-11-01T11:20:05.59Z" },
60
+ ]
61
+
62
+ [[package]]
63
+ name = "certifi"
64
+ version = "2026.11.20"
65
+ source = { registry = "https://pypi.org/simple" }
66
+ sdist = { url = "https://files.pythonhosted.org/packages/51/33/4cd27639502f010084bcef7a2036391dd637439901341ce1a530f36f6e51/certifi-2026.11.20.tar.gz", hash = "sha256:af1cb240a8133f105aa52684a3a3258339d7f2fd0bd4e2812698ff5cf5588c4e", size = 128901, upload-time = "2026-11-20T23:37:49.522Z" }
67
+ wheels = [
68
+ { url = "https://files.pythonhosted.org/packages/6d/39/5eec3296860b94ac20bb8ed807725b88f6adfab3f343df592afd975f5f86/certifi-2026.11.20-py3-none-any.whl", hash = "sha256:7422df25243767b9877031a2248cb14d09ddac9beee846f4cef3d5c9191d488f", size = 127913, upload-time = "2026-11-20T23:37:48.117Z" },
69
+ ]
70
+
71
+ [[package]]
72
+ name = "charset-normalizer"
73
+ version = "3.5.3"
74
+ source = { registry = "https://pypi.org/simple" }
75
+ sdist = { url = "https://files.pythonhosted.org/packages/c2/c3/cae6d3bdefd96a941ffc247c714ac4babc488a69012e11c058f6c17c6c47/charset_normalizer-3.5.3.tar.gz", hash = "sha256:a250888753faa289e2997962fbb17c4960cbdb58575533ca6fceee68c224bdff", size = 189359, upload-time = "2026-11-23T02:46:51.755Z" }
76
+ wheels = [
77
+ { url = "https://files.pythonhosted.org/packages/67/92/6db11254f4009dd980e17473a0ee4a4b54945df4d8346af4bef8999ab85a/charset_normalizer-3.5.3-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:e5e4785d8a0adeadfbdf75f4efc357911842674651cbafd7e97f69b11ec3cbc6", size = 257134, upload-time = "2026-11-23T02:43:57.512Z" },
78
+ { url = "https://files.pythonhosted.org/packages/fe/a1/172b880e2666371817666fff6b9e43cf0e50e8be91e38158fab8c83c29ba/charset_normalizer-3.5.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:366f5efe95a6149ecbcebf779c2594a6a4ff6fc116402826c72ed0eccd6aabe9", size = 259298, upload-time = "2026-11-23T02:44:11.73Z" },
79
+ { url = "https://files.pythonhosted.org/packages/82/78/7913aa5816c1606298274f47caf208efdd4245a0da1e309a13e518cc007b/charset_normalizer-3.5.3-cp312-cp312-win_amd64.whl", hash = "sha256:40b2ba91f0851aa864994b3c7022e4d96d09026717e6a72e44410d6fb3a74a13", size = 214472, upload-time = "2026-11-23T02:44:14.041Z" },
80
+ { url = "https://files.pythonhosted.org/packages/5f/02/b01868added37f27a6b0fd29e7fa19d0ae52b3fdbfc6fde6b9c98ef377ec/charset_normalizer-3.5.3-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:26c6ad87bb79628954b52f8f7b9e18ab5cd9667546712ded9689fb7677e630d6", size = 234407, upload-time = "2026-11-23T02:46:10.528Z" },
81
+ { url = "https://files.pythonhosted.org/packages/3a/fe/aa2706988f2e4e46e79a488383dfd2f4d166728e046d8ae29cf8466d38e2/charset_normalizer-3.5.3-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:3e8da696ef1935a019c10ec16555a062183ddf6d5901e296edeca4b2a8f84e1d", size = 236268, upload-time = "2026-11-23T02:46:24.607Z" },
82
+ { url = "https://files.pythonhosted.org/packages/a3/a5/cc188879ab8e8a36d295f888335f0a2875e39bcdacc6fe3207427c14036f/charset_normalizer-3.5.3-cp37-abi3-win_amd64.whl", hash = "sha256:a5a7e0326566759f9a7bc44f4b9a179cc40a297e09e759b0bc7c848c06347527", size = 200667, upload-time = "2026-11-23T02:46:27.221Z" },
83
+ { url = "https://files.pythonhosted.org/packages/d2/0d/07ab8eb9b7015274353eac2add4067bde1ab1b51912bbae505392905eedd/charset_normalizer-3.5.3-py3-none-any.whl", hash = "sha256:96e268b0cbda016ac519513294fcd17032264085b600abaac58b93049477e132", size = 68878, upload-time = "2026-11-23T02:46:50.665Z" },
84
+ ]
85
+
86
+ [[package]]
87
+ name = "click"
88
+ version = "8.5.1"
89
+ source = { registry = "https://pypi.org/simple" }
90
+ sdist = { url = "https://files.pythonhosted.org/packages/45/37/edbf1b0707709013c0cf2e8317e03d97ed29bf4cac709fe328904ae92a38/click-8.5.1.tar.gz", hash = "sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4", size = 399151, upload-time = "2026-11-06T17:37:01.021Z" }
91
+ wheels = [
92
+ { url = "https://files.pythonhosted.org/packages/31/7d/164b7ffc8624fe9efb4221bf9af485d5c1e41b9ae118045d2b6dc5457d8b/click-8.5.1-py3-none-any.whl", hash = "sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37", size = 126163, upload-time = "2026-11-06T17:36:59.287Z" },
93
+ ]
94
+
95
+ [[package]]
96
+ name = "colorama"
97
+ version = "0.4.6"
98
+ source = { registry = "https://pypi.org/simple" }
99
+ sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" }
100
+ wheels = [
101
+ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
102
+ ]
103
+
104
+ [[package]]
105
+ name = "contourpy"
106
+ version = "1.4.0"
107
+ source = { registry = "https://pypi.org/simple" }
108
+ dependencies = [
109
+ { name = "numpy" },
110
+ ]
111
+ sdist = { url = "https://files.pythonhosted.org/packages/83/5a/a55177dd22553a277388e8a1b3220e92de91bacb28356cdc73caa240121d/contourpy-1.4.0.tar.gz", hash = "sha256:20156f5a1ac4f8ce02656e39a61e82164a3d359796dc8026f75b062783d500e1", size = 13323726, upload-time = "2026-09-11T19:05:05.808Z" }
112
+ wheels = [
113
+ { url = "https://files.pythonhosted.org/packages/78/f9/b6831508960d559581c448532ba4df312217072975486dbf2b24fcc5b76f/contourpy-1.4.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:875f42444c9cf48d56f724f2637e60d0f73b3b12c9041e1484580a233edf9591", size = 383243, upload-time = "2026-09-11T19:02:58.638Z" },
114
+ { url = "https://files.pythonhosted.org/packages/d8/79/d68b1ce8539e4071518fed9523f558398f34dcd078b8927b109c72dad2ef/contourpy-1.4.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3863ef2e2b13fe93f8c0ebb08ee400cb07153b8b0e91c5acb26e4537f283634f", size = 1427243, upload-time = "2026-09-11T19:03:03.866Z" },
115
+ { url = "https://files.pythonhosted.org/packages/50/a9/dab08786bb4d77ef9a046b3c1be923be4e73c5d07d91f5a54e8ea9b09e41/contourpy-1.4.0-cp312-cp312-win_amd64.whl", hash = "sha256:6e697d94e69f499ff6bebb899cae97a58d5d14f0e1fe9568b43a0248d2f9af8c", size = 234083, upload-time = "2026-09-11T19:03:08.122Z" },
116
+ ]
117
+
118
+ [[package]]
119
+ name = "cuda-bindings"
120
+ version = "13.5.0"
121
+ source = { registry = "https://pypi.org/simple" }
122
+ dependencies = [
123
+ { name = "cuda-pathfinder" },
124
+ ]
125
+ wheels = [
126
+ { url = "https://files.pythonhosted.org/packages/27/68/14bf44f386672b03fcc0799be8d18df3e1c45847ee23b95721f6022abbaf/cuda_bindings-13.5.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a46a8cc84112d769d0f57bf3ae3fedc115cf09348f14da85a1a8200968b6f262", size = 8378158, upload-time = "2026-11-05T12:06:05.253Z" },
127
+ ]
128
+
129
+ [[package]]
130
+ name = "cuda-pathfinder"
131
+ version = "1.9.1"
132
+ source = { registry = "https://pypi.org/simple" }
133
+ wheels = [
134
+ { url = "https://files.pythonhosted.org/packages/62/8e/e6101ff068e7e78b362879ffc0c7cbfe68c9742943c9b034f009fe19f88f/cuda_pathfinder-1.9.1-py3-none-any.whl", hash = "sha256:b743c132f90ad2d1e71d43fd28f31ebcde518f943e50fd44aca62b2a80d5230d", size = 63462, upload-time = "2026-11-19T04:26:29.241Z" },
135
+ ]
136
+
137
+ [[package]]
138
+ name = "cuda-toolkit"
139
+ version = "13.2.2"
140
+ source = { registry = "https://pypi.org/simple" }
141
+ wheels = [
142
+ { url = "https://files.pythonhosted.org/packages/3d/62/854e4a141f5e87e5425513bad2a742a6260acfe06ef148001b5362148f31/cuda_toolkit-13.2.2-py2.py3-none-any.whl", hash = "sha256:d12edc1aad1356236a2ee10c0d794b1aff5d3e79bfeca54867c3bb8e5afd87b0", size = 2607, upload-time = "2026-07-16T10:13:01.07Z" },
143
+ ]
144
+
145
+ [package.optional-dependencies]
146
+ cublas = [
147
+ { name = "nvidia-cublas" },
148
+ { name = "nvidia-cuda-nvrtc" },
149
+ ]
150
+ cudart = [
151
+ { name = "nvidia-cuda-runtime" },
152
+ ]
153
+ cufft = [
154
+ { name = "nvidia-cufft" },
155
+ { name = "nvidia-nvjitlink" },
156
+ ]
157
+ cufile = [
158
+ { name = "nvidia-cufile" },
159
+ ]
160
+ cupti = [
161
+ { name = "nvidia-cuda-cupti" },
162
+ ]
163
+ cusolver = [
164
+ { name = "nvidia-cublas" },
165
+ { name = "nvidia-cusolver" },
166
+ { name = "nvidia-cusparse" },
167
+ { name = "nvidia-nvjitlink" },
168
+ ]
169
+ cusparse = [
170
+ { name = "nvidia-cusparse" },
171
+ { name = "nvidia-nvjitlink" },
172
+ ]
173
+ nvjitlink = [
174
+ { name = "nvidia-nvjitlink" },
175
+ ]
176
+ nvrtc = [
177
+ { name = "nvidia-cuda-nvrtc" },
178
+ ]
179
+ nvtx = [
180
+ { name = "nvidia-nvtx" },
181
+ ]
182
+
183
+ [[package]]
184
+ name = "cycler"
185
+ version = "0.12.1"
186
+ source = { registry = "https://pypi.org/simple" }
187
+ sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615, upload-time = "2023-10-07T05:32:18.335Z" }
188
+ wheels = [
189
+ { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" },
190
+ ]
191
+
192
+ [[package]]
193
+ name = "filelock"
194
+ version = "4.3.1"
195
+ source = { registry = "https://pypi.org/simple" }
196
+ sdist = { url = "https://files.pythonhosted.org/packages/e6/86/a5b9ec254b90efb180e390e31a4fa50a93b714d6e4174fa9a4ee25607159/filelock-4.3.1.tar.gz", hash = "sha256:4c5ee627c401f1863ac6a0de9a14a28d3bb5f8c730b45e2fd6e5dbc79cf34b9e", size = 742330, upload-time = "2026-11-23T18:01:13.656Z" }
197
+ wheels = [
198
+ { url = "https://files.pythonhosted.org/packages/53/7b/678c8fbd372ff96375ac0bbdd20b78f20ef8ba6ca5966c49548fa5886557/filelock-4.3.1-py3-none-any.whl", hash = "sha256:79e43df8e9fe509cd83a3899a7c186c8077cbbe4d200a1ed3705c2f3bb6bc487", size = 244559, upload-time = "2026-11-23T18:01:12.261Z" },
199
+ ]
200
+
201
+ [[package]]
202
+ name = "fonttools"
203
+ version = "4.68.0"
204
+ source = { registry = "https://pypi.org/simple" }
205
+ sdist = { url = "https://files.pythonhosted.org/packages/0c/b5/672312ae80ce8b8eb9779c56052a24c8f36652aa7293a1a420553bcf03e5/fonttools-4.68.0.tar.gz", hash = "sha256:73294e233070f71e2b3653b6bd8564af676d57f26d075761fb06d1ab2e4a7a5d", size = 3848583, upload-time = "2026-10-27T16:30:26.451Z" }
206
+ wheels = [
207
+ { url = "https://files.pythonhosted.org/packages/7f/58/fe13db71e3f5a020c6875f349806e84f7550f3f24cb3cdbabdd693968b1d/fonttools-4.68.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3edce69ecdefa73ab1041901ca22eefed6ebb93a77bc77e889d940479f25bf7d", size = 5443448, upload-time = "2026-10-27T16:28:27.898Z" },
208
+ { url = "https://files.pythonhosted.org/packages/cb/0d/09e9a433430e277e454eace1c4d02c3691a33d5257bd234702a427a9d090/fonttools-4.68.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7ab8097e7e191784974c5608eb95fb31e1243fe3054cb66778ac82558e9b36f8", size = 5563739, upload-time = "2026-10-27T16:28:32.691Z" },
209
+ { url = "https://files.pythonhosted.org/packages/1c/3e/ef786310a3774ae7aacaa288ca6d1e1dfd03c24214137478e4b630b76af0/fonttools-4.68.0-cp312-cp312-win_amd64.whl", hash = "sha256:fedc183bdbc3fdbfbdca26e0e04566d089cbb404712509a4e824608e9304cc77", size = 2533508, upload-time = "2026-10-27T16:28:37.085Z" },
210
+ { url = "https://files.pythonhosted.org/packages/35/74/4ea331ecc65ba05a58b1e4e8ccd604c8a15565f876dfbf93fc2a2ea2e22b/fonttools-4.68.0-py3-none-any.whl", hash = "sha256:d76f8fdcb6936f5e1045a0c9dd721a4bf11112e60d1e243bfa1d39f06a8b3104", size = 1248357, upload-time = "2026-10-27T16:30:24.389Z" },
211
+ ]
212
+
213
+ [[package]]
214
+ name = "fsspec"
215
+ version = "2026.9.0"
216
+ source = { registry = "https://pypi.org/simple" }
217
+ sdist = { url = "https://files.pythonhosted.org/packages/77/cd/9be253869fc42e764de7f3dedd6969af7d44ff9c3375214a3442a6f3fc08/fsspec-2026.9.0.tar.gz", hash = "sha256:0f08147951c8cb31d844c3547d631053b127863b60be04cf06e121333ee0e2fe", size = 333545, upload-time = "2026-09-18T17:50:42.825Z" }
218
+ wheels = [
219
+ { url = "https://files.pythonhosted.org/packages/6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl", hash = "sha256:8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5f", size = 221738, upload-time = "2026-09-18T17:50:41.341Z" },
220
+ ]
221
+
222
+ [[package]]
223
+ name = "h11"
224
+ version = "0.16.0"
225
+ source = { registry = "https://pypi.org/simple" }
226
+ sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" }
227
+ wheels = [
228
+ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },
229
+ ]
230
+
231
+ [[package]]
232
+ name = "hf-xet"
233
+ version = "1.8.0"
234
+ source = { registry = "https://pypi.org/simple" }
235
+ sdist = { url = "https://files.pythonhosted.org/packages/2f/18/d91c20f815df6cc496a5d0ad8db6d274dad5c0cfcd59babfa2440a9aba44/hf_xet-1.8.0.tar.gz", hash = "sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e", size = 1013014, upload-time = "2026-10-30T10:04:33.741Z" }
236
+ wheels = [
237
+ { url = "https://files.pythonhosted.org/packages/f8/1e/1e8ecc05ef034e9a95c18ed32d2ec07905a7cd2ca611a9d88e25ee1f4850/hf_xet-1.8.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d", size = 4292483, upload-time = "2026-10-30T10:04:22.875Z" },
238
+ { url = "https://files.pythonhosted.org/packages/48/77/886f09e91a5eadb054ce03b8855323cd2a72f20db76ab4119e0ecda65eef/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01", size = 4500689, upload-time = "2026-10-30T10:04:28.394Z" },
239
+ { url = "https://files.pythonhosted.org/packages/97/4d/2c76a992b370ff77d0b5219275779f8c9a7dabb8ee649deb265dfed84d0f/hf_xet-1.8.0-cp38-abi3-win_amd64.whl", hash = "sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec", size = 3911559, upload-time = "2026-10-30T10:04:30.165Z" },
240
+ ]
241
+
242
+ [[package]]
243
+ name = "httpcore"
244
+ version = "1.0.9"
245
+ source = { registry = "https://pypi.org/simple" }
246
+ dependencies = [
247
+ { name = "certifi" },
248
+ { name = "h11" },
249
+ ]
250
+ sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" }
251
+ wheels = [
252
+ { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" },
253
+ ]
254
+
255
+ [[package]]
256
+ name = "httpcore2"
257
+ version = "2.16.2"
258
+ source = { registry = "https://pypi.org/simple" }
259
+ dependencies = [
260
+ { name = "h11" },
261
+ { name = "truststore" },
262
+ ]
263
+ sdist = { url = "https://files.pythonhosted.org/packages/92/9d/df40b41f7db0370f82019820709244e7b660c52aa3da3c9e5c4e8141f6e6/httpcore2-2.16.2.tar.gz", hash = "sha256:6c519d0f7b44f7269fa9bbb4d2763db395a4a2370f046d8e8e0a4b38227815d2", size = 70064, upload-time = "2026-11-16T10:12:19.491Z" }
264
+ wheels = [
265
+ { url = "https://files.pythonhosted.org/packages/2a/e8/009c347feac27f8960605aa98d55ed263b5870dd4fd80b82fd1d00d5716c/httpcore2-2.16.2-py3-none-any.whl", hash = "sha256:16051ae2a42f776007543f32de9349a317b23d2cbb4e1456b4bac0e88b87419a", size = 85551, upload-time = "2026-11-16T10:12:16.674Z" },
266
+ ]
267
+
268
+ [[package]]
269
+ name = "httpx"
270
+ version = "0.28.1"
271
+ source = { registry = "https://pypi.org/simple" }
272
+ dependencies = [
273
+ { name = "anyio" },
274
+ { name = "certifi" },
275
+ { name = "httpcore" },
276
+ { name = "idna" },
277
+ ]
278
+ sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" }
279
+ wheels = [
280
+ { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" },
281
+ ]
282
+
283
+ [[package]]
284
+ name = "httpx2"
285
+ version = "2.16.2"
286
+ source = { registry = "https://pypi.org/simple" }
287
+ dependencies = [
288
+ { name = "anyio" },
289
+ { name = "httpcore2" },
290
+ { name = "idna" },
291
+ { name = "truststore" },
292
+ { name = "typing-extensions" },
293
+ ]
294
+ sdist = { url = "https://files.pythonhosted.org/packages/1c/77/6515121dc5ac3c743ad1bff5afe635bcd1a3f23cc40db3c5c89f7d02917d/httpx2-2.16.2.tar.gz", hash = "sha256:748b615678f07d8e3b183efe81ad13b655ca88bfc56ce4589219b2d442860574", size = 103370, upload-time = "2026-11-16T10:12:20.49Z" }
295
+ wheels = [
296
+ { url = "https://files.pythonhosted.org/packages/77/de/8c4306a3d6aa2495111986addf33a9e561eff4c47552e4c4b9251160d0ad/httpx2-2.16.2-py3-none-any.whl", hash = "sha256:f05c13aade4c45dbf1c9060647a1058f0acad62398fad96e741269edb33d46f5", size = 97893, upload-time = "2026-11-16T10:12:18.192Z" },
297
+ ]
298
+
299
+ [[package]]
300
+ name = "huggingface-hub"
301
+ version = "2.4.0"
302
+ source = { registry = "https://pypi.org/simple" }
303
+ dependencies = [
304
+ { name = "click" },
305
+ { name = "filelock" },
306
+ { name = "fsspec" },
307
+ { name = "hf-xet" },
308
+ { name = "httpx2" },
309
+ { name = "packaging" },
310
+ { name = "pyyaml" },
311
+ { name = "tqdm" },
312
+ { name = "typing-extensions" },
313
+ ]
314
+ sdist = { url = "https://files.pythonhosted.org/packages/b5/3b/2fcef1eabe52aec90fc8cd253cc154da1d02a446d7bbcdec59b4a51d4be7/huggingface_hub-2.4.0.tar.gz", hash = "sha256:13a6158b9e3393d9d3f248ce99074d50c2a0a1449fb9d8e2f710751e2084c188", size = 1066194, upload-time = "2026-10-29T15:30:12.321Z" }
315
+ wheels = [
316
+ { url = "https://files.pythonhosted.org/packages/d4/55/ff47f1b082ecf5f43f4bc1e3b932d68eead171dabbbd1a92666c686301d7/huggingface_hub-2.4.0-py3-none-any.whl", hash = "sha256:42ecfd93ede47bdd333daebbf66a32d7bfe2e18752754fe4d2d4f98a0179d801", size = 857021, upload-time = "2026-10-29T15:30:10.421Z" },
317
+ ]
318
+
319
+ [[package]]
320
+ name = "idna"
321
+ version = "3.20"
322
+ source = { registry = "https://pypi.org/simple" }
323
+ sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" }
324
+ wheels = [
325
+ { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" },
326
+ ]
327
+
328
+ [[package]]
329
+ name = "iniconfig"
330
+ version = "2.3.1"
331
+ source = { registry = "https://pypi.org/simple" }
332
+ sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" }
333
+ wheels = [
334
+ { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" },
335
+ ]
336
+
337
+ [[package]]
338
+ name = "jinja2"
339
+ version = "3.1.6"
340
+ source = { registry = "https://pypi.org/simple" }
341
+ dependencies = [
342
+ { name = "markupsafe" },
343
+ ]
344
+ sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" }
345
+ wheels = [
346
+ { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" },
347
+ ]
348
+
349
+ [[package]]
350
+ name = "kiwisolver"
351
+ version = "1.5.1"
352
+ source = { registry = "https://pypi.org/simple" }
353
+ sdist = { url = "https://files.pythonhosted.org/packages/ba/07/bd78e6a8fae171ea041ef5bba3ed21a003522fa088834b069b1909981f30/kiwisolver-1.5.1.tar.gz", hash = "sha256:f1303ef2eec81262a4b708c3e858afe58d7c75ad91c1c05266eda7673369859a", size = 104395, upload-time = "2026-08-28T10:28:27.153Z" }
354
+ wheels = [
355
+ { url = "https://files.pythonhosted.org/packages/fc/f4/dadfec469313c7f428efa7e84b4aba9732f813c13ea7131a24b7b008ef57/kiwisolver-1.5.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34633ecf50d16187ab8e5528b7a2530f2feb4e23f300db4672538b51cfc5cd38", size = 1477929, upload-time = "2026-08-28T10:25:31.495Z" },
356
+ { url = "https://files.pythonhosted.org/packages/ba/d3/024208ec1079d273f1047468d1bdffbf38bb75b7b268090fd3a0301b9d9a/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b03af77d77e50edba2030fd5f7c352ff209314b09030a3cba7c14edf9a09a444", size = 2295200, upload-time = "2026-08-28T10:25:46.984Z" },
357
+ { url = "https://files.pythonhosted.org/packages/6e/7c/7b210498f9f92e1cd7855f260fa69ef056881087b199ee20c208f0e4189a/kiwisolver-1.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:06a6917674de9e0fe3f66f5430787f59a9f2ddb64af9b714eaec547e29ef5c19", size = 70748, upload-time = "2026-08-28T10:25:48.444Z" },
358
+ { url = "https://files.pythonhosted.org/packages/16/45/c37a21ad5c0ab581a93c55ad544721aaa1f0ae94edb29c6a678a23d013e6/kiwisolver-1.5.1-graalpy312-graalpy250_312_native-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:072bdb15a3c19a5b5dbc8f8fb1f4e1884bf4f3507eeb4cc6334401274d37a5c0", size = 194292, upload-time = "2026-08-28T10:28:11.06Z" },
359
+ { url = "https://files.pythonhosted.org/packages/a6/c1/69f00d627949580e43d57af0aa465df46868d7c29801c137a55374101294/kiwisolver-1.5.1-graalpy312-graalpy250_312_native-win_amd64.whl", hash = "sha256:a5a00665d1a0e26763a7338d7e911d4598fbc1d50dd0d6b7919b7dc6c5d6569f", size = 73362, upload-time = "2026-08-28T10:28:12.449Z" },
360
+ ]
361
+
362
+ [[package]]
363
+ name = "markdown-it-py"
364
+ version = "4.3.0"
365
+ source = { registry = "https://pypi.org/simple" }
366
+ dependencies = [
367
+ { name = "mdurl" },
368
+ ]
369
+ sdist = { url = "https://files.pythonhosted.org/packages/16/fc/cee2c45553c9a9bf77d8b0c391560c556d7ed756b1f0bb35eb5d48db09ea/markdown_it_py-4.3.0.tar.gz", hash = "sha256:91a58fa5b72c71a40cf7177250fd767480d7a2bb3ac426ccfb76fb90305fdaaa", size = 242701, upload-time = "2026-11-10T16:18:30.467Z" }
370
+ wheels = [
371
+ { url = "https://files.pythonhosted.org/packages/c9/31/5f0ac2f1a1c67423c995c731a11cd4ad05d081a2be969d74f868bdb9cc70/markdown_it_py-4.3.0-py3-none-any.whl", hash = "sha256:7aa1511a46c39138de78d9eba92ce47e63124d8003fc98b3a351909e04239efa", size = 96951, upload-time = "2026-11-10T16:18:28.975Z" },
372
+ ]
373
+
374
+ [[package]]
375
+ name = "markupsafe"
376
+ version = "3.0.4"
377
+ source = { registry = "https://pypi.org/simple" }
378
+ sdist = { url = "https://files.pythonhosted.org/packages/38/9b/e422a865e1d5d57d0e509b4e0bf1c1a70a7f6382c29a5aa428df994c8bc8/markupsafe-3.0.4.tar.gz", hash = "sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6", size = 153777, upload-time = "2026-10-02T23:07:22.29Z" }
379
+ wheels = [
380
+ { url = "https://files.pythonhosted.org/packages/4f/a7/aeedb5140afa41fc74c225e9184ab96723a6e873b6ee1c9fede7283456d8/markupsafe-3.0.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8e124f974786f831d6043728e38296969d3579db8896fe004682f5758e613581", size = 22985, upload-time = "2026-10-02T23:04:57.521Z" },
381
+ { url = "https://files.pythonhosted.org/packages/0c/fe/fb1e79be0fea60aa32602ebefc9c35a82bb42b4df157285ab7dfec12341a/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c9a7f43c0b202b334cc9184af09bb8f21d3a209e038efaf106936fb69e6b026e", size = 23048, upload-time = "2026-10-02T23:05:04.479Z" },
382
+ { url = "https://files.pythonhosted.org/packages/3f/bf/62495e180b7000aaf30000fff849e933f74264638057176cf46852500adc/markupsafe-3.0.4-cp312-cp312-win_amd64.whl", hash = "sha256:11935df9bf455ed0c04eb87bcd720f02b1fe5e02128a9430f23aed6f93336fc7", size = 14303, upload-time = "2026-10-02T23:05:06.538Z" },
383
+ ]
384
+
385
+ [[package]]
386
+ name = "matplotlib"
387
+ version = "3.11.2"
388
+ source = { registry = "https://pypi.org/simple" }
389
+ dependencies = [
390
+ { name = "contourpy" },
391
+ { name = "cycler" },
392
+ { name = "fonttools" },
393
+ { name = "kiwisolver" },
394
+ { name = "numpy" },
395
+ { name = "packaging" },
396
+ { name = "pillow" },
397
+ { name = "pyparsing" },
398
+ { name = "python-dateutil" },
399
+ ]
400
+ sdist = { url = "https://files.pythonhosted.org/packages/e7/c8/9aa712a0afb882649424dd8de8ad9aa6235e796e84c6052e8f6dc1598d0d/matplotlib-3.11.2.tar.gz", hash = "sha256:cec596316640f2b394b8f0daa0ea61a8eae82d017b620b9f202befb972a59ea4", size = 32660610, upload-time = "2026-09-11T19:05:31.214Z" }
401
+ wheels = [
402
+ { url = "https://files.pythonhosted.org/packages/b8/90/2b3fd67ee273163faeda6d514be70b5596eaa0fd77b60ffc294ad0b34f5f/matplotlib-3.11.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:df4f7784aca81a94f254c0a2767d592ee25f407e488f5fa7203e51093fb6ca27", size = 9860353, upload-time = "2026-09-11T19:03:25.049Z" },
403
+ { url = "https://files.pythonhosted.org/packages/84/39/02e21b74f7439bd643d717ea846006d46e309e6d29b632b57751265311d6/matplotlib-3.11.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3aa4b8516fd26659e4363abbf317c703d9116496c5db2e9d0609a2866dd39dd2", size = 10810580, upload-time = "2026-09-11T19:03:31.402Z" },
404
+ { url = "https://files.pythonhosted.org/packages/04/93/0d239bde12b308262265c2d98909b2f0ecad2b5deeae96241642e822e9c7/matplotlib-3.11.2-cp312-cp312-win_amd64.whl", hash = "sha256:c5c1c68ee401fc98271263410f0e5ce88285abacf7627132914e8adf3d70ff43", size = 9349409, upload-time = "2026-09-11T19:03:34.195Z" },
405
+ ]
406
+
407
+ [[package]]
408
+ name = "mdurl"
409
+ version = "0.1.2"
410
+ source = { registry = "https://pypi.org/simple" }
411
+ sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" }
412
+ wheels = [
413
+ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" },
414
+ ]
415
+
416
+ [[package]]
417
+ name = "mpmath"
418
+ version = "1.3.0"
419
+ source = { registry = "https://pypi.org/simple" }
420
+ sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106, upload-time = "2023-03-07T16:47:11.061Z" }
421
+ wheels = [
422
+ { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" },
423
+ ]
424
+
425
+ [[package]]
426
+ name = "networkx"
427
+ version = "3.7"
428
+ source = { registry = "https://pypi.org/simple" }
429
+ sdist = { url = "https://files.pythonhosted.org/packages/dc/76/3af777226b63a5e64a6b36b1ec5855c14e2b94a37096d4760e595fc43511/networkx-3.7.tar.gz", hash = "sha256:fd77a511bd90f39f3d016351345b52cf5319b813bdca01de3f755d3cca62e96a", size = 1866482, upload-time = "2026-09-21T16:45:16.974Z" }
430
+ wheels = [
431
+ { url = "https://files.pythonhosted.org/packages/7e/cd/fe58041e9011f307c490e3e17dd48cc516448f7c698a3f2d9d9d65d7e6a8/networkx-3.7-py3-none-any.whl", hash = "sha256:e3fd2c13a7814cee3746340d8d7f8598a67f16a58bf47fb7f8793fab6efca1b0", size = 2142205, upload-time = "2026-09-21T16:45:14.609Z" },
432
+ ]
433
+
434
+ [[package]]
435
+ name = "numpy"
436
+ version = "2.5.5"
437
+ source = { registry = "https://pypi.org/simple" }
438
+ sdist = { url = "https://files.pythonhosted.org/packages/4e/3a/8770c288c47f0b5c2a786d3c20e79f66fd245f2d42cd232d7cd5e00e83e5/numpy-2.5.5.tar.gz", hash = "sha256:5cddc243c75114ba845f01b1f87aca1572dbf7b6c2d88636ed3e1d2bccd7f1bf", size = 20873892, upload-time = "2026-11-15T21:32:28.607Z" }
439
+ wheels = [
440
+ { url = "https://files.pythonhosted.org/packages/99/61/522b973ba38987b22a4a71beaed2ea6ac9fd4f687baaa2bc9a45100625e0/numpy-2.5.5-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:704d819265e5d1064d932968e9ee85fff2103ccc78c05b878c06943ba27b8507", size = 15720599, upload-time = "2026-11-15T21:30:21.273Z" },
441
+ { url = "https://files.pythonhosted.org/packages/f3/57/4fa4723e80be805f68af552731ed483974b2a11e511284a9ef6aafbcb3cf/numpy-2.5.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7fb87c4bcc73850ef433a0c42f096b010d3d3d284e9d00028bb030b43df3d078", size = 17082560, upload-time = "2026-11-15T21:30:26.224Z" },
442
+ { url = "https://files.pythonhosted.org/packages/d1/71/b1ce51834c21020d189332979d38ba7350eb6cd7ca8c8ec424a663b0ca6f/numpy-2.5.5-cp312-cp312-win_amd64.whl", hash = "sha256:919eb420662b0b4ba34889df503f3d5329775b0c1d5f7e5f5af4fba8315b1e30", size = 12580189, upload-time = "2026-11-15T21:30:30.025Z" },
443
+ ]
444
+
445
+ [[package]]
446
+ name = "nvidia-cublas"
447
+ version = "13.4.1.3"
448
+ source = { registry = "https://pypi.org/simple" }
449
+ dependencies = [
450
+ { name = "nvidia-cuda-nvrtc" },
451
+ ]
452
+ wheels = [
453
+ { url = "https://files.pythonhosted.org/packages/e1/97/d483a41da34df5c88727c57319576967f6d7befba5028d70928d2999635e/nvidia_cublas-13.4.1.3-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:a5917cb642cfb07f4a0231ee16aec7e2e0357d8cb8b1b78a0c9c68dba3e6afc7", size = 404870805, upload-time = "2026-07-16T09:46:05.62Z" },
454
+ ]
455
+
456
+ [[package]]
457
+ name = "nvidia-cuda-cccl"
458
+ version = "13.3.5.0.6"
459
+ source = { registry = "https://pypi.org/simple" }
460
+ wheels = [
461
+ { url = "https://files.pythonhosted.org/packages/a7/7e/4aa67cca14e0558b5a151a692f5ffe609930cdfc20d16c7a584de68424d4/nvidia_cuda_cccl-13.3.5.0.6-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d5230098fa2df5021e1a00c0c4eee41797671a91119d31e892463e5ccf3ee326", size = 4113651, upload-time = "2026-11-04T23:21:54.262Z" },
462
+ ]
463
+
464
+ [[package]]
465
+ name = "nvidia-cuda-cupti"
466
+ version = "13.2.86"
467
+ source = { registry = "https://pypi.org/simple" }
468
+ wheels = [
469
+ { url = "https://files.pythonhosted.org/packages/b4/76/a10d9fb5d9a0e46d5f95e5520bd1b2d8ad22a9c0a09d2f8c20c5ee842a96/nvidia_cuda_cupti-13.2.86-py3-none-manylinux_2_25_x86_64.whl", hash = "sha256:8fa29f15dd8336181f961764d9d95236fc6b931dd0c8fcf8cd70aab0c310b586", size = 11988600, upload-time = "2026-07-16T09:36:06.061Z" },
470
+ ]
471
+
472
+ [[package]]
473
+ name = "nvidia-cuda-nvrtc"
474
+ version = "13.2.86"
475
+ source = { registry = "https://pypi.org/simple" }
476
+ wheels = [
477
+ { url = "https://files.pythonhosted.org/packages/1e/39/c58835ec8392a91b8d7bad83760eafc3085f64788b722ec2b44a27b3ca3e/nvidia_cuda_nvrtc-13.2.86-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:8111c5130e967b78222ea2124145f8efe9ce201b752b2579a2513100a53be1c5", size = 47018468, upload-time = "2026-07-16T09:40:35.085Z" },
478
+ ]
479
+
480
+ [[package]]
481
+ name = "nvidia-cuda-runtime"
482
+ version = "13.2.86"
483
+ source = { registry = "https://pypi.org/simple" }
484
+ wheels = [
485
+ { url = "https://files.pythonhosted.org/packages/70/c6/8f8c5e893d183082ea78f973aebc7ebc845ee219d68bddac73b0f62490fe/nvidia_cuda_runtime-13.2.86-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3498247680dfddce31bad102af7e3e26fc795342a3cac64722bb0fa95e7f60f0", size = 2323576, upload-time = "2026-07-16T09:33:28.652Z" },
486
+ ]
487
+
488
+ [[package]]
489
+ name = "nvidia-cudnn-cu13"
490
+ version = "9.26.0.51"
491
+ source = { registry = "https://pypi.org/simple" }
492
+ dependencies = [
493
+ { name = "nvidia-cublas" },
494
+ ]
495
+ wheels = [
496
+ { url = "https://files.pythonhosted.org/packages/ac/1b/ea72dd62f26ce3e0a7870b85148b75a5987507629b712deebeb87f7cce9a/nvidia_cudnn_cu13-9.26.0.51-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:9c976d539786698c71d6bcdbe2053b7485fae062ff7e1215d2f2ff67b1a2149a", size = 519150073, upload-time = "2026-09-10T16:47:58.332Z" },
497
+ ]
498
+
499
+ [[package]]
500
+ name = "nvidia-cufft"
501
+ version = "12.2.0.57"
502
+ source = { registry = "https://pypi.org/simple" }
503
+ dependencies = [
504
+ { name = "nvidia-nvjitlink" },
505
+ ]
506
+ wheels = [
507
+ { url = "https://files.pythonhosted.org/packages/41/28/868ed0c6ade5e6a75b25166b3cf191f4a2ff58ad618c1e40befb776c97c5/nvidia_cufft-12.2.0.57-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34da27fadf3979b0b042c43823f0530be8408b86df31ee0108e1ca0b621d4ef6", size = 218258101, upload-time = "2026-07-16T09:47:50.978Z" },
508
+ ]
509
+
510
+ [[package]]
511
+ name = "nvidia-cufile"
512
+ version = "1.17.1.22"
513
+ source = { registry = "https://pypi.org/simple" }
514
+ wheels = [
515
+ { url = "https://files.pythonhosted.org/packages/23/c5/661a73a9042fc5f81cdd5fe6e89f4170b3b33f7962e709987e2b5e5f1381/nvidia_cufile-1.17.1.22-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:87feaf8c3ad20d3d03a01933181801ff6892bace5c8f0b1e4b48f319d3e62d36", size = 1387670, upload-time = "2026-04-13T09:52:57.783Z" },
516
+ ]
517
+
518
+ [[package]]
519
+ name = "nvidia-cusolver"
520
+ version = "12.2.0.11"
521
+ source = { registry = "https://pypi.org/simple" }
522
+ dependencies = [
523
+ { name = "nvidia-cublas" },
524
+ { name = "nvidia-cusparse" },
525
+ { name = "nvidia-nvjitlink" },
526
+ ]
527
+ wheels = [
528
+ { url = "https://files.pythonhosted.org/packages/e4/a4/90f7ade9992190788658c3c285f196fdb9bcc3a5bb93a325c245121d22fd/nvidia_cusolver-12.2.0.11-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:fab5778f6769947389a1a6abc07e635576825a08c0ffc68c3ae7f1392c794b42", size = 227913465, upload-time = "2026-07-16T09:50:56.976Z" },
529
+ ]
530
+
531
+ [[package]]
532
+ name = "nvidia-cusparse"
533
+ version = "12.7.10.12"
534
+ source = { registry = "https://pypi.org/simple" }
535
+ dependencies = [
536
+ { name = "nvidia-nvjitlink" },
537
+ ]
538
+ wheels = [
539
+ { url = "https://files.pythonhosted.org/packages/bc/46/3a9700cc13f30c9279af9a862363535c814fa27597199b21fd93cad66237/nvidia_cusparse-12.7.10.12-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:25907c75e4db1581685f06f61cc6cdecc04611765516a52373e0a18ebd69fa00", size = 150999307, upload-time = "2026-07-16T09:52:17.727Z" },
540
+ ]
541
+
542
+ [[package]]
543
+ name = "nvidia-cusparselt-cu13"
544
+ version = "0.8.1"
545
+ source = { registry = "https://pypi.org/simple" }
546
+ wheels = [
547
+ { url = "https://files.pythonhosted.org/packages/34/7d/2661f2fb3ac4302f3a246f5fc030213ac60c1fe0bce84f9783dbd831dbb7/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_x86_64.whl", hash = "sha256:786ce87568c303fadb5afcc7102d454cd3040d75f6f8626f5db460d1871f4dd0", size = 170148586, upload-time = "2025-09-05T18:50:50.248Z" },
548
+ ]
549
+
550
+ [[package]]
551
+ name = "nvidia-nccl-cu13"
552
+ version = "2.30.7"
553
+ source = { registry = "https://pypi.org/simple" }
554
+ wheels = [
555
+ { url = "https://files.pythonhosted.org/packages/3f/34/c500f90c7ae641b8e0f98965b36b8a7ac79cc8b296e8d251fe3eb592ee54/nvidia_nccl_cu13-2.30.7-py3-none-manylinux_2_18_x86_64.whl", hash = "sha256:cefa7fdb9710efd0f39c5f1be1d61ff6fc9a996c451265bd7fbdcf9455ed4b50", size = 215965170, upload-time = "2026-06-09T03:23:39.73Z" },
556
+ ]
557
+
558
+ [[package]]
559
+ name = "nvidia-nvjitlink"
560
+ version = "13.5.37"
561
+ source = { registry = "https://pypi.org/simple" }
562
+ wheels = [
563
+ { url = "https://files.pythonhosted.org/packages/cc/1f/2321702b8d60b4b4dd18b957f61612dbac9cb1c07e940cf6582106b7c8b8/nvidia_nvjitlink-13.5.37-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:280d7cb9649704145f074b8dbde500de04ce02d0872e066e20a83c17bcaa93eb", size = 46642491, upload-time = "2026-11-04T23:33:31.696Z" },
564
+ ]
565
+
566
+ [[package]]
567
+ name = "nvidia-nvshmem-cu13"
568
+ version = "3.7.2"
569
+ source = { registry = "https://pypi.org/simple" }
570
+ dependencies = [
571
+ { name = "nvidia-cuda-cccl" },
572
+ ]
573
+ wheels = [
574
+ { url = "https://files.pythonhosted.org/packages/4f/4a/037dfbbafc96ad1828ef62326f27970cae2c0eb271cf5b8e6922f32a7427/nvidia_nvshmem_cu13-3.7.2-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b9a4f843c62b5dded8ad33fd6d220e007dcd39f06cee549292f5ba14ce4c235c", size = 135397797, upload-time = "2026-07-17T19:25:26.4Z" },
575
+ ]
576
+
577
+ [[package]]
578
+ name = "nvidia-nvtx"
579
+ version = "13.2.86"
580
+ source = { registry = "https://pypi.org/simple" }
581
+ wheels = [
582
+ { url = "https://files.pythonhosted.org/packages/49/ee/16bde09927e7ffacd50b117cd7d1dc764d145f03249fc41fdf6dfba3301f/nvidia_nvtx-13.2.86-py3-none-manylinux1_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:968ce72baee2a01791c7d3254000eac81f24677b0b91c62d21b449a1f309c245", size = 153463, upload-time = "2026-07-16T09:41:23.242Z" },
583
+ ]
584
+
585
+ [[package]]
586
+ name = "packaging"
587
+ version = "26.4"
588
+ source = { registry = "https://pypi.org/simple" }
589
+ sdist = { url = "https://files.pythonhosted.org/packages/c3/75/ffb1dc0ed12352139fb4ca0e3fde4325a23e3d0f3f40efe89717bc4f557b/packaging-26.4.tar.gz", hash = "sha256:c4b671c41ddb9bf26e543c37723610d28fb6bf7affc4da17cf048d419d2c062a", size = 355877, upload-time = "2026-11-23T21:44:11.152Z" }
590
+ wheels = [
591
+ { url = "https://files.pythonhosted.org/packages/ba/7b/5504f91c9c2733f693d7759e50ede5d27119d4da7e5836c46d3b5ff81d56/packaging-26.4-py3-none-any.whl", hash = "sha256:81383611a09c1bc0b08b76e0fd5829d7c6824c65b27a6aee339da133f4233ea2", size = 140049, upload-time = "2026-11-23T21:44:09.531Z" },
592
+ ]
593
+
594
+ [[package]]
595
+ name = "peft"
596
+ version = "0.22.0"
597
+ source = { registry = "https://pypi.org/simple" }
598
+ dependencies = [
599
+ { name = "accelerate" },
600
+ { name = "huggingface-hub" },
601
+ { name = "numpy" },
602
+ { name = "packaging" },
603
+ { name = "psutil" },
604
+ { name = "pyyaml" },
605
+ { name = "safetensors" },
606
+ { name = "torch" },
607
+ { name = "tqdm" },
608
+ { name = "transformers" },
609
+ ]
610
+ sdist = { url = "https://files.pythonhosted.org/packages/14/47/277ac750804eb771f8b7d3126870c01bb1270121b63e5b0a12e6e19b8fe4/peft-0.22.0.tar.gz", hash = "sha256:e7fca396b98e6c1b0b02538e45efd84875c4d0d074c29c837e372cd7c845647a", size = 1108661, upload-time = "2026-11-19T14:55:41.595Z" }
611
+ wheels = [
612
+ { url = "https://files.pythonhosted.org/packages/60/f2/107e752b64f5636ff92aed4010bad2448d9dd15d9fcf6c1c01b1075dfd76/peft-0.22.0-py3-none-any.whl", hash = "sha256:397f09710e3e1b6ad730211468839aa271732b51a50e99d4f44f2a6e8d9a9f0b", size = 886740, upload-time = "2026-11-19T14:55:39.08Z" },
613
+ ]
614
+
615
+ [[package]]
616
+ name = "pillow"
617
+ version = "13.0.0"
618
+ source = { registry = "https://pypi.org/simple" }
619
+ sdist = { url = "https://files.pythonhosted.org/packages/ce/a4/9cc30690a394a8305e8be4c9036aa16d0dfddadd09079860b582f562496d/pillow-13.0.0.tar.gz", hash = "sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510", size = 47058631, upload-time = "2026-10-16T22:18:09.718Z" }
620
+ wheels = [
621
+ { url = "https://files.pythonhosted.org/packages/e6/99/fdf65cc539e266ab93546c261bdf98411fe165c6e4e13f9dbf597097192b/pillow-13.0.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:42d63be3af4f9b951b199b0a9d23365d37ab14687e6d77b74940432c8515c4ca", size = 7144542, upload-time = "2026-10-16T22:15:50.093Z" },
622
+ { url = "https://files.pythonhosted.org/packages/a8/7c/45ee28531f89ee4582967d8a17f7a26d71ca64cd902b93c269590cd60a00/pillow-13.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:23edf4ec4b6f4f240e8df6e4985e9ee2ced86474632433e55fb1e2548744bf40", size = 7228137, upload-time = "2026-10-16T22:15:54.009Z" },
623
+ { url = "https://files.pythonhosted.org/packages/ff/cd/73a79ecdc822076002eb24b5e1e4a530b0bb5310fcb6d239abbec877110b/pillow-13.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:ff3fe9eb621fbb9db4c4be33ab946f6bac5f98ab50ca8d3260503653656c961b", size = 7272166, upload-time = "2026-10-16T22:15:58.597Z" },
624
+ { url = "https://files.pythonhosted.org/packages/7b/fe/a10aba5503ca13e9e009b8bd0a1a4ce5584bdce246245fd6f3a83701369c/pillow-13.0.0-pp312-pypy312_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e65dd6e75de67b2362a4fa3e16aa627595f65054dc4ec73d64680c84d592fa61", size = 6043514, upload-time = "2026-10-16T22:18:04.538Z" },
625
+ { url = "https://files.pythonhosted.org/packages/c0/37/66b12dc476041fe523bca29c9d58fbf1ea92a4eaf73acfb9e993948f1191/pillow-13.0.0-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:567f20f1c75897d7663830da6ea8af719e03d712b1d9ee7f813319f9ece42e5a", size = 7366030, upload-time = "2026-10-16T22:18:06.638Z" },
626
+ ]
627
+
628
+ [[package]]
629
+ name = "pluggy"
630
+ version = "1.7.0"
631
+ source = { registry = "https://pypi.org/simple" }
632
+ sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" }
633
+ wheels = [
634
+ { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" },
635
+ ]
636
+
637
+ [[package]]
638
+ name = "psutil"
639
+ version = "7.2.2"
640
+ source = { registry = "https://pypi.org/simple" }
641
+ sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740, upload-time = "2026-01-28T18:14:54.428Z" }
642
+ wheels = [
643
+ { url = "https://files.pythonhosted.org/packages/b5/70/5d8df3b09e25bce090399cf48e452d25c935ab72dad19406c77f4e828045/psutil-7.2.2-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9", size = 155560, upload-time = "2026-01-28T18:15:25.976Z" },
644
+ { url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" },
645
+ { url = "https://files.pythonhosted.org/packages/b4/90/e2159492b5426be0c1fef7acba807a03511f97c5f86b3caeda6ad92351a7/psutil-7.2.2-cp37-abi3-win_amd64.whl", hash = "sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988", size = 137737, upload-time = "2026-01-28T18:15:33.849Z" },
646
+ ]
647
+
648
+ [[package]]
649
+ name = "pyarrow"
650
+ version = "26.0.1"
651
+ source = { registry = "https://pypi.org/simple" }
652
+ sdist = { url = "https://files.pythonhosted.org/packages/bc/5e/9cb2a56d5e293aab4e2fbecc5b0620d93227d66b8d5a63c554c31e1f80fe/pyarrow-26.0.1.tar.gz", hash = "sha256:93affcbd8a343e98dc19e9ec8fe17271ebf8fe98102d8b7454175074409f8b72", size = 1237985, upload-time = "2026-11-03T10:54:17.563Z" }
653
+ wheels = [
654
+ { url = "https://files.pythonhosted.org/packages/d3/79/e2fc9b1317b7a21e7bcd57eb035cac3fe72f47af3efe2ec3b4dea9a08a04/pyarrow-26.0.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:c718bf97a92a6dea97fd1062c3b9f9e2e83cb9cc926e752289fa4ffff41738f9", size = 55043763, upload-time = "2026-11-03T10:49:45.732Z" },
655
+ { url = "https://files.pythonhosted.org/packages/d1/b1/c91322fc4c1800c1f7dd78f911b1dd74187acaeb246d86478a0f064f6af5/pyarrow-26.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:73534fbda7f73cab0791b569b93112d4c9e1546cedd0f309d1f69889beb6a08f", size = 58625736, upload-time = "2026-11-03T10:50:01.442Z" },
656
+ { url = "https://files.pythonhosted.org/packages/30/61/d94decccacb4dd40a4ebeed0ff3b2cea8f0b680f50184ea7eb0264db779b/pyarrow-26.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:9379f0d1056cad6866c4697aec83a15830202ec7e0bd52f8bd508b316260fa61", size = 29078866, upload-time = "2026-11-03T10:50:06.854Z" },
657
+ ]
658
+
659
+ [[package]]
660
+ name = "pydantic"
661
+ version = "2.14.4"
662
+ source = { registry = "https://pypi.org/simple" }
663
+ dependencies = [
664
+ { name = "annotated-types" },
665
+ { name = "pydantic-core" },
666
+ { name = "typing-extensions" },
667
+ { name = "typing-inspection" },
668
+ ]
669
+ sdist = { url = "https://files.pythonhosted.org/packages/8e/25/3ec212432a6031b65f043eaca9c820ddf87c0d0aa330023e64f79fcb5db6/pydantic-2.14.4.tar.gz", hash = "sha256:7c19f1d46f8accf55a4617a6116e1ade64840870f397b846a2c53fb9019414ba", size = 927354, upload-time = "2026-11-19T12:57:39.767Z" }
670
+ wheels = [
671
+ { url = "https://files.pythonhosted.org/packages/8a/8c/824a686c4ba815ddb0722f9e66272088bccd4e1ae1d2f7015375e4a4fc7f/pydantic-2.14.4-py3-none-any.whl", hash = "sha256:653a2ad9f6d8858529c77c72717d0ea991d6c6837fe683246b2f4b2bbfc3fadc", size = 494865, upload-time = "2026-11-19T12:57:37.688Z" },
672
+ ]
673
+
674
+ [[package]]
675
+ name = "pydantic-core"
676
+ version = "2.50.5"
677
+ source = { registry = "https://pypi.org/simple" }
678
+ dependencies = [
679
+ { name = "typing-extensions" },
680
+ ]
681
+ sdist = { url = "https://files.pythonhosted.org/packages/fb/63/0ceb815a7762576027ce388544c573d440574f95afb1302a2496b96db548/pydantic_core-2.50.5.tar.gz", hash = "sha256:1e740886083ff95530d694e6a3f09ed914bcf92a496d16acd307c6c3484fc36d", size = 523285, upload-time = "2026-11-19T12:56:38.067Z" }
682
+ wheels = [
683
+ { url = "https://files.pythonhosted.org/packages/be/5b/897bf2e3cc5f65dc01507d90323c13cab659c0432cc3c70b353e5be40f2f/pydantic_core-2.50.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:470bbc2495367f60d3ca849a8039e4c164701d10637e7743f4427d92651bdb6d", size = 2264846, upload-time = "2026-11-19T12:54:13.244Z" },
684
+ { url = "https://files.pythonhosted.org/packages/08/b6/697b1f2af3fc0ea26934dc269458d72ef2340797a9dbe60e79ca36a589f9/pydantic_core-2.50.5-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:3cf575867ecaf89aca440e5a4253d2facf1ca37bab30a4e8c205ec611228126a", size = 2501161, upload-time = "2026-11-19T12:54:18.653Z" },
685
+ { url = "https://files.pythonhosted.org/packages/65/9d/666343e8bf3c1540f82e3a7bd1d3a844746e6827889c9b0a68561795e933/pydantic_core-2.50.5-cp312-cp312-win_amd64.whl", hash = "sha256:baa107902f8e38011a5f79836d905eb6bfaac1d4b0bd09fc86509b711d0b09c8", size = 2269672, upload-time = "2026-11-19T12:54:21.23Z" },
686
+ { url = "https://files.pythonhosted.org/packages/d4/d1/a720b66b4e13e0b5623370bd71b1e376a193d92e20e7dbef7748678c00df/pydantic_core-2.50.5-graalpy312-graalpy250_312_native-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:98b92dad690e6578cc0b504eda53d53adaa4f34bd09c97a547a957e419544eb7", size = 2283625, upload-time = "2026-11-19T12:56:16.458Z" },
687
+ ]
688
+
689
+ [[package]]
690
+ name = "pygments"
691
+ version = "2.21.0"
692
+ source = { registry = "https://pypi.org/simple" }
693
+ sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" }
694
+ wheels = [
695
+ { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" },
696
+ ]
697
+
698
+ [[package]]
699
+ name = "pyparsing"
700
+ version = "3.3.3"
701
+ source = { registry = "https://pypi.org/simple" }
702
+ sdist = { url = "https://files.pythonhosted.org/packages/e4/11/b213bebff182584360cb8d17c72c1677fec5c5c228de439e63bcf8ab1c8f/pyparsing-3.3.3.tar.gz", hash = "sha256:928ae7e20211f3b6f3915a72f06a0cfd29ab9d24279dd6346b6b1a7146397d36", size = 1050487, upload-time = "2026-09-20T20:59:05.609Z" }
703
+ wheels = [
704
+ { url = "https://files.pythonhosted.org/packages/38/bb/d215ee7c73b61497b28a5503f9f53523f294fcc936762b7caf90e0c1c2b5/pyparsing-3.3.3-py3-none-any.whl", hash = "sha256:ece8c00a69cf01b45d0b1dedabb469c90d8caf996d4fda40f147627a122849a4", size = 126420, upload-time = "2026-09-20T20:59:04.025Z" },
705
+ ]
706
+
707
+ [[package]]
708
+ name = "pypdf"
709
+ version = "7.1.1"
710
+ source = { registry = "https://pypi.org/simple" }
711
+ sdist = { url = "https://files.pythonhosted.org/packages/96/5f/f41984a8150ec37c6ee50fa6fa1868d065337b65ba510a155848b2ce0b62/pypdf-7.1.1.tar.gz", hash = "sha256:2eff4e2fc5fb22a6d6711e6f1166cdc9ab5765d90cd0d77dfea3f4aa91a27b1d", size = 7221452, upload-time = "2026-11-18T11:51:08.608Z" }
712
+ wheels = [
713
+ { url = "https://files.pythonhosted.org/packages/5b/ef/11ed995bd10a1632f7fea3da38ae8d42bc3ccc5b9969fe04d8620c844408/pypdf-7.1.1-py3-none-any.whl", hash = "sha256:04c5680d4b4cfa04ab505b09393fc949860c34a4dad6565284d11a2f5c3ce8b1", size = 421026, upload-time = "2026-11-18T11:51:06.563Z" },
714
+ ]
715
+
716
+ [[package]]
717
+ name = "pytest"
718
+ version = "9.2.0"
719
+ source = { registry = "https://pypi.org/simple" }
720
+ dependencies = [
721
+ { name = "colorama", marker = "sys_platform == 'win32'" },
722
+ { name = "iniconfig" },
723
+ { name = "packaging" },
724
+ { name = "pluggy" },
725
+ { name = "pygments" },
726
+ ]
727
+ sdist = { url = "https://files.pythonhosted.org/packages/79/42/bb4641652e58dedeac2ec51abc1f8cae4fee4ec63899a0999016229a0f2a/pytest-9.2.0.tar.gz", hash = "sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b", size = 1797555, upload-time = "2026-10-27T21:30:20.728Z" }
728
+ wheels = [
729
+ { url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" },
730
+ ]
731
+
732
+ [[package]]
733
+ name = "python-dateutil"
734
+ version = "4.0.0"
735
+ source = { registry = "https://pypi.org/simple" }
736
+ dependencies = [
737
+ { name = "tzdata" },
738
+ ]
739
+ sdist = { url = "https://files.pythonhosted.org/packages/18/39/b3927f3616f6223832f9b760e4208e8a7c7e1dea2b4d9ad7d32a5d214c3a/python_dateutil-4.0.0.tar.gz", hash = "sha256:d7295ff14fdc0f92f662100bfb6c551d160ca090f2939f1ec5b9794265c03f06", size = 250419, upload-time = "2026-11-01T07:02:42.426Z" }
740
+ wheels = [
741
+ { url = "https://files.pythonhosted.org/packages/2f/a9/52b89563d154433d79b51ed1eb4842bf7334cb2696891a7fe135618853d7/python_dateutil-4.0.0-py3-none-any.whl", hash = "sha256:a5e246f79eb80475e691bf93862cead98decd8a498cf53ba0516fcdc0f50dc1c", size = 92853, upload-time = "2026-11-01T07:02:40.797Z" },
742
+ ]
743
+
744
+ [[package]]
745
+ name = "python-dotenv"
746
+ version = "1.2.4"
747
+ source = { registry = "https://pypi.org/simple" }
748
+ sdist = { url = "https://files.pythonhosted.org/packages/74/26/2fbeedb218a787a5eea551c7532cac4e009f83d689dd2faa0d0353473f86/python_dotenv-1.2.4.tar.gz", hash = "sha256:f0d53e69935a851c0dcc78f3ab7aaccd8cabef0b92382b576b824212902873c0", size = 60824, upload-time = "2026-10-01T05:36:10Z" }
749
+ wheels = [
750
+ { url = "https://files.pythonhosted.org/packages/60/d1/38f3a3405989a89ac18390803e70c6ad7c7760da4f9b83cbeca0c44a0c72/python_dotenv-1.2.4-py3-none-any.whl", hash = "sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc", size = 23266, upload-time = "2026-10-01T05:36:08.633Z" },
751
+ ]
752
+
753
+ [[package]]
754
+ name = "pyyaml"
755
+ version = "6.0.4"
756
+ source = { registry = "https://pypi.org/simple" }
757
+ sdist = { url = "https://files.pythonhosted.org/packages/76/b8/c0b780928e2fb1c87e9e375818c6f121da2398b071012d1747be300b83f4/pyyaml-6.0.4.tar.gz", hash = "sha256:e24bf71af8a432d7808fabff134d38dfe16d3cbb41f2873bb4b1e42422de0a1a", size = 136336, upload-time = "2026-11-20T23:37:05.977Z" }
758
+ wheels = [
759
+ { url = "https://files.pythonhosted.org/packages/94/80/1d27f7084b983b7cfd1fb35e65a38276d9eddfdcdabc0922bb26cf9521bc/pyyaml-6.0.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:93bfb2459195406a518e2f487a9bbf01df240175f31e06f5a252ac6734c7bbf0", size = 849249, upload-time = "2026-11-20T23:35:05.457Z" },
760
+ { url = "https://files.pythonhosted.org/packages/05/bb/f7df529541b98113bea84129a78f93c3889acb08385ca25f9786823dce67/pyyaml-6.0.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f5c410f9e2ffc9286279a46f2e8c107edaf3b1123510af59c828a9c15b23c9db", size = 825424, upload-time = "2026-11-20T23:35:07.783Z" },
761
+ { url = "https://files.pythonhosted.org/packages/a3/95/307a6ceafbad9a08300743d19329c31726224e583e05c4fe5358522ba283/pyyaml-6.0.4-cp312-cp312-win_amd64.whl", hash = "sha256:131d11bd9b60d705a6388366d77ed67850995a4d2be85fe149785a257c17e531", size = 154452, upload-time = "2026-11-20T23:35:09.792Z" },
762
+ ]
763
+
764
+ [[package]]
765
+ name = "regex"
766
+ version = "2026.11.24"
767
+ source = { registry = "https://pypi.org/simple" }
768
+ sdist = { url = "https://files.pythonhosted.org/packages/e7/32/7c768de6489417ef32a49480af8a2dfba3adc5b1784d6e7142f32972018a/regex-2026.11.24.tar.gz", hash = "sha256:07f222de81cdcfd39eef8671e92d14f50f61f1666f756659b0e649cf700b1b10", size = 421559, upload-time = "2026-11-25T03:28:00.709Z" }
769
+ wheels = [
770
+ { url = "https://files.pythonhosted.org/packages/d8/fe/4d4c3a77bfc51ac4da7b2b30af8cc50bf6ee63b1f28a41cf4d36c82691c1/regex-2026.11.24-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0778f76a63e677ef022087a6a49c9b82de9bb1916bd7402a25abfe9f66bdd97f", size = 813229, upload-time = "2026-11-25T03:25:57.986Z" },
771
+ { url = "https://files.pythonhosted.org/packages/a0/bb/615cdb1102499d46bffef1b172f613accf2c1821c3e9dd4045d38025d7f2/regex-2026.11.24-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3ffc2fd4230ea139c9a8e4fe97d559c5ac1ae7cdf3cd0f489d5d2053b219a310", size = 800329, upload-time = "2026-11-25T03:26:05.757Z" },
772
+ { url = "https://files.pythonhosted.org/packages/99/59/108649b133bdefd33e0e53a3dd3a8e9ee5153c86bbc418334b25f40532b8/regex-2026.11.24-cp312-cp312-win_amd64.whl", hash = "sha256:4ee28b825b3544872b1c42914709a45ddd378154c7e58df1cf8a732134e315b2", size = 280826, upload-time = "2026-11-25T03:26:07.985Z" },
773
+ ]
774
+
775
+ [[package]]
776
+ name = "reportlab"
777
+ version = "5.1.1"
778
+ source = { registry = "https://pypi.org/simple" }
779
+ dependencies = [
780
+ { name = "charset-normalizer" },
781
+ { name = "pillow" },
782
+ ]
783
+ sdist = { url = "https://files.pythonhosted.org/packages/71/eb/176ef5717ebf0af4745a64501ff0d925341e9ae5560fa369bf20ec37abd8/reportlab-5.1.1.tar.gz", hash = "sha256:4bc6d7e5a961cabd320850637fa469c81dd9d6e32d0fe4191446086c6ea9a8d3", size = 4110241, upload-time = "2026-11-24T16:12:59.636Z" }
784
+ wheels = [
785
+ { url = "https://files.pythonhosted.org/packages/35/40/3b11dfcb2443a90c01f45e87c6e72f79bae3405a08bb9df61784f563f8af/reportlab-5.1.1-py3-none-any.whl", hash = "sha256:43af899b836179032807f68aa83b410182e8e6b1221e4339560c5ec44da843ab", size = 2015997, upload-time = "2026-11-24T16:13:20.33Z" },
786
+ ]
787
+
788
+ [[package]]
789
+ name = "rich"
790
+ version = "15.0.0"
791
+ source = { registry = "https://pypi.org/simple" }
792
+ dependencies = [
793
+ { name = "markdown-it-py" },
794
+ { name = "pygments" },
795
+ ]
796
+ sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" }
797
+ wheels = [
798
+ { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" },
799
+ ]
800
+
801
+ [[package]]
802
+ name = "safetensors"
803
+ version = "0.8.0"
804
+ source = { registry = "https://pypi.org/simple" }
805
+ sdist = { url = "https://files.pythonhosted.org/packages/45/06/f955dbbb1859e3bd23c8ac6141af5106e7ad5fedec4a3a6e3d60f94b7001/safetensors-0.8.0.tar.gz", hash = "sha256:fabaf3e0f18a6618d9b36560682562157f77c2b71fcffc7b432be2baed9d753d", size = 325846, upload-time = "2026-06-09T07:52:25.563Z" }
806
+ wheels = [
807
+ { url = "https://files.pythonhosted.org/packages/28/50/f203ff3a3ddfe19308efc83c5a3a29ed02bf786732ec35e68bf9162f3365/safetensors-0.8.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd6f3f93c9a0a7cc2788ee63fb763353d4bd2e89b0751bc78fcf7dda00bea774", size = 516040, upload-time = "2026-06-09T07:52:16.29Z" },
808
+ { url = "https://files.pythonhosted.org/packages/27/43/41c1621732edd934d868a00d1b891584c892a7b62a9aab82ea5a0a5623ee/safetensors-0.8.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8e080062fcde23be189565e1c3305d16751a218ecf9412c8601e64204eb6f846", size = 722361, upload-time = "2026-06-09T07:52:23.924Z" },
809
+ { url = "https://files.pythonhosted.org/packages/1b/6d/3fba214c1e5e0f69991677ec3bc17023f0421776975e1de0c682dca475e2/safetensors-0.8.0-cp310-abi3-win_amd64.whl", hash = "sha256:096ec1a98435df7beb08853bb5aa9081a84f23d0adc67ed1a0a10550f608373f", size = 355540, upload-time = "2026-06-09T07:52:27.832Z" },
810
+ ]
811
+
812
+ [[package]]
813
+ name = "scipy"
814
+ version = "1.18.1"
815
+ source = { registry = "https://pypi.org/simple" }
816
+ dependencies = [
817
+ { name = "numpy" },
818
+ ]
819
+ sdist = { url = "https://files.pythonhosted.org/packages/7e/74/66de6258867beb2ef08f35f9f2ac017a52cacd5081714d239ff1a442d458/scipy-1.18.1.tar.gz", hash = "sha256:52c4b7422442aba924d03ad4019852b08a92e64ea187b933135687bfe2747307", size = 30781235, upload-time = "2026-08-21T23:28:50.599Z" }
820
+ wheels = [
821
+ { url = "https://files.pythonhosted.org/packages/df/64/ff35eb9e54894cf471ff4716abd3c81eb0a0626869217ce3e6ba4ccf17d7/scipy-1.18.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f55fa87b6c612ecd6b058f167c53231b1d14e412efe361d3d6e38b3631c73218", size = 35344199, upload-time = "2026-08-21T23:24:07.844Z" },
822
+ { url = "https://files.pythonhosted.org/packages/91/4c/075e4f66471bac101141ac739e9e135549be1bae584571bd03a530c056e1/scipy-1.18.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d2924a03db38dc2e848bca2fe9f077dafb891480b91a00a0963a8cf86dfc31c1", size = 37480330, upload-time = "2026-08-21T23:24:19.608Z" },
823
+ { url = "https://files.pythonhosted.org/packages/39/e7/979fd14e75008623df31ba70d6bb144700f68feadcea042021c06a05bf82/scipy-1.18.1-cp312-cp312-win_amd64.whl", hash = "sha256:5e4d44984abc0020154ea81b247adeddcc3ac5527b975ff798bd1ba0adc513c2", size = 36658278, upload-time = "2026-08-21T23:24:25.463Z" },
824
+ ]
825
+
826
+ [[package]]
827
+ name = "setuptools"
828
+ version = "84.2.1"
829
+ source = { registry = "https://pypi.org/simple" }
830
+ sdist = { url = "https://files.pythonhosted.org/packages/70/b3/c19426f783614d625699a4b247faf628ea9ab1db228674491767b417f9e1/setuptools-84.2.1.tar.gz", hash = "sha256:3ff8b3b5492a0aa66960f4419365a86b84e013070d4313e4d4a6894f5d64d6bc", size = 1230289, upload-time = "2026-10-20T19:01:37.742Z" }
831
+ wheels = [
832
+ { url = "https://files.pythonhosted.org/packages/ef/55/6dc6d6bb953bdfc52519a0059592c52b6e3b8ad51cf8256dffceb55b0610/setuptools-84.2.1-py3-none-any.whl", hash = "sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2", size = 876263, upload-time = "2026-10-20T19:01:35.678Z" },
833
+ ]
834
+
835
+ [[package]]
836
+ name = "shellingham"
837
+ version = "1.5.4"
838
+ source = { registry = "https://pypi.org/simple" }
839
+ sdist = { url = "https://files.pythonhosted.org/packages/58/15/8b3609fd3830ef7b27b655beb4b4e9c62313a4e8da8c676e142cc210d58e/shellingham-1.5.4.tar.gz", hash = "sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de", size = 10310, upload-time = "2023-10-24T04:13:40.426Z" }
840
+ wheels = [
841
+ { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" },
842
+ ]
843
+
844
+ [[package]]
845
+ name = "sympy"
846
+ version = "1.14.0"
847
+ source = { registry = "https://pypi.org/simple" }
848
+ dependencies = [
849
+ { name = "mpmath" },
850
+ ]
851
+ sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" }
852
+ wheels = [
853
+ { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" },
854
+ ]
855
+
856
+ [[package]]
857
+ name = "thirdloss"
858
+ version = "0.1.0"
859
+ source = { editable = "." }
860
+ dependencies = [
861
+ { name = "filelock" },
862
+ { name = "httpx" },
863
+ { name = "huggingface-hub" },
864
+ { name = "matplotlib" },
865
+ { name = "numpy" },
866
+ { name = "peft" },
867
+ { name = "pyarrow" },
868
+ { name = "python-dotenv" },
869
+ { name = "reportlab" },
870
+ { name = "safetensors" },
871
+ { name = "scipy" },
872
+ { name = "tokenizers" },
873
+ { name = "torch" },
874
+ { name = "transformers" },
875
+ ]
876
+
877
+ [package.dev-dependencies]
878
+ dev = [
879
+ { name = "pypdf" },
880
+ { name = "pytest" },
881
+ ]
882
+
883
+ [package.metadata]
884
+ requires-dist = [
885
+ { name = "filelock", specifier = ">=3" },
886
+ { name = "httpx", specifier = ">=0.27" },
887
+ { name = "huggingface-hub", specifier = ">=1" },
888
+ { name = "matplotlib", specifier = ">=3.10" },
889
+ { name = "numpy", specifier = ">=2" },
890
+ { name = "peft", specifier = ">=0.22,<1" },
891
+ { name = "pyarrow", specifier = ">=20" },
892
+ { name = "python-dotenv", specifier = ">=1" },
893
+ { name = "reportlab", specifier = ">=4" },
894
+ { name = "safetensors", specifier = ">=0.5" },
895
+ { name = "scipy", specifier = ">=1.14" },
896
+ { name = "tokenizers", specifier = ">=0.22" },
897
+ { name = "torch", specifier = "==2.15.0", index = "https://download.pytorch.org/whl/cu132" },
898
+ { name = "transformers", specifier = ">=5.24,<6" },
899
+ ]
900
+
901
+ [package.metadata.requires-dev]
902
+ dev = [
903
+ { name = "pypdf", specifier = ">=5" },
904
+ { name = "pytest", specifier = ">=8" },
905
+ ]
906
+
907
+ [[package]]
908
+ name = "tokenizers"
909
+ version = "0.23.3"
910
+ source = { registry = "https://pypi.org/simple" }
911
+ dependencies = [
912
+ { name = "huggingface-hub" },
913
+ ]
914
+ sdist = { url = "https://files.pythonhosted.org/packages/e0/7c/2cabb2174e772636683008f2c5621949b645da7d303c596589e84516a184/tokenizers-0.23.3.tar.gz", hash = "sha256:cded33237c77caeef62944d32aa9a7ef42bdce2b3497e18d137e072a8c4be438", size = 385286, upload-time = "2026-10-09T10:16:55.759Z" }
915
+ wheels = [
916
+ { url = "https://files.pythonhosted.org/packages/3a/40/6706b82693715581457c6d5423eaa7faae576bb0526c5738a57085eb4449/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:376851d22bcf9d650a5c3090bb83e6cf9e895fbf0595369fa4cd43c1f69b5f87", size = 3396193, upload-time = "2026-10-09T10:01:05.48Z" },
917
+ { url = "https://files.pythonhosted.org/packages/26/e5/065625317690ea3548d834dad81f48ea1fd32e4964610e658e195d7fe28e/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e05ab7baf7f47b406a95fea6f3b0a484b2ddcd9e1d14b68844c457eb755085a3", size = 10266026, upload-time = "2026-10-09T10:16:33.054Z" },
918
+ { url = "https://files.pythonhosted.org/packages/d1/6c/24f074c9a0efb98e61b20aafe6b2641922d5db24e447d5d6daffd9e17555/tokenizers-0.23.3-cp310-abi3-win_amd64.whl", hash = "sha256:1f0823bb00c5fdc98e487354d54dd55a03848d61a1a0bf29a68c77f24f3b26c3", size = 2872101, upload-time = "2026-10-09T10:16:37.533Z" },
919
+ ]
920
+
921
+ [[package]]
922
+ name = "torch"
923
+ version = "2.15.0+cu132"
924
+ source = { registry = "https://download.pytorch.org/whl/cu132" }
925
+ dependencies = [
926
+ { name = "cuda-bindings", marker = "sys_platform != 'win32'" },
927
+ { name = "cuda-toolkit", extra = ["cublas", "cudart", "cufft", "cufile", "cupti", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "sys_platform != 'win32'" },
928
+ { name = "filelock" },
929
+ { name = "fsspec" },
930
+ { name = "jinja2" },
931
+ { name = "networkx" },
932
+ { name = "nvidia-cudnn-cu13", marker = "sys_platform != 'win32'" },
933
+ { name = "nvidia-cusparselt-cu13", marker = "sys_platform != 'win32'" },
934
+ { name = "nvidia-nccl-cu13", marker = "sys_platform != 'win32'" },
935
+ { name = "nvidia-nvshmem-cu13", marker = "sys_platform != 'win32'" },
936
+ { name = "setuptools" },
937
+ { name = "sympy" },
938
+ { name = "triton", marker = "sys_platform != 'win32'" },
939
+ { name = "typing-extensions" },
940
+ ]
941
+ wheels = [
942
+ { url = "https://download-r2.pytorch.org/whl/cu132/torch-2.15.0%2Bcu132-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:84936484ed0a2e55fc89f29c7e580be2eff4fb4c9c2c46c88849cf8062281f96", upload-time = "2026-10-28T13:23:20Z" },
943
+ { url = "https://download-r2.pytorch.org/whl/cu132/torch-2.15.0%2Bcu132-cp312-cp312-win_amd64.whl", hash = "sha256:14424b1514fc10a8a2352710234869c9af86a9223b582c3767b7512ec038f979", upload-time = "2026-10-28T13:24:14Z" },
944
+ ]
945
+
946
+ [[package]]
947
+ name = "tqdm"
948
+ version = "4.70.1"
949
+ source = { registry = "https://pypi.org/simple" }
950
+ dependencies = [
951
+ { name = "colorama", marker = "sys_platform == 'win32'" },
952
+ ]
953
+ sdist = { url = "https://files.pythonhosted.org/packages/0d/ea/b2a5bd54b28a324dae8211928b2d730b6547500342c7e6c6dea08bd0a485/tqdm-4.70.1.tar.gz", hash = "sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4", size = 171846, upload-time = "2026-09-11T07:25:16.601Z" }
954
+ wheels = [
955
+ { url = "https://files.pythonhosted.org/packages/a7/03/921a3d3c75785aca9ebfbfcabfbc3a1be12e2ab5265deb026d55a5a3f83e/tqdm-4.70.1-py3-none-any.whl", hash = "sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73", size = 80199, upload-time = "2026-09-11T07:25:14.599Z" },
956
+ ]
957
+
958
+ [[package]]
959
+ name = "transformers"
960
+ version = "5.24.1"
961
+ source = { registry = "https://pypi.org/simple" }
962
+ dependencies = [
963
+ { name = "huggingface-hub" },
964
+ { name = "numpy" },
965
+ { name = "packaging" },
966
+ { name = "pyyaml" },
967
+ { name = "regex" },
968
+ { name = "safetensors" },
969
+ { name = "tokenizers" },
970
+ { name = "tqdm" },
971
+ { name = "typer" },
972
+ ]
973
+ sdist = { url = "https://files.pythonhosted.org/packages/cb/35/b341c8fddb57f9b404438d048ff0d41d6523b3c6440f8eeed0bb3f4e1725/transformers-5.24.1.tar.gz", hash = "sha256:71fae247d9ad61f553fb84de2089f427f5ff2c080686f9deb51e660487e8c270", size = 10758394, upload-time = "2026-11-24T16:11:46.481Z" }
974
+ wheels = [
975
+ { url = "https://files.pythonhosted.org/packages/1c/45/8aa25aeec09086bfd5fa094b91917ff52025c55907363fc94022eac4a0df/transformers-5.24.1-py3-none-any.whl", hash = "sha256:505b39d3e45a3715f3acb81b858eb245ce1a462373b7f99e26f0dcd41ed4cd0f", size = 13556588, upload-time = "2026-11-24T16:11:43.459Z" },
976
+ ]
977
+
978
+ [[package]]
979
+ name = "triton"
980
+ version = "3.9.0"
981
+ source = { registry = "https://pypi.org/simple" }
982
+ wheels = [
983
+ { url = "https://files.pythonhosted.org/packages/3f/c9/af85b25e0d98bd921a7646ad1db1c8746250ee04b8f1595982d29b6283cf/triton-3.9.0-cp312-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5e52ab4e2f1d64f0ac494c9aa723697b793f81a91c4cae4c36608ca0bc4267bf", size = 285674620, upload-time = "2026-10-27T18:28:11.992Z" },
984
+ ]
985
+
986
+ [[package]]
987
+ name = "truststore"
988
+ version = "0.10.5"
989
+ source = { registry = "https://pypi.org/simple" }
990
+ sdist = { url = "https://files.pythonhosted.org/packages/ee/9f/c5201d42a484c061e528825fc8e2d565f5abd50a4ced6fb7d29c4ec99b2b/truststore-0.10.5.tar.gz", hash = "sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd", size = 28091, upload-time = "2026-10-12T22:27:31.808Z" }
991
+ wheels = [
992
+ { url = "https://files.pythonhosted.org/packages/51/e9/3a7820be2bb0fe53b6bc9c3be26d3d1158004e4c3ab953aa6840b955b1e9/truststore-0.10.5-py3-none-any.whl", hash = "sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c", size = 19017, upload-time = "2026-10-12T22:27:30.377Z" },
993
+ ]
994
+
995
+ [[package]]
996
+ name = "typer"
997
+ version = "0.29.2"
998
+ source = { registry = "https://pypi.org/simple" }
999
+ dependencies = [
1000
+ { name = "annotated-doc" },
1001
+ { name = "colorama", marker = "sys_platform == 'win32'" },
1002
+ { name = "pydantic" },
1003
+ { name = "rich" },
1004
+ { name = "shellingham" },
1005
+ ]
1006
+ sdist = { url = "https://files.pythonhosted.org/packages/bf/21/37383ece7d0a4995fb8ea97729207c4292b3ff94085002f37b2387063cfb/typer-0.29.2.tar.gz", hash = "sha256:b1998dc5f2c3dedafa1517a9521fa944cc4dc1fadcea085d81a3b10ebcaeb075", size = 205728, upload-time = "2026-11-18T11:09:46.189Z" }
1007
+ wheels = [
1008
+ { url = "https://files.pythonhosted.org/packages/62/f3/864dcb0e165b52e9f75aa3c7e0aeeb9876f139c66eb14d87856bb173b0fa/typer-0.29.2-py3-none-any.whl", hash = "sha256:f30731f8ca758368b836b3714872e58e395cef8fcaff918c853b1969ed5274e7", size = 121041, upload-time = "2026-11-18T11:09:45.03Z" },
1009
+ ]
1010
+
1011
+ [[package]]
1012
+ name = "typing-extensions"
1013
+ version = "4.16.0"
1014
+ source = { registry = "https://pypi.org/simple" }
1015
+ sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" }
1016
+ wheels = [
1017
+ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" },
1018
+ ]
1019
+
1020
+ [[package]]
1021
+ name = "typing-inspection"
1022
+ version = "0.4.5"
1023
+ source = { registry = "https://pypi.org/simple" }
1024
+ dependencies = [
1025
+ { name = "typing-extensions" },
1026
+ ]
1027
+ sdist = { url = "https://files.pythonhosted.org/packages/ff/50/0195198eb1d75bab716bb0a813abea4cc394bfa17a92a189f021a34859af/typing_inspection-0.4.5.tar.gz", hash = "sha256:7f16c411e7930dc79596d42ab44672a3fe5f60eb34b781a1647e7872363120c7", size = 81194, upload-time = "2026-11-04T14:13:23.774Z" }
1028
+ wheels = [
1029
+ { url = "https://files.pythonhosted.org/packages/de/0c/ea2544850a7c135e15033a5c7a8e7211136184b7ae63e2239d557c2b3019/typing_inspection-0.4.5-py3-none-any.whl", hash = "sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39", size = 14874, upload-time = "2026-11-04T14:13:22.616Z" },
1030
+ ]
1031
+
1032
+ [[package]]
1033
+ name = "tzdata"
1034
+ version = "2026.6"
1035
+ source = { registry = "https://pypi.org/simple" }
1036
+ sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" }
1037
+ wheels = [
1038
+ { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" },
1039
+ ]