Publish finite-gradient recovery and all numerical checks before adapter restart
Browse filesFiles changed (17)
- research/docs/study.json
- research/reports/experiments/abstracts-pilot-s00-third-r03/experiment.md+4-8
- research/reports/experiments/abstracts-pilot-s00-third-r03/learnings.md+1-1
- research/reports/experiments/learnings.md+1-1
- research/reports/paper.pdf
- research/reports/progress.md+1-1
- research/reports/reviews/adapter-verification.md+11-5
- research/results/verification/pythia-calibration-replay.jsonAdded+15
- research/results/verification/tests.json+32-22
- research/src/thirdloss/objectives.py+56-6
- research/src/thirdloss/penalties.py+15-8
- research/src/thirdloss/release.py+4-1
- research/src/thirdloss/report_records.py+5
- research/src/thirdloss/reporting.py+6-2
- research/src/thirdloss/train.py+13-1
- research/tests/test_derivatives.py+28
- research/tests/test_training.py+2
9 unmodified lines1011121314151617181920219 unmodified lines[Design and hyperparameter rationale](../../planned-runs.md) · [Saved configuration](../../../results/abstracts-pilot-s00-third-r03/config.json)## Recorded failure**Prompt**Error**Model continuation**FloatingPointError('Nonfinite or zero third calibration norm at draw 0: inf')9 unmodified lines10111213141516179 unmodified lines[Design and hyperparameter rationale](../../planned-runs.md) · [Saved configuration](../../../results/abstracts-pilot-s00-third-r03/config.json)## Recorded interruptions| Time (UTC) | Recorded exception || --- | --- || 2026-11-25T07:00:21+00:00 | FloatingPointError('Nonfinite or zero third calibration norm at draw 0: inf') |
12345# Run learningsThe run recorded a failure. The run ledger contains the error and last metrics.[Experiment and source records](experiment.md)12345# Run learningsThe run recorded a failure. The run ledger contains the error and last metrics. The run ledger records 1 interrupted attempt(s).[Experiment and source records](experiment.md)
5 unmodified lines67891011125 unmodified linesIndependent 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)- [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.- [stories-control-s00-initial-r00](./stories-control-s00-initial-r00/experiment.md) — The observed development NLL is 8.3437 nats per target token.5 unmodified lines67891011125 unmodified linesIndependent 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)- [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).- [stories-control-s00-initial-r00](./stories-control-s00-initial-r00/experiment.md) — The observed development NLL is 8.3437 nats per target token.
123456# Study progressUpdated 2026-11-25T07:01:31+00:00.12 training/control records and 0 final evaluations are complete. This is 10.0% of 120 planned model milestones.123456# Study progressUpdated 2026-11-25T07:08:06+00:00.12 training/control records and 0 final evaluations are complete. This is 10.0% of 120 planned model milestones.
12345# Adapter-coordinate numerical verificationBefore 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)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)1234567891011# Adapter-coordinate numerical verificationBefore 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)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)## First pretrained calibration interruptionThe 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)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)
123456789101112131415{
"timestamp": "2026-11-25T07:03:26+00:00",
"stage": "abstracts",
"method": "third",
"calibration_seed": 6247,
"draw": 0,
"trainable_coordinates": 786432,
"nonfinite_coordinates": 0,
"max_abs_gradient_repr": "4.378450575069125e+19",
"penalty_repr": "467331297837056.0",
"fp32_global_norm_repr": "inf",
"fp64_global_norm_repr": "3.02625175616504e+20",
"seconds": 63.49903899999845,
"peak_allocated_mib": 10961.75390625
}12345658 unmodified lines6566676869707113 unmodified lines858687888990913 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301313 unmodified lines1351361371381391401413 unmodified lines145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200{"checked_at": "2026-11-25T06:57:41+00:00","git_revision": "27a4b3fca137e9f5ddf655280151135426874f98","exit_code": 0,"cases": [{58 unmodified lines},{"test": "tests.test_analysis.test_partial_or_mismatched_results_never_unlock_primary_inference[mixed corpus]","seconds": 0.002,"outcome": "passed"},{13 unmodified lines},{"test": "tests.test_analysis.test_time_matched_comparison_uses_one_validation_population_across_methods","seconds": 0.001,"outcome": "passed"},{3 unmodified lines},{"test": "tests.test_data.test_prefix_candidates_match_exhaustive_jaccard_including_boundary","seconds": 0.052,"outcome": "passed"},{"test": "tests.test_data.test_abstract_submission_month_and_base_id_grouping","seconds": 0.035,"outcome": "passed"},{"test": "tests.test_data.test_prepare_from_parquet_proves_train_only_fit_packing_and_repair","seconds": 0.193,"outcome": "passed"},{"test": "tests.test_derivatives.test_gpu_production_decoder_third_order_update_matches_cpu","seconds": 3.191,"outcome": "passed"},{"test": "tests.test_derivatives.test_quartic_penalty_retains_fourth_derivative","seconds": 0.002,"outcome": "passed"},{"test": "tests.test_derivatives.test_mixed_cubic_exactly_averages_to_tensor_norm","seconds": 0.057,"outcome": "passed"},{"test": "tests.test_derivatives.test_random_probe_generator_gives_independent_directions","seconds": 0.221,"outcome": "passed"},{3 unmodified lines},{"test": "tests.test_derivatives.test_penalty_supports_linear_loss_and_unused_coordinates[trace]","seconds": 0.003,"outcome": "passed"},{3 unmodified lines},{"test": "tests.test_derivatives.test_quadratic_has_curvature_and_zero_third_derivative","seconds": 0.006,"outcome": "passed"},{"test": "tests.test_derivatives.test_signed_hessian_trace_and_squared_norm_have_correct_gradients","seconds": 0.004,"outcome": "passed"},{"test": "tests.test_derivatives.test_tiny_transformer_against_dense_tensor_and_finite_differences","seconds": 1.996,"outcome": "passed"},{"test": "tests.test_derivatives.test_actual_adamw_update_responds_to_the_third_order_term","seconds": 0.006,"outcome": "passed"},{"test": "tests.test_derivatives.test_production_story_model_exposes_full_weight_penalty_gradient","seconds": 0.053,"outcome": "passed"},{"test": "tests.test_derivatives.test_pythia_adapter_fourth_derivative_and_portable_checkpoint","seconds": 5.614,"outcome": "passed","measurements": {"adapter_directional_autograd": "9035.374247002468","adapter_directional_finite_difference": "9035.370018056445"}},{"test": "tests.test_reporting.test_snapshot_keeps_full_score_and_trace_semantics","seconds": 0.045,"outcome": "passed"},{"test": "tests.test_reporting.test_report_before_first_run_keeps_readme_and_emits_protocol_paper","seconds": 0.478,"outcome": "passed"},{"test": "tests.test_training.test_randomized_control_preserves_coordinate_magnitudes_and_zero_is_noop","seconds": 0.145,"outcome": "passed"},{"test": "tests.test_training.test_step_recovery_matches_uninterrupted_weights","seconds": 2.03,"outcome": "passed"}]12345658 unmodified lines6566676869707113 unmodified lines858687888990913 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301313 unmodified lines1351361371381391401413 unmodified lines145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210{"checked_at": "2026-11-25T07:06:53+00:00","git_revision": "a7b41b3aeb1db27465485c69c4fa31ed732a24a5","exit_code": 0,"cases": [{58 unmodified lines},{"test": "tests.test_analysis.test_partial_or_mismatched_results_never_unlock_primary_inference[mixed corpus]","seconds": 0.001,"outcome": "passed"},{13 unmodified lines},{"test": "tests.test_analysis.test_time_matched_comparison_uses_one_validation_population_across_methods","seconds": 0.002,"outcome": "passed"},{3 unmodified lines},{"test": "tests.test_data.test_prefix_candidates_match_exhaustive_jaccard_including_boundary","seconds": 0.057,"outcome": "passed"},{"test": "tests.test_data.test_abstract_submission_month_and_base_id_grouping","seconds": 0.05,"outcome": "passed"},{"test": "tests.test_data.test_prepare_from_parquet_proves_train_only_fit_packing_and_repair","seconds": 0.236,"outcome": "passed"},{"test": "tests.test_derivatives.test_gpu_production_decoder_third_order_update_matches_cpu","seconds": 2.469,"outcome": "passed"},{"test": "tests.test_derivatives.test_quartic_penalty_retains_fourth_derivative","seconds": 0.003,"outcome": "passed"},{"test": "tests.test_derivatives.test_mixed_cubic_exactly_averages_to_tensor_norm","seconds": 0.05,"outcome": "passed"},{"test": "tests.test_derivatives.test_random_probe_generator_gives_independent_directions","seconds": 0.179,"outcome": "passed"},{3 unmodified lines},{"test": "tests.test_derivatives.test_penalty_supports_linear_loss_and_unused_coordinates[trace]","seconds": 0.002,"outcome": "passed"},{3 unmodified lines},{"test": "tests.test_derivatives.test_quadratic_has_curvature_and_zero_third_derivative","seconds": 0.003,"outcome": "passed"},{"test": "tests.test_derivatives.test_signed_hessian_trace_and_squared_norm_have_correct_gradients","seconds": 0.003,"outcome": "passed"},{"test": "tests.test_derivatives.test_tiny_transformer_against_dense_tensor_and_finite_differences","seconds": 1.657,"outcome": "passed"},{"test": "tests.test_derivatives.test_actual_adamw_update_responds_to_the_third_order_term","seconds": 0.009,"outcome": "passed"},{"test": "tests.test_derivatives.test_production_story_model_exposes_full_weight_penalty_gradient","seconds": 0.042,"outcome": "passed"},{"test": "tests.test_derivatives.test_pythia_adapter_fourth_derivative_and_portable_checkpoint","seconds": 5.373,"outcome": "passed","measurements": {"adapter_directional_autograd": "9035.374247002468","adapter_directional_finite_difference": "9035.370018056445"}},{"test": "tests.test_derivatives.test_large_finite_gradient_norm_survives_squaring","seconds": 0.004,"outcome": "passed"},{"test": "tests.test_derivatives.test_sequential_windows_reproduce_joint_penalty_and_training_gradient","seconds": 0.124,"outcome": "passed"},{"test": "tests.test_reporting.test_snapshot_keeps_full_score_and_trace_semantics","seconds": 0.04,"outcome": "passed"},{"test": "tests.test_reporting.test_report_before_first_run_keeps_readme_and_emits_protocol_paper","seconds": 0.458,"outcome": "passed"},{"test": "tests.test_training.test_randomized_control_preserves_coordinate_magnitudes_and_zero_is_noop","seconds": 0.126,"outcome": "passed"},{"test": "tests.test_training.test_step_recovery_matches_uninterrupted_weights","seconds": 1.995,"outcome": "passed"}]
123456789101112 unmodified lines2425262728293031323334353612 unmodified lines4950515253545556575859606162636465666768697071"""Ordinary CE, probe gradients and fair train-only calibration on identical initial weights."""import statisticsimport torchfrom .models import build_model, logits_of, token_loss, token_nllfrom .penalties import estimate, partials, random_signsfrom .records import BATCHES, read_json, sha256, write_jsonfrom .windows import TrainingWindows, generator, probe_rows12 unmodified linesdef vector_norm(values):return torch.linalg.vector_norm(torch.stack([torch.linalg.vector_norm(x.detach()) for x in values]))def probe_gradient(model, parameters, inputs, targets, kind, seed, step):"""Differentiate the sampled penalty, including the fourth-order contraction."""rng = generator(inputs.device, seed, step, 827)rows = probe_rows(seed, step, len(inputs))base = token_loss(logits_of(model, inputs[rows]), targets[rows])value = estimate(base, parameters, kind, generator=rng)return value.detach(), partials(value, parameters, create_graph=False)12 unmodified linesmodel = build_model(stage, 0, device, storage)parameters = tuple(p for p in model.parameters() if p.requires_grad)windows = TrainingWindows(data/"train.bin", 6247, BATCHES[stage])rows = []for step in range(16):inputs, targets = windows.get(step, device)model.zero_grad(set_to_none=True)ce_backward(model, inputs, targets, microbatch)ce_norm = vector_norm(p.grad for p in parameters if p.grad is not None).item()model.zero_grad(set_to_none=True)value, grads = probe_gradient(model, parameters, inputs, targets, kind, 6247, step)norm = vector_norm(grads).item()if not (0 < norm < float("inf") and 0 < ce_norm < float("inf")):raise FloatingPointError(f"Nonfinite or zero {kind} calibration norm at draw {step}: {norm}")rows.append({"draw":step, "ce_grad_norm":ce_norm, "penalty_grad_norm":norm,"value":value.item(), "norm_ratio":ce_norm/norm})del gradsresult = statistics.median(row["norm_ratio"] for row in rows)write_json(path, {"stage":stage, "kind":kind, "data_manifest_sha256":fingerprint,"unit_lambda":result, "draws":rows})return result12345678910111212 unmodified lines252627282930313233343536373839404142434445464748495051525354555657585960616263646566676812 unmodified lines81828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121"""Ordinary CE, probe gradients and fair train-only calibration on identical initial weights."""import statisticsimport timeimport torchfrom .models import build_model, logits_of, token_loss, token_nllfrom .penalties import estimate, inner, partials, random_signs, third_contractionfrom .records import BATCHES, read_json, sha256, time_now, write_jsonfrom .windows import TrainingWindows, generator, probe_rows12 unmodified linesdef vector_norm(values):"""Preserve the ordinary reduction and widen it when finite FP32 coordinates overflow."""blocks = tuple(x.detach() for x in values)def norm(dtype=None):return torch.linalg.vector_norm(torch.stack([torch.linalg.vector_norm(x, dtype=dtype) for x in blocks]))ordinary = norm()return ordinary if torch.isfinite(ordinary) and ordinary != 0 else norm(torch.float64)def two_window_third_gradient(model, parameters, inputs, targets, u, v):"""Keep one large fourth-order graph at a time, retaining the exact joint penalty gradient.Write R=(r0+r1)/2 for the two equal-length windows, using the same two probes for both.The derivative of ||R||² with respect to *each* r_i is R. Backpropagate that cotangentthrough both live third-derivative graphs, recomputing the first window only. This isthe gradient-caching chain rule of https://arxiv.org/abs/2101.06983 applied to D³L."""if len(inputs)!=2 or targets.shape!=inputs.shape:raise ValueError("Two equal-length input/target windows are required for an adapter probe")def contraction(index, through_fourth):loss = token_loss(logits_of(model, inputs[index:index+1]), targets[index:index+1])return third_contraction(loss, parameters, u, v, create_graph=through_fourth)first = contraction(0,False)second = contraction(1,True)mean = tuple((a+b.detach())*0.5 for a,b in zip(first,second,strict=True))del firstgrad_second = partials(inner(second,mean),parameters,create_graph=False)del secondgrad_first = partials(inner(contraction(0,True),mean),parameters,create_graph=False)return inner(mean,mean), tuple(a+b for a,b in zip(grad_first,grad_second,strict=True))def probe_gradient(model, parameters, inputs, targets, kind, seed, step):"""Differentiate the sampled penalty, including the fourth-order contraction."""rng = generator(inputs.device, seed, step, 827)rows = probe_rows(seed, step, len(inputs))if kind == "third" and hasattr(model, "peft_config"):u, v = random_signs(parameters,rng), random_signs(parameters,rng)return two_window_third_gradient(model,parameters,inputs[rows],targets[rows],u,v)base = token_loss(logits_of(model, inputs[rows]), targets[rows])value = estimate(base, parameters, kind, generator=rng)return value.detach(), partials(value, parameters, create_graph=False)12 unmodified linesmodel = build_model(stage, 0, device, storage)parameters = tuple(p for p in model.parameters() if p.requires_grad)windows = TrainingWindows(data/"train.bin", 6247, BATCHES[stage])# Each draw has its own data/probe address. A reboot can resume a long calibration# without mixing corpora, physical batching or old estimator implementations.work = storage/"calibration"/f"{stage}-{kind}-draws.json"identity = {"data_manifest_sha256":fingerprint,"microbatch":microbatch,"version":2}partial = read_json(work) if work.exists() else {**identity,"draws":[]}if any(partial.get(k)!=v for k,v in identity.items()):raise ValueError(f"Different settings in partial calibration for {stage} {kind}")rows = partial["draws"]if [row["draw"] for row in rows] != list(range(len(rows))) or len(rows)>16:raise ValueError(f"Discontinuous calibration record for {stage} {kind}")for step in range(len(rows),16):inputs, targets = windows.get(step, device)model.zero_grad(set_to_none=True)ce_backward(model, inputs, targets, microbatch)ce_norm = vector_norm(p.grad for p in parameters if p.grad is not None).item()model.zero_grad(set_to_none=True)if device.type == "cuda":torch.cuda.reset_peak_memory_stats(device)started = time.perf_counter()value, grads = probe_gradient(model, parameters, inputs, targets, kind, 6247, step)norm = vector_norm(grads).item()probe_seconds = time.perf_counter()-startedif not (0 < norm < float("inf") and 0 < ce_norm < float("inf")):raise FloatingPointError(f"Nonfinite or zero {kind} calibration norm at draw {step}: {norm}")rows.append({"draw":step, "ce_grad_norm":ce_norm, "penalty_grad_norm":norm,"value":value.item(), "norm_ratio":ce_norm/norm,"probe_seconds":probe_seconds,"peak_allocated_mib":torch.cuda.max_memory_allocated(device)/2**20 if device.type=="cuda" else None})write_json(work,partial)print(f"{time_now()} [calibration] {stage} {kind} draw {step+1}/16 estimate {value.item():.6g}, "f"CE gradient norm {ce_norm:.6g}, penalty gradient norm {norm:.6g}, {probe_seconds:.2f} s",flush=True)del gradsresult = statistics.median(row["norm_ratio"] for row in rows)write_json(path, {"stage":stage, "kind":kind, "data_manifest_sha256":fingerprint,"unit_lambda":result, "draws":rows})work.unlink(missing_ok=True)return result
26 unmodified lines2728293031324 unmodified lines3738394041424344454647484950515226 unmodified linesreturn torch.stack([(a * b).sum() for a, b in zip(left, right, strict=True)]).sum()def estimate(loss, parameters, kind, u=None, v=None, generator=None):"""Return one differentiable estimate of trace(H), ||H||² or ||D³loss||².4 unmodified linesif not parameters or kind not in {"trace", "hessian_norm", "third"}:raise ValueError(f"Expected trainable parameters and a derivative penalty, received {kind!r}")u = random_signs(parameters, generator) if u is None else tuple(x.detach() for x in u)gradient = partials(loss, parameters)hu = partials(inner(gradient, u), parameters)if kind == "trace":value = inner(hu, u)elif kind == "hessian_norm":value = inner(hu, hu)else:v = random_signs(parameters, generator) if v is None else tuple(x.detach() for x in v)third_vector = partials(inner(hu, v), parameters)value = inner(third_vector, third_vector)# A constant cubic tensor still needs an explicitly verifiable zero training gradient.anchor = torch.stack([p.reshape(-1)[0] for p in parameters]).sum() * 0return value + anchor26 unmodified lines272829303132333435363738394041424 unmodified lines4748495051525354555657585926 unmodified linesreturn torch.stack([(a * b).sum() for a, b in zip(left, right, strict=True)]).sum()def hessian_vector(loss, parameters, direction):"""Apply the parameter Hessian through the gradient's directional contraction."""return partials(inner(partials(loss, parameters), direction), parameters)def third_contraction(loss, parameters, u, v, *, create_graph=True):"""Return the weight-shaped vector D³L[u,v,:], optionally retaining its fourth derivative."""return partials(inner(hessian_vector(loss, parameters, u), v), parameters, create_graph=create_graph)def estimate(loss, parameters, kind, u=None, v=None, generator=None):"""Return one differentiable estimate of trace(H), ||H||² or ||D³loss||².4 unmodified linesif not parameters or kind not in {"trace", "hessian_norm", "third"}:raise ValueError(f"Expected trainable parameters and a derivative penalty, received {kind!r}")u = random_signs(parameters, generator) if u is None else tuple(x.detach() for x in u)if kind == "third":v = random_signs(parameters, generator) if v is None else tuple(x.detach() for x in v)third_vector = third_contraction(loss, parameters, u, v)value = inner(third_vector, third_vector)else:hu = hessian_vector(loss, parameters, u)value = inner(hu, u if kind == "trace" else hu)# A constant cubic tensor still needs an explicitly verifiable zero training gradient.anchor = torch.stack([p.reshape(-1)[0] for p in parameters]).sum() * 0return value + anchor
25 unmodified lines262728293031325 unmodified lines38394041424325 unmodified linesgit("commit","-m",message,"--",*public)git("push","origin","main")# Allowlist tracked files, excluding the dataset bytes, .env, logs and local environments.from huggingface_hub import CommitOperationAddtracked = git("ls-files").splitlines()api = HfApi()operations = [CommitOperationAdd(path_in_repo="research/"+name, path_or_fileobj=project/name)5 unmodified linesprevious = read_json(cursor) if cursor.exists() else {}hashes = {op.path_in_repo:sha256(op.path_or_fileobj) for op in operations}changed = [op for op in operations if hashes[op.path_in_repo]!=previous.get(op.path_in_repo)]if changed:api.create_commit(repo_id=STUDY_HUB,operations=changed,commit_message=message)write_json(cursor,hashes)25 unmodified lines262728293031325 unmodified lines38394041424344454625 unmodified linesgit("commit","-m",message,"--",*public)git("push","origin","main")# Allowlist tracked files, excluding the dataset bytes, .env, logs and local environments.from huggingface_hub import CommitOperationAdd, CommitOperationDeletetracked = git("ls-files").splitlines()api = HfApi()operations = [CommitOperationAdd(path_in_repo="research/"+name, path_or_fileobj=project/name)5 unmodified linesprevious = read_json(cursor) if cursor.exists() else {}hashes = {op.path_in_repo:sha256(op.path_or_fileobj) for op in operations}changed = [op for op in operations if hashes[op.path_in_repo]!=previous.get(op.path_in_repo)]# Mirror deletions too, e.g. a transient failure marker archived under attempts.json after recovery.changed.extend(CommitOperationDelete(path_in_repo=name) for name in previous.keys()-hashes.keys()if name.startswith("research/"))if changed:api.create_commit(repo_id=STUDY_HUB,operations=changed,commit_message=message)write_json(cursor,hashes)
123 unmodified lines124125126127128129123 unmodified linesif "token_budget" in record:record["target_tokens"] = record["token_budget"]record["id"] = folder.nameif last_error and not summary:record["status"] = "failed"record["error"] = str(last_error.get("error", "Recorded failure"))123 unmodified lines124125126127128129130131132133134123 unmodified linesif "token_budget" in record:record["target_tokens"] = record["token_budget"]record["id"] = folder.namefailures = read_json(folder / "attempts.json").get("failures", [])if last_error and last_error not in failures:failures.append(last_error)if failures:record["failures"] = failuresif last_error and not summary:record["status"] = "failed"record["error"] = str(last_error.get("error", "Recorded failure"))
150 unmodified lines151152153154155156157158159160161162163150 unmodified lines"[Design and hyperparameter rationale](../../planned-runs.md) · "f"[Saved configuration]({raw_link}config.json)",]if run.get("error"):material += ["## Recorded failure", _sample({"prompt": "Error", "continuation": run["error"]})]if run["samples"]:material += ["## Fixed-prompt generations",*[_sample(sample) for sample in run["samples"]]]atomic_text(base / key / "experiment.md", "\n\n".join(material) + "\n")observation = _run_learning(run)atomic_text(base / key / "learnings.md", f"# Run learnings\n\n{observation}\n\n""[Experiment and source records](experiment.md)\n")learnings.append(f"- [{key}]({link}) — {observation}")150 unmodified lines151152153154155156157158159160161162163164165166167150 unmodified lines"[Design and hyperparameter rationale](../../planned-runs.md) · "f"[Saved configuration]({raw_link}config.json)",]if run.get("failures"):material += ["## Recorded interruptions", _table([[failure["timestamp"],failure["error"]] for failure in run["failures"]],["Time (UTC)","Recorded exception"])]if run["samples"]:material += ["## Fixed-prompt generations",*[_sample(sample) for sample in run["samples"]]]atomic_text(base / key / "experiment.md", "\n\n".join(material) + "\n")observation = _run_learning(run)if run.get("failures"):observation += f" The run ledger records {len(run['failures'])} interrupted attempt(s)."atomic_text(base / key / "learnings.md", f"# Run learnings\n\n{observation}\n\n""[Experiment and source records](experiment.md)\n")learnings.append(f"- [{key}]({link}) — {observation}")
104 unmodified lines105106107108109110111112113114104 unmodified lineslocks = storage / "locks"locks.mkdir(parents=True, exist_ok=True)with FileLock(str(locks/(config["id"]+".lock"))):try:return _run(project, storage, config, recorder, device, microbatch)except Exception as exc:write_json(recorder.directory/"failure.json", {"timestamp":time_now(), "error":repr(exc)})raise104 unmodified lines105106107108109110111112113114115116117118119120121122123124125126104 unmodified lineslocks = storage / "locks"locks.mkdir(parents=True, exist_ok=True)with FileLock(str(locks/(config["id"]+".lock"))):log = recorder.directory/"attempts.json"marker = recorder.directory/"failure.json"def remember(failure):"""Keep the original timestamp and exception across successful or repeated retries."""history = read_json(log) if log.exists() else {"failures":[]}if failure not in history["failures"]:history["failures"].append(failure)write_json(log,history)if marker.exists():remember(read_json(marker))try:return _run(project, storage, config, recorder, device, microbatch)except Exception as exc:failure = {"timestamp":time_now(), "error":repr(exc)}write_json(marker,failure)remember(failure)raise
269 unmodified lines270271272269 unmodified linesassert set(payload) == set(get_peft_model_state_dict(fresh))set_peft_model_state_dict(fresh, payload)torch.testing.assert_close(logits_of(fresh, ids), logits_of(model, ids), rtol=0, atol=0)269 unmodified lines270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300269 unmodified linesassert set(payload) == set(get_peft_model_state_dict(fresh))set_peft_model_state_dict(fresh, payload)torch.testing.assert_close(logits_of(fresh, ids), logits_of(model, ids), rtol=0, atol=0)def test_large_finite_gradient_norm_survives_squaring():"""The real adapter calibration exposed overflow only in the FP32 norm reduction."""from thirdloss.objectives import vector_normblocks = (torch.tensor([3e20]), torch.tensor([4e20]))actual = vector_norm(x for x in blocks)torch.testing.assert_close(actual.double(), torch.tensor(5e20, dtype=torch.float64), rtol=1e-7, atol=0)def test_sequential_windows_reproduce_joint_penalty_and_training_gradient():"""Shared probes preserve every cross-window term in the norm of the mean derivative."""from thirdloss.models import StoryConfig, StoryTransformer, token_lossfrom thirdloss.objectives import two_window_third_gradientfrom thirdloss.penalties import random_signstorch.manual_seed(23)model = StoryTransformer(StoryConfig(vocab_size=7,width=8,heads=2,layers=1,hidden=12,context=4)).double()params = tuple(model.parameters())x = torch.tensor([[2,3,1,0],[4,2,5,3]])y = (x+1)%7rng = torch.Generator().manual_seed(7)u,v = random_signs(params,rng),random_signs(params,rng)joint = estimate(token_loss(model(x),y),params,"third",u=u,v=v)reference = torch.autograd.grad(joint,params)value,gradient = two_window_third_gradient(model,params,x,y,u,v)torch.testing.assert_close(value,joint.detach(),rtol=3e-10,atol=1e-8)for cached,full in zip(gradient,reference,strict=True):torch.testing.assert_close(cached,full,rtol=1e-8,atol=1e-5)
70 unmodified lines71727374757670 unmodified linestrain.run_one(project,root,"stories","third","smoke",seed,0.03,torch.device("cpu"))monkeypatch.setattr(train,"save_state",saved)resumed = train.run_one(project,root,"stories","third","smoke",seed,0.03,torch.device("cpu"))import shutilreference = tmp_path/"reference"shutil.copytree(project/".git",reference/".git")70 unmodified lines717273747576777870 unmodified linestrain.run_one(project,root,"stories","third","smoke",seed,0.03,torch.device("cpu"))monkeypatch.setattr(train,"save_state",saved)resumed = train.run_one(project,root,"stories","third","smoke",seed,0.03,torch.device("cpu"))history = train.read_json(project/"results"/resumed["id"]/"attempts.json")["failures"]assert len(history) == 1 and "intentional restart fixture" in history[0]["error"]import shutilreference = tmp_path/"reference"shutil.copytree(project/".git",reference/".git")
research/docs/study.json
research/reports/experiments/abstracts-pilot-s00-third-r03/experiment.md+4-8
research/reports/experiments/abstracts-pilot-s00-third-r03/learnings.md+1-1
research/reports/experiments/learnings.md+1-1
research/reports/paper.pdf
research/reports/progress.md+1-1
research/reports/reviews/adapter-verification.md+11-5
research/results/verification/pythia-calibration-replay.jsonAdded+15
research/results/verification/tests.json+32-22
research/src/thirdloss/objectives.py+56-6
research/src/thirdloss/penalties.py+15-8
research/src/thirdloss/release.py+4-1
research/src/thirdloss/report_records.py+5
research/src/thirdloss/reporting.py+6-2
research/src/thirdloss/train.py+13-1
research/tests/test_derivatives.py+28
research/tests/test_training.py+2