BurnyCoder commited on
Commit
16198aa
·
verified ·
1 Parent(s): 1115bf9

Explain the flat-minima generalization hypothesis in the study materials

Browse files
research/README.md CHANGED
@@ -1,6 +1,8 @@
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
 
@@ -8,7 +10,7 @@ A minimum is **wide** if the weights can move a long way before the loss rises b
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
 
 
1
  # Third derivatives in language-model training
2
 
3
+ Sepp Hochreiter and Jürgen Schmidhuber proposed that **among models that fit the training data equally well, those in flatter minima may generalize better to unseen data**. In a flat minimum, many nearby weight settings still fit. If some weights can be rounded more coarsely without spoiling the fit, a good predictor can take fewer bits to describe under a fixed encoding. Their minimum-description-length argument links that shorter description to a lower risk of overfitting. [Hochreiter and Schmidhuber, *Flat Minima* (1997), §1](https://people.idsia.ch/~juergen/fm/node1.html)
4
+
5
+ Motivated by that hypothesis, this project asks whether penalizing rapid changes in loss curvature helps a language model predict unseen tokens. It 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)
6
 
7
  ## Can the penalty favor a wider minimum?
8
 
 
10
 
11
  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)
12
 
13
+ 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. The registered comparison tests prediction on held-out tokens at equal training-token counts. Whether the models reach wider minima is a separate hypothesis. The proposed late-training experiment would measure width in fixed weight coordinates, since rescaling weights can change measured sharpness while preserving predictions. [Training update](docs/third-derivative-penalty.md#the-actual-training-update) · [Preregistration](reports/preregistration.md) · [Follow-up plan](reports/plan.md#late-third-derivative-regularization) · [Dinh et al.](https://proceedings.mlr.press/v70/dinh17b.html)
14
 
15
  ![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)
16
 
research/docs/index.html CHANGED
@@ -1,109 +1,110 @@
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>
 
 
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">Hochreiter and Schmidhuber proposed that among equally good training fits, flatter minima may generalize better. If weights can be rounded more coarsely and still fit, a good predictor can take fewer bits to describe. Here the test of generalization is how well the model predicts unseen tokens. <a href="https://people.idsia.ch/~juergen/fm/node1.html">Flat Minima (1997) ↗</a></p>
96
+ <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>
97
+ <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>
98
+ <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">
99
+ <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>
100
+ <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">
101
+ <div class="method-links">
102
+ <a href="https://doi.org/10.1007/BFb0086566">Derivative roughness ↗</a>
103
+ <a href="https://arxiv.org/pdf/2208.05924">Hessian baseline ↗</a>
104
+ <a href="https://arxiv.org/pdf/2004.06433">Random probe estimator ↗</a>
105
+ </div>
106
+ </section>
107
+ </main>
108
+ <footer><span>Libor “Burny” Burian</span><a id="download-records" href="study.json">Download displayed records</a></footer>
109
+ </body>
110
+ </html>
research/docs/third-derivative-penalty.md CHANGED
@@ -1,189 +1,195 @@
1
- # How the project computes the third-derivative penalty
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. |
47
- | $H_{jk}=\partial_j g_k$ | How the slope along $k$ changes when $j$ moves. The **Hessian** $H_B$ is the table of all such second derivatives. |
48
- | $T_{ijk}=\partial_i H_{jk}$ | How that curvature changes when $i$ moves. The **third-derivative tensor** $T=\nabla_\theta^3\ell_B$ is the array of all ordered triples. |
49
- | $P_B=\sum_{i,j,k}T_{ijk}^2$ | The **squared Frobenius norm**. Square each entry and add over all three indices to get one training penalty. |
50
-
51
- A **pure** third derivative uses the same weight three times, as in $T_{xxx}$. A **mixed** derivative uses several weights, as in $T_{xxy}$. For a smooth loss, permuting these indices gives the same derivative value. Each ordered position still counts in the squared norm. Squaring lets increases and decreases both contribute. Two entries $+2$ and $-2$ would sum to zero, while their squares contribute $8$.
52
-
53
- ## A direct calculation beside an all-plus probe
54
-
55
- Take two weights, $x=1$ and $y=2$. Set $s=x+y$ and $\ell(x,y)=s^3/3$. In the table, differentiate the expressions in $x,y$ before substituting the values. Both $\partial_xs$ and $\partial_ys$ equal $1$.
56
-
57
- A **probe** is a vector used to take a weighted sum. Suppose the four independent sign draws for our two probes all happen to be $+1$. Then $u=v=(1,1)$ for this draw. Every weighted sum in the right column is ordinary addition.
58
-
59
- | Step | Direct derivatives, entry by entry | One probe pair, adding along the way |
60
- |---|---|---|
61
- | First derivative | $\partial_x\ell=(3s^2/3)\cdot1=s^2$. Likewise $\partial_y\ell=s^2$. The gradient is $(s^2,s^2)=(9,9)$. | Start with the same gradient. Use $u$ to add its two entries, giving $a=s^2+s^2=2s^2$. |
62
- | Second derivative | Each gradient entry has derivative $2s$ in $x$ and $2s$ in $y$. The Hessian has four entries, each $2s=6$. | Differentiate $a$ to get $(4s,4s)=(12,12)$. Use $v$ to add again, giving $b=4s+4s=8s$. |
63
- | Third derivative | Differentiate each of those four Hessian entries in both $x$ and $y$. Each derivative is $2\cdot1=2$. There are eight entries equal to $2$. | Differentiate $b$ to get $r=(\partial_x(8s),\partial_y(8s))=(8,8)$. |
64
- | Square and add | $8\times 2^2=\mathbf{32}$. | $8^2+8^2=\mathbf{128}$. |
65
-
66
- **Where did the extra contribution come from?** For the $x$ component alone, the direct calculation gives $2^2+2^2+2^2+2^2=16$. The probe gives $(2+2+2+2)^2=64$. The same thing happens for $y$. For the **raw sum**, the two routes agree exactly because the eight entries sum to $16$ and $r_x+r_y=8+8=16$. Keeping just the **pure** entries would give a squared sum of $2^2+2^2=8$. The full squared norm includes six mixed entries as well.
67
-
68
- **What happens with random signs?** For this Hessian, $u^\top H_Bv=2s(u_1+u_2)(v_1+v_2)$. If either vector has opposite entries, its sum is zero, so $r=(0,0)$. If the two entries within each vector match, both sums have magnitude $2$ and both entries of $r$ have magnitude $8$. Each vector has matching entries with probability $1/2$, independently of the other vector. Across the 16 equally likely probe pairs, 12 give $0$ and four give $128$. Their average is the exact $32$.
69
-
70
- ## Why two independent sign vectors work for any smooth loss
71
-
72
- Draw each entry of $u$ and $v$ independently, equally likely to be $+1$ or $-1$. These are **Rademacher** signs, with no division by the vector length. Hold them fixed while differentiating. The transpose in $u^\top H_Bv$ turns $u$ into a row. A dot product multiplies matching entries and adds them. In the following expansion, multiplying $H_B$ by $v$ sums along each row, and dotting with $u$ sums across rows.
73
-
74
- $$
75
- (H_Bv)_j=\sum_k H_{jk} v_k,\qquad
76
- u^\top H_Bv=\sum_j u_j(H_Bv)_j=\sum_{j,k}u_jv_k H_{jk}.
77
- $$
78
-
79
- Taking the gradient gives one number for each $i$. A derivative of a finite sum is the sum of its derivatives. The signs factor out as constants, so
80
-
81
- $$
82
- r_i=\partial_i(u^\top H_Bv)
83
- =\sum_{j,k}u_jv_k\,\partial_i H_{jk}
84
- =\sum_{j,k}u_jv_k\,T_{ijk}.
85
- $$
86
-
87
- This is the exact **contraction** for the chosen signs, meaning that two indices of the tensor have been summed and one is still free. The random estimate is the scalar $\widehat P_B=\lVert r\rVert_2^2=\sum_i r_i^2$, the squared **Euclidean length** of that vector.
88
-
89
- Squaring one component multiplies its sum by a second copy. Label the indices in the second copy $a,b$ so we can see which entries get paired.
90
-
91
- $$
92
- r_i^2=
93
- \left(\sum_{j,k}T_{ijk}u_jv_k\right)
94
- \left(\sum_{a,b}T_{iab}u_av_b\right)
95
- =\sum_{j,k,a,b}T_{ijk}T_{iab}\,u_j u_a v_k v_b.
96
- $$
97
-
98
- **Expectation** $\mathbb E$ means average over the signs at the same weights and on the same minibatch. If $j=a$, then $u_j u_a=1$. If $j\ne a$, the product is equally likely to be $+1$ or $-1$ and averages to zero. The same holds for $v_k v_b$. Independence between the vectors lets us multiply these two averages. Only $j=a$ **and** $k=b$ survive, giving
99
-
100
- $$
101
- \mathbb E_{u,v}[r_i^2]=\sum_{j,k}T_{ijk}^2,\qquad
102
- \mathbb E_{u,v}[\widehat P_B]=\sum_i\mathbb E_{u,v}[r_i^2]
103
- =\sum_{i,j,k}T_{ijk}^2=\lVert T\rVert_F^2 .
104
- $$
105
-
106
- One probe supplies signs for $j$, the other for $k$. The gradient already returns every $i$. The word **unbiased** refers to the equality after averaging. The example above shows how far a single draw can be from that average. The same identity follows from treating $(j,k)$ as a single column index in the matrix version of the result. [Bujanović and Kressner, Lemma 2.1](https://arxiv.org/pdf/2004.06433#page=3)
107
-
108
- ### What breaks if we reuse one vector?
109
-
110
- Take $\ell(x,y)=x^2y/2$. Its gradient is $(xy,x^2/2)$, so its Hessian and the two slices of its third derivative are
111
-
112
- $$
113
- H=\begin{pmatrix}y&x\\x&0\end{pmatrix},\qquad
114
- \partial_x H=\begin{pmatrix}0&1\\1&0\end{pmatrix},\qquad
115
- \partial_y H=\begin{pmatrix}1&0\\0&0\end{pmatrix}.
116
- $$
117
-
118
- Both pure third derivatives are zero. The three ones come from mixed derivatives, so the exact penalty is $3$. Multiply the Hessian by the two probes to get $u^\top H v=y u_1v_1+x(u_1v_2+u_2v_1)$. Differentiating in $x,y$ gives $r=(u_1v_2+u_2v_1,\ u_1v_1)$.
119
-
120
- | How the signs are drawn | What gets squared | Result |
121
- |---|---|---|
122
- | Independent $u,v$ | The two signs in $r_x$ reinforce half the time and cancel half the time. The square of $r_y$ is always $1$. | The estimate is $5$ or $1$ with equal probability. Its mean is $3$. |
123
- | Set $v=u$ on every draw | $r_x=u_1u_2+u_2u_1=2u_1u_2$ and $r_y=u_1^2=1$. | Every draw gives $4+1=5$. Its mean is $5$. |
124
-
125
- ## Why the project computes a vector instead of listing every derivative
126
-
127
- The ordinary training gradient already contains one exact automatic derivative per trainable coordinate, up to floating-point rounding. A third derivative has three coordinate slots. With $d$ weights the dense array has $d^3$ ordered entries. The counts below use the recorded trainable coordinates. The storage estimates count just one dense array at the arithmetic precision used by the corresponding derivative path. An exabyte (EB) is $10^{18}$ bytes. [Weight and loss definitions](../src/thirdloss/models.py) · [Adapter precision amendment](../reports/amendments/adapter-precision.md)
128
-
129
- | Trainable coordinates in this project | $d$ | Dense third-derivative entries, $d^3$ | Storage for those entries |
130
- |---|---:|---:|---:|
131
- | TinyStories decoder trained from scratch, including its shared input/output embedding | 2,557,632 | $1.67\times10^{19}$ | about 66.9 EB at 4 bytes per entry |
132
- | Research abstracts, rank-eight LoRA factors in Pythia-410M’s query/key/value projections. The pretrained base weights are frozen. | 786,432 | $4.86\times10^{17}$ | about 3.89 EB at 8 bytes per entry |
133
-
134
- To reproduce either row, read `trainable_parameters` from the linked record, cube it, and multiply by the bytes per entry. Symmetry can reduce storage to one entry per distinct unordered triple, $d(d+1)(d+2)/6$, which still grows cubically. [TinyStories parameter count](../results/stories-pilot-s00-third-r03/summary.json) · [Adapter parameter count](../results/abstracts-pilot-s00-third-r03/summary.json)
135
-
136
- You *can* compute the exact sum without storing all $d^3$ entries. For example, take $u=e_j$ and $v=e_k$, where $e_j$ has a one only at position $j$. Then $u^\top H_Bv=H_{jk}$ and $r_i=T_{ijk}$. Square and sum this vector and repeat for every ordered pair $(j,k)$. That direct scheme needs $d^2$ such vectors. The project takes one random pair on an active update. It trades an exact scalar for a noisy estimate while still differentiating the loss directly along the chosen directions. The small-model reference test explicitly builds the tensor and compares the two computations for the **same** signs. [Dense reference and derivative tests](../tests/test_derivatives.py) · [PyTorch’s Hessian–vector product tutorial](https://docs.pytorch.org/tutorials/intermediate/jacobians_hessians.html#computing-hessian-vector-products)
137
-
138
- ## The actual training update
139
-
140
- 1. **Compute the ordinary loss gradient.** Each update uses the mean next-token loss on the full training batch, 32 windows for TinyStories or eight for abstracts. In code, $\theta$ consists of the tensors with `requires_grad` enabled. [Training loop](../src/thirdloss/train.py) · [Registered batches and model configurations](../reports/planned-runs.md)
141
- 2. **Choose the derivative minibatch.** In the third-order arm, a random gate opens with probability $1/8$ per update. On an active update the code chooses two distinct windows from that batch, each with 128 target tokens. Their mean **unregularized** token loss is $\ell_B$. Averaging over signs gives the exact squared norm for those windows. Averaging over window selection as well targets $\mathbb E_B[\lVert\nabla_\theta^3\ell_B\rVert_F^2]$, the mean of the minibatch squared norms. [Window and gate sampling](../src/thirdloss/windows.py) · [Preregistration](../reports/preregistration.md)
142
- 3. **Differentiate with fixed probes.** `random_signs` draws $u,v$ separately. `hessian_vector` computes $Hu=\nabla_\theta(g^\top u)$. `third_contraction` takes $\nabla_\theta(v^\top Hu)$, and `estimate(..., "third")` computes `inner(r, r)`. For a smooth scalar loss the Hessian is symmetric, so the code’s $v^\top Hu$ equals $u^\top Hv$ in the proof. PyTorch differentiates the dot products directly and keeps their computation graph for the next derivative. [Penalty implementation](../src/thirdloss/penalties.py) · [PyTorch automatic differentiation](https://docs.pytorch.org/docs/2.15/generated/torch.autograd.grad.html)
143
- 4. **Apply the penalty gradient.** The penalty value uses third derivatives. To move the weights, the optimizer needs the derivative of that value, $\partial_m\widehat P_B=2\sum_i r_i\,\partial_m r_i$. Differentiating $r_i$ introduces **fourth** derivatives. The code adds $8\lambda\nabla_\theta\widehat P_B$ to the ordinary loss gradient on active updates, where $\lambda$ is the calibrated penalty coefficient. The factor eight compensates for the gate probability before gradient clipping and the AdamW update. For the one-weight example, differentiating the penalty $(24w)^2$ gives $1152w$. [Training objectives](../src/thirdloss/objectives.py) · [Training loop](../src/thirdloss/train.py) · [Quartic gradient check](../tests/test_derivatives.py)
144
-
145
- The amended adapter path computes derivatives in double precision on a copy with the current adapter weights. On the study laptop these calculations run on the CPU, and ordinary training uses the GPU. The code processes the two windows sequentially with the **same pair** of probes across windows. If their contractions are $r_1,r_2$, linearity gives $r_B=(r_1+r_2)/2$ for the mean loss. The code squares that mean, preserving the cross-window terms in the registered penalty. The row and column probes **within** the pair are independent. [Two-window implementation](../src/thirdloss/objectives.py) · [Precision and device choices](../reports/amendments/adapter-precision.md)
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
-
154
- Run this Python block from the repository root in the project’s locked environment. It differentiates both polynomials, enumerates every probe pair and reads the real models’ coordinate counts from their archived summaries. [SymPy differentiation](https://docs.sympy.org/latest/tutorials/intro-tutorial/calculus.html#derivatives)
155
-
156
- ~~~python
157
- from collections import Counter
158
- from itertools import product
159
- import json
160
- from pathlib import Path
161
- from sympy import Matrix, diff, hessian, symbols
162
-
163
- x, y = symbols("x y")
164
- weights = (x, y)
165
- probes = [Matrix(pair) for pair in product((-1, 1), repeat=2)]
166
-
167
- for loss in ((x + y)**3 / 3, x**2 * y / 2):
168
- entries = [diff(loss, *triple) for triple in product(weights, repeat=3)]
169
- exact = sum(entry**2 for entry in entries)
170
- H = hessian(loss, weights)
171
- counts = Counter()
172
- for u, v in product(probes, repeat=2):
173
- curvature = u.dot(H * v)
174
- r = [diff(curvature, weight) for weight in weights]
175
- counts[sum(entry**2 for entry in r)] += 1
176
- mean = sum(value * count for value, count in counts.items()) / counts.total()
177
- assert mean == exact
178
- print(loss, "exact", exact, "frequencies", sorted(counts.items()), "mean", mean)
179
-
180
- for run, bytes_per_entry in (("stories-pilot-s00-third-r03", 4),
181
- ("abstracts-pilot-s00-third-r03", 8)):
182
- summary = Path("results", run, "summary.json")
183
- d = json.loads(summary.read_text(encoding="utf-8"))["trainable_parameters"]
184
- entries = d**3
185
- print(run, f"{d:,} weights", f"{entries:.3g} entries",
186
- f"{entries * bytes_per_entry / 10**18:.3g} EB")
187
- ~~~
188
-
189
- </details>
 
 
 
 
 
 
 
1
+ # How the project computes the third-derivative penalty
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
+ ## Why might a flat minimum generalize better?
6
+
7
+ Hochreiter and Schmidhuber compared solutions that fit the training examples about equally well. They searched for a wide box of acceptable weight settings around a solution. The tolerated range for each weight determines how many digits can be discarded while preserving the fit. Under their encoding, a larger box can give a shorter description of the network. Their hypothesis was that these simpler fits would, on average, overfit less. [Box construction](https://people.idsia.ch/~juergen/fm/node2.html) · [Description-length argument](https://people.idsia.ch/~juergen/fm/node5.html) · [Assumptions about generalization](https://people.idsia.ch/~juergen/fm/node16.html)
8
+
9
+ This project compares two local quantities. The Hessian trace sums the curvatures along the principal directions. The third derivative measures changes in the full Hessian, including changes that leave the trace constant. Dinh et al. showed that rescaling a ReLU network can change measured sharpness while preserving every prediction. For that reason the proposed TinyStories follow-up measures perturbations in the same weight coordinates across runs. Wider measured directions with unchanged held-out token loss would show greater tolerance to those perturbations without evidence of better prediction. [Dinh et al., §4](https://proceedings.mlr.press/v70/dinh17b.pdf) · [Follow-up measurements](../reports/plan.md#late-third-derivative-regularization)
10
+
11
+ ## When can the penalty favor a wider minimum?
12
+
13
+ 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)
14
+
15
+ 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.
16
+
17
+ | What the objective penalizes | Term added to the loss | Term added to its gradient |
18
+ |---|---|---|
19
+ | Hessian trace (curvature in one dimension) | $\lambda\ell''$ | $\lambda\ell'''$ |
20
+ | Squared third derivative (how quickly curvature changes) | $\lambda(\ell''')^2$ | $2\lambda\ell'''\ell''''$ |
21
+
22
+ 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)
23
+
24
+ ![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)
25
+
26
+ *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)
27
+
28
+ - **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.
29
+ - **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)
30
+ - **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.
31
+
32
+ ### From a local penalty to basin width
33
+
34
+ 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.
35
+
36
+ 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
37
+
38
+ $$
39
+ \ell(w_0+r)-\ell(w_0)\ \le\ \tfrac12 h r^2+\tfrac16 M|r|^3 .
40
+ $$
41
+
42
+ 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)
43
+
44
+ ## What gets differentiated?
45
+
46
+ 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.
47
+
48
+ 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)
49
+
50
+ | Quantity | Meaning |
51
+ |---|---|
52
+ | $g_k=\partial_k\ell_B$ | The slope along weight $k$. The **gradient** $g=\nabla_\theta\ell_B$ lists these slopes for all weights. |
53
+ | $H_{jk}=\partial_j g_k$ | How the slope along $k$ changes when $j$ moves. The **Hessian** $H_B$ is the table of all such second derivatives. |
54
+ | $T_{ijk}=\partial_i H_{jk}$ | How that curvature changes when $i$ moves. The **third-derivative tensor** $T=\nabla_\theta^3\ell_B$ is the array of all ordered triples. |
55
+ | $P_B=\sum_{i,j,k}T_{ijk}^2$ | The **squared Frobenius norm**. Square each entry and add over all three indices to get one training penalty. |
56
+
57
+ A **pure** third derivative uses the same weight three times, as in $T_{xxx}$. A **mixed** derivative uses several weights, as in $T_{xxy}$. For a smooth loss, permuting these indices gives the same derivative value. Each ordered position still counts in the squared norm. Squaring lets increases and decreases both contribute. Two entries $+2$ and $-2$ would sum to zero, while their squares contribute $8$.
58
+
59
+ ## A direct calculation beside an all-plus probe
60
+
61
+ Take two weights, $x=1$ and $y=2$. Set $s=x+y$ and $\ell(x,y)=s^3/3$. In the table, differentiate the expressions in $x,y$ before substituting the values. Both $\partial_xs$ and $\partial_ys$ equal $1$.
62
+
63
+ A **probe** is a vector used to take a weighted sum. Suppose the four independent sign draws for our two probes all happen to be $+1$. Then $u=v=(1,1)$ for this draw. Every weighted sum in the right column is ordinary addition.
64
+
65
+ | Step | Direct derivatives, entry by entry | One probe pair, adding along the way |
66
+ |---|---|---|
67
+ | First derivative | $\partial_x\ell=(3s^2/3)\cdot1=s^2$. Likewise $\partial_y\ell=s^2$. The gradient is $(s^2,s^2)=(9,9)$. | Start with the same gradient. Use $u$ to add its two entries, giving $a=s^2+s^2=2s^2$. |
68
+ | Second derivative | Each gradient entry has derivative $2s$ in $x$ and $2s$ in $y$. The Hessian has four entries, each $2s=6$. | Differentiate $a$ to get $(4s,4s)=(12,12)$. Use $v$ to add again, giving $b=4s+4s=8s$. |
69
+ | Third derivative | Differentiate each of those four Hessian entries in both $x$ and $y$. Each derivative is $2\cdot1=2$. There are eight entries equal to $2$. | Differentiate $b$ to get $r=(\partial_x(8s),\partial_y(8s))=(8,8)$. |
70
+ | Square and add | $8\times 2^2=\mathbf{32}$. | $8^2+8^2=\mathbf{128}$. |
71
+
72
+ **Where did the extra contribution come from?** For the $x$ component alone, the direct calculation gives $2^2+2^2+2^2+2^2=16$. The probe gives $(2+2+2+2)^2=64$. The same thing happens for $y$. For the **raw sum**, the two routes agree exactly because the eight entries sum to $16$ and $r_x+r_y=8+8=16$. Keeping just the **pure** entries would give a squared sum of $2^2+2^2=8$. The full squared norm includes six mixed entries as well.
73
+
74
+ **What happens with random signs?** For this Hessian, $u^\top H_Bv=2s(u_1+u_2)(v_1+v_2)$. If either vector has opposite entries, its sum is zero, so $r=(0,0)$. If the two entries within each vector match, both sums have magnitude $2$ and both entries of $r$ have magnitude $8$. Each vector has matching entries with probability $1/2$, independently of the other vector. Across the 16 equally likely probe pairs, 12 give $0$ and four give $128$. Their average is the exact $32$.
75
+
76
+ ## Why two independent sign vectors work for any smooth loss
77
+
78
+ Draw each entry of $u$ and $v$ independently, equally likely to be $+1$ or $-1$. These are **Rademacher** signs, with no division by the vector length. Hold them fixed while differentiating. The transpose in $u^\top H_Bv$ turns $u$ into a row. A dot product multiplies matching entries and adds them. In the following expansion, multiplying $H_B$ by $v$ sums along each row, and dotting with $u$ sums across rows.
79
+
80
+ $$
81
+ (H_Bv)_j=\sum_k H_{jk} v_k,\qquad
82
+ u^\top H_Bv=\sum_j u_j(H_Bv)_j=\sum_{j,k}u_jv_k H_{jk}.
83
+ $$
84
+
85
+ Taking the gradient gives one number for each $i$. A derivative of a finite sum is the sum of its derivatives. The signs factor out as constants, so
86
+
87
+ $$
88
+ r_i=\partial_i(u^\top H_Bv)
89
+ =\sum_{j,k}u_jv_k\,\partial_i H_{jk}
90
+ =\sum_{j,k}u_jv_k\,T_{ijk}.
91
+ $$
92
+
93
+ This is the exact **contraction** for the chosen signs, meaning that two indices of the tensor have been summed and one is still free. The random estimate is the scalar $\widehat P_B=\lVert r\rVert_2^2=\sum_i r_i^2$, the squared **Euclidean length** of that vector.
94
+
95
+ Squaring one component multiplies its sum by a second copy. Label the indices in the second copy $a,b$ so we can see which entries get paired.
96
+
97
+ $$
98
+ r_i^2=
99
+ \left(\sum_{j,k}T_{ijk}u_jv_k\right)
100
+ \left(\sum_{a,b}T_{iab}u_av_b\right)
101
+ =\sum_{j,k,a,b}T_{ijk}T_{iab}\,u_j u_a v_k v_b.
102
+ $$
103
+
104
+ **Expectation** $\mathbb E$ means average over the signs at the same weights and on the same minibatch. If $j=a$, then $u_j u_a=1$. If $j\ne a$, the product is equally likely to be $+1$ or $-1$ and averages to zero. The same holds for $v_k v_b$. Independence between the vectors lets us multiply these two averages. Only $j=a$ **and** $k=b$ survive, giving
105
+
106
+ $$
107
+ \mathbb E_{u,v}[r_i^2]=\sum_{j,k}T_{ijk}^2,\qquad
108
+ \mathbb E_{u,v}[\widehat P_B]=\sum_i\mathbb E_{u,v}[r_i^2]
109
+ =\sum_{i,j,k}T_{ijk}^2=\lVert T\rVert_F^2 .
110
+ $$
111
+
112
+ One probe supplies signs for $j$, the other for $k$. The gradient already returns every $i$. The word **unbiased** refers to the equality after averaging. The example above shows how far a single draw can be from that average. The same identity follows from treating $(j,k)$ as a single column index in the matrix version of the result. [Bujanović and Kressner, Lemma 2.1](https://arxiv.org/pdf/2004.06433#page=3)
113
+
114
+ ### What breaks if we reuse one vector?
115
+
116
+ Take $\ell(x,y)=x^2y/2$. Its gradient is $(xy,x^2/2)$, so its Hessian and the two slices of its third derivative are
117
+
118
+ $$
119
+ H=\begin{pmatrix}y&x\\x&0\end{pmatrix},\qquad
120
+ \partial_x H=\begin{pmatrix}0&1\\1&0\end{pmatrix},\qquad
121
+ \partial_y H=\begin{pmatrix}1&0\\0&0\end{pmatrix}.
122
+ $$
123
+
124
+ Both pure third derivatives are zero. The three ones come from mixed derivatives, so the exact penalty is $3$. Multiply the Hessian by the two probes to get $u^\top H v=y u_1v_1+x(u_1v_2+u_2v_1)$. Differentiating in $x,y$ gives $r=(u_1v_2+u_2v_1,\ u_1v_1)$.
125
+
126
+ | How the signs are drawn | What gets squared | Result |
127
+ |---|---|---|
128
+ | Independent $u,v$ | The two signs in $r_x$ reinforce half the time and cancel half the time. The square of $r_y$ is always $1$. | The estimate is $5$ or $1$ with equal probability. Its mean is $3$. |
129
+ | Set $v=u$ on every draw | $r_x=u_1u_2+u_2u_1=2u_1u_2$ and $r_y=u_1^2=1$. | Every draw gives $4+1=5$. Its mean is $5$. |
130
+
131
+ ## Why the project computes a vector instead of listing every derivative
132
+
133
+ The ordinary training gradient already contains one exact automatic derivative per trainable coordinate, up to floating-point rounding. A third derivative has three coordinate slots. With $d$ weights the dense array has $d^3$ ordered entries. The counts below use the recorded trainable coordinates. The storage estimates count just one dense array at the arithmetic precision used by the corresponding derivative path. An exabyte (EB) is $10^{18}$ bytes. [Weight and loss definitions](../src/thirdloss/models.py) · [Adapter precision amendment](../reports/amendments/adapter-precision.md)
134
+
135
+ | Trainable coordinates in this project | $d$ | Dense third-derivative entries, $d^3$ | Storage for those entries |
136
+ |---|---:|---:|---:|
137
+ | TinyStories decoder trained from scratch, including its shared input/output embedding | 2,557,632 | $1.67\times10^{19}$ | about 66.9 EB at 4 bytes per entry |
138
+ | Research abstracts, rank-eight LoRA factors in Pythia-410M’s query/key/value projections. The pretrained base weights are frozen. | 786,432 | $4.86\times10^{17}$ | about 3.89 EB at 8 bytes per entry |
139
+
140
+ To reproduce either row, read `trainable_parameters` from the linked record, cube it, and multiply by the bytes per entry. Symmetry can reduce storage to one entry per distinct unordered triple, $d(d+1)(d+2)/6$, which still grows cubically. [TinyStories parameter count](../results/stories-pilot-s00-third-r03/summary.json) · [Adapter parameter count](../results/abstracts-pilot-s00-third-r03/summary.json)
141
+
142
+ You *can* compute the exact sum without storing all $d^3$ entries. For example, take $u=e_j$ and $v=e_k$, where $e_j$ has a one only at position $j$. Then $u^\top H_Bv=H_{jk}$ and $r_i=T_{ijk}$. Square and sum this vector and repeat for every ordered pair $(j,k)$. That direct scheme needs $d^2$ such vectors. The project takes one random pair on an active update. It trades an exact scalar for a noisy estimate while still differentiating the loss directly along the chosen directions. The small-model reference test explicitly builds the tensor and compares the two computations for the **same** signs. [Dense reference and derivative tests](../tests/test_derivatives.py) · [PyTorch’s Hessian–vector product tutorial](https://docs.pytorch.org/tutorials/intermediate/jacobians_hessians.html#computing-hessian-vector-products)
143
+
144
+ ## The actual training update
145
+
146
+ 1. **Compute the ordinary loss gradient.** Each update uses the mean next-token loss on the full training batch, 32 windows for TinyStories or eight for abstracts. In code, $\theta$ consists of the tensors with `requires_grad` enabled. [Training loop](../src/thirdloss/train.py) · [Registered batches and model configurations](../reports/planned-runs.md)
147
+ 2. **Choose the derivative minibatch.** In the third-order arm, a random gate opens with probability $1/8$ per update. On an active update the code chooses two distinct windows from that batch, each with 128 target tokens. Their mean **unregularized** token loss is $\ell_B$. Averaging over signs gives the exact squared norm for those windows. Averaging over window selection as well targets $\mathbb E_B[\lVert\nabla_\theta^3\ell_B\rVert_F^2]$, the mean of the minibatch squared norms. [Window and gate sampling](../src/thirdloss/windows.py) · [Preregistration](../reports/preregistration.md)
148
+ 3. **Differentiate with fixed probes.** `random_signs` draws $u,v$ separately. `hessian_vector` computes $Hu=\nabla_\theta(g^\top u)$. `third_contraction` takes $\nabla_\theta(v^\top Hu)$, and `estimate(..., "third")` computes `inner(r, r)`. For a smooth scalar loss the Hessian is symmetric, so the code’s $v^\top Hu$ equals $u^\top Hv$ in the proof. PyTorch differentiates the dot products directly and keeps their computation graph for the next derivative. [Penalty implementation](../src/thirdloss/penalties.py) · [PyTorch automatic differentiation](https://docs.pytorch.org/docs/2.15/generated/torch.autograd.grad.html)
149
+ 4. **Apply the penalty gradient.** The penalty value uses third derivatives. To move the weights, the optimizer needs the derivative of that value, $\partial_m\widehat P_B=2\sum_i r_i\,\partial_m r_i$. Differentiating $r_i$ introduces **fourth** derivatives. The code adds $8\lambda\nabla_\theta\widehat P_B$ to the ordinary loss gradient on active updates, where $\lambda$ is the calibrated penalty coefficient. The factor eight compensates for the gate probability before gradient clipping and the AdamW update. For the one-weight example, differentiating the penalty $(24w)^2$ gives $1152w$. [Training objectives](../src/thirdloss/objectives.py) · [Training loop](../src/thirdloss/train.py) · [Quartic gradient check](../tests/test_derivatives.py)
150
+
151
+ The amended adapter path computes derivatives in double precision on a copy with the current adapter weights. On the study laptop these calculations run on the CPU, and ordinary training uses the GPU. The code processes the two windows sequentially with the **same pair** of probes across windows. If their contractions are $r_1,r_2$, linearity gives $r_B=(r_1+r_2)/2$ for the mean loss. The code squares that mean, preserving the cross-window terms in the registered penalty. The row and column probes **within** the pair are independent. [Two-window implementation](../src/thirdloss/objectives.py) · [Precision and device choices](../reports/amendments/adapter-precision.md)
152
+
153
+ 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)
154
+
155
+ 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)
156
+
157
+ <details>
158
+ <summary>Reproduce the worked examples and the dense storage estimates</summary>
159
+
160
+ Run this Python block from the repository root in the project’s locked environment. It differentiates both polynomials, enumerates every probe pair and reads the real models’ coordinate counts from their archived summaries. [SymPy differentiation](https://docs.sympy.org/latest/tutorials/intro-tutorial/calculus.html#derivatives)
161
+
162
+ ~~~python
163
+ from collections import Counter
164
+ from itertools import product
165
+ import json
166
+ from pathlib import Path
167
+ from sympy import Matrix, diff, hessian, symbols
168
+
169
+ x, y = symbols("x y")
170
+ weights = (x, y)
171
+ probes = [Matrix(pair) for pair in product((-1, 1), repeat=2)]
172
+
173
+ for loss in ((x + y)**3 / 3, x**2 * y / 2):
174
+ entries = [diff(loss, *triple) for triple in product(weights, repeat=3)]
175
+ exact = sum(entry**2 for entry in entries)
176
+ H = hessian(loss, weights)
177
+ counts = Counter()
178
+ for u, v in product(probes, repeat=2):
179
+ curvature = u.dot(H * v)
180
+ r = [diff(curvature, weight) for weight in weights]
181
+ counts[sum(entry**2 for entry in r)] += 1
182
+ mean = sum(value * count for value, count in counts.items()) / counts.total()
183
+ assert mean == exact
184
+ print(loss, "exact", exact, "frequencies", sorted(counts.items()), "mean", mean)
185
+
186
+ for run, bytes_per_entry in (("stories-pilot-s00-third-r03", 4),
187
+ ("abstracts-pilot-s00-third-r03", 8)):
188
+ summary = Path("results", run, "summary.json")
189
+ d = json.loads(summary.read_text(encoding="utf-8"))["trainable_parameters"]
190
+ entries = d**3
191
+ print(run, f"{d:,} weights", f"{entries:.3g} entries",
192
+ f"{entries * bytes_per_entry / 10**18:.3g} EB")
193
+ ~~~
194
+
195
+ </details>
research/reports/literature-review.md CHANGED
@@ -1,24 +1,25 @@
1
- # Literature review
2
-
3
- **Question.** Does explicitly discouraging variation of the parameter Hessian improve out-of-sample next-token predictions? The search covered parameter-Hessian penalties, high-order derivative regularization, tensor norm estimation, automatic differentiation, compact LM benchmarks and public implementations. Input derivatives, optimizer approximations, and parameter-loss derivatives answer different questions.
4
-
5
- | Source | What it establishes | Decision for this study |
6
- |---|---|---|
7
- | [Duchon, 1977, pp. 85–87](https://doi.org/10.1007/BFb0086566) | Integrating sums of squared derivatives gives rotation-invariant roughness functionals. | Apply the local order-three density at training weights. Spline interpolation theorems do not carry over to neural training. |
8
- | [Lellmann, Morel and Schönlieb](https://www.lellmann.net/work/_media/lellmann_ssvm13.pdf) | Third-order regularizers for reconstructing surfaces use mixed partials. Isotropic smoothing can erase features on their elevation data. | Compare predictive loss independently of any reduction in curvature variation. Their total-variation penalty has a different power and integration domain. |
9
- | [Liu, Yu and Lin, equations 9–12 and §5.2](https://arxiv.org/pdf/2208.05924) | The paper defines cross-entropy plus a signed Hessian trace and reports WikiText-2 LSTM and GRU experiments. Algorithm 1 uses dense Rademacher probes. The language experiments use the sparsified variant. | Adapt the dense equation to causal Transformers. Published recurrent-model scores are external results. |
10
- | [Authors’ trace implementation](https://github.com/Dean-lyc/Hessian-Regularization/blob/7d18787b06ba3e7912bf841ea9ebe4505a6191b3/hess.py#L87-L98) | In this public code path the trace is converted to a Python number. Adding it to cross-entropy cannot transmit its parameter gradient. | Test optimizer motion and the penalty gradient. The observation concerns this released implementation path. |
11
- | [Bujanović and Kressner, especially §3](https://arxiv.org/pdf/2004.06433) | Products of independent sign vectors support unbiased trace estimation with structured probes. The randomness has different concentration properties than a full independent probe. | Unfold the order-three tensor along one index, apply a rank-one probe and square the resulting vector norm. Preserve independent probes and log stochastic variability. |
12
- | [Wolinski, ECML PKDD](https://ecmlpkdd-storage.s3.eu-central-1.amazonaws.com/preprints/2025/research/preprint_ecml_pkdd_2025_research_332.pdf) | Grouped directional derivatives make higher-order parameter information accessible for optimization. | Compute directional contractions but use their magnitude as a term in the training objective. |
13
- | [Chattopadhyay et al., equation 10](https://arxiv.org/pdf/1710.11063#page=4) · [Grad-CAM++ implementation](https://github.com/adityac94/Grad_CAM_plus_plus) | A prediction explanation weights convolutional features using diagonal second and third derivatives of a differentiable class score with respect to each feature activation. | The differentiation coordinates, scalar objective and use of cross-partials distinguish the parameter-space training penalty from this image explanation method. |
14
- | [Liu et al., ICML 2023](https://proceedings.mlr.press/v202/liu23ao.html) | Language-model runs can have similar pretraining losses and different downstream behavior. | Limit the main claim to within-domain next-token prediction. |
15
- | [Dinh et al.](https://proceedings.mlr.press/v70/dinh17b.html) | Reparameterization can alter local geometry while preserving the predictor. | Interpret geometry in the fixed training coordinates. Compare methods within each model stage. |
16
- | [Eldan and Li](https://arxiv.org/pdf/2305.07759) | Synthetic English stories allow small causal models to exhibit meaningful language behavior. | Use full-weight pretraining with fixed-prompt, uncurated continuations. |
17
- | [Pythia](https://arxiv.org/pdf/2304.01373), [LoRA](https://arxiv.org/pdf/2106.09685), [Common Pile](https://huggingface.co/datasets/common-pile/arxiv_abstracts_filtered) | An open pretrained decoder, low-rank adaptation and a dated abstracts collection support a second-domain experiment. | Restrict derivatives to the trained QKV adapters. Use first-submission months after the Pythia release. |
18
- | [Bouthillier et al.](https://proceedings.mlsys.org/paper_files/paper/2021/hash/0184b0cd3cfb185989f858a1d9f5c1eb-Abstract.html), [Lones](https://arxiv.org/abs/2108.02497), [NeurIPS checklist](https://neurips.cc/public/guides/PaperChecklist) | Evaluation needs explicit variability, data isolation, reporting and reproducibility. | Pair seeds, fix the estimand and tuning budget, and report individual runs and both comparisons. |
19
-
20
- ### Third derivatives with respect to language-model weights
21
-
22
- Yang et al. use a third weight derivative of minibatch training loss in a Taylor expansion of the Adam update. Their FUT++ method takes finite differences of approximate Hessians at successive reference checkpoints. They compare predictions for reordered batches against actual retraining of a 636-million-parameter LLaMA-style model on WikiText-103. Those measurements use the reference training trajectory. Our regularizer samples directions independently in weight space to estimate a squared norm over all mixed third partials. [Yang et al., §5.1 and Table 1](https://arxiv.org/pdf/2505.22042#page=6) · [Appendix A.1, equations 14–15](https://arxiv.org/pdf/2505.22042#page=15)
23
-
24
- McGee et al. derive a cubic model using a directional slope and two symmetric function evaluations along an optimizer step. In their language-model fine-tuning runs, GRPO supplies the slope and a separate reward-minus-KL score supplies the function evaluations. The fitted cubic combines these quantities to select a step size. Interpreting its coefficient as one objective's directional third derivative requires the slope and function values to come from that same objective. [McGee, Bergou and Dutta, §2](https://arxiv.org/pdf/2610.02190) · [Implementation, Appendix C.1.1](https://arxiv.org/pdf/2610.02190#page=28)
 
 
1
+ # Literature review
2
+
3
+ **Question.** Does explicitly discouraging variation of the parameter Hessian improve out-of-sample next-token predictions? The search covered parameter-Hessian penalties, high-order derivative regularization, tensor norm estimation, automatic differentiation, compact LM benchmarks and public implementations. Input derivatives, optimizer approximations, and parameter-loss derivatives answer different questions.
4
+
5
+ | Source | What it establishes | Decision for this study |
6
+ |---|---|---|
7
+ | [Hochreiter and Schmidhuber, *Flat Minima* (1997), §1](https://people.idsia.ch/~juergen/fm/node1.html) · [Noisy classification experiment, Table 1](https://people.idsia.ch/~juergen/fm/node7.html) | Their description-length argument predicts less expected overfitting when coarser weights suffice for a comparable fit. On their noisy classification task, flat-minimum search had lower test mean squared error than conventional backprop at every paired initialization they reported. | Test prediction on unseen tokens directly. The proposed follow-up also measures directional width within one model’s weight coordinates. [Follow-up design](plan.md#late-third-derivative-regularization) |
8
+ | [Duchon, 1977, pp. 85–87](https://doi.org/10.1007/BFb0086566) | Integrating sums of squared derivatives gives rotation-invariant roughness functionals. | Apply the local order-three density at training weights. Spline interpolation theorems do not carry over to neural training. |
9
+ | [Lellmann, Morel and Schönlieb](https://www.lellmann.net/work/_media/lellmann_ssvm13.pdf) | Third-order regularizers for reconstructing surfaces use mixed partials. Isotropic smoothing can erase features on their elevation data. | Compare predictive loss independently of any reduction in curvature variation. Their total-variation penalty has a different power and integration domain. |
10
+ | [Liu, Yu and Lin, equations 9–12 and §5.2](https://arxiv.org/pdf/2208.05924) | The paper defines cross-entropy plus a signed Hessian trace and reports WikiText-2 LSTM and GRU experiments. Algorithm 1 uses dense Rademacher probes. The language experiments use the sparsified variant. | Adapt the dense equation to causal Transformers. Published recurrent-model scores are external results. |
11
+ | [Authors’ trace implementation](https://github.com/Dean-lyc/Hessian-Regularization/blob/7d18787b06ba3e7912bf841ea9ebe4505a6191b3/hess.py#L87-L98) | In this public code path the trace is converted to a Python number. Adding it to cross-entropy cannot transmit its parameter gradient. | Test optimizer motion and the penalty gradient. The observation concerns this released implementation path. |
12
+ | [Bujanović and Kressner, especially §3](https://arxiv.org/pdf/2004.06433) | Products of independent sign vectors support unbiased trace estimation with structured probes. The randomness has different concentration properties than a full independent probe. | Unfold the order-three tensor along one index, apply a rank-one probe and square the resulting vector norm. Preserve independent probes and log stochastic variability. |
13
+ | [Wolinski, ECML PKDD](https://ecmlpkdd-storage.s3.eu-central-1.amazonaws.com/preprints/2025/research/preprint_ecml_pkdd_2025_research_332.pdf) | Grouped directional derivatives make higher-order parameter information accessible for optimization. | Compute directional contractions but use their magnitude as a term in the training objective. |
14
+ | [Chattopadhyay et al., equation 10](https://arxiv.org/pdf/1710.11063#page=4) · [Grad-CAM++ implementation](https://github.com/adityac94/Grad_CAM_plus_plus) | A prediction explanation weights convolutional features using diagonal second and third derivatives of a differentiable class score with respect to each feature activation. | The differentiation coordinates, scalar objective and use of cross-partials distinguish the parameter-space training penalty from this image explanation method. |
15
+ | [Liu et al., ICML 2023](https://proceedings.mlr.press/v202/liu23ao.html) | Language-model runs can have similar pretraining losses and different downstream behavior. | Limit the main claim to within-domain next-token prediction. |
16
+ | [Dinh et al.](https://proceedings.mlr.press/v70/dinh17b.html) | Reparameterization can alter local geometry while preserving the predictor. | Interpret geometry in the fixed training coordinates. Compare methods within each model stage. |
17
+ | [Eldan and Li](https://arxiv.org/pdf/2305.07759) | Synthetic English stories allow small causal models to exhibit meaningful language behavior. | Use full-weight pretraining with fixed-prompt, uncurated continuations. |
18
+ | [Pythia](https://arxiv.org/pdf/2304.01373), [LoRA](https://arxiv.org/pdf/2106.09685), [Common Pile](https://huggingface.co/datasets/common-pile/arxiv_abstracts_filtered) | An open pretrained decoder, low-rank adaptation and a dated abstracts collection support a second-domain experiment. | Restrict derivatives to the trained QKV adapters. Use first-submission months after the Pythia release. |
19
+ | [Bouthillier et al.](https://proceedings.mlsys.org/paper_files/paper/2021/hash/0184b0cd3cfb185989f858a1d9f5c1eb-Abstract.html), [Lones](https://arxiv.org/abs/2108.02497), [NeurIPS checklist](https://neurips.cc/public/guides/PaperChecklist) | Evaluation needs explicit variability, data isolation, reporting and reproducibility. | Pair seeds, fix the estimand and tuning budget, and report individual runs and both comparisons. |
20
+
21
+ ### Third derivatives with respect to language-model weights
22
+
23
+ Yang et al. use a third weight derivative of minibatch training loss in a Taylor expansion of the Adam update. Their FUT++ method takes finite differences of approximate Hessians at successive reference checkpoints. They compare predictions for reordered batches against actual retraining of a 636-million-parameter LLaMA-style model on WikiText-103. Those measurements use the reference training trajectory. Our regularizer samples directions independently in weight space to estimate a squared norm over all mixed third partials. [Yang et al., §5.1 and Table 1](https://arxiv.org/pdf/2505.22042#page=6) · [Appendix A.1, equations 14–15](https://arxiv.org/pdf/2505.22042#page=15)
24
+
25
+ McGee et al. derive a cubic model using a directional slope and two symmetric function evaluations along an optimizer step. In their language-model fine-tuning runs, GRPO supplies the slope and a separate reward-minus-KL score supplies the function evaluations. The fitted cubic combines these quantities to select a step size. Interpreting its coefficient as one objective's directional third derivative requires the slope and function values to come from that same objective. [McGee, Bergou and Dutta, §2](https://arxiv.org/pdf/2610.02190) · [Implementation, Appendix C.1.1](https://arxiv.org/pdf/2610.02190#page=28)
research/reports/paper.pdf CHANGED
Binary files a/research/reports/paper.pdf and b/research/reports/paper.pdf differ
 
research/reports/plan.md CHANGED
@@ -1,6 +1,6 @@
1
  # Research plan
2
 
3
- The study asks whether penalizing variation in token-loss curvature improves predictions at equal training tokens. Train a small causal decoder from scratch, then examine the same intervention in the trainable attention adapters of a pretrained decoder on a second corpus. The comparison targets predictive performance in each setting. [Preregistration](preregistration.md) · [Run matrix and optimizer settings](planned-runs.md)
4
 
5
  | Phase | Deliverable and release criterion |
6
  |---|---|
@@ -22,4 +22,4 @@ The dated progress record gives completed milestones and outstanding work. Sourc
22
 
23
  **Comparisons.** For each seed, branch from the same trace-trained weights and AdamW state. Continue with trace alone, increase trace alone, or add the third-derivative term. Use the same ramp for both increases. On training batches, match the norm of the extra trace gradient to that of the added penalty gradient before clipping. Compare timing against a fourth run using both penalties from the start. Match initialization, data order and training tokens across runs.
24
 
25
- **Readouts.** At the switch and at prespecified later checkpoints, perturb the weights both ways along fixed unit vectors. Measure the width between the first points where unregularized next-token loss on fixed training examples rises by a prespecified amount. For each seed, compare the change in median width between arms. If stronger trace preserves as much width, the result weakens the case for a distinct third-derivative effect. Compare held-out development loss at equal tokens to assess prediction separately. [Width definition](../docs/third-derivative-penalty.md#from-a-local-penalty-to-basin-width)
 
1
  # Research plan
2
 
3
+ Hochreiter and Schmidhuber hypothesized that, at comparable training loss, a model in a broad region of acceptable weights may need fewer bits to describe and may generalize better. This study asks whether penalizing variation in token-loss curvature improves held-out predictions at equal training tokens. It compares methods within a small decoder trained from scratch and within the trainable attention adapters of a pretrained decoder on a second corpus. [*Flat Minima*, §1](https://people.idsia.ch/~juergen/fm/node1.html) · [Preregistration](preregistration.md) · [Run matrix and optimizer settings](planned-runs.md)
4
 
5
  | Phase | Deliverable and release criterion |
6
  |---|---|
 
22
 
23
  **Comparisons.** For each seed, branch from the same trace-trained weights and AdamW state. Continue with trace alone, increase trace alone, or add the third-derivative term. Use the same ramp for both increases. On training batches, match the norm of the extra trace gradient to that of the added penalty gradient before clipping. Compare timing against a fourth run using both penalties from the start. Match initialization, data order and training tokens across runs.
24
 
25
+ **Readouts.** At the switch and at prespecified later checkpoints, perturb the weights both ways along fixed unit vectors. Measure the width between the first points where unregularized next-token loss on fixed training examples rises by a prespecified amount. For each seed, compare the change in median width between arms. If stronger trace preserves as much width, the result weakens the case for a distinct third-derivative effect. Compare held-out development loss at equal tokens. A width gain accompanied by lower development loss at comparable training fit would be consistent with the flat-minima hypothesis. A width gain alone would support only the geometric prediction. [Width definition](../docs/third-derivative-penalty.md#from-a-local-penalty-to-basin-width)
research/src/thirdloss/report_paper.py CHANGED
@@ -1,434 +1,436 @@
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)
 
 
 
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 (1994), Simplifying neural nets by discovering flat minima",
30
+ "https://proceedings.neurips.cc/paper/1994/hash/01882513d5fa7c329e940dda99b12147-Abstract.html"),
31
+ "flat_mdl": ("Hochreiter and Schmidhuber (1997), Flat Minima",
32
+ "https://people.idsia.ch/~juergen/fm/node1.html"),
33
+ "gpt_trace": ("Zhang, Li and Ju, Noise Stability Optimization for Finding Flat Minima: A Hessian-based Regularization Approach",
34
+ "https://arxiv.org/pdf/2306.08553#page=12"),
35
+ "roughness": ("Duchon, Splines minimizing rotation-invariant semi-norms in Sobolev spaces",
36
+ "https://doi.org/10.1007/BFb0086566"),
37
+ "trace": ("Liu, Yu and Lin, Regularizing deep neural networks with stochastic estimators of Hessian trace",
38
+ "https://arxiv.org/pdf/2208.05924"),
39
+ "sketch": ("Bujanović and Kressner, Norm and trace estimation with random rank-one vectors",
40
+ "https://arxiv.org/pdf/2004.06433"),
41
+ "fut": ("Yang et al., Estimating the effects of sample training orders for large language models without retraining",
42
+ "https://arxiv.org/pdf/2505.22042#page=16"),
43
+ "stories": ("Eldan and Li, TinyStories", "https://arxiv.org/pdf/2305.07759"),
44
+ "pythia": ("Biderman et al., Pythia", "https://arxiv.org/pdf/2304.01373"),
45
+ "lora": ("Hu et al., Low-rank adaptation of large language models", "https://arxiv.org/pdf/2106.09685"),
46
+ "abstracts": ("Common Pile, Filtered arXiv abstracts", "https://huggingface.co/datasets/common-pile/arxiv_abstracts_filtered"),
47
+ "seeds": ("Bouthillier et al., Accounting for variance in machine learning benchmarks",
48
+ "https://proceedings.mlsys.org/paper_files/paper/2021/hash/0184b0cd3cfb185989f858a1d9f5c1eb-Abstract.html"),
49
+ "coordinates": ("Dinh et al., Sharp minima can generalize for deep nets",
50
+ "https://proceedings.mlr.press/v70/dinh17b.html"),
51
+ }
52
+ TEAL = "#006c60"
53
+ INK = "#263735"
54
+ MUTED = "#4b5e59"
55
+
56
+
57
+ def _link(url, label):
58
+ return f"<link href={quoteattr(url)} color='{TEAL}'><u>{escape(str(label))}</u></link>"
59
+
60
+
61
+ def _cite(key):
62
+ label, url = REFERENCES[key]
63
+ return _link(url, label.rsplit(", ",1)[0])
64
+
65
+
66
+ def _styles():
67
+ """Use embedded Unicode fonts shipped with Matplotlib on every supported machine."""
68
+ fonts = Path(get_data_path()) / "fonts" / "ttf"
69
+ for name, file in (("PaperSans", "DejaVuSans.ttf"), ("PaperBold", "DejaVuSans-Bold.ttf"),
70
+ ("PaperSerif", "DejaVuSerif.ttf")):
71
+ if name not in pdfmetrics.getRegisteredFontNames():
72
+ pdfmetrics.registerFont(TTFont(name, str(fonts / file)))
73
+ pdfmetrics.registerFontFamily("PaperSans", normal="PaperSans", bold="PaperBold",
74
+ italic="PaperSans", boldItalic="PaperBold")
75
+ base = dict(fontName="PaperSans", fontSize=9.0, leading=14, textColor=colors.HexColor(INK),
76
+ alignment=TA_LEFT, spaceAfter=7, splitLongWords=True)
77
+ styles = {"body": ParagraphStyle("body", **base)}
78
+ for name, changes in {
79
+ "title": dict(fontName="PaperSerif", fontSize=25, leading=30, spaceAfter=9, keepWithNext=True),
80
+ "heading": dict(fontName="PaperSerif", fontSize=15, leading=20, spaceBefore=8, spaceAfter=6, keepWithNext=True),
81
+ "subheading": dict(fontName="PaperBold", fontSize=10.4, leading=14, spaceBefore=6, keepWithNext=True),
82
+ "byline": dict(fontSize=9.5, leading=15, textColor=colors.HexColor(TEAL), spaceAfter=13),
83
+ "caption": dict(fontSize=7.8, leading=11.2, textColor=colors.HexColor(MUTED), spaceAfter=7),
84
+ "cell": dict(fontSize=7.45, leading=10.4, spaceAfter=0),
85
+ "headcell": dict(fontName="PaperBold", fontSize=7.3, leading=10.4, textColor=colors.white, spaceAfter=0),
86
+ "equation": dict(fontName="PaperSerif", fontSize=12.4, leading=19, leftIndent=9,
87
+ spaceBefore=3, spaceAfter=9),
88
+ }.items():
89
+ styles[name] = ParagraphStyle(name, parent=styles["body"], **changes)
90
+ return styles
91
+
92
+
93
+ def _grid(styles, headers, rows, widths):
94
+ """Repeat the column labels if the growing experiment table spans multiple pages."""
95
+ def line(cells, style):
96
+ return [Paragraph(escape(str(cell)), styles[style]) for cell in cells]
97
+ table = LongTable([line(headers, "headcell"), *[line(r, "cell") for r in rows]],
98
+ colWidths=widths, repeatRows=1, hAlign="LEFT", splitByRow=True)
99
+ table.setStyle(TableStyle([
100
+ ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#34504a")),
101
+ ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f0f5f2")]),
102
+ ("VALIGN", (0, 0), (-1, -1), "TOP"),
103
+ ("LEFTPADDING", (0, 0), (-1, -1), 5), ("RIGHTPADDING", (0, 0), (-1, -1), 5),
104
+ ("TOPPADDING", (0, 0), (-1, -1), 4.5), ("BOTTOMPADDING", (0, 0), (-1, -1), 4.5),
105
+ ]))
106
+ return table
107
+
108
+
109
+ def _figure(path, max_width=477, max_height=240):
110
+ image = Image(str(path))
111
+ scale = min(max_width / image.imageWidth, max_height / image.imageHeight)
112
+ image.drawWidth = image.imageWidth * scale
113
+ image.drawHeight = image.imageHeight * scale
114
+ image.hAlign = "LEFT"
115
+ return image
116
+
117
+
118
+ def _result_tables(study):
119
+ """Group scores at equal token horizons and compare resource use on like hardware."""
120
+ groups = {}
121
+ for run in study["runs"]:
122
+ if completed(run):
123
+ key = (run.get("stage"), run.get("phase"), run.get("method"),
124
+ run.get("ratio"), run.get("tokens"))
125
+ groups.setdefault(key, []).append(run)
126
+ scores, resources = [], {}
127
+
128
+ def middle(runs, key, digits):
129
+ values = [r[key] for r in runs if finite(r.get(key))]
130
+ return fmt(median(values), digits) if values else "—"
131
+
132
+ for (stage, phase, method, ratio, tokens), runs in groups.items():
133
+ arm = [STAGES.get(stage, stage), phase, METHODS.get(method, method), fmt(ratio)]
134
+ scores.append([*arm, len(runs), fmt(tokens, 0), middle(runs, "dev_nll", 4), middle(runs, "test_nll", 4)])
135
+ devices = {}
136
+ for run in runs:
137
+ hardware = run.get("gpu") or run.get("device") or "Hardware unrecorded"
138
+ devices.setdefault(hardware, []).append(run)
139
+ for device, subset in devices.items():
140
+ timed = [r for r in subset if finite(r.get("train_seconds")) and r["train_seconds"] > 0]
141
+ gpu = [r for r in subset if r.get("gpu") or str(r.get("device", "")).startswith("cuda")]
142
+ resources.setdefault(device, []).append([
143
+ *arm, len(subset), fmt(tokens, 0), middle(timed, "train_seconds", 1),
144
+ middle(timed, "tokens_per_sec", 0), middle(gpu, "peak_vram_mb", 1),
145
+ ])
146
+ return scores, resources
147
+
148
+
149
+ def _matched_rows(study,key="matched_time"):
150
+ """Print every matched seed, including each arm's distance from the shared cutoff."""
151
+ rows = []
152
+ for stage, outcome in study["stages"].items():
153
+ for entry in outcome.get(key, []):
154
+ cutoff = entry["cutoff_seconds"]
155
+ losses = []
156
+ for method in ("ce", "trace", "third"):
157
+ point = entry["by_method"][method]
158
+ lag = point["staleness_seconds"]
159
+ losses.append(f"{fmt(point['dev_nll'], 4)} ({fmt(lag, 1)})")
160
+ rows.append([STAGES[stage], entry["seed"], fmt(cutoff, 1), *losses])
161
+ return rows
162
+
163
+
164
+ def write_paper(study: dict, output: Path, figure_dir: Path, figures: dict) -> None:
165
+ """Create the dated paper, with pretraining and adaptation interpreted separately."""
166
+ styles = _styles()
167
+ flow = []
168
+
169
+ def p(markup, style="body"):
170
+ flow.append(Paragraph(markup, styles[style]))
171
+
172
+ try:
173
+ local_time = datetime.fromisoformat(study["generated_at"]).astimezone(ZoneInfo("Europe/Berlin"))
174
+ except ZoneInfoNotFoundError:
175
+ local_time = datetime.fromisoformat(study["generated_at"]).astimezone()
176
+ rendered = local_time.strftime("%d %B %Y")
177
+ p("Third-derivative regularization for causal language models", "title")
178
+ p(f"Libor “Burny” Burian &nbsp;·&nbsp; {rendered}", "byline")
179
+ p("Abstract", "heading")
180
+ p("We study whether a language model improves its predictions when training penalizes "
181
+ "variation in the curvature of its next-token loss. Independent random signs produce "
182
+ "a differentiable estimate of the squared norm of all third partial derivatives in "
183
+ "the trainable coordinates. Two matched interventions compare this objective with "
184
+ "ordinary AdamW and a signed Hessian-trace penalty. " +
185
+ " ".join(f"{STAGES[s]}: {escape(verdict_text(outcome))}" for s, outcome in study["stages"].items()))
186
+ p("Motivation and related work", "heading")
187
+ p("Hochreiter and Schmidhuber proposed that flatter minima may generalize better at comparable "
188
+ "training error. Coarser weights can preserve the fit, so fewer bits can describe it. Their "
189
+ "minimum-description-length argument predicts less expected overfitting. Rescaling can alter "
190
+ "sharpness while preserving predictions, so we measure held-out token loss. "
191
+ f"{_cite('flat')} · {_cite('flat_mdl')} · {_cite('coordinates')}")
192
+ p("The Hessian can change at constant trace. Squared third partials penalize this variation, "
193
+ "adapting an order-three spline roughness measure. Earlier work studied trace regularization "
194
+ "in recurrent language models and a symmetric perturbation approximation in GPT-2 fine-tuning. "
195
+ f"{_cite('roughness')} · {_cite('trace')} · {_cite('gpt_trace')}, Table 5")
196
+ p("FUT++ uses differences between Hessian estimates at consecutive checkpoints to approximate "
197
+ "third weight derivatives and predict the effect of reordering training batches. Here the "
198
+ "squared norm enters the loss and changes the optimizer update. "
199
+ f"{_cite('fut')}, Appendix A.1, equations 14–15.")
200
+ p("The estimator and its update", "heading")
201
+ p("J(θ) = L(θ) + λ · ‖D³L(θ)‖²<sub>F</sub>", "equation")
202
+ p("For independent Rademacher vectors u and v, form r = ∇(uᵀHv). Squaring and summing "
203
+ "its coordinates, then averaging over probes, cancels every cross term with unmatched "
204
+ "indices. The expectation is the squared Frobenius norm of the minibatch third derivative. "
205
+ "The gradient through r supplies a fourth-derivative contraction to AdamW. The "
206
+ "derivative minibatch contains two windows. A Bernoulli gate samples one eighth of "
207
+ "updates and multiplies the active contribution by eight. "
208
+ f"{_cite('sketch')} · {_link(REPOSITORY + '/blob/main/reports/preregistration.md', 'Preregistration')}")
209
+ flow.append(KeepTogether([_figure(figure_dir / figures["architecture"], max_height=140),
210
+ Paragraph("Figure 1. Trainable coordinate sets and the stochastic "
211
+ "regularization path.", styles["caption"])]))
212
+ flow.append(PageBreak())
213
+ p("Experimental design", "heading")
214
+ p("Full-weight pretraining uses a four-block causal Transformer with width 192, four heads, "
215
+ "a gated 512-wide MLP, tied embeddings and 128 targets per window. Stories use a "
216
+ "train-only vocabulary of 4,096 tokens. The adapter stage freezes Pythia-410M and trains "
217
+ "rank-eight attention QKV adapters with scale alpha 16. The first-submission timestamp "
218
+ "sets the split within 2024, grouping versions by base arXiv identifier. January through April supply training text, May supplies "
219
+ "development text, and June supplies the held-out test. "
220
+ f"{_cite('stories')} · {_cite('pythia')} · {_cite('lora')} · {_cite('abstracts')}")
221
+ p("The confirmatory horizons are 16,777,216 target tokens for stories and 524,288 for "
222
+ "abstracts. Within a stage, each seed pairs starting weights, text order and optimizer "
223
+ "schedule. The pilot calibrates penalty gradients on training data and selects strength "
224
+ "at equal development horizons. The squared-Hessian, sign-randomized and combined arms "
225
+ "test derivative order, gradient direction and incremental benefit. Initial checkpoints "
226
+ "and token unigrams supply untrained references. "
227
+ f"{_link(REPOSITORY + '/blob/main/reports/planned-runs.md', 'Run matrix')}")
228
+ p("Each update averages 32 windows for stories or eight for adapters. AdamW uses β₁ = 0.9, "
229
+ "β₂ = 0.95, matrix weight decay 0.1 and gradient norm clipping at one. Peak learning "
230
+ "rates are 0.0003 and 0.0001, respectively, with 5% warmup and cosine decay to 10% of peak. "
231
+ "Across 16 batches at the shared pilot initialization, the median ordinary-to-penalty "
232
+ "gradient-norm ratio sets the scale. Both regularizers try 1%, 3% and 10% of this scale. "
233
+ f"{_link(REPOSITORY + '/blob/main/reports/preregistration.md', 'Training and selection protocol')}")
234
+ p("Normalize and deduplicate whole documents before fitting the stories tokenizer. Prioritize "
235
+ "evaluation records when removing overlaps, and audit word-shingle similarity between "
236
+ "splits. Pack documents with an end-of-sequence token. Full evaluation counts each valid "
237
+ "target once. During training, the development curve uses a fixed subset of windows. "
238
+ f"{_link(REPOSITORY + '/blob/main/docs/data.md', 'Data preparation and overlap audit')}")
239
+ data_rows = [[STAGES[stage], name, fmt(split.get("documents"), 0), fmt(split.get("tokens"), 0)]
240
+ for stage, context in study["context"].items()
241
+ for name, split in context["datasets"].get("splits", {}).items()]
242
+ if data_rows:
243
+ flow.append(_grid(styles, ["Corpus", "Split", "Retained documents", "Packed tokens"],
244
+ data_rows, [112, 90, 132, 141]))
245
+ p("Packed-token counts include document separators. The number of valid next-token "
246
+ "targets is recorded separately during evaluation.", "caption")
247
+ p("Statistical analysis", "heading")
248
+ p("Corpus negative log-likelihood sums token losses and divides by the valid target count. "
249
+ "For each baseline, paired differences subtract baseline NLL from third-order NLL at the "
250
+ "same token budget. The registered stage decision requires both one-sided exact paired "
251
+ "sign tests to pass Holm correction at 0.05 across eight seed pairs. Ties are removed "
252
+ "from sign-test denominators. A distribution-free order-statistic interval quantifies "
253
+ "uncertainty in the median paired difference. Equal-time analyses use the latest logged "
254
+ "development checkpoint within the shortest final training time of that seed triple. "
255
+ f"{_cite('seeds')} · {_link(REPOSITORY + '/blob/main/reports/preregistration.md', 'Decision rule')}")
256
+ p("Results", "heading")
257
+ numerical = study.get("numerics",{})
258
+ single = numerical.get("pythia-joint-cuda",{})
259
+ double = numerical.get("pythia-fp64-agreement",{})
260
+ if single and double:
261
+ p("Numerical accuracy on the pretrained checkpoint", "subheading")
262
+ p(f"For identical Pythia weights and probe signs, changing the FP32 CUDA batching gave a "
263
+ f"{100*single['relative_gradient_difference']:.1f}% relative discrepancy in the training gradient. "
264
+ f"In FP64 the CPU and GPU gradients agreed to relative error {double['relative_gradient_difference']:.2g}. "
265
+ "The initial FP32 pilot is retained as a diagnostic. The amended adapter arms compute their "
266
+ "penalties in FP64 on the CPU and use CUDA for the ordinary loss and optimizer updates. "
267
+ f"{_link(REPOSITORY + '/blob/main/reports/amendments/adapter-precision.md','Pre-test amendment and raw checks')}")
268
+ run_count = len(study["runs"])
269
+ done_count = sum(completed(run) for run in study["runs"])
270
+ p(f"The ledger contains {run_count} runs and {done_count} completed summaries. "
271
+ f"{_link(REPOSITORY + '/tree/main/results', 'Raw records')} · "
272
+ f"{_link(REPOSITORY + '/blob/main/reports/experiments/experiments.md', 'Per-run ledger')}")
273
+ for stage, outcome in study["stages"].items():
274
+ p(f"<b>{STAGES[stage]}.</b> {escape(verdict_text(outcome))}")
275
+ context = study["context"][stage]
276
+ selected = context["selection"].get("ratios", {})
277
+ if selected:
278
+ p(f"Development selected trace ratio {fmt(selected.get('trace'))} and third-order "
279
+ f"ratio {fmt(selected.get('third'))}. "
280
+ f"{_link(REPOSITORY + '/blob/main/results/selection/' + stage + '.json', 'All candidate scores')}")
281
+ hours = context["feasibility"].get("projected_confirm_training_hours")
282
+ if finite(hours):
283
+ p(f"The selected-arm pilot speeds project {hours:.2f} training hours for this full "
284
+ "confirmatory stage. This estimate covers optimization time. "
285
+ f"{_link(REPOSITORY + '/blob/main/results/feasibility/' + stage + '.json', 'Measured timing basis')}")
286
+ pilots = study["pilot_comparisons"][stage]
287
+ if pilots:
288
+ changes = ", ".join(f"{describe_difference(row['delta'])} against "
289
+ f"{METHODS[row['method']]}" for row in pilots)
290
+ p(f"In the development pilot at {pilots[0]['tokens']:,} training targets, third-order "
291
+ f"training recorded {changes}. The comparison uses one seed and "
292
+ f"{pilots[0]['strength_basis']}.")
293
+ evaluated, resources = _result_tables(study)
294
+ if evaluated:
295
+ p("Scores across methods", "subheading")
296
+ flow.append(_grid(styles, ["Corpus", "Phase", "Method", "Ratio", "Runs", "Tokens/run", "Dev NLL", "Test NLL"],
297
+ evaluated, [60, 53, 105, 36, 34, 69, 58, 60]))
298
+ p("Table 1. Medians over available completed runs sharing corpus, method, development "
299
+ "strength and token horizon. NLL is in nats per target token. Dashes mark missing "
300
+ "observations. The paired seed analyses use individual final test scores.", "caption")
301
+ for key, caption in (("curves", "Development NLL by logged token count. Each line is a run; "
302
+ "panels separate training stages and phases."),
303
+ ("paired", "Individual differences in test NLL. Diamonds mark median "
304
+ "differences and horizontal segments show their registered intervals.")):
305
+ if key in figures:
306
+ flow.append(KeepTogether([_figure(figure_dir / figures[key]),
307
+ Paragraph(caption, styles["caption"])]))
308
+ p("Discussion and limitations", "heading")
309
+ p("A wide minimum permits large weight displacements at a fixed loss increase. If curvature "
310
+ "starts small and changes slowly over the displacement, the loss stays low. For the loss "
311
+ "w<super>4</super>, the squared third derivative grows quadratically with distance from the bottom, so "
312
+ "a small descent step can pull displaced weights back. A steep quadratic has constant curvature "
313
+ "and receives zero third-derivative penalty everywhere. Finding wider basins remains a "
314
+ "geometric hypothesis. "
315
+ f"{_cite('coordinates')} · {_link(REPOSITORY + '/blob/main/docs/third-derivative-penalty.md#when-can-the-penalty-favor-a-wider-minimum', 'Derivation and examples')}")
316
+ p("Predictive utility requires lower held-out loss against both baselines. A reduction in "
317
+ "the derivative estimate alone describes local geometry. Parameterization changes its "
318
+ "magnitude, including the low-rank factorization used for abstracts. The estimate targets "
319
+ "expected two-window minibatch roughness. The small datasets, limited seed count and "
320
+ "two tokenization schemes bound the interpretation. More tokens per GPU hour can change "
321
+ "the practical ranking. "
322
+ f"{_cite('coordinates')} · {_link(REPOSITORY + '/blob/main/reports/preregistration.md', 'Scope of inference')}")
323
+ p("Conclusion", "heading")
324
+ if all(outcome.get("complete") for outcome in study["stages"].values()):
325
+ confirmed = [STAGES[s] for s, outcome in study["stages"].items() if outcome.get("success")]
326
+ if confirmed:
327
+ p("The registered dual-baseline criterion was met in " + " and ".join(confirmed) +
328
+ ". The observed gain applies to the reported data, trainable coordinates and token horizons.")
329
+ else:
330
+ p("Neither stage established the registered dual-baseline improvement. The paired "
331
+ "effects and uncertainty intervals quantify the range compatible with these data.")
332
+ else:
333
+ p("The outstanding paired evaluations determine which claims can be made about prediction quality "
334
+ "at the registered horizons. The run ledger preserves every available observation and implementation failure.")
335
+ p("Appendix · Computational cost", "heading")
336
+ if resources:
337
+ for device, rows in resources.items():
338
+ p(escape(str(device)), "subheading")
339
+ flow.append(_grid(styles, ["Corpus", "Phase", "Method", "Ratio", "Runs", "Targets/run",
340
+ "Train (s)", "Targets/s", "Peak GPU (MiB)"],
341
+ rows, [56, 49, 78, 35, 34, 64, 48, 57, 54]))
342
+ p("Times and rates are per-run medians within each hardware, method, phase, strength and "
343
+ "target budget. The clock sums synchronized training steps, including batch transfer and "
344
+ "the optimizer update and any host FP64 probe while the GPU is reserved. Evaluation, checkpointing and uploads take additional time. Peak "
345
+ "memory is PyTorch’s recorded maximum allocated GPU tensor memory during the run, including "
346
+ "evaluation. Untrained controls have no training speed.", "caption")
347
+ else:
348
+ p("Hardware, training speed and peak allocated memory will appear with the first completed run.")
349
+ p("Development NLL at matched GPU training time", "subheading")
350
+ p("For each seed the cutoff is the shortest completed training time across AdamW, trace and "
351
+ "third-order training. Fixed-window development evaluations occur at discrete checkpoints. "
352
+ "We take the latest checkpoint at or before the cutoff. Each cell gives NLL in nats per target "
353
+ "token, followed by its lag behind the cutoff in seconds. Larger lags make the time comparison "
354
+ "coarser. The archived per-seed table also records the token count at each checkpoint. "
355
+ f"{_link(REPOSITORY + '/blob/main/reports/summary.md', 'Per-seed timing records')}", "caption")
356
+ matched = _matched_rows(study)
357
+ if matched:
358
+ flow.append(_grid(styles, ["Corpus", "Seed", "Cutoff (s)", "AdamW NLL (lag s)",
359
+ "Trace NLL (lag s)", "Third NLL (lag s)"],
360
+ matched, [82, 34, 65, 98, 98, 98]))
361
+ else:
362
+ p("Awaiting a complete, timed three-method confirmatory seed with eligible development checkpoints.", "caption")
363
+ nonhost = _matched_rows(study,"matched_nonhost_time")
364
+ if nonhost:
365
+ p("Adapter timing after subtracting host derivative calls", "subheading")
366
+ p("This supplementary clock removes the observed duration of host derivative calls including their "
367
+ "transfers. The table uses the same fixed development windows and reports checkpoint lags in seconds. "
368
+ "Individual CUDA kernel durations were not profiled.", "caption")
369
+ flow.append(_grid(styles,["Corpus","Seed","Cutoff (s)","AdamW NLL (lag s)",
370
+ "Trace NLL (lag s)","Third NLL (lag s)"],nonhost,[82,34,65,98,98,98]))
371
+ pair_rows = [[STAGES[stage], METHODS.get(base, base), pair["seed"],
372
+ fmt(pair["third_nll"], 5), fmt(pair["baseline_nll"], 5), fmt(pair["delta"], 5)]
373
+ for stage, outcome in study["stages"].items()
374
+ for base, stats in outcome.get("comparisons", {}).items() for pair in stats["pairs"]]
375
+ if pair_rows:
376
+ p("Appendix · Paired effects", "heading")
377
+ flow.append(_grid(styles, ["Corpus", "Baseline", "Seed", "Third NLL", "Baseline NLL", "ΔNLL"],
378
+ pair_rows, [85, 110, 40, 78, 82, 80]))
379
+ for stage, outcome in study["stages"].items():
380
+ for base, stats in outcome.get("comparisons", {}).items():
381
+ lo, hi = stats["median_ci"]
382
+ p(f"{STAGES[stage]} / {METHODS[base]}: median ΔNLL {fmt(stats['median_delta'], 5)}, "
383
+ f"interval [{fmt(lo,5)}, {fmt(hi,5)}] at achieved coverage {fmt(stats['ci_coverage'],4)}. "
384
+ f"Holm-adjusted p = {fmt(stats['p_holm'], 5)}.", "caption")
385
+ has_examples = any(run["samples"] for run in study["runs"])
386
+ if has_examples:
387
+ p("Appendix · Output examples", "heading")
388
+ p("For each stage and method, the first saved sample in run-ID order is shown in excerpt. "
389
+ "The experiment ledger contains every full saved continuation and its corresponding "
390
+ f"reference when recorded. {_link(REPOSITORY + '/tree/main/reports/experiments', 'All outputs')}")
391
+ seen = set()
392
+ for run in study["runs"]:
393
+ key = (run.get("stage"), run.get("method"))
394
+ if not run["samples"] or key in seen:
395
+ continue
396
+ seen.add(key)
397
+ sample = run["samples"][0]
398
+ label = f"{STAGES.get(key[0], key[0])} · {METHODS.get(key[1], key[1])}"
399
+ example = [Paragraph(escape(label), styles["subheading"])]
400
+ for field, name in (("prompt", "Prompt"), ("reference", "Reference"), ("continuation", "Prediction")):
401
+ if sample.get(field) is not None:
402
+ value = str(sample[field])
403
+ excerpt = value[:420] + (" […]" if len(value) > 420 else "")
404
+ example.append(Paragraph(f"<b>{name}.</b> {escape(excerpt)}", styles["caption"]))
405
+ flow.append(KeepTogether(example))
406
+ p("References and reproducibility", "heading")
407
+ for title, url in REFERENCES.values():
408
+ p(_link(url, title), "caption")
409
+ p(f"Rebuild tables, figures, the explorer and this paper with <b>uv run thirdloss report</b>. "
410
+ f"{_link(REPOSITORY, 'Code and versioned protocol')}", "caption")
411
+ p("AI statement", "subheading")
412
+ p("Codex wrote the codebase and paper from the exact specification provided by a human. "
413
+ "Human cleanup and rewriting are in progress.", "caption")
414
+
415
+ def footer(canvas, doc):
416
+ canvas.saveState()
417
+ canvas.setStrokeColor(colors.HexColor("#ccd8d3"))
418
+ canvas.line(doc.leftMargin, 40, A4[0] - doc.rightMargin, 40)
419
+ canvas.setFillColor(colors.HexColor(MUTED))
420
+ canvas.setFont("PaperSans", 7.4)
421
+ canvas.drawString(doc.leftMargin, 27, "THIRD-DERIVATIVE REGULARIZATION")
422
+ canvas.drawRightString(A4[0] - doc.rightMargin, 27, str(doc.page))
423
+ canvas.restoreState()
424
+
425
+ output.parent.mkdir(parents=True, exist_ok=True)
426
+ with NamedTemporaryFile(dir=output.parent, suffix=".pdf", delete=False) as handle:
427
+ tmp = Path(handle.name)
428
+ try:
429
+ document = SimpleDocTemplate(str(tmp), pagesize=A4, leftMargin=49, rightMargin=49,
430
+ topMargin=43, bottomMargin=54,
431
+ title="Third-derivative regularization for causal language models",
432
+ author="Libor “Burny” Burian")
433
+ document.build(flow, onFirstPage=footer, onLaterPages=footer)
434
+ os.replace(tmp, output)
435
+ finally:
436
+ tmp.unlink(missing_ok=True)