BurnyCoder commited on
Commit
27edc4f
·
verified ·
1 Parent(s): 7d6dc2a

Explain how the tested curvature penalty can favor a flat minimum

Browse files
.gitattributes CHANGED
@@ -35,3 +35,4 @@ saved_model/**/* 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
37
  research/docs/figures/curves.png 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
37
  research/docs/figures/curves.png filter=lfs diff=lfs merge=lfs -text
38
+ research/docs/figures/penalty-directions.png filter=lfs diff=lfs merge=lfs -text
research/README.md CHANGED
@@ -1,21 +1,32 @@
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
- | Hessian penalties in language models | Zhang, Li and Ju approximate a Hessian-trace penalty with symmetric weight perturbations when fine-tuning GPT-2 on CommonsenseQA and StrategyQA. Liu, Yu and Lin add a signed trace term in WikiText-2 LSTM and GRU experiments. | [GPT-2 experiments, Table 5](https://arxiv.org/pdf/2306.08553#page=12) · [Noise stability optimization code](https://github.com/VirtuosoResearch/Noise-stability-optimization) · [Recurrent LM penalty, §5.2](https://arxiv.org/pdf/2208.05924) |
11
  | Other uses of Hessians in LLMs | Sophia uses stochastic curvature estimates to precondition GPT training updates. Liu et al. measure Hessian trace and study the downstream behavior of pretrained language models. | [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) |
12
  | 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) |
13
  | 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) |
14
  | 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) |
 
15
 
16
- 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.
17
-
18
- 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. [Worked examples and the training implementation](docs/third-derivative-penalty.md) · [Duchon](https://doi.org/10.1007/BFb0086566) · [Bujanović and Kressner](https://arxiv.org/pdf/2004.06433) · [Hessian comparator](https://arxiv.org/pdf/2208.05924)
19
 
20
  The protocol and run matrix were published before model execution. The scores, comparisons and continuations below are regenerated from each run’s raw records. [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)
21
 
 
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 the squared third derivatives of next-token loss. It trains a TinyStories decoder from scratch and fine-tunes Pythia-410M’s low-rank attention adapters on research abstracts. [Study design](reports/planned-runs.md)
4
+
5
+ ## Can the penalty favor a wider minimum?
6
+
7
+ A minimum is **wide** if the weights can move a long way before the loss rises by a chosen amount. Near a smooth minimum, the Hessian trace predicts the average loss increase from a small nudge in a uniformly random direction. The third derivative measures **how curvature changes** as weights move. If curvature starts small and changes slowly nearby, the loss can stay low over a larger distance. [Basin width, Definition 1](https://proceedings.mlr.press/v70/dinh17b/dinh17b.pdf#page=2) · [Hessian and random perturbations, equation 4](https://arxiv.org/pdf/2306.08553#page=5)
8
+
9
+ The penalty can help weights **stay** near a flat bottom. For $L(w)=w^4$, nudging the weight to either side makes the penalty rise, so a small descent step pulls it back. A steep quadratic such as $L(w)=100w^2$ has constant curvature and receives zero third-derivative penalty everywhere. [Worked examples](docs/third-derivative-penalty.md#when-can-the-penalty-favor-a-wider-minimum)
10
+
11
+ In the language models, an active update measures curvature change for the next-token cross-entropy of **two text windows**, with respect to all decoder weights for TinyStories or only the adapter weights for Pythia. Differentiating this penalty gives AdamW a fourth-derivative contribution. Whether the models **find wider minima** is a hypothesis. The registered comparison tests whether they predict held-out tokens better at equal training-token counts. [Training update](docs/third-derivative-penalty.md#the-actual-training-update) · [Preregistration](reports/preregistration.md)
12
+
13
+ ![One-weight loss and penalty curves. At the asymmetric minimum the trace pushes left and the third-derivative penalty pushes right. In the quartic both pull displaced weights back. In the steep quadratic both penalty curves are constant.](docs/figures/penalty-directions.png)
14
+
15
+ *Analytic examples. The circles mark the ordinary loss minima. Arrows show downhill directions for the two penalties. Each panel has its own vertical scale.*
16
 
17
  ## Flat minima, Hessians and third derivatives in earlier work
18
 
19
  | Setting | What the researchers used the derivatives for | Original papers and projects |
20
  |---|---|---|
21
  | 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/) |
22
+ | Hessian penalties in language models | Zhang, Li and Ju approximate a Hessian-trace penalty with symmetric weight perturbations when fine-tuning GPT-2 on CommonsenseQA and StrategyQA. Liu, Yu and Lin propose a signed trace objective and report WikiText-2 LSTM and GRU experiments. | [GPT-2 experiments, Table 5](https://arxiv.org/pdf/2306.08553#page=12) · [Noise stability optimization code](https://github.com/VirtuosoResearch/Noise-stability-optimization) · [Recurrent LM penalty, §5.2](https://arxiv.org/pdf/2208.05924) |
23
  | Other uses of Hessians in LLMs | Sophia uses stochastic curvature estimates to precondition GPT training updates. Liu et al. measure Hessian trace and study the downstream behavior of pretrained language models. | [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) |
24
  | 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) |
25
  | 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) |
26
  | 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) |
27
+ | Third derivatives in image classifiers | Grad-CAM++ uses diagonal third derivatives of a class score with respect to convolutional feature activations to locate image regions that contribute to a prediction. | [Chattopadhyay et al., equation 10](https://arxiv.org/pdf/1710.11063#page=4) · [Authors’ implementation](https://github.com/adityac94/Grad_CAM_plus_plus) |
28
 
29
+ Two independent random sign vectors estimate the squared Frobenius norm of the minibatch third derivative, including mixed partials between different weights. [Estimator derivation](docs/third-derivative-penalty.md#why-two-independent-sign-vectors-work-for-any-smooth-loss) · [Duchon](https://doi.org/10.1007/BFb0086566) · [Bujanović and Kressner](https://arxiv.org/pdf/2004.06433)
 
 
30
 
31
  The protocol and run matrix were published before model execution. The scores, comparisons and continuations below are regenerated from each run’s raw records. [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)
32
 
research/docs/figures/penalty-directions.png ADDED

Git LFS Details

  • SHA256: c0a16ca06b027e3ef397dc4f4553961c1e786af3c79cac80905bc04428282ff4
  • Pointer size: 131 Bytes
  • Size of remote file: 156 kB
research/docs/index.html CHANGED
@@ -1,106 +1,109 @@
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 id="download-records" href="study.json">Download displayed records</a></footer>
105
- </body>
106
- </html>
 
 
 
 
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. On active updates, two independent random sign vectors estimate how quickly that curvature changes for the next-token loss of two text windows. The derivatives cover all TinyStories decoder weights or only Pythia’s trainable attention adapters, including interactions between trainable weights.</p>
96
+ <p class="prose">When moving away from a flat bottom makes curvature change faster, the third-derivative penalty can pull the weights back. A steep bowl with constant curvature receives zero penalty from this term. Whether the optimizer finds wider minima is a separate question from the measured next-token loss.</p>
97
+ <img class="architecture" src="figures/penalty-directions.png" alt="Analytic loss curves. Trace and third-derivative penalties push in opposite directions at an asymmetric minimum. They pull displaced weights back in a flat quartic and give zero update in a steep quadratic." loading="lazy">
98
+ <p class="curve-note">Circles mark the ordinary loss minima. Arrows show downhill directions for each penalty. The vertical scales vary by panel. <a href="https://github.com/BurnyCoder/llm-training-with-penalizing-rapid-changes-of-curvature-of-its-loss/blob/main/docs/third-derivative-penalty.md#when-can-the-penalty-favor-a-wider-minimum">Worked examples and the basin-width bound ↗</a></p>
99
+ <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">
100
+ <div class="method-links">
101
+ <a href="https://doi.org/10.1007/BFb0086566">Derivative roughness ↗</a>
102
+ <a href="https://arxiv.org/pdf/2208.05924">Hessian baseline ↗</a>
103
+ <a href="https://arxiv.org/pdf/2004.06433">Random probe estimator ↗</a>
104
+ </div>
105
+ </section>
106
+ </main>
107
+ <footer><span>Libor “Burny” Burian</span><a id="download-records" href="study.json">Download displayed records</a></footer>
108
+ </body>
109
+ </html>
research/docs/study.json CHANGED
The diff for this file is too large to render. See raw diff
 
research/docs/third-derivative-penalty.md CHANGED
@@ -2,12 +2,45 @@
2
 
3
  The model assigns a probability to each possible next token. Its **loss** is the mean negative log probability it assigns to the tokens that actually follow. The project differentiates this number **with respect to the trainable weights**. The first derivative gives the slope of the loss, the second gives its curvature, and the third tells us how that curvature changes as a weight moves. The training penalty adds up the **squares** of those changes. [Token loss](../src/thirdloss/models.py) · [Preregistered objective](../reports/preregistration.md)
4
 
5
- With one weight $w$, you can just differentiate three times. For $\ell(w)=w^4$, the successive derivatives are $4w^3$, $12w^2$ and $24w$. The penalty is $(24w)^2$. With many weights you also choose **which weight** to differentiate at each step. PyTorch directly differentiates the minibatch loss along the chosen directions by applying the chain rule at the current weights. The estimate enters when one pair of directions stands in for the sum of squares over **all** weight triples. [Project’s scalar derivative check](../tests/test_derivatives.py) · [Penalty code](../src/thirdloss/penalties.py)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  ## What gets differentiated?
8
 
9
  Let $\theta=(\theta_1,\ldots,\theta_d)$ be the $d$ trainable numbers. Let $B$ be the fixed **minibatch**, the training examples whose mean loss is $\ell_B(\theta)$. Write $\partial_i$ for the rate of change as weight $\theta_i$ moves with all other weights held fixed.
10
 
 
 
11
  | Quantity | Meaning |
12
  |---|---|
13
  | $g_k=\partial_k\ell_B$ | The slope along weight $k$. The **gradient** $g=\nabla_\theta\ell_B$ lists these slopes for all weights. |
@@ -113,6 +146,8 @@ The amended adapter path computes derivatives in double precision on a copy with
113
 
114
  The ordinary AdamW baseline passes the first gradient straight to clipping and the optimizer. The Hessian-trace arm uses one probe twice in $u^\top Hu$ because its target is the **trace**, the sum of the Hessian’s diagonal entries. The squared-Hessian arm uses $\lVert Hu\rVert_2^2$. The combined arm adds trace and third-order penalties. The sign-randomized control uses additional signs on the **finished penalty gradient**, a separate operation from choosing $u,v$ to measure the third derivative. [Comparator implementations](../src/thirdloss/penalties.py) · [Control and combined updates](../src/thirdloss/objectives.py) · [Planned comparisons](../reports/planned-runs.md)
115
 
 
 
116
  <details>
117
  <summary>Reproduce the worked examples and the dense storage estimates</summary>
118
 
 
2
 
3
  The model assigns a probability to each possible next token. Its **loss** is the mean negative log probability it assigns to the tokens that actually follow. The project differentiates this number **with respect to the trainable weights**. The first derivative gives the slope of the loss, the second gives its curvature, and the third tells us how that curvature changes as a weight moves. The training penalty adds up the **squares** of those changes. [Token loss](../src/thirdloss/models.py) · [Preregistered objective](../reports/preregistration.md)
4
 
5
+ ## When can the penalty favor a wider minimum?
6
+
7
+ Think of moving one weight $w$ while holding the data fixed. Pick a tolerable loss increase $\epsilon$. The width of a minimum is the length of the interval around it where the loss stays within $\epsilon$ of its value at the bottom. In many dimensions one can measure this distance along a specified direction, or the volume of the connected low-loss region. Both depend on the weight coordinates and the chosen tolerance. [Dinh et al., Definition 1 and Figure 1](https://proceedings.mlr.press/v70/dinh17b/dinh17b.pdf#page=2)
8
+
9
+ For one weight and a positive coefficient $\lambda$, adding a penalty to the ordinary loss $\ell$ changes the gradient as follows. A small gradient-descent step moves opposite the gradient. At a minimum of $\ell$, the ordinary slope is zero, so the penalty can determine the initial direction.
10
+
11
+ | What the objective penalizes | Term added to the loss | Term added to its gradient |
12
+ |---|---|---|
13
+ | Hessian trace (curvature in one dimension) | $\lambda\ell''$ | $\lambda\ell'''$ |
14
+ | Squared third derivative (how quickly curvature changes) | $\lambda(\ell''')^2$ | $2\lambda\ell'''\ell''''$ |
15
+
16
+ With many weights, the trace adds the curvatures along the Hessian’s principal directions. Near a smooth minimum, a lower trace means a smaller average loss increase from small, isotropic weight perturbations to second order. The combined training arm adds the trace term and the squared third-derivative estimate with separately calibrated coefficients. The figure illustrates the signs for plain gradient descent. The model runs use sampled minibatches and probes, gradient clipping and AdamW. [Noise stability, equation 4](https://arxiv.org/pdf/2306.08553#page=5) · [Training update](#the-actual-training-update)
17
+
18
+ ![Ordinary loss, trace and squared third derivative for an asymmetric minimum, a flat quartic and a steep quadratic. Arrows mark opposing directions, a pull toward the quartic bottom, and no penalty gradient for the quadratic.](figures/penalty-directions.png)
19
+
20
+ *The circles mark $w=0$, a minimum of each ordinary loss. Arrows give the direction of a decrease in each penalty. Their lengths are illustrative and the vertical scales differ. The report command draws these curves from their formulas.* [Figure source](../src/thirdloss/report_figures.py)
21
+
22
+ - **Opposite directions at the same minimum.** The first loss has $\ell(0)=\ell'(0)=0$ and $\ell''(w)=2\sqrt{1+w}$ for $w>-1$. Moving right increases curvature, and its rate of increase slows. The trace penalty therefore pushes left. The squared third derivative is $1/(1+w)$, which decreases to the right, so that penalty pushes right.
23
+ - **A pull back after a displacement.** For $\ell(w)=w^4$, curvature is $12w^2$ and the third derivative is $24w$. The unweighted penalty is $576w^2$. Its gradient $1152w$ vanishes at zero and gives a descent step toward zero from either side. This is a mechanism for staying near a flat bottom after a small perturbation. [Analytic gradient check](../tests/test_derivatives.py)
24
+ - **A sharp minimum with zero penalty.** For $\ell(w)=a w^2$ with $a>0$, curvature is the constant $2a$. Increasing $a$ makes the low-loss interval narrower at any fixed tolerance, yet every member of this family has zero third derivative everywhere. The trace assigns a larger cost to the steeper quadratic, though its own gradient within each quadratic is also zero.
25
+
26
+ ### From a local penalty to basin width
27
+
28
+ Stretch the same loss horizontally without changing its depth, so $\ell_s(w)=\ell(w/s)$ for $s>1$. At a fixed loss increase the width grows by $s$. At corresponding points the curvature scales by $s^{-2}$ and the third derivative by $s^{-3}$. Thus a wider version of the same valley can score lower on the third-derivative penalty. Even here, $\ell(w)=w^4$ and $16w^4$ both have zero third derivative at the bottom, although the former is twice as wide at a given loss increase.
29
+
30
+ There is a sufficient condition for the loss to stay low over a displacement $r$. If the curvature at a smooth minimum $w_0$ is $h$ and $|\ell'''|\le M$ **throughout the interval** to $w_0+r$, Taylor’s theorem gives
31
+
32
+ $$
33
+ \ell(w_0+r)-\ell(w_0)\ \le\ \tfrac12 h r^2+\tfrac16 M|r|^3 .
34
+ $$
35
+
36
+ Small initial curvature and slowly changing curvature across the interval together limit the loss increase. The training code samples the third derivative of two-window cross-entropy at the **current weights**. For TinyStories these coordinates include the whole decoder. For research abstracts they include only the trainable low-rank attention factors of Pythia-410M. A width measurement would therefore need a fixed loss tolerance and perturbations in the corresponding stage’s trainable coordinates. The logged penalty estimates describe local curvature change. The preregistered test compares held-out next-token loss across matched seeds at equal training tokens. [Taylor remainder, equation 22](https://link.springer.com/article/10.1007/s10288-023-00541-9) · [Stage definitions](../reports/planned-runs.md) · [Preregistered comparison](../reports/preregistration.md)
37
 
38
  ## What gets differentiated?
39
 
40
  Let $\theta=(\theta_1,\ldots,\theta_d)$ be the $d$ trainable numbers. Let $B$ be the fixed **minibatch**, the training examples whose mean loss is $\ell_B(\theta)$. Write $\partial_i$ for the rate of change as weight $\theta_i$ moves with all other weights held fixed.
41
 
42
+ With many weights you choose **which weight** to differentiate at each step. PyTorch applies the chain rule at the current weights along the chosen directions. The estimate enters when one pair of directions stands in for the sum of squares over all weight triples. [Penalty implementation](../src/thirdloss/penalties.py)
43
+
44
  | Quantity | Meaning |
45
  |---|---|
46
  | $g_k=\partial_k\ell_B$ | The slope along weight $k$. The **gradient** $g=\nabla_\theta\ell_B$ lists these slopes for all weights. |
 
146
 
147
  The ordinary AdamW baseline passes the first gradient straight to clipping and the optimizer. The Hessian-trace arm uses one probe twice in $u^\top Hu$ because its target is the **trace**, the sum of the Hessian’s diagonal entries. The squared-Hessian arm uses $\lVert Hu\rVert_2^2$. The combined arm adds trace and third-order penalties. The sign-randomized control uses additional signs on the **finished penalty gradient**, a separate operation from choosing $u,v$ to measure the third derivative. [Comparator implementations](../src/thirdloss/penalties.py) · [Control and combined updates](../src/thirdloss/objectives.py) · [Planned comparisons](../reports/planned-runs.md)
148
 
149
+ Hochreiter and Schmidhuber’s original flatness penalty used first derivatives of **network outputs** with respect to weights. Its update used second derivatives of those outputs. Liu, Yu and Lin’s later Hessian-trace objective, if differentiated, contributes third derivatives of the **loss**. Their released estimator converts the trace to a Python number before returning it, which cuts off the gradient through that code path. This project’s trace comparator differentiates through the estimate. [Original flat-minimum update, equations 1–2](https://people.idsia.ch/~juergen/fm/node3.html) · [Hessian-trace objective, equation 10](https://arxiv.org/pdf/2208.05924#page=5) · [Released estimator](https://github.com/Dean-lyc/Hessian-Regularization/blob/7d18787b06ba3e7912bf841ea9ebe4505a6191b3/hess.py#L87-L98) · [Project gradient calculation](../src/thirdloss/objectives.py)
150
+
151
  <details>
152
  <summary>Reproduce the worked examples and the dense storage estimates</summary>
153
 
research/reports/paper.pdf CHANGED
Binary files a/research/reports/paper.pdf and b/research/reports/paper.pdf differ
 
research/src/thirdloss/report_figures.py CHANGED
@@ -1,141 +1,186 @@
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Analytic method diagrams and publication figures from the explorer's raw-run snapshot."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from tempfile import NamedTemporaryFile
6
+
7
+ import numpy as np
8
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
9
+ from matplotlib.figure import Figure
10
+ from matplotlib.patches import FancyBboxPatch
11
+
12
+ from .report_records import COLORS, METHODS, STAGES, finite
13
+
14
+ INK = "#263735"
15
+ GRID = "#dbe2df"
16
+
17
+
18
+ def _save(figure: Figure, path: Path) -> None:
19
+ """Write a stable PNG atomically for Pages and the ReportLab paper."""
20
+ FigureCanvasAgg(figure)
21
+ with NamedTemporaryFile(dir=path.parent, suffix=".png", delete=False) as handle:
22
+ temp = Path(handle.name)
23
+ try:
24
+ figure.savefig(temp, format="png", dpi=170, bbox_inches="tight", facecolor="white")
25
+ os.replace(temp, path)
26
+ finally:
27
+ temp.unlink(missing_ok=True)
28
+ figure.clear()
29
+
30
+
31
+ def architecture(path: Path) -> None:
32
+ """Draw the mathematical computation graph and the trainable coordinate choice."""
33
+ fig = Figure(figsize=(10.2, 3.2))
34
+ ax = fig.subplots()
35
+ ax.set(xlim=(0, 10), ylim=(0, 3.25))
36
+ ax.axis("off")
37
+
38
+ def box(x, y, w, h, line1, line2, fill):
39
+ ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.02,rounding_size=0.1",
40
+ facecolor=fill, edgecolor="#afc7c0", linewidth=1.1))
41
+ ax.text(x + w / 2, y + h * 0.63, line1, ha="center", va="center",
42
+ color=INK, fontsize=9.6, fontweight="semibold")
43
+ ax.text(x + w / 2, y + h * 0.29, line2, ha="center", va="center", color=INK, fontsize=8.5)
44
+
45
+ def arrow(start, end):
46
+ ax.annotate("", xy=end, xytext=start, arrowprops={"arrowstyle": "-|>", "color": "#506c65",
47
+ "lw": 1.25, "shrinkA": 1, "shrinkB": 2})
48
+
49
+ box(0.06, 2.12, 2.01, 0.77, "TinyStories", "all decoder weights", "#e7f2ef")
50
+ box(0.06, 0.42, 2.01, 0.77, "Research abstracts", "Pythia QKV adapters", "#e7f2ef")
51
+ box(2.65, 1.27, 1.85, 0.77, "Next-token loss", "cross-entropy L", "#f0f3f1")
52
+ box(5.15, 2.12, 2.0, 0.77, "Hessian contraction", "independent signs u, v", "#f6ede6")
53
+ box(7.84, 2.12, 2.0, 0.77, "Third derivative", "r = grad(uᵀ H v)", "#e7f2ef")
54
+ box(7.84, 0.42, 2.0, 0.77, "Training objective", "L + weighted ‖r‖²", "#d9eee8")
55
+ arrow((2.08, 2.48), (2.65, 1.83))
56
+ arrow((2.08, 0.80), (2.65, 1.47))
57
+ arrow((4.51, 1.84), (5.14, 2.47))
58
+ arrow((7.17, 2.5), (7.82, 2.5))
59
+ arrow((8.84, 2.08), (8.84, 1.2))
60
+ arrow((4.51, 1.43), (7.80, 0.73))
61
+ ax.text(5.8, 0.5, "AdamW differentiates the complete objective",
62
+ fontsize=8, color="#526863", ha="center")
63
+ _save(fig, path)
64
+
65
+
66
+ def _axes_style(ax, xlabel, ylabel):
67
+ """Give each scale its units and never imply a zero baseline for a difference plot."""
68
+ ax.set_xlabel(xlabel, fontsize=9)
69
+ ax.set_ylabel(ylabel, fontsize=9)
70
+ ax.grid(axis="y", color=GRID, linewidth=0.6)
71
+ ax.set_axisbelow(True)
72
+ ax.spines[["top", "right"]].set_visible(False)
73
+ ax.spines[["left", "bottom"]].set_color("#91a09c")
74
+ ax.tick_params(labelsize=8, color="#91a09c")
75
+
76
+
77
+ def penalty_directions(path: Path) -> None:
78
+ """Illustrate local penalty gradients on known losses, independently of training data."""
79
+ w = np.linspace(-0.75, 0.75, 301)
80
+ # Integrate L'' = 2 sqrt(1+w) twice, fixing the loss and its slope at zero at the origin.
81
+ asymmetric = (8 / 15) * ((1 + w)**2.5 - 1) - (4 / 3) * w
82
+ examples = (
83
+ ("Asymmetric minimum\n" + r"$L''=2\sqrt{1+w}$", (asymmetric, 2 * np.sqrt(1 + w), 1 / (1 + w))),
84
+ ("Flat quartic\n" + r"$L=w^4$", (w**4, 12 * w**2, (24 * w)**2)),
85
+ ("Steep quadratic\n" + r"$L=100w^2$", (100 * w**2, np.full_like(w, 200), np.zeros_like(w))),
86
+ )
87
+ labels = ("Ordinary loss $L$", "Hessian trace $L''$", "Third-derivative penalty $[L''']^2$")
88
+ colors = (COLORS["ce"], COLORS["trace"], COLORS["third"])
89
+ fig = Figure(figsize=(10.2, 5.9), layout="constrained")
90
+ axes = fig.subplots(3, 3, sharex=True)
91
+ for column, (title, curves) in enumerate(examples):
92
+ axes[0, column].set_title(title, fontsize=13, color=INK)
93
+ for row, values in enumerate(curves):
94
+ ax = axes[row, column]
95
+ _axes_style(ax, "Weight $w$" if row == 2 else "", labels[row] if column == 0 else "")
96
+ ax.locator_params(axis="y", nbins=4)
97
+ ax.set_xticks([-.5, 0, .5])
98
+ ax.axvline(0, color="#9eaaa5", lw=.85, linestyle=":")
99
+ ax.plot(w, values, lw=2.2, color=colors[row])
100
+ ax.plot(0, np.interp(0, w, values), "o", ms=5, mfc="white", mec=colors[row], mew=1.5)
101
+
102
+ # Arrows indicate the algebraic descent direction. Their length is for legibility.
103
+ if row and column == 0:
104
+ steps = [(0, -.23 if row == 1 else .23)]
105
+ elif row and column == 1:
106
+ steps = [(-.55, -.32), (.55, .32)]
107
+ else:
108
+ steps = []
109
+ for start, end in steps:
110
+ y_start, y_end = np.interp([start, end], w, values)
111
+ ax.annotate("", (end, y_end), (start, y_start),
112
+ arrowprops={"arrowstyle": "-|>", "mutation_scale": 17,
113
+ "lw": 2.2, "color": colors[row], "shrinkA": 3, "shrinkB": 0})
114
+ # Common zero references make constant positive curvature and a zero penalty easy to read.
115
+ axes[1, 2].set(ylim=(-12, 232), yticks=[0, 100, 200])
116
+ axes[2, 2].set(ylim=(-.12, 1.05), yticks=[0, .5, 1])
117
+ _save(fig, path)
118
+
119
+
120
+ def _curves(study, path) -> bool:
121
+ """Draw actual development measurements in stage/phase panels, preserving run identity."""
122
+ groups = {}
123
+ for run in study["runs"]:
124
+ points = [(e["tokens"], e["dev_nll"]) for e in run["events"]
125
+ if finite(e.get("tokens")) and finite(e.get("dev_nll"))]
126
+ if points:
127
+ groups.setdefault((run.get("stage"), run.get("phase")), []).append((run, points))
128
+ if not groups:
129
+ return False
130
+ fig = Figure(figsize=(8, 2.8 * len(groups)), layout="constrained")
131
+ axes = fig.subplots(len(groups), 1, squeeze=False).ravel()
132
+ for ax, ((stage, phase), series) in zip(axes, groups.items()):
133
+ labels = set()
134
+ for run, points in series:
135
+ method = run.get("method")
136
+ label = METHODS.get(method, method) if method not in labels else "_nolegend_"
137
+ labels.add(method)
138
+ tokens, losses = zip(*points)
139
+ ax.plot(tokens, losses, color=COLORS.get(method, "#777"), marker=".",
140
+ markersize=3, linewidth=1, alpha=0.78, label=label)
141
+ _axes_style(ax, "Training target tokens", "Development NLL (nats/token)")
142
+ ax.set_title(f"{STAGES.get(stage, stage)} / {phase}", loc="left", fontsize=11, color=INK)
143
+ ax.legend(loc="best", fontsize=7, frameon=False, ncol=2)
144
+ _save(fig, path)
145
+ return True
146
+
147
+
148
+ def _paired(study, path) -> bool:
149
+ """Show every seed and the median interval for each registered comparison."""
150
+ rows = [(stage, baseline, stats) for stage, outcome in study["stages"].items()
151
+ for baseline, stats in outcome.get("comparisons", {}).items() if stats.get("pairs")]
152
+ if not rows:
153
+ return False
154
+ fig = Figure(figsize=(8.5, 1.5 + 0.72 * len(rows)), layout="constrained")
155
+ ax = fig.subplots()
156
+ axis_labels = []
157
+ for index, (stage, baseline, stats) in enumerate(rows):
158
+ axis_labels.append(f"{STAGES[stage]} / {METHODS[baseline]}")
159
+ pairs = stats["pairs"]
160
+ y = [index + (k - (len(pairs) - 1) / 2) * 0.036 for k in range(len(pairs))]
161
+ ax.scatter([pair["delta"] for pair in pairs], y, color=COLORS["third"], s=21, zorder=2)
162
+ lo, hi = stats["median_ci"]
163
+ if finite(lo) and finite(hi):
164
+ ax.hlines(index + 0.22, lo, hi, color=INK, linewidth=1.5)
165
+ ax.scatter([stats["median_delta"]], [index + 0.22], color=INK, marker="D", s=25, zorder=3)
166
+ ax.axvline(0, color="#677572", linewidth=0.8, linestyle="--")
167
+ ax.set_yticks(range(len(rows)), axis_labels)
168
+ _axes_style(ax, "Test NLL difference, third-order minus baseline (nats/token)", "")
169
+ ax.set_title("Paired seeds and median intervals", loc="left", fontsize=11, color=INK)
170
+ _save(fig, path)
171
+ return True
172
+
173
+
174
+ def build_figures(study: dict, directory: Path) -> dict:
175
+ """Always emit the method illustrations and add measured plots when observations exist."""
176
+ directory.mkdir(parents=True, exist_ok=True)
177
+ architecture(directory / "architecture.png")
178
+ penalty_directions(directory / "penalty-directions.png")
179
+ products = {"architecture": "architecture.png", "penalty_directions": "penalty-directions.png"}
180
+ for key, draw in (("curves", _curves), ("paired", _paired)):
181
+ file = directory / f"{key}.png"
182
+ if draw(study, file):
183
+ products[key] = file.name
184
+ else:
185
+ file.unlink(missing_ok=True)
186
+ return products
research/src/thirdloss/report_paper.py CHANGED
@@ -1,427 +1,434 @@
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
- "flat": ("Hochreiter and Schmidhuber, Simplifying neural nets by discovering flat minima",
30
- "https://proceedings.neurips.cc/paper/1994/hash/01882513d5fa7c329e940dda99b12147-Abstract.html"),
31
- "gpt_trace": ("Zhang, Li and Ju, Noise Stability Optimization for Finding Flat Minima: A Hessian-based Regularization Approach",
32
- "https://arxiv.org/pdf/2306.08553#page=12"),
33
- "roughness": ("Duchon, Splines minimizing rotation-invariant semi-norms in Sobolev spaces",
34
- "https://doi.org/10.1007/BFb0086566"),
35
- "trace": ("Liu, Yu and Lin, Regularizing deep neural networks with stochastic estimators of Hessian trace",
36
- "https://arxiv.org/pdf/2208.05924"),
37
- "sketch": ("Bujanović and Kressner, Norm and trace estimation with random rank-one vectors",
38
- "https://arxiv.org/pdf/2004.06433"),
39
- "fut": ("Yang et al., Estimating the effects of sample training orders for large language models without retraining",
40
- "https://arxiv.org/pdf/2505.22042#page=16"),
41
- "stories": ("Eldan and Li, TinyStories", "https://arxiv.org/pdf/2305.07759"),
42
- "pythia": ("Biderman et al., Pythia", "https://arxiv.org/pdf/2304.01373"),
43
- "lora": ("Hu et al., Low-rank adaptation of large language models", "https://arxiv.org/pdf/2106.09685"),
44
- "abstracts": ("Common Pile, Filtered arXiv abstracts", "https://huggingface.co/datasets/common-pile/arxiv_abstracts_filtered"),
45
- "seeds": ("Bouthillier et al., Accounting for variance in machine learning benchmarks",
46
- "https://proceedings.mlsys.org/paper_files/paper/2021/hash/0184b0cd3cfb185989f858a1d9f5c1eb-Abstract.html"),
47
- "coordinates": ("Dinh et al., Sharp minima can generalize for deep nets",
48
- "https://proceedings.mlr.press/v70/dinh17b.html"),
49
- }
50
- TEAL = "#006c60"
51
- INK = "#263735"
52
- MUTED = "#4b5e59"
53
-
54
-
55
- def _link(url, label):
56
- return f"<link href={quoteattr(url)} color='{TEAL}'><u>{escape(str(label))}</u></link>"
57
-
58
-
59
- def _cite(key):
60
- label, url = REFERENCES[key]
61
- return _link(url, label.rsplit(", ",1)[0])
62
-
63
-
64
- def _styles():
65
- """Use embedded Unicode fonts shipped with Matplotlib on every supported machine."""
66
- fonts = Path(get_data_path()) / "fonts" / "ttf"
67
- for name, file in (("PaperSans", "DejaVuSans.ttf"), ("PaperBold", "DejaVuSans-Bold.ttf"),
68
- ("PaperSerif", "DejaVuSerif.ttf")):
69
- if name not in pdfmetrics.getRegisteredFontNames():
70
- pdfmetrics.registerFont(TTFont(name, str(fonts / file)))
71
- pdfmetrics.registerFontFamily("PaperSans", normal="PaperSans", bold="PaperBold",
72
- italic="PaperSans", boldItalic="PaperBold")
73
- base = dict(fontName="PaperSans", fontSize=9.0, leading=14, textColor=colors.HexColor(INK),
74
- alignment=TA_LEFT, spaceAfter=7, splitLongWords=True)
75
- styles = {"body": ParagraphStyle("body", **base)}
76
- for name, changes in {
77
- "title": dict(fontName="PaperSerif", fontSize=25, leading=30, spaceAfter=9, keepWithNext=True),
78
- "heading": dict(fontName="PaperSerif", fontSize=15, leading=20, spaceBefore=8, spaceAfter=6, keepWithNext=True),
79
- "subheading": dict(fontName="PaperBold", fontSize=10.4, leading=14, spaceBefore=6, keepWithNext=True),
80
- "byline": dict(fontSize=9.5, leading=15, textColor=colors.HexColor(TEAL), spaceAfter=13),
81
- "caption": dict(fontSize=7.8, leading=11.2, textColor=colors.HexColor(MUTED), spaceAfter=7),
82
- "cell": dict(fontSize=7.45, leading=10.4, spaceAfter=0),
83
- "headcell": dict(fontName="PaperBold", fontSize=7.3, leading=10.4, textColor=colors.white, spaceAfter=0),
84
- "equation": dict(fontName="PaperSerif", fontSize=12.4, leading=19, leftIndent=9,
85
- spaceBefore=3, spaceAfter=9),
86
- }.items():
87
- styles[name] = ParagraphStyle(name, parent=styles["body"], **changes)
88
- return styles
89
-
90
-
91
- def _grid(styles, headers, rows, widths):
92
- """Repeat the column labels if the growing experiment table spans multiple pages."""
93
- def line(cells, style):
94
- return [Paragraph(escape(str(cell)), styles[style]) for cell in cells]
95
- table = LongTable([line(headers, "headcell"), *[line(r, "cell") for r in rows]],
96
- colWidths=widths, repeatRows=1, hAlign="LEFT", splitByRow=True)
97
- table.setStyle(TableStyle([
98
- ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#34504a")),
99
- ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f0f5f2")]),
100
- ("VALIGN", (0, 0), (-1, -1), "TOP"),
101
- ("LEFTPADDING", (0, 0), (-1, -1), 5), ("RIGHTPADDING", (0, 0), (-1, -1), 5),
102
- ("TOPPADDING", (0, 0), (-1, -1), 4.5), ("BOTTOMPADDING", (0, 0), (-1, -1), 4.5),
103
- ]))
104
- return table
105
-
106
-
107
- def _figure(path, max_width=477, max_height=240):
108
- image = Image(str(path))
109
- scale = min(max_width / image.imageWidth, max_height / image.imageHeight)
110
- image.drawWidth = image.imageWidth * scale
111
- image.drawHeight = image.imageHeight * scale
112
- image.hAlign = "LEFT"
113
- return image
114
-
115
-
116
- def _result_tables(study):
117
- """Group scores at equal token horizons and compare resource use on like hardware."""
118
- groups = {}
119
- for run in study["runs"]:
120
- if completed(run):
121
- key = (run.get("stage"), run.get("phase"), run.get("method"),
122
- run.get("ratio"), run.get("tokens"))
123
- groups.setdefault(key, []).append(run)
124
- scores, resources = [], {}
125
-
126
- def middle(runs, key, digits):
127
- values = [r[key] for r in runs if finite(r.get(key))]
128
- return fmt(median(values), digits) if values else "—"
129
-
130
- for (stage, phase, method, ratio, tokens), runs in groups.items():
131
- arm = [STAGES.get(stage, stage), phase, METHODS.get(method, method), fmt(ratio)]
132
- scores.append([*arm, len(runs), fmt(tokens, 0), middle(runs, "dev_nll", 4), middle(runs, "test_nll", 4)])
133
- devices = {}
134
- for run in runs:
135
- hardware = run.get("gpu") or run.get("device") or "Hardware unrecorded"
136
- devices.setdefault(hardware, []).append(run)
137
- for device, subset in devices.items():
138
- timed = [r for r in subset if finite(r.get("train_seconds")) and r["train_seconds"] > 0]
139
- gpu = [r for r in subset if r.get("gpu") or str(r.get("device", "")).startswith("cuda")]
140
- resources.setdefault(device, []).append([
141
- *arm, len(subset), fmt(tokens, 0), middle(timed, "train_seconds", 1),
142
- middle(timed, "tokens_per_sec", 0), middle(gpu, "peak_vram_mb", 1),
143
- ])
144
- return scores, resources
145
-
146
-
147
- def _matched_rows(study,key="matched_time"):
148
- """Print every matched seed, including each arm's distance from the shared cutoff."""
149
- rows = []
150
- for stage, outcome in study["stages"].items():
151
- for entry in outcome.get(key, []):
152
- cutoff = entry["cutoff_seconds"]
153
- losses = []
154
- for method in ("ce", "trace", "third"):
155
- point = entry["by_method"][method]
156
- lag = point["staleness_seconds"]
157
- losses.append(f"{fmt(point['dev_nll'], 4)} ({fmt(lag, 1)})")
158
- rows.append([STAGES[stage], entry["seed"], fmt(cutoff, 1), *losses])
159
- return rows
160
-
161
-
162
- def write_paper(study: dict, output: Path, figure_dir: Path, figures: dict) -> None:
163
- """Create the dated paper, with pretraining and adaptation interpreted separately."""
164
- styles = _styles()
165
- flow = []
166
-
167
- def p(markup, style="body"):
168
- flow.append(Paragraph(markup, styles[style]))
169
-
170
- try:
171
- local_time = datetime.fromisoformat(study["generated_at"]).astimezone(ZoneInfo("Europe/Berlin"))
172
- except ZoneInfoNotFoundError:
173
- local_time = datetime.fromisoformat(study["generated_at"]).astimezone()
174
- rendered = local_time.strftime("%d %B %Y")
175
- p("Third-derivative regularization for causal language models", "title")
176
- p(f"Libor “Burny” Burian &nbsp;·&nbsp; {rendered}", "byline")
177
- p("Abstract", "heading")
178
- p("We study whether a language model improves its predictions when training penalizes "
179
- "variation in the curvature of its next-token loss. Independent random signs produce "
180
- "a differentiable estimate of the squared norm of all third partial derivatives in "
181
- "the trainable coordinates. Two matched interventions compare this objective with "
182
- "ordinary AdamW and a signed Hessian-trace penalty. " +
183
- " ".join(f"{STAGES[s]}: {escape(verdict_text(outcome))}" for s, outcome in study["stages"].items()))
184
- p("Motivation and related work", "heading")
185
- p("A Hessian gives a local quadratic description of loss. Two nearby sets of weights "
186
- "can share its trace while individual curvature components vary. Summing squared "
187
- "third partials assigns a nonnegative cost to that variation in the chosen coordinates. "
188
- "The proposed local density adapts an order-three spline roughness measure. The "
189
- "original flat-minima work searched for broad regions of low training error. Liu, Yu and Lin "
190
- "regularized recurrent language models with the Hessian trace. Zhang, Li and Ju investigated "
191
- "a symmetric approximation to trace regularization in GPT-2 downstream fine-tuning. "
192
- f"{_cite('roughness')} · {_cite('flat')} · {_cite('trace')} · {_cite('gpt_trace')}, Table 5 · {_cite('coordinates')}")
193
- p("FUT++ approximates third weight derivatives of minibatch language-model loss with "
194
- "differences between Hessian estimates at consecutive reference checkpoints. It uses "
195
- "these terms to predict the effect of reordering training batches. Here the squared "
196
- "norm enters the loss itself, so its gradient changes the training trajectory. "
197
- f"{_cite('fut')}, Appendix A.1, equations 14–15.")
198
- p("The estimator and its update", "heading")
199
- p("J(θ) = L(θ) + λ · ‖D³L(θ)‖²<sub>F</sub>", "equation")
200
- p("For independent Rademacher vectors u and v, form r = ∇(uᵀHv). Squaring and summing "
201
- "its coordinates, then averaging over probes, cancels every cross term with unmatched "
202
- "indices. The expectation is the squared Frobenius norm of the minibatch third derivative. "
203
- "The gradient through r supplies a fourth-derivative contraction to AdamW. The "
204
- "derivative minibatch contains two windows. A Bernoulli gate samples one eighth of "
205
- "updates and multiplies the active contribution by eight. "
206
- f"{_cite('sketch')} · {_link(REPOSITORY + '/blob/main/reports/preregistration.md', 'Preregistration')}")
207
- flow.append(KeepTogether([_figure(figure_dir / figures["architecture"], max_height=140),
208
- Paragraph("Figure 1. Trainable coordinate sets and the stochastic "
209
- "regularization path.", styles["caption"])]))
210
- flow.append(PageBreak())
211
- p("Experimental design", "heading")
212
- p("Full-weight pretraining uses a four-block causal Transformer with width 192, four heads, "
213
- "a gated 512-wide MLP, tied embeddings and 128 targets per window. Stories use a "
214
- "train-only vocabulary of 4,096 tokens. The adapter stage freezes Pythia-410M and trains "
215
- "rank-eight attention QKV adapters with scale alpha 16. The first-submission timestamp "
216
- "sets the split within 2024, grouping versions by base arXiv identifier. January through April supply training text, May supplies "
217
- "development text, and June supplies the held-out test. "
218
- f"{_cite('stories')} · {_cite('pythia')} · {_cite('lora')} · {_cite('abstracts')}")
219
- p("The confirmatory horizons are 16,777,216 target tokens for stories and 524,288 for "
220
- "abstracts. Within a stage, each seed pairs starting weights, text order and optimizer "
221
- "schedule. The pilot calibrates penalty gradients on training data and selects strength "
222
- "at equal development horizons. The squared-Hessian, sign-randomized and combined arms "
223
- "test derivative order, gradient direction and incremental benefit. Initial checkpoints "
224
- "and token unigrams supply untrained references. "
225
- f"{_link(REPOSITORY + '/blob/main/reports/planned-runs.md', 'Run matrix')}")
226
- p("Each update averages 32 windows for stories or eight for adapters. AdamW uses β₁ = 0.9, "
227
- "β₂ = 0.95, matrix weight decay 0.1 and gradient norm clipping at one. Peak learning "
228
- "rates are 0.0003 and 0.0001, respectively, with 5% warmup and cosine decay to 10% of peak. "
229
- "Across 16 batches at the shared pilot initialization, the median ordinary-to-penalty "
230
- "gradient-norm ratio sets the scale. Both regularizers try 1%, 3% and 10% of this scale. "
231
- f"{_link(REPOSITORY + '/blob/main/reports/preregistration.md', 'Training and selection protocol')}")
232
- p("Normalize and deduplicate whole documents before fitting the stories tokenizer. Prioritize "
233
- "evaluation records when removing overlaps, and audit word-shingle similarity between "
234
- "splits. Pack documents with an end-of-sequence token. Full evaluation counts each valid "
235
- "target once. During training, the development curve uses a fixed subset of windows. "
236
- f"{_link(REPOSITORY + '/blob/main/docs/data.md', 'Data preparation and overlap audit')}")
237
- data_rows = [[STAGES[stage], name, fmt(split.get("documents"), 0), fmt(split.get("tokens"), 0)]
238
- for stage, context in study["context"].items()
239
- for name, split in context["datasets"].get("splits", {}).items()]
240
- if data_rows:
241
- flow.append(_grid(styles, ["Corpus", "Split", "Retained documents", "Packed tokens"],
242
- data_rows, [112, 90, 132, 141]))
243
- p("Packed-token counts include document separators. The number of valid next-token "
244
- "targets is recorded separately during evaluation.", "caption")
245
- p("Statistical analysis", "heading")
246
- p("Corpus negative log-likelihood sums token losses and divides by the valid target count. "
247
- "For each baseline, paired differences subtract baseline NLL from third-order NLL at the "
248
- "same token budget. The registered stage decision requires both one-sided exact paired "
249
- "sign tests to pass Holm correction at 0.05 across eight seed pairs. Ties are removed "
250
- "from sign-test denominators. A distribution-free order-statistic interval quantifies "
251
- "uncertainty in the median paired difference. Equal-time analyses use the latest logged "
252
- "development checkpoint within the shortest final training time of that seed triple. "
253
- f"{_cite('seeds')} · {_link(REPOSITORY + '/blob/main/reports/preregistration.md', 'Decision rule')}")
254
- p("Results", "heading")
255
- numerical = study.get("numerics",{})
256
- single = numerical.get("pythia-joint-cuda",{})
257
- double = numerical.get("pythia-fp64-agreement",{})
258
- if single and double:
259
- p("Numerical accuracy on the pretrained checkpoint", "subheading")
260
- p(f"For identical Pythia weights and probe signs, changing the FP32 CUDA batching gave a "
261
- f"{100*single['relative_gradient_difference']:.1f}% relative discrepancy in the training gradient. "
262
- f"In FP64 the CPU and GPU gradients agreed to relative error {double['relative_gradient_difference']:.2g}. "
263
- "The initial FP32 pilot is retained as a diagnostic. The amended adapter arms compute their "
264
- "penalties in FP64 on the CPU and use CUDA for the ordinary loss and optimizer updates. "
265
- f"{_link(REPOSITORY + '/blob/main/reports/amendments/adapter-precision.md','Pre-test amendment and raw checks')}")
266
- run_count = len(study["runs"])
267
- done_count = sum(completed(run) for run in study["runs"])
268
- p(f"The ledger contains {run_count} runs and {done_count} completed summaries. "
269
- f"{_link(REPOSITORY + '/tree/main/results', 'Raw records')} · "
270
- f"{_link(REPOSITORY + '/blob/main/reports/experiments/experiments.md', 'Per-run ledger')}")
271
- for stage, outcome in study["stages"].items():
272
- p(f"<b>{STAGES[stage]}.</b> {escape(verdict_text(outcome))}")
273
- context = study["context"][stage]
274
- selected = context["selection"].get("ratios", {})
275
- if selected:
276
- p(f"Development selected trace ratio {fmt(selected.get('trace'))} and third-order "
277
- f"ratio {fmt(selected.get('third'))}. "
278
- f"{_link(REPOSITORY + '/blob/main/results/selection/' + stage + '.json', 'All candidate scores')}")
279
- hours = context["feasibility"].get("projected_confirm_training_hours")
280
- if finite(hours):
281
- p(f"The selected-arm pilot speeds project {hours:.2f} training hours for this full "
282
- "confirmatory stage. This estimate covers optimization time. "
283
- f"{_link(REPOSITORY + '/blob/main/results/feasibility/' + stage + '.json', 'Measured timing basis')}")
284
- pilots = study["pilot_comparisons"][stage]
285
- if pilots:
286
- changes = ", ".join(f"{describe_difference(row['delta'])} against "
287
- f"{METHODS[row['method']]}" for row in pilots)
288
- p(f"In the development pilot at {pilots[0]['tokens']:,} training targets, third-order "
289
- f"training recorded {changes}. The comparison uses one seed and "
290
- f"{pilots[0]['strength_basis']}.")
291
- evaluated, resources = _result_tables(study)
292
- if evaluated:
293
- p("Scores across methods", "subheading")
294
- flow.append(_grid(styles, ["Corpus", "Phase", "Method", "Ratio", "Runs", "Tokens/run", "Dev NLL", "Test NLL"],
295
- evaluated, [60, 53, 105, 36, 34, 69, 58, 60]))
296
- p("Table 1. Medians over available completed runs sharing corpus, method, development "
297
- "strength and token horizon. NLL is in nats per target token. Dashes mark missing "
298
- "observations. The paired seed analyses use individual final test scores.", "caption")
299
- for key, caption in (("curves", "Development NLL by logged token count. Each line is a run; "
300
- "panels separate training stages and phases."),
301
- ("paired", "Individual differences in test NLL. Diamonds mark median "
302
- "differences and horizontal segments show their registered intervals.")):
303
- if key in figures:
304
- flow.append(KeepTogether([_figure(figure_dir / figures[key]),
305
- Paragraph(caption, styles["caption"])]))
306
- p("Discussion and limitations", "heading")
307
- p("Predictive utility requires lower held-out loss against both baselines. A reduction in "
308
- "the derivative estimate alone describes local geometry. Parameterization changes its "
309
- "magnitude, including the low-rank factorization used for abstracts. The estimate targets "
310
- "expected two-window minibatch roughness. The small datasets, limited seed count and "
311
- "two tokenization schemes bound the interpretation. More tokens per GPU hour can change "
312
- "the practical ranking. "
313
- f"{_cite('coordinates')} · {_link(REPOSITORY + '/blob/main/reports/preregistration.md', 'Scope of inference')}")
314
- p("Conclusion", "heading")
315
- if all(outcome.get("complete") for outcome in study["stages"].values()):
316
- confirmed = [STAGES[s] for s, outcome in study["stages"].items() if outcome.get("success")]
317
- if confirmed:
318
- p("The registered dual-baseline criterion was met in " + " and ".join(confirmed) +
319
- ". The observed gain applies to the reported data, trainable coordinates and token horizons.")
320
- else:
321
- p("Neither stage established the registered dual-baseline improvement. The paired "
322
- "effects and uncertainty intervals quantify the range compatible with these data.")
323
- else:
324
- p("The outstanding paired evaluations determine which claims can be made about prediction quality "
325
- "at the registered horizons. The run ledger preserves every available observation and implementation failure.")
326
- p("Appendix · Computational cost", "heading")
327
- if resources:
328
- for device, rows in resources.items():
329
- p(escape(str(device)), "subheading")
330
- flow.append(_grid(styles, ["Corpus", "Phase", "Method", "Ratio", "Runs", "Targets/run",
331
- "Train (s)", "Targets/s", "Peak GPU (MiB)"],
332
- rows, [56, 49, 78, 35, 34, 64, 48, 57, 54]))
333
- p("Times and rates are per-run medians within each hardware, method, phase, strength and "
334
- "target budget. The clock sums synchronized training steps, including batch transfer and "
335
- "the optimizer update and any host FP64 probe while the GPU is reserved. Evaluation, checkpointing and uploads take additional time. Peak "
336
- "memory is PyTorch’s recorded maximum allocated GPU tensor memory during the run, including "
337
- "evaluation. Untrained controls have no training speed.", "caption")
338
- else:
339
- p("Hardware, training speed and peak allocated memory will appear with the first completed run.")
340
- p("Development NLL at matched GPU training time", "subheading")
341
- p("For each seed the cutoff is the shortest completed training time across AdamW, trace and "
342
- "third-order training. Fixed-window development evaluations occur at discrete checkpoints. "
343
- "We take the latest checkpoint at or before the cutoff. Each cell gives NLL in nats per target "
344
- "token, followed by its lag behind the cutoff in seconds. Larger lags make the time comparison "
345
- "coarser. The archived per-seed table also records the token count at each checkpoint. "
346
- f"{_link(REPOSITORY + '/blob/main/reports/summary.md', 'Per-seed timing records')}", "caption")
347
- matched = _matched_rows(study)
348
- if matched:
349
- flow.append(_grid(styles, ["Corpus", "Seed", "Cutoff (s)", "AdamW NLL (lag s)",
350
- "Trace NLL (lag s)", "Third NLL (lag s)"],
351
- matched, [82, 34, 65, 98, 98, 98]))
352
- else:
353
- p("Awaiting a complete, timed three-method confirmatory seed with eligible development checkpoints.", "caption")
354
- nonhost = _matched_rows(study,"matched_nonhost_time")
355
- if nonhost:
356
- p("Adapter timing after subtracting host derivative calls", "subheading")
357
- p("This supplementary clock removes the observed duration of host derivative calls including their "
358
- "transfers. The table uses the same fixed development windows and reports checkpoint lags in seconds. "
359
- "Individual CUDA kernel durations were not profiled.", "caption")
360
- flow.append(_grid(styles,["Corpus","Seed","Cutoff (s)","AdamW NLL (lag s)",
361
- "Trace NLL (lag s)","Third NLL (lag s)"],nonhost,[82,34,65,98,98,98]))
362
- pair_rows = [[STAGES[stage], METHODS.get(base, base), pair["seed"],
363
- fmt(pair["third_nll"], 5), fmt(pair["baseline_nll"], 5), fmt(pair["delta"], 5)]
364
- for stage, outcome in study["stages"].items()
365
- for base, stats in outcome.get("comparisons", {}).items() for pair in stats["pairs"]]
366
- if pair_rows:
367
- p("Appendix · Paired effects", "heading")
368
- flow.append(_grid(styles, ["Corpus", "Baseline", "Seed", "Third NLL", "Baseline NLL", "ΔNLL"],
369
- pair_rows, [85, 110, 40, 78, 82, 80]))
370
- for stage, outcome in study["stages"].items():
371
- for base, stats in outcome.get("comparisons", {}).items():
372
- lo, hi = stats["median_ci"]
373
- p(f"{STAGES[stage]} / {METHODS[base]}: median ΔNLL {fmt(stats['median_delta'], 5)}, "
374
- f"interval [{fmt(lo,5)}, {fmt(hi,5)}] at achieved coverage {fmt(stats['ci_coverage'],4)}. "
375
- f"Holm-adjusted p = {fmt(stats['p_holm'], 5)}.", "caption")
376
- has_examples = any(run["samples"] for run in study["runs"])
377
- if has_examples:
378
- p("Appendix · Output examples", "heading")
379
- p("For each stage and method, the first saved sample in run-ID order is shown in excerpt. "
380
- "The experiment ledger contains every full saved continuation and its corresponding "
381
- f"reference when recorded. {_link(REPOSITORY + '/tree/main/reports/experiments', 'All outputs')}")
382
- seen = set()
383
- for run in study["runs"]:
384
- key = (run.get("stage"), run.get("method"))
385
- if not run["samples"] or key in seen:
386
- continue
387
- seen.add(key)
388
- sample = run["samples"][0]
389
- label = f"{STAGES.get(key[0], key[0])} · {METHODS.get(key[1], key[1])}"
390
- example = [Paragraph(escape(label), styles["subheading"])]
391
- for field, name in (("prompt", "Prompt"), ("reference", "Reference"), ("continuation", "Prediction")):
392
- if sample.get(field) is not None:
393
- value = str(sample[field])
394
- excerpt = value[:420] + (" […]" if len(value) > 420 else "")
395
- example.append(Paragraph(f"<b>{name}.</b> {escape(excerpt)}", styles["caption"]))
396
- flow.append(KeepTogether(example))
397
- p("References and reproducibility", "heading")
398
- for title, url in REFERENCES.values():
399
- p(_link(url, title), "caption")
400
- p(f"Rebuild tables, figures, the explorer and this paper with <b>uv run thirdloss report</b>. "
401
- f"{_link(REPOSITORY, 'Code and versioned protocol')}", "caption")
402
- p("AI statement", "subheading")
403
- p("Codex wrote the codebase and paper from the exact specification provided by a human. "
404
- "Human cleanup and rewriting are in progress.", "caption")
405
-
406
- def footer(canvas, doc):
407
- canvas.saveState()
408
- canvas.setStrokeColor(colors.HexColor("#ccd8d3"))
409
- canvas.line(doc.leftMargin, 40, A4[0] - doc.rightMargin, 40)
410
- canvas.setFillColor(colors.HexColor(MUTED))
411
- canvas.setFont("PaperSans", 7.4)
412
- canvas.drawString(doc.leftMargin, 27, "THIRD-DERIVATIVE REGULARIZATION")
413
- canvas.drawRightString(A4[0] - doc.rightMargin, 27, str(doc.page))
414
- canvas.restoreState()
415
-
416
- output.parent.mkdir(parents=True, exist_ok=True)
417
- with NamedTemporaryFile(dir=output.parent, suffix=".pdf", delete=False) as handle:
418
- tmp = Path(handle.name)
419
- try:
420
- document = SimpleDocTemplate(str(tmp), pagesize=A4, leftMargin=49, rightMargin=49,
421
- topMargin=43, bottomMargin=54,
422
- title="Third-derivative regularization for causal language models",
423
- author="Libor “Burny” Burian")
424
- document.build(flow, onFirstPage=footer, onLaterPages=footer)
425
- os.replace(tmp, output)
426
- finally:
427
- tmp.unlink(missing_ok=True)
 
 
 
 
 
 
 
 
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
+ "flat": ("Hochreiter and Schmidhuber, Simplifying neural nets by discovering flat minima",
30
+ "https://proceedings.neurips.cc/paper/1994/hash/01882513d5fa7c329e940dda99b12147-Abstract.html"),
31
+ "gpt_trace": ("Zhang, Li and Ju, Noise Stability Optimization for Finding Flat Minima: A Hessian-based Regularization Approach",
32
+ "https://arxiv.org/pdf/2306.08553#page=12"),
33
+ "roughness": ("Duchon, Splines minimizing rotation-invariant semi-norms in Sobolev spaces",
34
+ "https://doi.org/10.1007/BFb0086566"),
35
+ "trace": ("Liu, Yu and Lin, Regularizing deep neural networks with stochastic estimators of Hessian trace",
36
+ "https://arxiv.org/pdf/2208.05924"),
37
+ "sketch": ("Bujanović and Kressner, Norm and trace estimation with random rank-one vectors",
38
+ "https://arxiv.org/pdf/2004.06433"),
39
+ "fut": ("Yang et al., Estimating the effects of sample training orders for large language models without retraining",
40
+ "https://arxiv.org/pdf/2505.22042#page=16"),
41
+ "stories": ("Eldan and Li, TinyStories", "https://arxiv.org/pdf/2305.07759"),
42
+ "pythia": ("Biderman et al., Pythia", "https://arxiv.org/pdf/2304.01373"),
43
+ "lora": ("Hu et al., Low-rank adaptation of large language models", "https://arxiv.org/pdf/2106.09685"),
44
+ "abstracts": ("Common Pile, Filtered arXiv abstracts", "https://huggingface.co/datasets/common-pile/arxiv_abstracts_filtered"),
45
+ "seeds": ("Bouthillier et al., Accounting for variance in machine learning benchmarks",
46
+ "https://proceedings.mlsys.org/paper_files/paper/2021/hash/0184b0cd3cfb185989f858a1d9f5c1eb-Abstract.html"),
47
+ "coordinates": ("Dinh et al., Sharp minima can generalize for deep nets",
48
+ "https://proceedings.mlr.press/v70/dinh17b.html"),
49
+ }
50
+ TEAL = "#006c60"
51
+ INK = "#263735"
52
+ MUTED = "#4b5e59"
53
+
54
+
55
+ def _link(url, label):
56
+ return f"<link href={quoteattr(url)} color='{TEAL}'><u>{escape(str(label))}</u></link>"
57
+
58
+
59
+ def _cite(key):
60
+ label, url = REFERENCES[key]
61
+ return _link(url, label.rsplit(", ",1)[0])
62
+
63
+
64
+ def _styles():
65
+ """Use embedded Unicode fonts shipped with Matplotlib on every supported machine."""
66
+ fonts = Path(get_data_path()) / "fonts" / "ttf"
67
+ for name, file in (("PaperSans", "DejaVuSans.ttf"), ("PaperBold", "DejaVuSans-Bold.ttf"),
68
+ ("PaperSerif", "DejaVuSerif.ttf")):
69
+ if name not in pdfmetrics.getRegisteredFontNames():
70
+ pdfmetrics.registerFont(TTFont(name, str(fonts / file)))
71
+ pdfmetrics.registerFontFamily("PaperSans", normal="PaperSans", bold="PaperBold",
72
+ italic="PaperSans", boldItalic="PaperBold")
73
+ base = dict(fontName="PaperSans", fontSize=9.0, leading=14, textColor=colors.HexColor(INK),
74
+ alignment=TA_LEFT, spaceAfter=7, splitLongWords=True)
75
+ styles = {"body": ParagraphStyle("body", **base)}
76
+ for name, changes in {
77
+ "title": dict(fontName="PaperSerif", fontSize=25, leading=30, spaceAfter=9, keepWithNext=True),
78
+ "heading": dict(fontName="PaperSerif", fontSize=15, leading=20, spaceBefore=8, spaceAfter=6, keepWithNext=True),
79
+ "subheading": dict(fontName="PaperBold", fontSize=10.4, leading=14, spaceBefore=6, keepWithNext=True),
80
+ "byline": dict(fontSize=9.5, leading=15, textColor=colors.HexColor(TEAL), spaceAfter=13),
81
+ "caption": dict(fontSize=7.8, leading=11.2, textColor=colors.HexColor(MUTED), spaceAfter=7),
82
+ "cell": dict(fontSize=7.45, leading=10.4, spaceAfter=0),
83
+ "headcell": dict(fontName="PaperBold", fontSize=7.3, leading=10.4, textColor=colors.white, spaceAfter=0),
84
+ "equation": dict(fontName="PaperSerif", fontSize=12.4, leading=19, leftIndent=9,
85
+ spaceBefore=3, spaceAfter=9),
86
+ }.items():
87
+ styles[name] = ParagraphStyle(name, parent=styles["body"], **changes)
88
+ return styles
89
+
90
+
91
+ def _grid(styles, headers, rows, widths):
92
+ """Repeat the column labels if the growing experiment table spans multiple pages."""
93
+ def line(cells, style):
94
+ return [Paragraph(escape(str(cell)), styles[style]) for cell in cells]
95
+ table = LongTable([line(headers, "headcell"), *[line(r, "cell") for r in rows]],
96
+ colWidths=widths, repeatRows=1, hAlign="LEFT", splitByRow=True)
97
+ table.setStyle(TableStyle([
98
+ ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#34504a")),
99
+ ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f0f5f2")]),
100
+ ("VALIGN", (0, 0), (-1, -1), "TOP"),
101
+ ("LEFTPADDING", (0, 0), (-1, -1), 5), ("RIGHTPADDING", (0, 0), (-1, -1), 5),
102
+ ("TOPPADDING", (0, 0), (-1, -1), 4.5), ("BOTTOMPADDING", (0, 0), (-1, -1), 4.5),
103
+ ]))
104
+ return table
105
+
106
+
107
+ def _figure(path, max_width=477, max_height=240):
108
+ image = Image(str(path))
109
+ scale = min(max_width / image.imageWidth, max_height / image.imageHeight)
110
+ image.drawWidth = image.imageWidth * scale
111
+ image.drawHeight = image.imageHeight * scale
112
+ image.hAlign = "LEFT"
113
+ return image
114
+
115
+
116
+ def _result_tables(study):
117
+ """Group scores at equal token horizons and compare resource use on like hardware."""
118
+ groups = {}
119
+ for run in study["runs"]:
120
+ if completed(run):
121
+ key = (run.get("stage"), run.get("phase"), run.get("method"),
122
+ run.get("ratio"), run.get("tokens"))
123
+ groups.setdefault(key, []).append(run)
124
+ scores, resources = [], {}
125
+
126
+ def middle(runs, key, digits):
127
+ values = [r[key] for r in runs if finite(r.get(key))]
128
+ return fmt(median(values), digits) if values else "—"
129
+
130
+ for (stage, phase, method, ratio, tokens), runs in groups.items():
131
+ arm = [STAGES.get(stage, stage), phase, METHODS.get(method, method), fmt(ratio)]
132
+ scores.append([*arm, len(runs), fmt(tokens, 0), middle(runs, "dev_nll", 4), middle(runs, "test_nll", 4)])
133
+ devices = {}
134
+ for run in runs:
135
+ hardware = run.get("gpu") or run.get("device") or "Hardware unrecorded"
136
+ devices.setdefault(hardware, []).append(run)
137
+ for device, subset in devices.items():
138
+ timed = [r for r in subset if finite(r.get("train_seconds")) and r["train_seconds"] > 0]
139
+ gpu = [r for r in subset if r.get("gpu") or str(r.get("device", "")).startswith("cuda")]
140
+ resources.setdefault(device, []).append([
141
+ *arm, len(subset), fmt(tokens, 0), middle(timed, "train_seconds", 1),
142
+ middle(timed, "tokens_per_sec", 0), middle(gpu, "peak_vram_mb", 1),
143
+ ])
144
+ return scores, resources
145
+
146
+
147
+ def _matched_rows(study,key="matched_time"):
148
+ """Print every matched seed, including each arm's distance from the shared cutoff."""
149
+ rows = []
150
+ for stage, outcome in study["stages"].items():
151
+ for entry in outcome.get(key, []):
152
+ cutoff = entry["cutoff_seconds"]
153
+ losses = []
154
+ for method in ("ce", "trace", "third"):
155
+ point = entry["by_method"][method]
156
+ lag = point["staleness_seconds"]
157
+ losses.append(f"{fmt(point['dev_nll'], 4)} ({fmt(lag, 1)})")
158
+ rows.append([STAGES[stage], entry["seed"], fmt(cutoff, 1), *losses])
159
+ return rows
160
+
161
+
162
+ def write_paper(study: dict, output: Path, figure_dir: Path, figures: dict) -> None:
163
+ """Create the dated paper, with pretraining and adaptation interpreted separately."""
164
+ styles = _styles()
165
+ flow = []
166
+
167
+ def p(markup, style="body"):
168
+ flow.append(Paragraph(markup, styles[style]))
169
+
170
+ try:
171
+ local_time = datetime.fromisoformat(study["generated_at"]).astimezone(ZoneInfo("Europe/Berlin"))
172
+ except ZoneInfoNotFoundError:
173
+ local_time = datetime.fromisoformat(study["generated_at"]).astimezone()
174
+ rendered = local_time.strftime("%d %B %Y")
175
+ p("Third-derivative regularization for causal language models", "title")
176
+ p(f"Libor “Burny” Burian &nbsp;·&nbsp; {rendered}", "byline")
177
+ p("Abstract", "heading")
178
+ p("We study whether a language model improves its predictions when training penalizes "
179
+ "variation in the curvature of its next-token loss. Independent random signs produce "
180
+ "a differentiable estimate of the squared norm of all third partial derivatives in "
181
+ "the trainable coordinates. Two matched interventions compare this objective with "
182
+ "ordinary AdamW and a signed Hessian-trace penalty. " +
183
+ " ".join(f"{STAGES[s]}: {escape(verdict_text(outcome))}" for s, outcome in study["stages"].items()))
184
+ p("Motivation and related work", "heading")
185
+ p("A Hessian gives a local quadratic description of loss. Two nearby sets of weights "
186
+ "can share its trace while individual curvature components vary. Summing squared "
187
+ "third partials assigns a nonnegative cost to that variation in the chosen coordinates. "
188
+ "The proposed local density adapts an order-three spline roughness measure. The "
189
+ "original flat-minima work searched for broad regions of low training error. Liu, Yu and Lin "
190
+ "proposed a Hessian-trace objective and reported recurrent language-model experiments. Zhang, Li and Ju investigated "
191
+ "a symmetric approximation to trace regularization in GPT-2 downstream fine-tuning. "
192
+ f"{_cite('roughness')} · {_cite('flat')} · {_cite('trace')} · {_cite('gpt_trace')}, Table 5 · {_cite('coordinates')}")
193
+ p("FUT++ approximates third weight derivatives of minibatch language-model loss with "
194
+ "differences between Hessian estimates at consecutive reference checkpoints. It uses "
195
+ "these terms to predict the effect of reordering training batches. Here the squared "
196
+ "norm enters the loss itself, so its gradient changes the training trajectory. "
197
+ f"{_cite('fut')}, Appendix A.1, equations 14–15.")
198
+ p("The estimator and its update", "heading")
199
+ p("J(θ) = L(θ) + λ · ‖D³L(θ)‖²<sub>F</sub>", "equation")
200
+ p("For independent Rademacher vectors u and v, form r = ∇(uᵀHv). Squaring and summing "
201
+ "its coordinates, then averaging over probes, cancels every cross term with unmatched "
202
+ "indices. The expectation is the squared Frobenius norm of the minibatch third derivative. "
203
+ "The gradient through r supplies a fourth-derivative contraction to AdamW. The "
204
+ "derivative minibatch contains two windows. A Bernoulli gate samples one eighth of "
205
+ "updates and multiplies the active contribution by eight. "
206
+ f"{_cite('sketch')} · {_link(REPOSITORY + '/blob/main/reports/preregistration.md', 'Preregistration')}")
207
+ flow.append(KeepTogether([_figure(figure_dir / figures["architecture"], max_height=140),
208
+ Paragraph("Figure 1. Trainable coordinate sets and the stochastic "
209
+ "regularization path.", styles["caption"])]))
210
+ flow.append(PageBreak())
211
+ p("Experimental design", "heading")
212
+ p("Full-weight pretraining uses a four-block causal Transformer with width 192, four heads, "
213
+ "a gated 512-wide MLP, tied embeddings and 128 targets per window. Stories use a "
214
+ "train-only vocabulary of 4,096 tokens. The adapter stage freezes Pythia-410M and trains "
215
+ "rank-eight attention QKV adapters with scale alpha 16. The first-submission timestamp "
216
+ "sets the split within 2024, grouping versions by base arXiv identifier. January through April supply training text, May supplies "
217
+ "development text, and June supplies the held-out test. "
218
+ f"{_cite('stories')} · {_cite('pythia')} · {_cite('lora')} · {_cite('abstracts')}")
219
+ p("The confirmatory horizons are 16,777,216 target tokens for stories and 524,288 for "
220
+ "abstracts. Within a stage, each seed pairs starting weights, text order and optimizer "
221
+ "schedule. The pilot calibrates penalty gradients on training data and selects strength "
222
+ "at equal development horizons. The squared-Hessian, sign-randomized and combined arms "
223
+ "test derivative order, gradient direction and incremental benefit. Initial checkpoints "
224
+ "and token unigrams supply untrained references. "
225
+ f"{_link(REPOSITORY + '/blob/main/reports/planned-runs.md', 'Run matrix')}")
226
+ p("Each update averages 32 windows for stories or eight for adapters. AdamW uses β₁ = 0.9, "
227
+ "β₂ = 0.95, matrix weight decay 0.1 and gradient norm clipping at one. Peak learning "
228
+ "rates are 0.0003 and 0.0001, respectively, with 5% warmup and cosine decay to 10% of peak. "
229
+ "Across 16 batches at the shared pilot initialization, the median ordinary-to-penalty "
230
+ "gradient-norm ratio sets the scale. Both regularizers try 1%, 3% and 10% of this scale. "
231
+ f"{_link(REPOSITORY + '/blob/main/reports/preregistration.md', 'Training and selection protocol')}")
232
+ p("Normalize and deduplicate whole documents before fitting the stories tokenizer. Prioritize "
233
+ "evaluation records when removing overlaps, and audit word-shingle similarity between "
234
+ "splits. Pack documents with an end-of-sequence token. Full evaluation counts each valid "
235
+ "target once. During training, the development curve uses a fixed subset of windows. "
236
+ f"{_link(REPOSITORY + '/blob/main/docs/data.md', 'Data preparation and overlap audit')}")
237
+ data_rows = [[STAGES[stage], name, fmt(split.get("documents"), 0), fmt(split.get("tokens"), 0)]
238
+ for stage, context in study["context"].items()
239
+ for name, split in context["datasets"].get("splits", {}).items()]
240
+ if data_rows:
241
+ flow.append(_grid(styles, ["Corpus", "Split", "Retained documents", "Packed tokens"],
242
+ data_rows, [112, 90, 132, 141]))
243
+ p("Packed-token counts include document separators. The number of valid next-token "
244
+ "targets is recorded separately during evaluation.", "caption")
245
+ p("Statistical analysis", "heading")
246
+ p("Corpus negative log-likelihood sums token losses and divides by the valid target count. "
247
+ "For each baseline, paired differences subtract baseline NLL from third-order NLL at the "
248
+ "same token budget. The registered stage decision requires both one-sided exact paired "
249
+ "sign tests to pass Holm correction at 0.05 across eight seed pairs. Ties are removed "
250
+ "from sign-test denominators. A distribution-free order-statistic interval quantifies "
251
+ "uncertainty in the median paired difference. Equal-time analyses use the latest logged "
252
+ "development checkpoint within the shortest final training time of that seed triple. "
253
+ f"{_cite('seeds')} · {_link(REPOSITORY + '/blob/main/reports/preregistration.md', 'Decision rule')}")
254
+ p("Results", "heading")
255
+ numerical = study.get("numerics",{})
256
+ single = numerical.get("pythia-joint-cuda",{})
257
+ double = numerical.get("pythia-fp64-agreement",{})
258
+ if single and double:
259
+ p("Numerical accuracy on the pretrained checkpoint", "subheading")
260
+ p(f"For identical Pythia weights and probe signs, changing the FP32 CUDA batching gave a "
261
+ f"{100*single['relative_gradient_difference']:.1f}% relative discrepancy in the training gradient. "
262
+ f"In FP64 the CPU and GPU gradients agreed to relative error {double['relative_gradient_difference']:.2g}. "
263
+ "The initial FP32 pilot is retained as a diagnostic. The amended adapter arms compute their "
264
+ "penalties in FP64 on the CPU and use CUDA for the ordinary loss and optimizer updates. "
265
+ f"{_link(REPOSITORY + '/blob/main/reports/amendments/adapter-precision.md','Pre-test amendment and raw checks')}")
266
+ run_count = len(study["runs"])
267
+ done_count = sum(completed(run) for run in study["runs"])
268
+ p(f"The ledger contains {run_count} runs and {done_count} completed summaries. "
269
+ f"{_link(REPOSITORY + '/tree/main/results', 'Raw records')} · "
270
+ f"{_link(REPOSITORY + '/blob/main/reports/experiments/experiments.md', 'Per-run ledger')}")
271
+ for stage, outcome in study["stages"].items():
272
+ p(f"<b>{STAGES[stage]}.</b> {escape(verdict_text(outcome))}")
273
+ context = study["context"][stage]
274
+ selected = context["selection"].get("ratios", {})
275
+ if selected:
276
+ p(f"Development selected trace ratio {fmt(selected.get('trace'))} and third-order "
277
+ f"ratio {fmt(selected.get('third'))}. "
278
+ f"{_link(REPOSITORY + '/blob/main/results/selection/' + stage + '.json', 'All candidate scores')}")
279
+ hours = context["feasibility"].get("projected_confirm_training_hours")
280
+ if finite(hours):
281
+ p(f"The selected-arm pilot speeds project {hours:.2f} training hours for this full "
282
+ "confirmatory stage. This estimate covers optimization time. "
283
+ f"{_link(REPOSITORY + '/blob/main/results/feasibility/' + stage + '.json', 'Measured timing basis')}")
284
+ pilots = study["pilot_comparisons"][stage]
285
+ if pilots:
286
+ changes = ", ".join(f"{describe_difference(row['delta'])} against "
287
+ f"{METHODS[row['method']]}" for row in pilots)
288
+ p(f"In the development pilot at {pilots[0]['tokens']:,} training targets, third-order "
289
+ f"training recorded {changes}. The comparison uses one seed and "
290
+ f"{pilots[0]['strength_basis']}.")
291
+ evaluated, resources = _result_tables(study)
292
+ if evaluated:
293
+ p("Scores across methods", "subheading")
294
+ flow.append(_grid(styles, ["Corpus", "Phase", "Method", "Ratio", "Runs", "Tokens/run", "Dev NLL", "Test NLL"],
295
+ evaluated, [60, 53, 105, 36, 34, 69, 58, 60]))
296
+ p("Table 1. Medians over available completed runs sharing corpus, method, development "
297
+ "strength and token horizon. NLL is in nats per target token. Dashes mark missing "
298
+ "observations. The paired seed analyses use individual final test scores.", "caption")
299
+ for key, caption in (("curves", "Development NLL by logged token count. Each line is a run; "
300
+ "panels separate training stages and phases."),
301
+ ("paired", "Individual differences in test NLL. Diamonds mark median "
302
+ "differences and horizontal segments show their registered intervals.")):
303
+ if key in figures:
304
+ flow.append(KeepTogether([_figure(figure_dir / figures[key]),
305
+ Paragraph(caption, styles["caption"])]))
306
+ p("Discussion and limitations", "heading")
307
+ p("A wide minimum permits large weight displacements at a fixed loss increase. If curvature "
308
+ "starts small and changes slowly over the displacement, the loss stays low. For the loss "
309
+ "w<super>4</super>, the squared third derivative grows quadratically with distance from the bottom, so "
310
+ "a small descent step can pull displaced weights back. A steep quadratic has constant curvature "
311
+ "and receives zero third-derivative penalty everywhere. Finding wider basins remains a "
312
+ "geometric hypothesis. "
313
+ f"{_cite('coordinates')} · {_link(REPOSITORY + '/blob/main/docs/third-derivative-penalty.md#when-can-the-penalty-favor-a-wider-minimum', 'Derivation and examples')}")
314
+ p("Predictive utility requires lower held-out loss against both baselines. A reduction in "
315
+ "the derivative estimate alone describes local geometry. Parameterization changes its "
316
+ "magnitude, including the low-rank factorization used for abstracts. The estimate targets "
317
+ "expected two-window minibatch roughness. The small datasets, limited seed count and "
318
+ "two tokenization schemes bound the interpretation. More tokens per GPU hour can change "
319
+ "the practical ranking. "
320
+ f"{_cite('coordinates')} · {_link(REPOSITORY + '/blob/main/reports/preregistration.md', 'Scope of inference')}")
321
+ p("Conclusion", "heading")
322
+ if all(outcome.get("complete") for outcome in study["stages"].values()):
323
+ confirmed = [STAGES[s] for s, outcome in study["stages"].items() if outcome.get("success")]
324
+ if confirmed:
325
+ p("The registered dual-baseline criterion was met in " + " and ".join(confirmed) +
326
+ ". The observed gain applies to the reported data, trainable coordinates and token horizons.")
327
+ else:
328
+ p("Neither stage established the registered dual-baseline improvement. The paired "
329
+ "effects and uncertainty intervals quantify the range compatible with these data.")
330
+ else:
331
+ p("The outstanding paired evaluations determine which claims can be made about prediction quality "
332
+ "at the registered horizons. The run ledger preserves every available observation and implementation failure.")
333
+ p("Appendix · Computational cost", "heading")
334
+ if resources:
335
+ for device, rows in resources.items():
336
+ p(escape(str(device)), "subheading")
337
+ flow.append(_grid(styles, ["Corpus", "Phase", "Method", "Ratio", "Runs", "Targets/run",
338
+ "Train (s)", "Targets/s", "Peak GPU (MiB)"],
339
+ rows, [56, 49, 78, 35, 34, 64, 48, 57, 54]))
340
+ p("Times and rates are per-run medians within each hardware, method, phase, strength and "
341
+ "target budget. The clock sums synchronized training steps, including batch transfer and "
342
+ "the optimizer update and any host FP64 probe while the GPU is reserved. Evaluation, checkpointing and uploads take additional time. Peak "
343
+ "memory is PyTorch’s recorded maximum allocated GPU tensor memory during the run, including "
344
+ "evaluation. Untrained controls have no training speed.", "caption")
345
+ else:
346
+ p("Hardware, training speed and peak allocated memory will appear with the first completed run.")
347
+ p("Development NLL at matched GPU training time", "subheading")
348
+ p("For each seed the cutoff is the shortest completed training time across AdamW, trace and "
349
+ "third-order training. Fixed-window development evaluations occur at discrete checkpoints. "
350
+ "We take the latest checkpoint at or before the cutoff. Each cell gives NLL in nats per target "
351
+ "token, followed by its lag behind the cutoff in seconds. Larger lags make the time comparison "
352
+ "coarser. The archived per-seed table also records the token count at each checkpoint. "
353
+ f"{_link(REPOSITORY + '/blob/main/reports/summary.md', 'Per-seed timing records')}", "caption")
354
+ matched = _matched_rows(study)
355
+ if matched:
356
+ flow.append(_grid(styles, ["Corpus", "Seed", "Cutoff (s)", "AdamW NLL (lag s)",
357
+ "Trace NLL (lag s)", "Third NLL (lag s)"],
358
+ matched, [82, 34, 65, 98, 98, 98]))
359
+ else:
360
+ p("Awaiting a complete, timed three-method confirmatory seed with eligible development checkpoints.", "caption")
361
+ nonhost = _matched_rows(study,"matched_nonhost_time")
362
+ if nonhost:
363
+ p("Adapter timing after subtracting host derivative calls", "subheading")
364
+ p("This supplementary clock removes the observed duration of host derivative calls including their "
365
+ "transfers. The table uses the same fixed development windows and reports checkpoint lags in seconds. "
366
+ "Individual CUDA kernel durations were not profiled.", "caption")
367
+ flow.append(_grid(styles,["Corpus","Seed","Cutoff (s)","AdamW NLL (lag s)",
368
+ "Trace NLL (lag s)","Third NLL (lag s)"],nonhost,[82,34,65,98,98,98]))
369
+ pair_rows = [[STAGES[stage], METHODS.get(base, base), pair["seed"],
370
+ fmt(pair["third_nll"], 5), fmt(pair["baseline_nll"], 5), fmt(pair["delta"], 5)]
371
+ for stage, outcome in study["stages"].items()
372
+ for base, stats in outcome.get("comparisons", {}).items() for pair in stats["pairs"]]
373
+ if pair_rows:
374
+ p("Appendix · Paired effects", "heading")
375
+ flow.append(_grid(styles, ["Corpus", "Baseline", "Seed", "Third NLL", "Baseline NLL", "ΔNLL"],
376
+ pair_rows, [85, 110, 40, 78, 82, 80]))
377
+ for stage, outcome in study["stages"].items():
378
+ for base, stats in outcome.get("comparisons", {}).items():
379
+ lo, hi = stats["median_ci"]
380
+ p(f"{STAGES[stage]} / {METHODS[base]}: median ΔNLL {fmt(stats['median_delta'], 5)}, "
381
+ f"interval [{fmt(lo,5)}, {fmt(hi,5)}] at achieved coverage {fmt(stats['ci_coverage'],4)}. "
382
+ f"Holm-adjusted p = {fmt(stats['p_holm'], 5)}.", "caption")
383
+ has_examples = any(run["samples"] for run in study["runs"])
384
+ if has_examples:
385
+ p("Appendix · Output examples", "heading")
386
+ p("For each stage and method, the first saved sample in run-ID order is shown in excerpt. "
387
+ "The experiment ledger contains every full saved continuation and its corresponding "
388
+ f"reference when recorded. {_link(REPOSITORY + '/tree/main/reports/experiments', 'All outputs')}")
389
+ seen = set()
390
+ for run in study["runs"]:
391
+ key = (run.get("stage"), run.get("method"))
392
+ if not run["samples"] or key in seen:
393
+ continue
394
+ seen.add(key)
395
+ sample = run["samples"][0]
396
+ label = f"{STAGES.get(key[0], key[0])} · {METHODS.get(key[1], key[1])}"
397
+ example = [Paragraph(escape(label), styles["subheading"])]
398
+ for field, name in (("prompt", "Prompt"), ("reference", "Reference"), ("continuation", "Prediction")):
399
+ if sample.get(field) is not None:
400
+ value = str(sample[field])
401
+ excerpt = value[:420] + (" […]" if len(value) > 420 else "")
402
+ example.append(Paragraph(f"<b>{name}.</b> {escape(excerpt)}", styles["caption"]))
403
+ flow.append(KeepTogether(example))
404
+ p("References and reproducibility", "heading")
405
+ for title, url in REFERENCES.values():
406
+ p(_link(url, title), "caption")
407
+ p(f"Rebuild tables, figures, the explorer and this paper with <b>uv run thirdloss report</b>. "
408
+ f"{_link(REPOSITORY, 'Code and versioned protocol')}", "caption")
409
+ p("AI statement", "subheading")
410
+ p("Codex wrote the codebase and paper from the exact specification provided by a human. "
411
+ "Human cleanup and rewriting are in progress.", "caption")
412
+
413
+ def footer(canvas, doc):
414
+ canvas.saveState()
415
+ canvas.setStrokeColor(colors.HexColor("#ccd8d3"))
416
+ canvas.line(doc.leftMargin, 40, A4[0] - doc.rightMargin, 40)
417
+ canvas.setFillColor(colors.HexColor(MUTED))
418
+ canvas.setFont("PaperSans", 7.4)
419
+ canvas.drawString(doc.leftMargin, 27, "THIRD-DERIVATIVE REGULARIZATION")
420
+ canvas.drawRightString(A4[0] - doc.rightMargin, 27, str(doc.page))
421
+ canvas.restoreState()
422
+
423
+ output.parent.mkdir(parents=True, exist_ok=True)
424
+ with NamedTemporaryFile(dir=output.parent, suffix=".pdf", delete=False) as handle:
425
+ tmp = Path(handle.name)
426
+ try:
427
+ document = SimpleDocTemplate(str(tmp), pagesize=A4, leftMargin=49, rightMargin=49,
428
+ topMargin=43, bottomMargin=54,
429
+ title="Third-derivative regularization for causal language models",
430
+ author="Libor “Burny” Burian")
431
+ document.build(flow, onFirstPage=footer, onLaterPages=footer)
432
+ os.replace(tmp, output)
433
+ finally:
434
+ tmp.unlink(missing_ok=True)
research/tests/test_reporting.py CHANGED
@@ -1,44 +1,46 @@
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
 
 
 
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
+ # The geometry examples have exact formulas and can be drawn before any training run.
37
+ assert (tmp_path / "docs" / "figures" / "penalty-directions.png").is_file()
38
+ assert not (tmp_path / "docs" / "figures" / "paired.png").exists()
39
+ assert "Related work." in readme.read_text(encoding="utf-8")
40
+ assert "## Reproduction" in readme.read_text(encoding="utf-8")
41
+ assert "AI statement" not in readme.read_text(encoding="utf-8")
42
+ reader = PdfReader(tmp_path / "reports" / "paper.pdf")
43
+ text = " ".join(page.extract_text() for page in reader.pages)
44
+ assert "AI statement" in text
45
+ assert "Awaiting paired test results" in text
46
+ assert "Libor" in text