Wen Dong · NeurIPS 2026 · GitHub repository · Paper · Executed notebook · PDF reading copy · Citation
Why can training remain numerically stable while ceasing to learn? Which network interfaces amplify or suppress useful signals? Which fluctuations of the weights actually affect predictions? This tutorial connects these questions through local interactions between parameters and intermediate network states.
The paper’s equations are followed by their mathematical implementation, executed examples, and recorded checkpoint diagnostics. The main capabilities are exposing architecture in a sparse precision matrix, distinguishing stability from active response, locating signal attenuation, and reconstructing a split-certified PAC-Bayes table.
One Python tutorial, original experimental implementations. Mathematical kernels and saved-data calculations use NumPy/SciPy. The split-certified models and precision builders use TensorFlow; the criticality vision/GPT checkpoint paths use PyTorch. These are the original experimental paths, not interchangeable backend ports.
Run the default workflow. From the repository root,
install requirements.txt, then execute this notebook or run
python reproduce_main_artifacts.py. This checks small
identities, recomputes Table 1 from saved posterior evaluations, and
redraws diagnostic curves from saved measurements. Training, checkpoint
replay, and architecture re-extraction are explicit opt-ins. No
checkpoint or dataset download is needed by default.
The architecture previews are retained paper figures; their TensorFlow builders are linked alongside them. Every empirical plot identifies its saved inputs. Code needed to follow an equation is expanded; setup and plotting orchestration are collapsible in the HTML reading copy.
A network is represented by trainable parameters and intermediate states . Local module relations, loss, and regularization define the lifted energy and a checkpoint-local precision. The same representation gives three complementary calculations.
| Calculation | Mathematical object | What the output tells us |
|---|---|---|
| Activation elimination | Schur complement of a positive quadratic | How local state constraints induce parameter curvature |
| Criticality and boundary gains | Sampled gradient Grams and loss adjoints | Whether the measured update is stable and active, and where sensitivity changes |
| Distribution geometry and certificates | Inverse-metric drift defect; separately, exact local Gaussian prior KL | Which stochastic directions affect predictions, and a certified bounded-risk table |
For a positive lifted quadratic with blocks , stationarity in the state displacement gives . Substitution yields . This is the softened curvature at finite module precision and state ridge . Theorem 1 recovers deterministic-network Fisher/Gauss–Newton curvature in its stated hard-constraint limit; finite precision alone is not enough.
For example, gives , approaching as . The small check below verifies both the finite value and the limit.
For a quadratic gradient step in a fixed preconditioned coordinate, , the upper edge is . An active-space coordinate also asks whether loss-changing directions respond. The experiments use observed-gradient Gram proxies and an optimizer-state scalar projection. These are checkpoint diagnostics, rather than a full spectral stability certificate for Momentum or AdamW.
At adjacent retained boundaries, gives the measured directional gain . This localizes attenuation or amplification in the observed loss direction; it is not the separator operator norm itself.
On a fixed comparison space, the drift defect is . Theorem 4 bounds KL-to-Gibbs under its contraction and diffusion assumptions. The camera-ready Table 1 instead uses an explicit, build-dependent Gaussian prior and posterior with exact and an independent certificate sample. A frozen checkpoint defect is not substituted for that prior KL.
# Default: saved-data calculations only. These switches never silently fall
# back to synthetic data or initiate training when a file is missing.
import os
RUN_STAGE1_LONG_JOBS = os.environ.get('RUN_STAGE1_LONG_JOBS', '0') == '1'
RECOMPUTE_CHECKPOINT_DIAGNOSTICS = os.environ.get('RECOMPUTE_CHECKPOINT_DIAGNOSTICS', '0') == '1'
RUN_STAGE5_RENDERERS = os.environ.get('RUN_STAGE5_RENDERERS', '0') == '1'
os.environ['CODEBOOK_EXECUTE_LIGHT'] = '0' if RECOMPUTE_CHECKPOINT_DIAGNOSTICS else '1'from __future__ import annotations
import inspect
import importlib.util
import os
import shutil
import sys
from pathlib import Path
import numpy as np
import pandas as pd
from IPython.display import Image, Markdown, display
PROJECT_ROOT = Path.cwd().resolve()
assert (PROJECT_ROOT / 'code/core_math_identities.py').exists(), 'Run from the repository root.'
SRC = PROJECT_ROOT / 'code'
OUTPUT_ROOT = PROJECT_ROOT / 'output'
WORK_DIR = OUTPUT_ROOT / '_runtime'
OUT_DIR = WORK_DIR
for directory in (WORK_DIR, OUTPUT_ROOT): directory.mkdir(parents=True, exist_ok=True)
os.environ['PAPER_ZIP_CODE_ROOT'] = str(PROJECT_ROOT)
os.environ['PAPER_ZIP_OUTPUT_DIR'] = str(WORK_DIR)
os.environ['MPLBACKEND'] = 'Agg'
sys.path.insert(0, str(SRC))
def relpath(path):
return str(Path(path).resolve().relative_to(PROJECT_ROOT))state = {}# These display functions expose actual source, not separately transcribed code.
def show_source_with_file_lines(function, **kwargs):
path = relpath(inspect.getsourcefile(function))
display(Markdown(f"Implementation: [{function.__name__}]({path})"))
display(Markdown('```python\n' + inspect.getsource(function).rstrip() + '\n```'))
show_source = show_source_with_file_lines
def display_pdf(path, height=420, max_pages=1):
import fitz
path = Path(path)
if not path.exists(): raise FileNotFoundError(path)
preview = OUTPUT_ROOT / 'figures' / (path.stem + '.png')
preview.parent.mkdir(exist_ok=True)
public = OUTPUT_ROOT / 'artifacts' / path.name
public.parent.mkdir(exist_ok=True)
shutil.copy2(path, public)
with fitz.open(path) as document:
document[0].get_pixmap(matrix=fitz.Matrix(2, 2), alpha=False).save(preview)
display(Image(filename=str(preview)))
display(Markdown(f'[Download figure PDF]({relpath(public)})'))
def show_df(frame, n=8):
display(frame.head(n).style.format(precision=5))The default path is CPU-only and reads the included evidence.
Numerical calculations are rerun; expensive trained-network evaluations
are reused. verify_core_identities.py checks Schur
elimination, the hard-constraint limit, Gram spectra and eigenvector
lifting, centering, defect expansion, KL integration, and Gaussian
certificate terms. Deliberately wrong finite-precision and missing-MC
calculations are rejected. These finite examples check implementations
of the identities; they do not establish the statistical assumptions of
a training run.
import subprocess
result = subprocess.run([sys.executable, 'verify_core_identities.py'],
check=True, text=True, capture_output=True)
print(result.stdout)
import core_math_identities as math_core
show_source(math_core.schur_curvature)
for kappa in (1., 10., 100., 10000.):
curvature = math_core.schur_curvature(np.array([[kappa]]),
np.array([[-kappa]]), np.array([[kappa + 1.]]))[0, 0]
print(f'kappa={kappa:8.0f}: softened curvature={curvature:.8f}; hard limit=1')[OK] Schur complement elimination
[OK] Gram-spectrum equivalence
[OK] retained-defect quadratic expansion
[OK] finite-time KL recursion
[OK] finite precision versus hard-constraint limit; negative control
[OK] covariance centering, eigenvector lift, and zero-contraction limit
[OK] same-support Gaussian KL and nonzero Monte Carlo correction
All core identity checks passed.
Implementation: schur_curvature
def schur_curvature(parameter_precision, cross_precision, state_precision):
"""Minimize a Gaussian quadratic over its state displacement.
For blocks (A, B; B.T, D), stationary states solve D du = -B.T dtheta.
Substitution gives dtheta.T (A - B solve(D,B.T)) dtheta / 2.
D must be positive definite here; no silent pseudoinverse is substituted.
At finite module precision this is softened curvature. Recovering the
deterministic-network curvature additionally requires the hard-constraint
limit stated in Theorem 1.
"""
np.linalg.cholesky(state_precision)
return parameter_precision - cross_precision @ np.linalg.solve(
state_precision, cross_precision.T)kappa= 1: softened curvature=0.50000000; hard limit=1
kappa= 10: softened curvature=0.90909091; hard limit=1
kappa= 100: softened curvature=0.99009901; hard limit=1
kappa= 10000: softened curvature=0.99990001; hard limit=1
The original checkpoint inventory links model families, diagnostic
inputs, and training entry points. The default reports the inventory and
skips training. RUN_STAGE1_LONG_JOBS=1 is reserved for
explicitly requested long jobs; select individual jobs rather than
launching every experiment.
Training reference examples and the exact certificate producer are distinguished in Section 8. The revised five-model Table 1 is reconstructed from its frozen July 31 records, not from the earlier compact training examples. Optional checkpoint replay requires the original weights, optimizer state when used by the diagnostic, and the matching data/configuration. Missing files stop that replay; they never trigger automatic training.
import checkpoint_artifact_plan as paper_ckpts
from supplement_paths import write_table
display(Markdown('**Stage 1 checkpoint producer manifest**'))
stage1_checkpoint_producers = paper_ckpts.compact_stage1_checkpoint_producer_manifest()
show_df(stage1_checkpoint_producers, n=len(stage1_checkpoint_producers))
# Stage 1 checkpoint generation entry point.
# Default is status-only. Set RUN_STAGE1_LONG_JOBS=1 to launch checkpoint generation.
RUN_STAGE1_LONG_JOBS = os.environ.get('RUN_STAGE1_LONG_JOBS', '0') == '1'
DEVICE = os.environ.get('STAGE1_DEVICE', 'cuda')
_jobs_env = os.environ.get('STAGE1_JOBS', '').strip()
STAGE1_JOBS = [job.strip() for job in _jobs_env.split(',') if job.strip()] or None
stage1_result = paper_ckpts.compact_stage1_checkpoint_contract(
OUT_DIR,
run_long_jobs=RUN_STAGE1_LONG_JOBS,
device=DEVICE,
jobs=STAGE1_JOBS,
)
stage1_required = stage1_result['required_artifacts']
stage1_required_path = stage1_result['paths']['required_artifacts']
state['stage1_required_artifacts'] = stage1_required_path
state['stage1_generated_paths'] = stage1_result.get('generated_paths', {})
missing = stage1_required[~stage1_required['present'].astype(bool)] if 'present' in stage1_required.columns else pd.DataFrame()
display(Markdown('**Checkpoint inputs used by later stages**'))
show_df(stage1_required, n=len(stage1_required))
if RUN_STAGE1_LONG_JOBS:
display(Markdown('**Checkpoint generation launched through compact Python wrappers**'))
for job, path in stage1_result.get('generated_paths', {}).items():
display(Markdown(f'- `{job}` -> `{path}`'))
else:
print('Checkpoint generation skipped. Set RUN_STAGE1_LONG_JOBS=1 to generate checkpoints.')
print(f'Optional full checkpoint bundles present for long replay: {len(stage1_required) - len(missing)}/{len(stage1_required)} families.')
if len(missing):
print('This is expected for the quick reader path; compact paper-data summaries and paper artifacts are bundled.')Stage 1 checkpoint producer manifest
| needed_by | checkpoint_family | producer_function | guarded_job | expected_outputs |
|---|---|---|---|---|
| Stage 2A/2B/4 | main-text vision criticality checkpoints | run_main_text_stage1_vision | main_text_vision_baselines | /criticality_outputs |
| Stage 2A/2B/4 | vision architecture-ablation checkpoints | run_appendix_vision_ablation | vision_architecture_ablation | /criticality_vision_repair_outputs/runs//checkpoints/epoch_.pt |
| Stage 2A/2B/4 | GPT-20M baseline raw checkpoints | run_gpt20m_baseline | gpt20m_baseline | /criticality_bpe_gpt20m_outputs/runs//checkpoints/step_.pt |
| Stage 2B/4 | GPT-20M residual/norm ablation checkpoints and gains | run_gpt20m_ablation_suite | gpt20m_residual_norm_ablation | /criticality_bpe_gpt20m_outputs_repair/runs/* |
| Stage 2B/4 | SSM sequence checkpoints | run_ssm_sequence_ablation | ssm_sequence_ablation | /criticality_ssm_outputs/runs//checkpoints/step_.pt |
| Stage 3 | resolved KL-to-Gibbs theorem/PAC-Bayes MNIST+CIFAR weights | run_stage3_pac_bayes_checkpoints | stage3_pac_bayes_checkpoints | /out_paper_ready_mnist_mlp_v1/final.weights.h5; /out_paper_ready_mnist_lenet_v1/final.weights.h5; /out_cifar10_resnet32_cropflip_b64_sgdnesterov90_v1/epoch_090.weights.h5; /out_cifar10_wrn16_4_cropflip_b64_sgdnesterov90_v1/epoch_090.weights.h5; /out_cifar10_densenet_small_cropflip_b64_sgdnesterov90_v1/epoch_090.weights.h5 |
| Stage 6 | ResNet cropflip/mixcut direction-diagnostic weights | run_stage6_direction_model_checkpoints | stage6_direction_checkpoints | /out_cifar10_resnet32_cropflip_sgdnesterov90_v1/epoch_090.weights.h5; /out_cifar10_resnet32_mixcut_sgdnesterov90_v1/epoch_090.weights.h5 |
Checkpoint inputs used by later stages
| needed_by | artifact_family | root | pattern | current_count | minimum_for_current_notebook | present |
|---|---|---|---|---|---|---|
| Stage 2A criticality coordinates; Stage 2B vision backward gain | vision CIFAR architecture checkpoints | /criticality_vision_repair_outputs | runs//checkpoints/epoch_.pt | 0 | >=18 checkpoint files for main-text subset; full appendix currently has 103 | False |
| Stage 2A GPT criticality coordinates | BPE GPT-20M baseline raw checkpoints | /criticality_bpe_gpt20m_outputs | runs/gpt_bpe_baseline_seed19M/checkpoints/step.pt | 0 | 33 = 3 seeds x 11 checkpoint steps | False |
| Stage 2B GPT backward gain | BPE GPT-20M baseline and ablation gain files | /criticality_bpe_gpt20m_outputs and /criticality_bpe_gpt20m_outputs_repair | runs//gains/step_.npz | 0 | all restored baseline/repair gain files; currently 179 | False |
| Stage 2B SSM backward gain panel | selective diagonal SSM checkpoints and retained raw backward-gain table | /criticality_ssm_outputs and /criticality_outputs/aggregate/paper_v3/tables | runs//checkpoints/step_.pt plus ssm_repaired_backward_gain_by_block_raw.csv | 0 | 18 SSM checkpoints plus one retained raw SSM table | False |
| paper-v3 reference inventory and optional main-text regeneration | main-text MLP/LeNet/CIFAR baseline criticality outputs | /criticality_outputs | aggregate/paper_v3/tables/*.csv | 0 | paper reference tables optional for current compact recomputation | False |
| Stage 3 checkpoint-to-PAC-Bayes table | resolved KL-to-Gibbs theorem/PAC-Bayes model weight checkpoints | /out_paper_ready_* and /out_cifar10_cropflip_b64 | /out_paper_ready_mnist_mlp_v1/final.weights.h5; /out_paper_ready_mnist_lenet_v1/final.weights.h5; /out_cifar10_resnet32_cropflip_b64_sgdnesterov90_v1/epoch_090.weights.h5; /out_cifar10_wrn16_4_cropflip_b64_sgdnesterov90_v1/epoch_090.weights.h5; /out_cifar10_densenet_small_cropflip_b64_sgdnesterov90_v1/epoch_090.weights.h5 | 0 | 5 exact TensorFlow/Keras .weights.h5 files | False |
| Stage 6 ResNet direction taxonomy and augmentation tangent diagnostics | Stage 6 ResNet cropflip/mixcut model weight checkpoints | /out_cifar10_resnet32_cropflip_sgdnesterov90_v1 and /out_cifar10_resnet32_mixcut_sgdnesterov90_v1 | /out_cifar10_resnet32_cropflip_sgdnesterov90_v1/epoch_090.weights.h5; /out_cifar10_resnet32_mixcut_sgdnesterov90_v1/epoch_090.weights.h5 | 0 | 2 exact TensorFlow/Keras .weights.h5 files | False |
| Stage 6 fast figure regeneration when long diagnostics are not rerun | Stage 6 retained-spectrum/input-tangent diagnostic artifacts | /out_neurips_pb_experiments_tau09_full and /out_cifar10_resnet32_*_gibbs_probe_v1 | /out_neurips_pb_experiments_tau09_full; /out_cifar10_resnet32_strict_retained_gibbs_probe_v1/all_direction_coefficients.csv; /out_cifar10_resnet32_cropflip_b64_strict_retained_gibbs_probe_v1/all_direction_coefficients.csv | 0 | MNIST input-tangent root plus at least one ResNet all_direction_coefficients.csv table | False |
Checkpoint generation skipped. Set RUN_STAGE1_LONG_JOBS=1 to generate checkpoints.
Optional full checkpoint bundles present for long replay: 0/8 families.
This is expected for the quick reader path; compact paper-data summaries and paper artifacts are bundled.
Stage 2A is the checkpoint-to-criticality-coordinate path. It consumes saved checkpoints or bundled checkpoint summaries and writes one row per checkpoint with the quantities used in the main two-sided criticality figure. The row contains an upper-side stability coordinate and a lower-side active-plasticity coordinate.
The code displayed immediately below is the mathematical kernel. It excludes checkpoint loading, optimizer-state parsing, CSV writing, and plotting. The application cell after it reads checkpoints when available, otherwise uses packaged paper-data summaries.
At checkpoint , let be the parameters, the current training gradient in the coordinate being tested, and the next optimizer update reconstructed from the saved optimizer state. The scalar step used in the upper-band comparison is
This scalar is the component of the actual update parallel to the
chosen gradient; an orthogonal update component may remain. For SGD with
momentum,
is reconstructed from the momentum buffer. For AdamW, it is
reconstructed from the first- and second-moment buffers. The helper
effective_learning_rate_parallel implements exactly this
projection.
The dense reduced curvature proxy is not formed. With probe gradients stacked as
the observed-gradient outer-product proxy is
The nonzero eigenvalues of equal those of the smaller row Gram matrix
The measured scalar edge proxy is therefore
The helper gram_top_eigenvalue implements this row-Gram
computation. Its center flag controls whether the rows are
centered. In the upper-edge coordinate, the paper-facing vision path
uses the uncentered PSD probe in the relevant optimizer coordinate;
centered variants are diagnostic and used elsewhere in the
supplement.
For SGD-with-momentum vision runs, the coordinate table also reports the scalar heavy-ball adjustment used by the paper figures:
For AdamW/GPT, is already reconstructed from the optimizer state, so the coordinate is reported directly in the measured state-effective units.
The lower side is not a global smallest eigenvalue and not a lower learning-rate floor. It asks whether the directions currently used by the optimizer still have loss-changing curvature.
Let have orthonormal columns spanning a small active subspace, typically built from recent or probe gradient directions. Given a probe-gradient matrix , define the centered version
The centered active-space proxy used in this implementation is
The helper active_subspace_lower_eigenvalue computes
The paper-facing active-plasticity coordinate is
The helper criticality_coordinates assembles the upper
edge, actual effective step, upper coordinate, active lower eigenvalue,
and active-plasticity coordinate into the table columns consumed by
Stage 4A.
The application cell uses these math kernels in two data paths.
For vision checkpoints,
recompute_vision_criticality_coordinates_from_checkpoints
restores the paper models, optimizer states, and selected epochs, then
builds the upper-edge and active-subspace rows. The vision checkpoint
path includes coupled weight decay in the SGD gradient because the saved
optimizer update is compared to the same coupled-L2 field.
For GPT checkpoints,
collect_gpt_criticality_coordinates_from_available_artifacts(..., require_raw_checkpoints=True)
restores raw state-complete AdamW checkpoints and reconstructs the
actual state-effective update. If raw checkpoint files are absent, the
long replay path fails rather than silently replacing the computation by
aggregate paper metrics. The quick path uses bundled paper-data
summaries.
show_source(math_core.gram_top_eigenvalue)
show_source(math_core.active_subspace_lower_eigenvalue)
show_source(math_core.effective_learning_rate_parallel)Implementation: gram_top_eigenvalue
def gram_top_eigenvalue(
gradient_rows: np.ndarray,
denom: int | None = None,
center: bool = False,
) -> float:
"""Top eigenvalue of the empirical Fisher/GGN row Gram matrix.
Math:
G = [g_1^T; ...; g_M^T],
X = G - 1 mean(G)^T if center else G,
K = X X^T / M,
lambda_max(F) = lambda_max(K),
because F = X^T X / M and K have the same nonzero eigenvalues.
"""
G = np.asarray(gradient_rows, dtype=float)
if G.ndim != 2 or G.shape[0] == 0:
raise ValueError("gradient_rows must have shape (M, d) with M > 0")
M = int(denom or G.shape[0])
X = G - G.mean(axis=0, keepdims=True) if center and G.shape[0] > 1 else G
K = (X @ X.T) / max(1, M)
K = 0.5 * (K + K.T)
eigs = np.maximum(np.linalg.eigvalsh(K), 0.0)
return float(eigs.max() if eigs.size else 0.0)Implementation: active_subspace_lower_eigenvalue
def active_subspace_lower_eigenvalue(
gradient_rows: np.ndarray,
active_basis: np.ndarray,
denom: int | None = None,
center: bool = True,
) -> float:
"""Smallest empirical-Fisher eigenvalue on a chosen active subspace.
Math:
Q^T Q = I,
X = G - 1 mean(G)^T if center else G,
F = X^T X / M,
F_Q = Q^T F Q = (X Q)^T (X Q) / M,
lambda_active = lambda_min(F_Q).
"""
G = np.asarray(gradient_rows, dtype=float)
Q = np.asarray(active_basis, dtype=float)
if G.ndim != 2 or Q.ndim != 2 or G.shape[1] != Q.shape[0]:
raise ValueError("expected G shape (M,d) and Q shape (d,r)")
X = G - G.mean(axis=0, keepdims=True) if center and G.shape[0] > 1 else G
M = int(denom or (X.shape[0] - int(center and X.shape[0] > 1)))
GQ = X @ Q
F_Q = (GQ.T @ GQ) / max(1, M)
F_Q = 0.5 * (F_Q + F_Q.T)
eigs = np.maximum(np.linalg.eigvalsh(F_Q), 0.0)
return float(eigs.min() if eigs.size else 0.0)Implementation: effective_learning_rate_parallel
def effective_learning_rate_parallel(update_delta: np.ndarray, gradient: np.ndarray) -> float:
"""Signed scalar eta satisfying update_delta ~= -eta * gradient.
Math:
eta_eff_parallel = - <Delta theta, g> / ||g||^2.
This converts an optimizer-state update, including momentum or AdamW, into
the scalar learning-rate coordinate comparable to an upper stability edge.
"""
delta = np.asarray(update_delta, dtype=float).reshape(-1)
grad = np.asarray(gradient, dtype=float).reshape(-1)
return float(-np.dot(delta, grad) / max(np.dot(grad, grad), EPS))import criticality_coordinates as crit
# Stage 2A application: generate compact-owned criticality-coordinate CSVs from checkpoints.
# Set CODEBOOK_EXECUTE_LIGHT=1 to render the executed notebook from existing compact CSVs.
display(Markdown('**Stage 2A application: checkpoint-to-coordinate computation**'))
LIGHT_EXECUTE = not RECOMPUTE_CHECKPOINT_DIAGNOSTICS
vision_coord_path = OUT_DIR / 'compact_stage2a_vision_criticality_coordinates.csv'
gpt_coord_path = OUT_DIR / 'compact_stage2a_gpt_criticality_coordinates.csv'
paper_criticality_data = PROJECT_ROOT / 'paper_data' / 'criticality'
if LIGHT_EXECUTE and not (vision_coord_path.exists() and gpt_coord_path.exists()):
for src, dst in [
(paper_criticality_data / 'compact_stage2a_vision_criticality_coordinates.csv', vision_coord_path),
(paper_criticality_data / 'compact_stage2a_gpt_criticality_coordinates.csv', gpt_coord_path),
]:
if not src.exists():
raise FileNotFoundError(src)
shutil.copy2(src, dst)
if LIGHT_EXECUTE and vision_coord_path.exists() and gpt_coord_path.exists():
vision_coordinates = pd.read_csv(vision_coord_path)
gpt_coordinates = pd.read_csv(gpt_coord_path)
else:
# This branch is the real checkpoint-to-coordinate path. It reads restored
# checkpoints and computes the criticality rows; it does not train models.
vision_coordinates = crit.recompute_vision_criticality_coordinates_from_checkpoints(
Path('/content/criticality_vision_repair_outputs'),
output_dir=OUT_DIR,
maintext_only=True,
epochs={0, 1, 3, 8, 16, 32},
)
gpt_coordinates = crit.collect_gpt_criticality_coordinates_from_available_artifacts(
[Path('/content/criticality_bpe_gpt20m_outputs')],
output_dir=OUT_DIR,
require_raw_checkpoints=True,
)
vision_coordinates.to_csv(vision_coord_path, index=False)
gpt_coordinates.to_csv(gpt_coord_path, index=False)
criticality_coord_paths = {'vision': vision_coord_path, 'gpt': gpt_coord_path}
state['criticality_coordinates_coordinate_paths'] = criticality_coord_paths
compact_stage4_input_paths = crit.write_compact_maintext_criticality_plot_inputs(
criticality_coord_paths['vision'],
criticality_coord_paths['gpt'],
OUT_DIR / 'compact_stage4_criticality_tables',
)
state['compact_stage4_criticality_input_paths'] = compact_stage4_input_paths
# Compact previews; the source CSVs retain all identifiers and columns.
display(Markdown('**Vision criticality coordinates: first eight records**'))
preview = vision_coordinates[['arch_label', 'condition', 'epoch', 'upper_coordinate', 'active_lower_coordinate']].copy()
preview['condition'] = preview['condition'].str.replace('_', ' ')
show_df(preview.rename(columns={'arch_label': 'Architecture', 'condition': 'Condition', 'epoch': 'Epoch', 'upper_coordinate': 'Upper', 'active_lower_coordinate': 'Active'}), n=8)
display(Markdown('**GPT criticality coordinates: first eight records**'))
show_df(gpt_coordinates[['seed', 'step', 'tokens_seen', 'upper_coordinate', 'active_lower_coordinate']].rename(columns={'seed': 'Seed', 'step': 'Step', 'tokens_seen': 'Tokens', 'upper_coordinate': 'Upper', 'active_lower_coordinate': 'Active'}), n=8)Stage 2A application: checkpoint-to-coordinate computation
Vision criticality coordinates: first eight records
| Architecture | Condition | Epoch | Upper | Active |
|---|---|---|---|---|
| DenseNet-BC | densenet baseline | 0 | 0.01666 | 0.00049 |
| DenseNet-BC | densenet baseline | 1 | 0.01380 | 1.13518 |
| DenseNet-BC | densenet baseline | 3 | 0.01522 | 0.77639 |
| DenseNet-BC | densenet baseline | 8 | 0.01188 | 0.95754 |
| DenseNet-BC | densenet baseline | 16 | 0.01659 | 1.43475 |
| DenseNet-BC | densenet baseline | 32 | 0.01484 | 0.94055 |
| ResNet-18 | resnet baseline | 0 | 0.12227 | 0.22682 |
| ResNet-18 | resnet baseline | 1 | 0.03279 | 0.61005 |
GPT criticality coordinates: first eight records
| Seed | Step | Tokens | Upper | Active |
|---|---|---|---|---|
| 0 | 0 | 0 | 0.00561 | 0.00372 |
| 0 | 10 | 81920 | 0.01315 | 0.00880 |
| 0 | 25 | 204800 | 0.01045 | 0.00449 |
| 0 | 50 | 409600 | 0.01703 | 0.00527 |
| 0 | 100 | 819200 | 0.02896 | 0.01050 |
| 0 | 200 | 1638400 | 0.02760 | 0.04081 |
| 0 | 500 | 4096000 | 0.06129 | 0.07069 |
| 0 | 6103 | 49995776 | 0.15907 | 0.18264 |
Stage 2B supports the separator-transfer mechanism. The criticality theorem says that architecture changes trainability by changing how perturbation and backward-sensitivity signal passes through interfaces. The code here measures a checkpoint-local directional version of that transport.
At checkpoint , choose architecture-native retained boundaries
such as an input boundary, residual block outputs, DenseNet transition outputs, GPT block outputs, or SSM scan/state boundaries. For a probe minibatch , define the training loss
and retain the boundary adjoints
The local backward gain is
The helper boundary_gradient_l2_norm computes
,
and adjacent_backward_gain computes the adjacent ratio. A
gain near one means near-neutral transport in the measured direction;
sustained gains above or below one indicate amplification or
attenuation.
The theorem-level separator transfer for eliminating internal variables from a clique to a separator can be written schematically as
The measured is not a full operator-norm proof of . It is the checkpoint-local directional VJP proxy in the actual loss direction. It answers the operational question behind the theorem: where does the architecture preserve, magnify, or damp the signal that later appears in the reduced Jacobian and curvature coordinates?
A path gain can also be summarized as
but the paper-facing figure emphasizes layer/block-local gains because they localize which architectural interface is responsible.
The displayed source functions are the math-facing part:
boundary_gradient_l2_norm: computes the L2 norm of a
retained boundary adjoint.adjacent_backward_gain: computes the adjacent gain
ratio.compact_vision_backward_gain_rows: shows the checkpoint
replay pattern for vision models: register forward hooks at retained
modules, retain gradients, backpropagate cross-entropy, read the
boundary adjoints, and emit one row per adjacent boundary.Longer functions such as
compute_vision_checkpoint_backward_gains_from_checkpoints,
collect_gpt_checkpoint_backward_gains, and
table-normalization helpers are execution plumbing and are not
source-dumped in the notebook. The Stage 2B application cells read or
regenerate the raw and summary gain tables consumed by Stage 4B.
show_source(math_core.boundary_gradient_l2_norm)
show_source(math_core.adjacent_backward_gain)Implementation: boundary_gradient_l2_norm
def boundary_gradient_l2_norm(boundary_gradient: np.ndarray) -> float:
"""L2 norm of the adjoint at a retained architecture boundary.
Math:
A_l = dL / dh_l,
r_l = ||A_l||_2 = sqrt(sum_j A_{l,j}^2).
"""
A = np.asarray(boundary_gradient, dtype=float)
return float(np.sqrt(np.sum(A * A))) if A.size else float("nan")Implementation: adjacent_backward_gain
def adjacent_backward_gain(left_norm: float, right_norm: float, tiny: float = EPS) -> float:
"""Local backward gain between adjacent retained boundaries.
Math:
gamma_l = r_l / max(r_{l+1}, tiny).
"""
return float(float(left_norm) / max(float(right_norm), float(tiny)))# Vision backward-gain table from completed Stage-2B replay.
# Set FORCE_STAGE2B_RECOMPUTE=True only when intentionally replaying the
# expensive checkpoint backward pass.
FORCE_STAGE2B_RECOMPUTE = RECOMPUTE_CHECKPOINT_DIAGNOSTICS
checkpoint_roots = {
'vision': Path('/content/criticality_vision_repair_outputs'),
'gpt_baseline': Path('/content/criticality_bpe_gpt20m_outputs'),
'gpt_repair': Path('/content/criticality_bpe_gpt20m_outputs_repair'),
'ssm': Path('/content/criticality_ssm_outputs'),
}
recomputed_tables = OUT_DIR / 'paper_checkpoint_recomputed_backward_gain_tables'
recomputed_tables.mkdir(parents=True, exist_ok=True)
paper_backward_tables = PROJECT_ROOT / 'paper_data' / 'criticality' / 'backward_gain_tables'
if os.environ.get('CODEBOOK_EXECUTE_LIGHT', '0') == '1' and paper_backward_tables.exists():
for src in sorted(paper_backward_tables.glob('*.csv')):
shutil.copy2(src, recomputed_tables / src.name)
vision_raw_table = recomputed_tables / 'vision_repaired_backward_gain_by_layer_raw.csv'
vision_table = recomputed_tables / 'vision_repaired_backward_gain_by_layer.csv'
if FORCE_STAGE2B_RECOMPUTE or not (vision_raw_table.exists() and vision_table.exists()):
vision_root = checkpoint_roots['vision']
vision_ckpts = sorted((vision_root / 'runs').glob('*/checkpoints/epoch_*.pt'))
if not vision_ckpts:
raise FileNotFoundError(
'Vision paper checkpoints are required for Stage 2B recompute. Expected '
f'{vision_root}/runs/*/checkpoints/epoch_*.pt. Restore them before running this path.'
)
vision_raw_gains, vision_summary = crit.compute_vision_checkpoint_backward_gains_from_checkpoints(
vision_root,
device='cuda' if importlib.util.find_spec('torch') is not None and __import__('torch').cuda.is_available() else 'cpu',
)
vision_raw_gains.to_csv(vision_raw_table, index=False)
vision_summary.to_csv(vision_table, index=False)
else:
vision_raw_gains = pd.read_csv(vision_raw_table)
vision_summary = pd.read_csv(vision_table)
state.update({
'checkpoint_roots': checkpoint_roots,
'paper_checkpoint_recomputed_tables': recomputed_tables,
'vision_raw_gains': vision_raw_gains,
'vision_backward_gain_summary': vision_summary,
})
display(Markdown('**Vision backward-gain summary**'))
show_df(vision_summary[['family', 'from_boundary', 'to_boundary', 'backward_gain', 'n_checkpoints']].rename(columns={'backward_gain': 'Gain', 'n_checkpoints': 'Checkpoints'}), n=4)Vision backward-gain summary
| family | from_boundary | to_boundary | Gain | Checkpoints |
|---|---|---|---|---|
| densenet | input | conv0 | 2.91152 | 7 |
| densenet | conv0 | features.0 | 1.70606 | 7 |
| densenet | features.0 | features.1 | 1.08907 | 7 |
| densenet | features.1 | features.2 | 1.03666 | 7 |
# GPT and SSM backward-gain tables.
gpt_roots = [checkpoint_roots['gpt_baseline'], checkpoint_roots['gpt_repair']]
gpt_raw_table = recomputed_tables / 'gpt_repaired_backward_gain_by_block_raw.csv'
gpt_table = recomputed_tables / 'gpt_repaired_backward_gain_by_block.csv'
if FORCE_STAGE2B_RECOMPUTE or not (gpt_raw_table.exists() and gpt_table.exists()):
for root in gpt_roots:
if not root.exists():
raise FileNotFoundError(root)
gpt_raw_gains, gpt_summary = crit.collect_gpt_checkpoint_backward_gains(gpt_roots)
gpt_raw_gains.to_csv(gpt_raw_table, index=False)
gpt_summary.to_csv(gpt_table, index=False)
else:
gpt_raw_gains = pd.read_csv(gpt_raw_table)
gpt_summary = pd.read_csv(gpt_table)
ssm_raw_table = recomputed_tables / 'ssm_repaired_backward_gain_by_block_raw.csv'
ssm_table = recomputed_tables / 'ssm_repaired_backward_gain_by_block.csv'
if FORCE_STAGE2B_RECOMPUTE or not (ssm_raw_table.exists() and ssm_table.exists()):
paper_stage4_paths_for_ssm = crit.paper_stage4_paths(PROJECT_ROOT)
ssm_raw_source = paper_stage4_paths_for_ssm['paper_tables'] / 'ssm_repaired_backward_gain_by_block_raw.csv'
if not ssm_raw_source.exists():
raise FileNotFoundError(ssm_raw_source)
ssm_raw_gains = pd.read_csv(ssm_raw_source)
ssm_summary = (
ssm_raw_gains.groupby(['label', 'block_index', 'block'], as_index=False)
.agg(
backward_gain=('backward_gain', 'mean'),
backward_gain_min=('backward_gain', 'min'),
backward_gain_max=('backward_gain', 'max'),
n_checkpoints=('backward_gain', 'count'),
n_seeds=('seed', 'nunique'),
first_tokens_seen=('tokens_seen', 'min'),
last_tokens_seen=('tokens_seen', 'max'),
)
.sort_values(['label', 'block_index'])
)
ssm_raw_gains.to_csv(ssm_raw_table, index=False)
ssm_summary.to_csv(ssm_table, index=False)
else:
ssm_raw_gains = pd.read_csv(ssm_raw_table)
ssm_summary = pd.read_csv(ssm_table)
paper_compact_gain_sources = [
PROJECT_ROOT / 'paper_data' / 'criticality' / 'compact_backward_gain_gpt.csv',
PROJECT_ROOT / 'paper_data' / 'criticality' / 'compact_backward_gain_ssm.csv',
PROJECT_ROOT / 'paper_data' / 'criticality' / 'compact_backward_gain_vision.csv',
]
if os.environ.get('CODEBOOK_EXECUTE_LIGHT', '0') == '1' and all(p.exists() for p in paper_compact_gain_sources):
compact_gain_csv_list = []
for src in paper_compact_gain_sources:
dst = OUT_DIR / src.name
shutil.copy2(src, dst)
compact_gain_csv_list.append(dst)
else:
compact_gain_csv_list = crit.write_paper_aligned_backward_gain_tables(recomputed_tables, OUT_DIR)
compact_gain_csvs = {p.stem: p for p in compact_gain_csv_list}
state.update({
'gpt_raw_gains': gpt_raw_gains,
'gpt_backward_gain_summary': gpt_summary,
'ssm_raw_gains': ssm_raw_gains,
'ssm_backward_gain_summary': ssm_summary,
'compact_gain_csv_list': compact_gain_csv_list,
})
display(Markdown('**GPT backward-gain summary**'))
show_df(gpt_summary[['label', 'block', 'backward_gain', 'n_checkpoints']].rename(columns={'backward_gain': 'Gain', 'n_checkpoints': 'Checkpoints'}), n=4)
display(Markdown('**SSM backward-gain summary**'))
show_df(ssm_summary[['label', 'block', 'backward_gain', 'n_checkpoints']].rename(columns={'backward_gain': 'Gain', 'n_checkpoints': 'Checkpoints'}), n=4)GPT backward-gain summary
| label | block | Gain | Checkpoints |
|---|---|---|---|
| RMSNorm | b0 | 5.12215 | 24 |
| RMSNorm | b1 | 1.58518 | 24 |
| RMSNorm | b2 | 1.31490 | 24 |
| RMSNorm | b3 | 1.24116 | 24 |
SSM backward-gain summary
| label | block | Gain | Checkpoints |
|---|---|---|---|
| baseline | ssm0 | 4.95339 | 6 |
| baseline | ssm1 | 1.39681 | 6 |
| baseline | ssm2 | 1.35686 | 6 |
| baseline | ssm3 | 1.32721 | 6 |
# The measured direction tables are loaded in Section 7.Fix a comparison space and positive diffusion eigenvalues on it. Let be the drift-mismatch coordinate at , and the bounded-loss score coordinate. Expanding each square gives The inverse factor explains why weakly fluctuating directions can dominate this metric. It does not, by itself, establish that such directions matter for prediction.
Under the theorem’s fixed-space diffusion and contraction assumptions, an envelope satisfies . Multiplication by the integrating factor and integration over an interval gives For , the forcing term is . The code also integrates piecewise-varying coefficients. A numerical checkpoint estimate of is not automatically an upper bound along the entire path, and an assumed contraction rate is not an empirically established log-Sobolev constant.
Table 1 uses a separate static construction. Conditional on build data, freeze the checkpoint , orthonormal retained basis , and predictor . Freeze and with and (on the selected parameter blocks). Both laws have the same support.
KL derivation. In dimensions, . Taking yields This is an exact Gaussian KL, not a frozen drift-defect proxy.
The loss is
.
MNIST uses 50,000 build and 10,000 certificate examples; CIFAR-10 uses
40,000 build and 10,000 certificate examples. The split seed is
20260731. Test examples are audit-only and were accessed
after all certificate rows were finalized.
For posterior draw , let . With , , and unbiased across-draw variance , the one-sided empirical-Bernstein correction is The variance here is across network draws, each evaluated on the complete certificate sample; it is not a variance over examples substituted into this formula.
For fixed , the bounded-loss exponential inequality and change of measure give with the stated confidence. Conditional on build data, and its KL are fixed, so can be chosen before certificate access. Substitution and the MC upper bound yield Each row uses and ; a union bound over five rows gives simultaneous confidence at least . Independence from the certificate sample is conditional on build data; averaging this conditional guarantee gives the joint statement.
The saved evaluations allow every table term to be recalculated without retraining. The bound concerns posterior-averaged normalized clipped NLL, not classification error or the deterministic checkpoint. The accompanying test risk is a separate held-out measurement.
show_source(math_core.defect_coefficients)
show_source(math_core.finite_time_kl_bound)
from pac_bayes_certificate import gaussian_kl, certificate_from_draws, reconstruct_table
show_source(gaussian_kl)
show_source(certificate_from_draws)Implementation: defect_coefficients
def defect_coefficients(lambdas: np.ndarray, u_coords: np.ndarray, z_coords: np.ndarray) -> DefectCoefficients:
"""Compute d0,d1,d2 from retained eigen-coordinates.
For retained eigenpair (lambda_i, v_i), define:
u_i = <u, v_i>,
z_i = <z, v_i>.
The retained inverse-metric defect is:
D_tau(beta)
= sum_i (u_i - beta lambda_i z_i / 2)^2 / lambda_i
= sum_i u_i^2/lambda_i
- beta sum_i u_i z_i
+ beta^2/4 sum_i lambda_i z_i^2.
Therefore:
d0 = sum_i u_i^2/lambda_i,
d1 = -sum_i u_i z_i,
d2 = (1/4) sum_i lambda_i z_i^2.
"""
lam = np.maximum(np.asarray(lambdas, dtype=float), EPS)
u = np.asarray(u_coords, dtype=float)
z = np.asarray(z_coords, dtype=float)
if not (lam.shape == u.shape == z.shape):
raise ValueError("lambdas, u_coords, z_coords must have the same shape")
return DefectCoefficients(
# d0: deterministic drift mismatch penalized by inverse SGD diffusion.
d0=float(np.sum((u * u) / lam)),
# d1: cross term between SGD drift mismatch and Gibbs bounded-loss score.
d1=float(-np.sum(u * z)),
# d2: Gibbs score contribution measured in the SGD diffusion metric.
d2=float(0.25 * np.sum(lam * z * z)),
)Implementation: finite_time_kl_bound
def finite_time_kl_bound(
kl_initial: float,
defect_value: float,
alpha: float,
time: float,
epsilon: float = 1.0,
) -> float:
"""Frozen-coefficient closed form of the finite-time KL integral.
Math:
KL_t <= exp(-alpha t) KL_0
+ (1/(2 epsilon)) D int_0^t exp[-alpha(t-s)] ds.
This is still an integration, but it is the analytic value of that
integration after freezing D_s = D and alpha_s = alpha on [0,t]. It is
appropriate for endpoint/asymptotic local diagnostics. The checkpoint-path
theorem-level curve should use finite_time_kl_path_bound below.
"""
# Initial mismatch decays exponentially under retained contraction.
decay = float(np.exp(-float(alpha) * float(time)))
# Defect source enters through the exponentially weighted time integral.
path = float(defect_value) * exponential_integral_multiplier(alpha, time) / (2.0 * float(epsilon))
return float(decay * float(kl_initial) + path)Implementation: gaussian_kl
def gaussian_kl(k, sigma_q, sigma_p):
"""KL[N(0,sigma_q^2 I_k) || N(0,sigma_p^2 I_k)].
Taking the Q expectation of log(q/p) gives
k/2 * [sigma_q^2/sigma_p^2 - 1 + log(sigma_p^2/sigma_q^2)].
Both distributions live on the same frozen retained affine subspace.
"""
ratio = (sigma_q / sigma_p) ** 2
return 0.5 * k * (ratio - 1 - np.log(ratio))Implementation: certificate_from_draws
def certificate_from_draws(risks, k, sigma_q, sigma_p, n,
delta_pb=0.008, delta_mc=0.002):
"""Separate posterior Monte Carlo uncertainty from the PAC-Bayes term.
risks[s] is the empirical loss, averaged over all n certificate examples,
for one independent posterior network. Each entry is in [0,1].
The empirical-Bernstein upper correction uses the variance ACROSS draws.
A fixed-prior/fixed-Q Hoeffding PAC-Bayes calculation supplies the PB term;
the build-only Q and bound parameter are frozen before certificate access.
Five rows allocate 5*(delta_pb + delta_mc) = 0.05 failure probability.
"""
risks = np.asarray(risks, dtype=np.float64)
assert risks.ndim == 1 and len(risks) > 1 and n > 0
assert np.isfinite(risks).all() and np.all((0 <= risks) & (risks <= 1))
S = len(risks)
mean, variance = risks.mean(), risks.var(ddof=1)
log_mc = np.log(2 / delta_mc)
mc = np.sqrt(2 * variance * log_mc / S) + 7 * log_mc / (3 * (S - 1))
kl = gaussian_kl(k, sigma_q, sigma_p)
pb = np.sqrt((kl + np.log(1 / delta_pb)) / (2 * n))
return dict(certificate_mean=mean, mc_correction=mc, kl=kl,
pb_complexity=pb, population_bound=mean + mc + pb)# Recompute from the 20,480 saved certificate-network evaluations.
evidence = PROJECT_ROOT / 'paper_data/pac_bayes'
verified = subprocess.run([sys.executable, str(evidence / 'verify_compact_evidence.py')],
check=True, text=True, capture_output=True)
certificate_table = reconstruct_table(evidence)
certificate_table.to_csv(OUTPUT_ROOT / 'table1_recomputed.csv', index=False)
display(certificate_table[['dataset', 'model', 'k', 'kl', 'population_bound', 'test_risk']]
.rename(columns={'kl':'Exact KL', 'population_bound':'Bound ↓', 'test_risk':'Test risk ↓'})
.style.format({'Exact KL':'{:.5f}', 'Bound ↓':'{:.5f}', 'Test risk ↓':'{:.5f}'}))
print('All five rows match the frozen table; compact evidence hashes and arithmetic pass.')| dataset | model | k | Exact KL | Bound ↓ | Test risk ↓ |
|---|---|---|---|---|---|
| MNIST | MLP | 1 | 0.31815 | 0.04258 | 0.02198 |
| MNIST | LeNet | 1 | 0.31815 | 0.02983 | 0.00898 |
| CIFAR-10 | ResNet-32 | 16 | 5.09035 | 0.07657 | 0.05840 |
| CIFAR-10 | WideResNet-16-4 | 11 | 3.49962 | 0.06349 | 0.04448 |
| CIFAR-10 | DenseNet-small | 8 | 2.54518 | 0.07669 | 0.06100 |
All five rows match the frozen table; compact evidence hashes and arithmetic pass.
Interpretation. The five bounds are nonvacuous for a
loss bounded by one. They concern the specified local randomized
predictors and the independent certificate protocol. The Gaussian KL
grows with retained dimension
;
this table does not claim an unrestricted full-weight posterior
certificate. The original TensorFlow producer and all frozen settings
are included under paper_data/pac_bayes/experiment/; the
compact reader above is the same statistical calculation, with no
optimizer or training dependency.
The following curves are redrawn from the recorded checkpoint-coordinate CSVs. The upper row compares the optimizer-state scalar step with the sampled-curvature edge. The lower row examines active-space response. These are complementary: remaining below an upper edge does not ensure substantial useful response. The two sides describe local quadratic diagnostics, not a global convergence guarantee.
# Plotting entry point: code/criticality_coordinates.pycriticality_coord_paths = {'vision': vision_coord_path, 'gpt': gpt_coord_path}
paper_stage4_written = crit.render_compact_main_criticality_2x4(
vision_coord_path, gpt_coord_path, OUT_DIR)
state['paper_stage4_written'] = paper_stage4_written
display_pdf(OUT_DIR / 'criticality_coordinates_2x4_panel.pdf')
Backward-gain curves are regenerated from the saved boundary-gradient summaries. Their role is localization: a global scalar can indicate weak response, whereas the layerwise curve shows the interfaces where the observed loss sensitivity changes. The dashed neutral-gain reference is one; gains are directional and scale-dependent, so they should be compared within the stated boundary convention.
# Numerical inputs: paper_data/criticality/backward_gain_tables/import criticality_coordinates as crit
# Stage 4B application: render the unified backward-gain figure from Stage 2B outputs.
recomputed_tables = Path(state.get('paper_checkpoint_recomputed_tables', OUT_DIR / 'paper_checkpoint_recomputed_backward_gain_tables'))
required_stage2_tables = [
recomputed_tables / 'vision_repaired_backward_gain_by_layer_raw.csv',
recomputed_tables / 'vision_repaired_backward_gain_by_layer.csv',
recomputed_tables / 'gpt_repaired_backward_gain_by_block_raw.csv',
recomputed_tables / 'gpt_repaired_backward_gain_by_block.csv',
recomputed_tables / 'ssm_repaired_backward_gain_by_block_raw.csv',
recomputed_tables / 'ssm_repaired_backward_gain_by_block.csv',
]
missing_stage2 = [str(path) for path in required_stage2_tables if not path.exists()]
if missing_stage2:
raise RuntimeError('Stage 4B requires Stage 2B backward-gain tables. Missing: ' + ', '.join(missing_stage2))
compact_gain_csv_list = [Path(p) for p in state.get('compact_gain_csv_list', [
OUT_DIR / 'compact_backward_gain_gpt.csv',
OUT_DIR / 'compact_backward_gain_ssm.csv',
OUT_DIR / 'compact_backward_gain_vision.csv',
])]
missing_gain_csvs = [str(path) for path in compact_gain_csv_list if not path.exists()]
if missing_gain_csvs:
raise RuntimeError('Stage 4B requires Stage 2B compact backward-gain CSV aliases. Missing: ' + ', '.join(missing_gain_csvs))
criticality_unified_gain_pdf = crit.make_unified_backward_gain(
compact_gain_csv_list,
OUT_DIR / 'criticality_unified_backward_gain.pdf',
)
criticality_unified_gain_png = crit.make_unified_backward_gain(
compact_gain_csv_list,
OUT_DIR / 'criticality_unified_backward_gain.png',
)
compact_gain_csvs = {Path(p).stem: Path(p) for p in compact_gain_csv_list}
state.update({
'criticality_unified_backward_gain_path': criticality_unified_gain_pdf,
'criticality_unified_backward_gain_png_path': criticality_unified_gain_png,
'compact_backward_gain_gpt_path': compact_gain_csvs['compact_backward_gain_gpt'],
'compact_backward_gain_ssm_path': compact_gain_csvs['compact_backward_gain_ssm'],
'compact_backward_gain_vision_path': compact_gain_csvs['compact_backward_gain_vision'],
'stage4b_pdfs': [criticality_unified_gain_pdf],
})
display_pdf(criticality_unified_gain_pdf, height=420, max_pages=1)
This section presents the lifted precision figures used to introduce the paper’s local-interaction object. These figures are the code supplement’s bridge from the computation graph to the Schur-complement curvature identity.
The lifted state is , where are parameters and are intermediate states already present in the forward computation. Each local factor touches a small scope of these variables. At a checkpoint, a residual-form factor has first variation
With local weight , this factor contributes the embedded information block
to the lifted precision matrix. Thus the support pattern of the lifted precision is determined by which variable groups co-occur in local computational factors.
After assembling the lifted precision,
partition it into parameter and state blocks. Eliminating intermediate states gives
At finite precision this is the softened curvature; Theorem 1 supplies the additional hard-constraint limit. The figures shown in this section visualize the sparse object before elimination. They make the architecture-visible locality clear: MLP blocks produce short chain-like supports; residual CNN blocks add skip and normalization interfaces; transformer blocks add residual-stream, attention, and feed-forward couplings.
The displayed source function
generate_block_precision_figures is the compact entry
point. It calls the renderer, writes the MLP, residual-CNN, and
transformer block figures, and copies them under stable paper-facing
names. The exact support builders are mentioned with file/line locations
rather than source-dumped because the transformer support builder is
long:
exact_mlp_block_elementwise_supportexact_resnet_block_elementwise_supportexact_transformer_block_elementwise_supportThe whole-network panels are generated or copied in the following cell. They use the same lifted-support principle, but at a larger architecture scale.
The default previews retain the paper PDFs. Their TensorFlow builders
are included; RUN_STAGE5_RENDERERS=1 explicitly re-extracts
and redraws the architecture supports. This rendering switch does not
train the models.
import inspect
import re
import block_precision_figures as struct
display(Markdown("""
**Lifted precision: implementation entry point**
The short entry point assembles the block figures. The detailed elementwise support builders are linked below it.
"""))
show_source_with_file_lines(struct.generate_block_precision_figures)
def source_line_for_function(source_file: Path, function_name: str) -> int:
pattern = re.compile(rf'^def {re.escape(function_name)}\b')
for lineno, line in enumerate(source_file.read_text().splitlines(), start=1):
if pattern.match(line):
return lineno
raise ValueError(f'could not find {function_name} in {source_file}')
support_source = SRC / 'local_precision_pattern_renderer.py'
display(Markdown('**Exact support builders available for inspection**'))
for function_name in [
'exact_mlp_block_elementwise_support',
'exact_resnet_block_elementwise_support',
'exact_transformer_block_elementwise_support',
]:
display(Markdown(f"- `local_precision_pattern_renderer.{function_name}`: `{relpath(support_source)}:{source_line_for_function(support_source, function_name)}`"))Lifted precision: implementation entry point
The short entry point assembles the block figures. The detailed elementwise support builders are linked below it.
Implementation: generate_block_precision_figures
def generate_block_precision_figures(out_dir: Path = OUT_DIR) -> list[Path]:
"""Generate paper-facing MLP/ResNet/Transformer block precision figures."""
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
renderer = _import_renderer()
old_argv = sys.argv[:]
try:
sys.argv = [
"local_precision_pattern_renderer.py",
"--out_dir",
str(out_dir),
"--batch_size_display",
"3",
"--max_points",
"1000000",
]
renderer.main()
finally:
sys.argv = old_argv
written: list[Path] = []
for paper_name, compact_name in PAPER_BLOCK_FILES.items():
paper_path = out_dir / paper_name
compact_path = out_dir / compact_name
if not paper_path.exists():
raise FileNotFoundError(f"renderer did not write {paper_path}")
shutil.copy2(paper_path, compact_path)
written.extend([paper_path, compact_path])
overview = out_dir / "lifted_precision_overview.pdf"
compact_triptych = out_dir / "compact_lifted_precision_triptych.pdf"
if overview.exists():
shutil.copy2(overview, compact_triptych)
written.append(compact_triptych)
return writtenExact support builders available for inspection
local_precision_pattern_renderer.exact_mlp_block_elementwise_support:
code/local_precision_pattern_renderer.py:2207
local_precision_pattern_renderer.exact_resnet_block_elementwise_support:
code/local_precision_pattern_renderer.py:2253
local_precision_pattern_renderer.exact_transformer_block_elementwise_support:
code/local_precision_pattern_renderer.py:2333
import block_precision_figures as struct
# Exact block-level schematic plus precision panels.
RUN_STAGE5_RENDERERS = os.environ.get('RUN_STAGE5_RENDERERS', '0') == '1'
block_figure_names = [
'mlp_block_schematic_plus_precision.pdf',
'resnet_block_schematic_plus_precision.pdf',
'transformer_block_schematic_plus_precision.pdf',
]
if RUN_STAGE5_RENDERERS:
block_paths = struct.generate_block_precision_figures(OUT_DIR)
else:
block_paths = []
for name in block_figure_names:
src = PROJECT_ROOT / 'paper_artifacts' / name
dst = OUT_DIR / name
shutil.copy2(src, dst)
block_paths.append(dst)
state['block_precision_paths'] = block_paths
state['triptych_path'] = OUT_DIR / 'compact_lifted_precision_triptych.pdf'
for p in [OUT_DIR / name for name in block_figure_names]:
display_pdf(p, height=360)


# Exact whole-network all-variable panels.
RUN_STAGE5_RENDERERS = os.environ.get('RUN_STAGE5_RENDERERS', '0') == '1'
whole_figure_names = [
'resnet20_schematic_joint_parameter_allvars.pdf',
'distilbert_whole_schematic_joint_parameter_allvars.pdf',
]
if RUN_STAGE5_RENDERERS:
import whole_network_precision_figures as whole
whole_paths = whole.generate_whole_network_figures(OUT_DIR, batch_size=3, seed=0)
else:
whole_paths = []
for name in whole_figure_names:
src = PROJECT_ROOT / 'paper_artifacts' / name
dst = OUT_DIR / name
shutil.copy2(src, dst)
whole_paths.append(dst)
state['whole_network_paths'] = whole_paths
for p in [OUT_DIR / name for name in whole_figure_names]:
display_pdf(p, height=420)

This section explains the probability geometry behind the resolved KL/PAC-Bayes construction. A Gibbs comparison over the full parameter space uses an inverse covariance metric. Directions with very small minibatch-gradient covariance eigenvalues can therefore dominate the full-parameter Gibbs defect, even when finite movement along those directions changes held-out predictions very little. The theorem studies a declared comparison space. The split-certified table separately freezes its local prior and posterior on a common retained affine space; the geometry plots alone do not establish that certificate.
Let be the vector of logits on a measured batch , and let be its parameter Jacobian.
A symmetry direction is a parameter displacement for which on the measured batch. It changes coordinates while leaving the represented function nearly unchanged on the measured data.
A structural gauge is a known coordinate redundancy, such as ReLU/BatchNorm scaling, that produces or approximates such a symmetry.
A loss-space gauge is an output redundancy. For softmax cross-entropy, adding the same scalar to every logit leaves probabilities unchanged.
A loss tangent is a direction whose output tangent has small bounded-loss curvature, for example
where is the positive-semidefinite local output curvature on a smooth loss region. Such a direction can move logits while barely changing clipped loss or classification error.
An augmentation tangent compares with a data-transformation response for a transformation such as crop, color, MixUp, or CutMix. This probes whether a parameter direction resembles a data-space transformation in output space.
The weak-direction panels focus on low-covariance directions that are not already identified by explicit symmetry or gauge probes. The XAI plots then inspect whether those remaining directions are better explained as output/loss tangents or as simple input-transform tangents.
For each condition and direction , the direction table provides a minibatch-gradient covariance eigenvalue and an inverse-metric Gibbs-defect contribution , such as a directionwise . Normalize these into
When a GGN/train-Fisher curvature is available, the ordinary-geometry mass is
Here is the minibatch-gradient covariance eigenvalue in direction . If is the drift/reference mismatch coordinate, then
is the directionwise inverse-metric contribution to the Gibbs defect at . When available, is the train Fisher/GGN Rayleigh value used as ordinary curvature mass.
For a low-covariance tail , the aggregate comparison is
Large with small and means that the ambient full-parameter Gibbs defect is dominated by directions that carry little ordinary covariance or train-Fisher mass.
For selected direction groups, the code perturbs the checkpoint at a fixed radius and recomputes held-out clipped-loss and error changes. This asks whether a high inverse-metric defect group produces visible finite predictive movement.
For augmentation probes, the code compares a direction-induced output tangent with transformation tangents using
The spectrum overlays and retained train/validation alignment plot use these direction-level quantities to explain how augmentation changes the local probability geometry.
The first panel compares inverse-metric defect, covariance mass, curvature, and finite prediction changes for the same low-covariance directions. In these ResNet records the tail carries about 0.11/0.08 of covariance mass but 0.80/0.78 of probed curvature mass. Thus small diffusion does not imply small curvature. The finite-radius measurements provide the separate evidence for small predictive movement; a zero error-rate change is shown as zero.
The next panels compare retained-direction train/validation alignment and clean train/validation/test risks for crop/flip and MixUp/CutMix. These are checkpoint diagnostics, not new training runs or additional population certificates.
All three panels use the archived ResNet tables listed in
paper_data/measured_directions/SOURCES.json. Constructed
examples are kept separately under
paper_data/illustrations/ and are excluded from this
empirical path.
import resolved_direction_figures as dirs
show_source(math_core.direction_defect_contributions)Implementation: direction_defect_contributions
def direction_defect_contributions(
lambdas: np.ndarray,
u_coords: np.ndarray,
z_coords: np.ndarray,
) -> dict[str, np.ndarray]:
"""Directionwise d0,d1,d2 terms used before prefix selection.
For each covariance eigen-direction v_i:
lambda_i = retained SGD diffusion eigenvalue,
u_i = <u, v_i>,
z_i = <z, v_i>.
The one-direction contribution is
D_i(beta)
= (u_i - beta lambda_i z_i / 2)^2 / lambda_i
= d0_i + beta d1_i + beta^2 d2_i,
where
d0_i = u_i^2 / lambda_i,
d1_i = -u_i z_i,
d2_i = lambda_i z_i^2 / 4.
"""
lam = np.maximum(np.asarray(lambdas, dtype=float), EPS)
u = np.asarray(u_coords, dtype=float)
z = np.asarray(z_coords, dtype=float)
if not (lam.shape == u.shape == z.shape):
raise ValueError("lambdas, u_coords, z_coords must have the same shape")
return {
"d0_contrib": (u * u) / lam,
"d1_contrib": -(u * z),
"d2_contrib": 0.25 * lam * z * z,
}# Use measured records only. Missing inputs raise an error; no synthetic fallback.
d = PROJECT_ROOT / 'paper_data/measured_directions'
paths = [
dirs.make_paper_resnet_kl_prediction_summary(
d / 'resnet_full_blockwise_spectrum_stats.csv',
d / 'resnet_bottom32_audited_direction_stats.csv',
d / 'resnet_mechanism_defect_shares.csv',
OUT_DIR / 'measured_defect_and_prediction.pdf'),
dirs.make_paper_modern_aug_train_val_alignment(
d / 'retained_direction_rows.csv', OUT_DIR / 'measured_train_validation_alignment.pdf'),
dirs.make_paper_modern_aug_generalization(
d / 'clean_generalization_metrics.csv', OUT_DIR / 'measured_augmentation_generalization.pdf'),
]
for path in paths: display_pdf(path)
state['measured_direction_figures'] = paths


| Reader task | Entry point | Inputs | Framework |
|---|---|---|---|
| Follow the equations | code/core_math_identities.py |
Small arrays | NumPy |
| Reconstruct Table 1 | code/pac_bayes_certificate.py |
Frozen per-network risks | NumPy/Pandas |
| Verify the evidence | paper_data/pac_bayes/verify_compact_evidence.py |
Hashed records | Python standard library |
| Redraw criticality curves | code/criticality_coordinates.py |
Recorded CSVs | Matplotlib; PyTorch for checkpoint replay |
| Read architecture supports | code/local_precision_pattern_renderer.py |
Module scopes | TensorFlow |
| Inspect direction geometry | code/resolved_direction_figures.py |
Measured direction tables | NumPy/Matplotlib |
| Inspect the original certificate run | paper_data/pac_bayes/experiment/run_safe_table1.py |
Original data, checkpoints and basis | TensorFlow |
Open README.executed.html to read the tutorial, or
README.executed.ipynb to inspect its executed cells. The
clean source is README.ipynb. Run
python verify_core_identities.py for the algebraic checks
and python reproduce_main_artifacts.py for the notebook’s
default calculations. The latter writes
README.executed.ipynb and results under
output/. It reconstructs statistics from saved
measurements; it does not retrain models.
Optional checkpoint replay needs the original weights, optimizer
state where used, and matching data.
RECOMPUTE_CHECKPOINT_DIAGNOSTICS=1 enables that path;
RUN_STAGE5_RENDERERS=1 enables the TensorFlow precision
builders. Missing checkpoints stop execution rather than silently
triggering training.
For original training, distinguish
code/checkpoint_training_reference.py (whose default
examples include synthetic execution checks) from the exact
revised-table producer
paper_data/pac_bayes/experiment/run_safe_table1.py. Its
five checkpoint manifests record TensorFlow 2.20.0; submitted settings,
source dependencies, frozen protocol and training logs accompany it. It
retains its original directory assumptions: its sibling imports must be
restored from reference_sources/ before launching it.
RUN_STAGE1_LONG_JOBS=1 is not a one-command reproduction of
all published training.
The evidence verifier checks saved hashes, arithmetic and recorded
access order; it does not independently re-evaluate the omitted
networks. The complete checkpoint/basis archive is optional, with
omitted filenames and hashes recorded in
paper_data/pac_bayes/OMITTED_HEAVY_ARTIFACTS.csv. The
default tutorial needs neither that archive nor a cloud account.
# Export only newly computed reader artifacts. Preserve other user output files.
artifacts_out = OUTPUT_ROOT / 'artifacts'
artifacts_out.mkdir(exist_ok=True)
for path in sorted(OUT_DIR.glob('*.pdf')):
shutil.copy2(path, artifacts_out / path.name)
print('Completed: mathematical checks, verified Table 1, and saved-data diagnostic figures.')
print('Training launched:', RUN_STAGE1_LONG_JOBS)
print('Checkpoint measurements recomputed:', RECOMPUTE_CHECKPOINT_DIAGNOSTICS)Completed: mathematical checks, verified Table 1, and saved-data diagnostic figures.
Training launched: False
Checkpoint measurements recomputed: False