BurnyCoder commited on
Commit
4115a81
·
verified ·
1 Parent(s): 4e4aff8

Publish finite-gradient recovery and all numerical checks before adapter restart

Browse files
research/docs/study.json CHANGED
The diff for this file is too large to render. See raw diff
 
research/reports/experiments/abstracts-pilot-s00-third-r03/experiment.md CHANGED
@@ -10,12 +10,8 @@ Training time is — seconds. Peak allocated GPU memory is — MiB. Development
10
 
11
  [Design and hyperparameter rationale](../../planned-runs.md) · [Saved configuration](../../../results/abstracts-pilot-s00-third-r03/config.json)
12
 
13
- ## Recorded failure
14
 
15
- **Prompt**
16
-
17
- Error
18
-
19
- **Model continuation**
20
-
21
- FloatingPointError('Nonfinite or zero third calibration norm at draw 0: inf')
 
10
 
11
  [Design and hyperparameter rationale](../../planned-runs.md) · [Saved configuration](../../../results/abstracts-pilot-s00-third-r03/config.json)
12
 
13
+ ## Recorded interruptions
14
 
15
+ | Time (UTC) | Recorded exception |
16
+ | --- | --- |
17
+ | 2026-11-25T07:00:21+00:00 | FloatingPointError('Nonfinite or zero third calibration norm at draw 0: inf') |
 
 
 
 
research/reports/experiments/abstracts-pilot-s00-third-r03/learnings.md CHANGED
@@ -1,5 +1,5 @@
1
  # Run learnings
2
 
3
- The run recorded a failure. The run ledger contains the error and last metrics.
4
 
5
  [Experiment and source records](experiment.md)
 
1
  # Run learnings
2
 
3
+ The run recorded a failure. The run ledger contains the error and last metrics. The run ledger records 1 interrupted attempt(s).
4
 
5
  [Experiment and source records](experiment.md)
research/reports/experiments/learnings.md CHANGED
@@ -6,7 +6,7 @@
6
 
7
  Independent random signs include mixed weight derivatives in the expected penalty. The trace implementation motivating the gradient check converted its estimate to a Python number. [Derivation and references](../literature-review.md)
8
 
9
- - [abstracts-pilot-s00-third-r03](./abstracts-pilot-s00-third-r03/experiment.md) — The run recorded a failure. The run ledger contains the error and last metrics.
10
 
11
  - [stories-control-s00-initial-r00](./stories-control-s00-initial-r00/experiment.md) — The observed development NLL is 8.3437 nats per target token.
12
 
 
6
 
7
  Independent random signs include mixed weight derivatives in the expected penalty. The trace implementation motivating the gradient check converted its estimate to a Python number. [Derivation and references](../literature-review.md)
8
 
9
+ - [abstracts-pilot-s00-third-r03](./abstracts-pilot-s00-third-r03/experiment.md) — The run recorded a failure. The run ledger contains the error and last metrics. The run ledger records 1 interrupted attempt(s).
10
 
11
  - [stories-control-s00-initial-r00](./stories-control-s00-initial-r00/experiment.md) — The observed development NLL is 8.3437 nats per target token.
12
 
research/reports/paper.pdf CHANGED
Binary files a/research/reports/paper.pdf and b/research/reports/paper.pdf differ
 
research/reports/progress.md CHANGED
@@ -1,6 +1,6 @@
1
  # Study progress
2
 
3
- Updated 2026-11-25T07:01:31+00:00.
4
 
5
  12 training/control records and 0 final evaluations are complete. This is 10.0% of 120 planned model milestones.
6
 
 
1
  # Study progress
2
 
3
+ Updated 2026-11-25T07:08:06+00:00.
4
 
5
  12 training/control records and 0 final evaluations are complete. This is 10.0% of 120 planned model milestones.
6
 
research/reports/reviews/adapter-verification.md CHANGED
@@ -1,5 +1,11 @@
1
- # Adapter-coordinate numerical verification
2
-
3
- Before interpreting adapter training, we checked the same GPT-NeoX, LayerNorm and PEFT modules used by the experiment on a small offline backbone. The check differentiates the squared sampled third derivative along a fixed joint displacement of the two trainable QKV factors. It also recovers the perturbed logits from an exported adapter loaded into a fresh copy of the backbone. [Executable check](../../tests/test_derivatives.py) · [PEFT checkpoint format](https://huggingface.co/docs/peft/developer_guides/checkpoint)
4
-
5
- The first version used a single close pair of parameter displacements. The finite difference disagreed with autograd at the test tolerance. Inspection of GPT-NeoX showed that eager attention explicitly evaluates softmax in single precision even with double-precision parameters. A sweep of displacement sizes showed loss of accuracy at the smallest displacements and truncation error at the largest. The revised oracle cancels the leading central-difference error using two larger displacements. Its tolerance and the model code stayed the same. The verification record archives the autograd and finite-difference values. [Upstream eager attention](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt_neox/modeling_gpt_neox.py) · [Numerical differentiation and step size](https://docs.scipy.org/doc/scipy/reference/generated/scipy.differentiate.derivative.html) · [Recorded checks](../../results/verification/tests.json)
 
 
 
 
 
 
 
1
+ # Adapter-coordinate numerical verification
2
+
3
+ Before interpreting adapter training, we checked the same GPT-NeoX, LayerNorm and PEFT modules used by the experiment on a small offline backbone. The check differentiates the squared sampled third derivative along a fixed joint displacement of the two trainable QKV factors. It also recovers the perturbed logits from an exported adapter loaded into a fresh copy of the backbone. [Executable check](../../tests/test_derivatives.py) · [PEFT checkpoint format](https://huggingface.co/docs/peft/developer_guides/checkpoint)
4
+
5
+ The first version used a single close pair of parameter displacements. The finite difference disagreed with autograd at the test tolerance. Inspection of GPT-NeoX showed that eager attention explicitly evaluates softmax in single precision even with double-precision parameters. A sweep of displacement sizes showed loss of accuracy at the smallest displacements and truncation error at the largest. The revised oracle cancels the leading central-difference error using two larger displacements. Its tolerance and the model code stayed the same. The verification record archives the autograd and finite-difference values. [Upstream eager attention](https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt_neox/modeling_gpt_neox.py) · [Numerical differentiation and step size](https://docs.scipy.org/doc/scipy/reference/generated/scipy.differentiate.derivative.html) · [Recorded checks](../../results/verification/tests.json)
6
+
7
+ ## First pretrained calibration interruption
8
+
9
+ The first probe of the pretrained model produced finite adapter-gradient coordinates but an infinite single-precision norm. A replay of the same training windows and random signs found that the sum of squares overflowed. The implementation widens the norm reduction to double precision when the ordinary result is infinite or zero. Scores, calibration draws, gates and tuning ratios keep their registered definitions. The original measurements include the number of nonfinite coordinates, both norms, elapsed time, and peak device allocations. [Replay record](../../results/verification/pythia-calibration-replay.json) · [PyTorch norm accumulation](https://docs.pytorch.org/docs/stable/generated/torch.linalg.vector_norm.html)
10
+
11
+ The joint computation also allocated more memory than the device’s dedicated VRAM. The adapter path now differentiates the two windows sequentially. For fixed probes, write their contractions as r₀ and r₁ and their mean as R. The derivative of the squared norm of R with respect to each rᵢ equals R. Propagating this cotangent through each window’s third-derivative graph and summing the resulting fourth-order contributions includes the cross-window terms. The two windows use identical probes, frozen weights during the calculation, and deterministic forwards. The verification suite compares the scalar and every gradient coordinate against a joint calculation in double precision. [Source](../../src/thirdloss/objectives.py) · [Gradient caching and the chain rule](https://arxiv.org/abs/2101.06983) · [Test](../../tests/test_derivatives.py)
research/results/verification/pythia-calibration-replay.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "timestamp": "2026-11-25T07:03:26+00:00",
3
+ "stage": "abstracts",
4
+ "method": "third",
5
+ "calibration_seed": 6247,
6
+ "draw": 0,
7
+ "trainable_coordinates": 786432,
8
+ "nonfinite_coordinates": 0,
9
+ "max_abs_gradient_repr": "4.378450575069125e+19",
10
+ "penalty_repr": "467331297837056.0",
11
+ "fp32_global_norm_repr": "inf",
12
+ "fp64_global_norm_repr": "3.02625175616504e+20",
13
+ "seconds": 63.49903899999845,
14
+ "peak_allocated_mib": 10961.75390625
15
+ }
research/results/verification/tests.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
- "checked_at": "2026-11-25T06:57:41+00:00",
3
- "git_revision": "27a4b3fca137e9f5ddf655280151135426874f98",
4
  "exit_code": 0,
5
  "cases": [
6
  {
@@ -65,7 +65,7 @@
65
  },
66
  {
67
  "test": "tests.test_analysis.test_partial_or_mismatched_results_never_unlock_primary_inference[mixed corpus]",
68
- "seconds": 0.002,
69
  "outcome": "passed"
70
  },
71
  {
@@ -85,7 +85,7 @@
85
  },
86
  {
87
  "test": "tests.test_analysis.test_time_matched_comparison_uses_one_validation_population_across_methods",
88
- "seconds": 0.001,
89
  "outcome": "passed"
90
  },
91
  {
@@ -95,37 +95,37 @@
95
  },
96
  {
97
  "test": "tests.test_data.test_prefix_candidates_match_exhaustive_jaccard_including_boundary",
98
- "seconds": 0.052,
99
  "outcome": "passed"
100
  },
101
  {
102
  "test": "tests.test_data.test_abstract_submission_month_and_base_id_grouping",
103
- "seconds": 0.035,
104
  "outcome": "passed"
105
  },
106
  {
107
  "test": "tests.test_data.test_prepare_from_parquet_proves_train_only_fit_packing_and_repair",
108
- "seconds": 0.193,
109
  "outcome": "passed"
110
  },
111
  {
112
  "test": "tests.test_derivatives.test_gpu_production_decoder_third_order_update_matches_cpu",
113
- "seconds": 3.191,
114
  "outcome": "passed"
115
  },
116
  {
117
  "test": "tests.test_derivatives.test_quartic_penalty_retains_fourth_derivative",
118
- "seconds": 0.002,
119
  "outcome": "passed"
120
  },
121
  {
122
  "test": "tests.test_derivatives.test_mixed_cubic_exactly_averages_to_tensor_norm",
123
- "seconds": 0.057,
124
  "outcome": "passed"
125
  },
126
  {
127
  "test": "tests.test_derivatives.test_random_probe_generator_gives_independent_directions",
128
- "seconds": 0.221,
129
  "outcome": "passed"
130
  },
131
  {
@@ -135,7 +135,7 @@
135
  },
136
  {
137
  "test": "tests.test_derivatives.test_penalty_supports_linear_loss_and_unused_coordinates[trace]",
138
- "seconds": 0.003,
139
  "outcome": "passed"
140
  },
141
  {
@@ -145,56 +145,66 @@
145
  },
146
  {
147
  "test": "tests.test_derivatives.test_quadratic_has_curvature_and_zero_third_derivative",
148
- "seconds": 0.006,
149
  "outcome": "passed"
150
  },
151
  {
152
  "test": "tests.test_derivatives.test_signed_hessian_trace_and_squared_norm_have_correct_gradients",
153
- "seconds": 0.004,
154
  "outcome": "passed"
155
  },
156
  {
157
  "test": "tests.test_derivatives.test_tiny_transformer_against_dense_tensor_and_finite_differences",
158
- "seconds": 1.996,
159
  "outcome": "passed"
160
  },
161
  {
162
  "test": "tests.test_derivatives.test_actual_adamw_update_responds_to_the_third_order_term",
163
- "seconds": 0.006,
164
  "outcome": "passed"
165
  },
166
  {
167
  "test": "tests.test_derivatives.test_production_story_model_exposes_full_weight_penalty_gradient",
168
- "seconds": 0.053,
169
  "outcome": "passed"
170
  },
171
  {
172
  "test": "tests.test_derivatives.test_pythia_adapter_fourth_derivative_and_portable_checkpoint",
173
- "seconds": 5.614,
174
  "outcome": "passed",
175
  "measurements": {
176
  "adapter_directional_autograd": "9035.374247002468",
177
  "adapter_directional_finite_difference": "9035.370018056445"
178
  }
179
  },
 
 
 
 
 
 
 
 
 
 
180
  {
181
  "test": "tests.test_reporting.test_snapshot_keeps_full_score_and_trace_semantics",
182
- "seconds": 0.045,
183
  "outcome": "passed"
184
  },
185
  {
186
  "test": "tests.test_reporting.test_report_before_first_run_keeps_readme_and_emits_protocol_paper",
187
- "seconds": 0.478,
188
  "outcome": "passed"
189
  },
190
  {
191
  "test": "tests.test_training.test_randomized_control_preserves_coordinate_magnitudes_and_zero_is_noop",
192
- "seconds": 0.145,
193
  "outcome": "passed"
194
  },
195
  {
196
  "test": "tests.test_training.test_step_recovery_matches_uninterrupted_weights",
197
- "seconds": 2.03,
198
  "outcome": "passed"
199
  }
200
  ]
 
1
  {
2
+ "checked_at": "2026-11-25T07:06:53+00:00",
3
+ "git_revision": "a7b41b3aeb1db27465485c69c4fa31ed732a24a5",
4
  "exit_code": 0,
5
  "cases": [
6
  {
 
65
  },
66
  {
67
  "test": "tests.test_analysis.test_partial_or_mismatched_results_never_unlock_primary_inference[mixed corpus]",
68
+ "seconds": 0.001,
69
  "outcome": "passed"
70
  },
71
  {
 
85
  },
86
  {
87
  "test": "tests.test_analysis.test_time_matched_comparison_uses_one_validation_population_across_methods",
88
+ "seconds": 0.002,
89
  "outcome": "passed"
90
  },
91
  {
 
95
  },
96
  {
97
  "test": "tests.test_data.test_prefix_candidates_match_exhaustive_jaccard_including_boundary",
98
+ "seconds": 0.057,
99
  "outcome": "passed"
100
  },
101
  {
102
  "test": "tests.test_data.test_abstract_submission_month_and_base_id_grouping",
103
+ "seconds": 0.05,
104
  "outcome": "passed"
105
  },
106
  {
107
  "test": "tests.test_data.test_prepare_from_parquet_proves_train_only_fit_packing_and_repair",
108
+ "seconds": 0.236,
109
  "outcome": "passed"
110
  },
111
  {
112
  "test": "tests.test_derivatives.test_gpu_production_decoder_third_order_update_matches_cpu",
113
+ "seconds": 2.469,
114
  "outcome": "passed"
115
  },
116
  {
117
  "test": "tests.test_derivatives.test_quartic_penalty_retains_fourth_derivative",
118
+ "seconds": 0.003,
119
  "outcome": "passed"
120
  },
121
  {
122
  "test": "tests.test_derivatives.test_mixed_cubic_exactly_averages_to_tensor_norm",
123
+ "seconds": 0.05,
124
  "outcome": "passed"
125
  },
126
  {
127
  "test": "tests.test_derivatives.test_random_probe_generator_gives_independent_directions",
128
+ "seconds": 0.179,
129
  "outcome": "passed"
130
  },
131
  {
 
135
  },
136
  {
137
  "test": "tests.test_derivatives.test_penalty_supports_linear_loss_and_unused_coordinates[trace]",
138
+ "seconds": 0.002,
139
  "outcome": "passed"
140
  },
141
  {
 
145
  },
146
  {
147
  "test": "tests.test_derivatives.test_quadratic_has_curvature_and_zero_third_derivative",
148
+ "seconds": 0.003,
149
  "outcome": "passed"
150
  },
151
  {
152
  "test": "tests.test_derivatives.test_signed_hessian_trace_and_squared_norm_have_correct_gradients",
153
+ "seconds": 0.003,
154
  "outcome": "passed"
155
  },
156
  {
157
  "test": "tests.test_derivatives.test_tiny_transformer_against_dense_tensor_and_finite_differences",
158
+ "seconds": 1.657,
159
  "outcome": "passed"
160
  },
161
  {
162
  "test": "tests.test_derivatives.test_actual_adamw_update_responds_to_the_third_order_term",
163
+ "seconds": 0.009,
164
  "outcome": "passed"
165
  },
166
  {
167
  "test": "tests.test_derivatives.test_production_story_model_exposes_full_weight_penalty_gradient",
168
+ "seconds": 0.042,
169
  "outcome": "passed"
170
  },
171
  {
172
  "test": "tests.test_derivatives.test_pythia_adapter_fourth_derivative_and_portable_checkpoint",
173
+ "seconds": 5.373,
174
  "outcome": "passed",
175
  "measurements": {
176
  "adapter_directional_autograd": "9035.374247002468",
177
  "adapter_directional_finite_difference": "9035.370018056445"
178
  }
179
  },
180
+ {
181
+ "test": "tests.test_derivatives.test_large_finite_gradient_norm_survives_squaring",
182
+ "seconds": 0.004,
183
+ "outcome": "passed"
184
+ },
185
+ {
186
+ "test": "tests.test_derivatives.test_sequential_windows_reproduce_joint_penalty_and_training_gradient",
187
+ "seconds": 0.124,
188
+ "outcome": "passed"
189
+ },
190
  {
191
  "test": "tests.test_reporting.test_snapshot_keeps_full_score_and_trace_semantics",
192
+ "seconds": 0.04,
193
  "outcome": "passed"
194
  },
195
  {
196
  "test": "tests.test_reporting.test_report_before_first_run_keeps_readme_and_emits_protocol_paper",
197
+ "seconds": 0.458,
198
  "outcome": "passed"
199
  },
200
  {
201
  "test": "tests.test_training.test_randomized_control_preserves_coordinate_magnitudes_and_zero_is_noop",
202
+ "seconds": 0.126,
203
  "outcome": "passed"
204
  },
205
  {
206
  "test": "tests.test_training.test_step_recovery_matches_uninterrupted_weights",
207
+ "seconds": 1.995,
208
  "outcome": "passed"
209
  }
210
  ]
research/src/thirdloss/objectives.py CHANGED
@@ -1,11 +1,12 @@
1
  """Ordinary CE, probe gradients and fair train-only calibration on identical initial weights."""
2
 
3
  import statistics
 
4
  import torch
5
 
6
  from .models import build_model, logits_of, token_loss, token_nll
7
- from .penalties import estimate, partials, random_signs
8
- from .records import BATCHES, read_json, sha256, write_json
9
  from .windows import TrainingWindows, generator, probe_rows
10
 
11
 
@@ -24,13 +25,44 @@ def ce_backward(model, inputs, targets, microbatch):
24
 
25
 
26
  def vector_norm(values):
27
- return torch.linalg.vector_norm(torch.stack([torch.linalg.vector_norm(x.detach()) for x in values]))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
 
30
  def probe_gradient(model, parameters, inputs, targets, kind, seed, step):
31
  """Differentiate the sampled penalty, including the fourth-order contraction."""
32
  rng = generator(inputs.device, seed, step, 827)
33
  rows = probe_rows(seed, step, len(inputs))
 
 
 
34
  base = token_loss(logits_of(model, inputs[rows]), targets[rows])
35
  value = estimate(base, parameters, kind, generator=rng)
36
  return value.detach(), partials(value, parameters, create_graph=False)
@@ -49,23 +81,41 @@ def calibrate(project, storage, stage, kind, device, microbatch):
49
  model = build_model(stage, 0, device, storage)
50
  parameters = tuple(p for p in model.parameters() if p.requires_grad)
51
  windows = TrainingWindows(data/"train.bin", 6247, BATCHES[stage])
52
- rows = []
53
- for step in range(16):
 
 
 
 
 
 
 
 
 
54
  inputs, targets = windows.get(step, device)
55
  model.zero_grad(set_to_none=True)
56
  ce_backward(model, inputs, targets, microbatch)
57
  ce_norm = vector_norm(p.grad for p in parameters if p.grad is not None).item()
58
  model.zero_grad(set_to_none=True)
 
 
 
59
  value, grads = probe_gradient(model, parameters, inputs, targets, kind, 6247, step)
60
  norm = vector_norm(grads).item()
 
61
  if not (0 < norm < float("inf") and 0 < ce_norm < float("inf")):
62
  raise FloatingPointError(f"Nonfinite or zero {kind} calibration norm at draw {step}: {norm}")
63
  rows.append({"draw":step, "ce_grad_norm":ce_norm, "penalty_grad_norm":norm,
64
- "value":value.item(), "norm_ratio":ce_norm/norm})
 
 
 
 
65
  del grads
66
  result = statistics.median(row["norm_ratio"] for row in rows)
67
  write_json(path, {"stage":stage, "kind":kind, "data_manifest_sha256":fingerprint,
68
  "unit_lambda":result, "draws":rows})
 
69
  return result
70
 
71
 
 
1
  """Ordinary CE, probe gradients and fair train-only calibration on identical initial weights."""
2
 
3
  import statistics
4
+ import time
5
  import torch
6
 
7
  from .models import build_model, logits_of, token_loss, token_nll
8
+ from .penalties import estimate, inner, partials, random_signs, third_contraction
9
+ from .records import BATCHES, read_json, sha256, time_now, write_json
10
  from .windows import TrainingWindows, generator, probe_rows
11
 
12
 
 
25
 
26
 
27
  def vector_norm(values):
28
+ """Preserve the ordinary reduction and widen it when finite FP32 coordinates overflow."""
29
+ blocks = tuple(x.detach() for x in values)
30
+ def norm(dtype=None):
31
+ return torch.linalg.vector_norm(torch.stack([torch.linalg.vector_norm(x, dtype=dtype) for x in blocks]))
32
+ ordinary = norm()
33
+ return ordinary if torch.isfinite(ordinary) and ordinary != 0 else norm(torch.float64)
34
+
35
+
36
+ def two_window_third_gradient(model, parameters, inputs, targets, u, v):
37
+ """Keep one large fourth-order graph at a time, retaining the exact joint penalty gradient.
38
+
39
+ Write R=(r0+r1)/2 for the two equal-length windows, using the same two probes for both.
40
+ The derivative of ||R||² with respect to *each* r_i is R. Backpropagate that cotangent
41
+ through both live third-derivative graphs, recomputing the first window only. This is
42
+ the gradient-caching chain rule of https://arxiv.org/abs/2101.06983 applied to D³L.
43
+ """
44
+ if len(inputs)!=2 or targets.shape!=inputs.shape:
45
+ raise ValueError("Two equal-length input/target windows are required for an adapter probe")
46
+ def contraction(index, through_fourth):
47
+ loss = token_loss(logits_of(model, inputs[index:index+1]), targets[index:index+1])
48
+ return third_contraction(loss, parameters, u, v, create_graph=through_fourth)
49
+ first = contraction(0,False)
50
+ second = contraction(1,True)
51
+ mean = tuple((a+b.detach())*0.5 for a,b in zip(first,second,strict=True))
52
+ del first
53
+ grad_second = partials(inner(second,mean),parameters,create_graph=False)
54
+ del second
55
+ grad_first = partials(inner(contraction(0,True),mean),parameters,create_graph=False)
56
+ return inner(mean,mean), tuple(a+b for a,b in zip(grad_first,grad_second,strict=True))
57
 
58
 
59
  def probe_gradient(model, parameters, inputs, targets, kind, seed, step):
60
  """Differentiate the sampled penalty, including the fourth-order contraction."""
61
  rng = generator(inputs.device, seed, step, 827)
62
  rows = probe_rows(seed, step, len(inputs))
63
+ if kind == "third" and hasattr(model, "peft_config"):
64
+ u, v = random_signs(parameters,rng), random_signs(parameters,rng)
65
+ return two_window_third_gradient(model,parameters,inputs[rows],targets[rows],u,v)
66
  base = token_loss(logits_of(model, inputs[rows]), targets[rows])
67
  value = estimate(base, parameters, kind, generator=rng)
68
  return value.detach(), partials(value, parameters, create_graph=False)
 
81
  model = build_model(stage, 0, device, storage)
82
  parameters = tuple(p for p in model.parameters() if p.requires_grad)
83
  windows = TrainingWindows(data/"train.bin", 6247, BATCHES[stage])
84
+ # Each draw has its own data/probe address. A reboot can resume a long calibration
85
+ # without mixing corpora, physical batching or old estimator implementations.
86
+ work = storage/"calibration"/f"{stage}-{kind}-draws.json"
87
+ identity = {"data_manifest_sha256":fingerprint,"microbatch":microbatch,"version":2}
88
+ partial = read_json(work) if work.exists() else {**identity,"draws":[]}
89
+ if any(partial.get(k)!=v for k,v in identity.items()):
90
+ raise ValueError(f"Different settings in partial calibration for {stage} {kind}")
91
+ rows = partial["draws"]
92
+ if [row["draw"] for row in rows] != list(range(len(rows))) or len(rows)>16:
93
+ raise ValueError(f"Discontinuous calibration record for {stage} {kind}")
94
+ for step in range(len(rows),16):
95
  inputs, targets = windows.get(step, device)
96
  model.zero_grad(set_to_none=True)
97
  ce_backward(model, inputs, targets, microbatch)
98
  ce_norm = vector_norm(p.grad for p in parameters if p.grad is not None).item()
99
  model.zero_grad(set_to_none=True)
100
+ if device.type == "cuda":
101
+ torch.cuda.reset_peak_memory_stats(device)
102
+ started = time.perf_counter()
103
  value, grads = probe_gradient(model, parameters, inputs, targets, kind, 6247, step)
104
  norm = vector_norm(grads).item()
105
+ probe_seconds = time.perf_counter()-started
106
  if not (0 < norm < float("inf") and 0 < ce_norm < float("inf")):
107
  raise FloatingPointError(f"Nonfinite or zero {kind} calibration norm at draw {step}: {norm}")
108
  rows.append({"draw":step, "ce_grad_norm":ce_norm, "penalty_grad_norm":norm,
109
+ "value":value.item(), "norm_ratio":ce_norm/norm,"probe_seconds":probe_seconds,
110
+ "peak_allocated_mib":torch.cuda.max_memory_allocated(device)/2**20 if device.type=="cuda" else None})
111
+ write_json(work,partial)
112
+ print(f"{time_now()} [calibration] {stage} {kind} draw {step+1}/16 estimate {value.item():.6g}, "
113
+ f"CE gradient norm {ce_norm:.6g}, penalty gradient norm {norm:.6g}, {probe_seconds:.2f} s",flush=True)
114
  del grads
115
  result = statistics.median(row["norm_ratio"] for row in rows)
116
  write_json(path, {"stage":stage, "kind":kind, "data_manifest_sha256":fingerprint,
117
  "unit_lambda":result, "draws":rows})
118
+ work.unlink(missing_ok=True)
119
  return result
120
 
121
 
research/src/thirdloss/penalties.py CHANGED
@@ -27,6 +27,16 @@ def inner(left, right):
27
  return torch.stack([(a * b).sum() for a, b in zip(left, right, strict=True)]).sum()
28
 
29
 
 
 
 
 
 
 
 
 
 
 
30
  def estimate(loss, parameters, kind, u=None, v=None, generator=None):
31
  """Return one differentiable estimate of trace(H), ||H||² or ||D³loss||².
32
 
@@ -37,16 +47,13 @@ def estimate(loss, parameters, kind, u=None, v=None, generator=None):
37
  if not parameters or kind not in {"trace", "hessian_norm", "third"}:
38
  raise ValueError(f"Expected trainable parameters and a derivative penalty, received {kind!r}")
39
  u = random_signs(parameters, generator) if u is None else tuple(x.detach() for x in u)
40
- gradient = partials(loss, parameters)
41
- hu = partials(inner(gradient, u), parameters)
42
- if kind == "trace":
43
- value = inner(hu, u)
44
- elif kind == "hessian_norm":
45
- value = inner(hu, hu)
46
- else:
47
  v = random_signs(parameters, generator) if v is None else tuple(x.detach() for x in v)
48
- third_vector = partials(inner(hu, v), parameters)
49
  value = inner(third_vector, third_vector)
 
 
 
50
  # A constant cubic tensor still needs an explicitly verifiable zero training gradient.
51
  anchor = torch.stack([p.reshape(-1)[0] for p in parameters]).sum() * 0
52
  return value + anchor
 
27
  return torch.stack([(a * b).sum() for a, b in zip(left, right, strict=True)]).sum()
28
 
29
 
30
+ def hessian_vector(loss, parameters, direction):
31
+ """Apply the parameter Hessian through the gradient's directional contraction."""
32
+ return partials(inner(partials(loss, parameters), direction), parameters)
33
+
34
+
35
+ def third_contraction(loss, parameters, u, v, *, create_graph=True):
36
+ """Return the weight-shaped vector D³L[u,v,:], optionally retaining its fourth derivative."""
37
+ return partials(inner(hessian_vector(loss, parameters, u), v), parameters, create_graph=create_graph)
38
+
39
+
40
  def estimate(loss, parameters, kind, u=None, v=None, generator=None):
41
  """Return one differentiable estimate of trace(H), ||H||² or ||D³loss||².
42
 
 
47
  if not parameters or kind not in {"trace", "hessian_norm", "third"}:
48
  raise ValueError(f"Expected trainable parameters and a derivative penalty, received {kind!r}")
49
  u = random_signs(parameters, generator) if u is None else tuple(x.detach() for x in u)
50
+ if kind == "third":
 
 
 
 
 
 
51
  v = random_signs(parameters, generator) if v is None else tuple(x.detach() for x in v)
52
+ third_vector = third_contraction(loss, parameters, u, v)
53
  value = inner(third_vector, third_vector)
54
+ else:
55
+ hu = hessian_vector(loss, parameters, u)
56
+ value = inner(hu, u if kind == "trace" else hu)
57
  # A constant cubic tensor still needs an explicitly verifiable zero training gradient.
58
  anchor = torch.stack([p.reshape(-1)[0] for p in parameters]).sum() * 0
59
  return value + anchor
research/src/thirdloss/release.py CHANGED
@@ -26,7 +26,7 @@ def publish_snapshot(project, message):
26
  git("commit","-m",message,"--",*public)
27
  git("push","origin","main")
28
  # Allowlist tracked files, excluding the dataset bytes, .env, logs and local environments.
29
- from huggingface_hub import CommitOperationAdd
30
  tracked = git("ls-files").splitlines()
31
  api = HfApi()
32
  operations = [CommitOperationAdd(path_in_repo="research/"+name, path_or_fileobj=project/name)
@@ -38,6 +38,9 @@ def publish_snapshot(project, message):
38
  previous = read_json(cursor) if cursor.exists() else {}
39
  hashes = {op.path_in_repo:sha256(op.path_or_fileobj) for op in operations}
40
  changed = [op for op in operations if hashes[op.path_in_repo]!=previous.get(op.path_in_repo)]
 
 
 
41
  if changed:
42
  api.create_commit(repo_id=STUDY_HUB,operations=changed,commit_message=message)
43
  write_json(cursor,hashes)
 
26
  git("commit","-m",message,"--",*public)
27
  git("push","origin","main")
28
  # Allowlist tracked files, excluding the dataset bytes, .env, logs and local environments.
29
+ from huggingface_hub import CommitOperationAdd, CommitOperationDelete
30
  tracked = git("ls-files").splitlines()
31
  api = HfApi()
32
  operations = [CommitOperationAdd(path_in_repo="research/"+name, path_or_fileobj=project/name)
 
38
  previous = read_json(cursor) if cursor.exists() else {}
39
  hashes = {op.path_in_repo:sha256(op.path_or_fileobj) for op in operations}
40
  changed = [op for op in operations if hashes[op.path_in_repo]!=previous.get(op.path_in_repo)]
41
+ # Mirror deletions too, e.g. a transient failure marker archived under attempts.json after recovery.
42
+ changed.extend(CommitOperationDelete(path_in_repo=name) for name in previous.keys()-hashes.keys()
43
+ if name.startswith("research/"))
44
  if changed:
45
  api.create_commit(repo_id=STUDY_HUB,operations=changed,commit_message=message)
46
  write_json(cursor,hashes)
research/src/thirdloss/report_records.py CHANGED
@@ -124,6 +124,11 @@ def run_record(folder: Path) -> dict:
124
  if "token_budget" in record:
125
  record["target_tokens"] = record["token_budget"]
126
  record["id"] = folder.name
 
 
 
 
 
127
  if last_error and not summary:
128
  record["status"] = "failed"
129
  record["error"] = str(last_error.get("error", "Recorded failure"))
 
124
  if "token_budget" in record:
125
  record["target_tokens"] = record["token_budget"]
126
  record["id"] = folder.name
127
+ failures = read_json(folder / "attempts.json").get("failures", [])
128
+ if last_error and last_error not in failures:
129
+ failures.append(last_error)
130
+ if failures:
131
+ record["failures"] = failures
132
  if last_error and not summary:
133
  record["status"] = "failed"
134
  record["error"] = str(last_error.get("error", "Recorded failure"))
research/src/thirdloss/reporting.py CHANGED
@@ -151,13 +151,17 @@ def _experiments(root, study):
151
  "[Design and hyperparameter rationale](../../planned-runs.md) · "
152
  f"[Saved configuration]({raw_link}config.json)",
153
  ]
154
- if run.get("error"):
155
- material += ["## Recorded failure", _sample({"prompt": "Error", "continuation": run["error"]})]
 
 
156
  if run["samples"]:
157
  material += ["## Fixed-prompt generations",
158
  *[_sample(sample) for sample in run["samples"]]]
159
  atomic_text(base / key / "experiment.md", "\n\n".join(material) + "\n")
160
  observation = _run_learning(run)
 
 
161
  atomic_text(base / key / "learnings.md", f"# Run learnings\n\n{observation}\n\n"
162
  "[Experiment and source records](experiment.md)\n")
163
  learnings.append(f"- [{key}]({link}) — {observation}")
 
151
  "[Design and hyperparameter rationale](../../planned-runs.md) · "
152
  f"[Saved configuration]({raw_link}config.json)",
153
  ]
154
+ if run.get("failures"):
155
+ material += ["## Recorded interruptions", _table(
156
+ [[failure["timestamp"],failure["error"]] for failure in run["failures"]],
157
+ ["Time (UTC)","Recorded exception"])]
158
  if run["samples"]:
159
  material += ["## Fixed-prompt generations",
160
  *[_sample(sample) for sample in run["samples"]]]
161
  atomic_text(base / key / "experiment.md", "\n\n".join(material) + "\n")
162
  observation = _run_learning(run)
163
+ if run.get("failures"):
164
+ observation += f" The run ledger records {len(run['failures'])} interrupted attempt(s)."
165
  atomic_text(base / key / "learnings.md", f"# Run learnings\n\n{observation}\n\n"
166
  "[Experiment and source records](experiment.md)\n")
167
  learnings.append(f"- [{key}]({link}) — {observation}")
research/src/thirdloss/train.py CHANGED
@@ -105,10 +105,22 @@ def run_one(project, storage, stage, method, phase, seed, ratio, device, microba
105
  locks = storage / "locks"
106
  locks.mkdir(parents=True, exist_ok=True)
107
  with FileLock(str(locks/(config["id"]+".lock"))):
 
 
 
 
 
 
 
 
 
 
108
  try:
109
  return _run(project, storage, config, recorder, device, microbatch)
110
  except Exception as exc:
111
- write_json(recorder.directory/"failure.json", {"timestamp":time_now(), "error":repr(exc)})
 
 
112
  raise
113
 
114
 
 
105
  locks = storage / "locks"
106
  locks.mkdir(parents=True, exist_ok=True)
107
  with FileLock(str(locks/(config["id"]+".lock"))):
108
+ log = recorder.directory/"attempts.json"
109
+ marker = recorder.directory/"failure.json"
110
+ def remember(failure):
111
+ """Keep the original timestamp and exception across successful or repeated retries."""
112
+ history = read_json(log) if log.exists() else {"failures":[]}
113
+ if failure not in history["failures"]:
114
+ history["failures"].append(failure)
115
+ write_json(log,history)
116
+ if marker.exists():
117
+ remember(read_json(marker))
118
  try:
119
  return _run(project, storage, config, recorder, device, microbatch)
120
  except Exception as exc:
121
+ failure = {"timestamp":time_now(), "error":repr(exc)}
122
+ write_json(marker,failure)
123
+ remember(failure)
124
  raise
125
 
126
 
research/tests/test_derivatives.py CHANGED
@@ -270,3 +270,31 @@ def test_pythia_adapter_fourth_derivative_and_portable_checkpoint(tmp_path, monk
270
  assert set(payload) == set(get_peft_model_state_dict(fresh))
271
  set_peft_model_state_dict(fresh, payload)
272
  torch.testing.assert_close(logits_of(fresh, ids), logits_of(model, ids), rtol=0, atol=0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
  assert set(payload) == set(get_peft_model_state_dict(fresh))
271
  set_peft_model_state_dict(fresh, payload)
272
  torch.testing.assert_close(logits_of(fresh, ids), logits_of(model, ids), rtol=0, atol=0)
273
+
274
+
275
+ def test_large_finite_gradient_norm_survives_squaring():
276
+ """The real adapter calibration exposed overflow only in the FP32 norm reduction."""
277
+ from thirdloss.objectives import vector_norm
278
+ blocks = (torch.tensor([3e20]), torch.tensor([4e20]))
279
+ actual = vector_norm(x for x in blocks)
280
+ torch.testing.assert_close(actual.double(), torch.tensor(5e20, dtype=torch.float64), rtol=1e-7, atol=0)
281
+
282
+
283
+ def test_sequential_windows_reproduce_joint_penalty_and_training_gradient():
284
+ """Shared probes preserve every cross-window term in the norm of the mean derivative."""
285
+ from thirdloss.models import StoryConfig, StoryTransformer, token_loss
286
+ from thirdloss.objectives import two_window_third_gradient
287
+ from thirdloss.penalties import random_signs
288
+ torch.manual_seed(23)
289
+ model = StoryTransformer(StoryConfig(vocab_size=7,width=8,heads=2,layers=1,hidden=12,context=4)).double()
290
+ params = tuple(model.parameters())
291
+ x = torch.tensor([[2,3,1,0],[4,2,5,3]])
292
+ y = (x+1)%7
293
+ rng = torch.Generator().manual_seed(7)
294
+ u,v = random_signs(params,rng),random_signs(params,rng)
295
+ joint = estimate(token_loss(model(x),y),params,"third",u=u,v=v)
296
+ reference = torch.autograd.grad(joint,params)
297
+ value,gradient = two_window_third_gradient(model,params,x,y,u,v)
298
+ torch.testing.assert_close(value,joint.detach(),rtol=3e-10,atol=1e-8)
299
+ for cached,full in zip(gradient,reference,strict=True):
300
+ torch.testing.assert_close(cached,full,rtol=1e-8,atol=1e-5)
research/tests/test_training.py CHANGED
@@ -71,6 +71,8 @@ def test_step_recovery_matches_uninterrupted_weights(tmp_path,monkeypatch):
71
  train.run_one(project,root,"stories","third","smoke",seed,0.03,torch.device("cpu"))
72
  monkeypatch.setattr(train,"save_state",saved)
73
  resumed = train.run_one(project,root,"stories","third","smoke",seed,0.03,torch.device("cpu"))
 
 
74
  import shutil
75
  reference = tmp_path/"reference"
76
  shutil.copytree(project/".git",reference/".git")
 
71
  train.run_one(project,root,"stories","third","smoke",seed,0.03,torch.device("cpu"))
72
  monkeypatch.setattr(train,"save_state",saved)
73
  resumed = train.run_one(project,root,"stories","third","smoke",seed,0.03,torch.device("cpu"))
74
+ history = train.read_json(project/"results"/resumed["id"]/"attempts.json")["failures"]
75
+ assert len(history) == 1 and "intentional restart fixture" in history[0]["error"]
76
  import shutil
77
  reference = tmp_path/"reference"
78
  shutil.copytree(project/".git",reference/".git")