Local-Interaction Learning Dynamics

A Markov Random Field View of Deep Learning

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.

What the computations establish

A network is represented by trainable parameters θ\theta and intermediate states uu. Local module relations, loss, and regularization define the lifted energy E(θ,u)E(\theta,u) 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

Activation elimination and the hard-constraint limit

For a positive lifted quadratic with blocks P=(ABB⊤D)P=\begin{pmatrix}A&B\\B^\top&D\end{pmatrix}, stationarity in the state displacement gives Δu*=−D−1B⊤Δθ\Delta u_*=-D^{-1}B^\top\Delta\theta. Substitution yields Fκ,τ=A−BD−1B⊤F_{\kappa,\tau}=A-BD^{-1}B^\top. This is the softened curvature at finite module precision κ\kappa and state ridge τ\tau. Theorem 1 recovers deterministic-network Fisher/Gauss–Newton curvature in its stated hard-constraint limit; finite precision alone is not enough.

For example, E=κ(u−θ)2/2+u2/2E=\kappa(u-\theta)^2/2+u^2/2 gives Fκ=κ/(κ+1)F_\kappa=\kappa/(\kappa+1), approaching 11 as κ→∞\kappa\to\infty. The small check below verifies both the finite value and the limit.

Criticality and measured proxies

For a quadratic gradient step in a fixed preconditioned coordinate, F‾=P1/2FredP1/2\bar F=P^{1/2}F_\mathrm{red}P^{1/2}, the upper edge is ηmax=2/λmax(F‾)\eta_{\max}=2/\lambda_{\max}(\bar F). An active-space coordinate ρact=|ηeff|λmin(F‾|𝒰act)\rho_\mathrm{act}=|\eta_\mathrm{eff}|\lambda_{\min}(\bar F|_{\mathcal U_\mathrm{act}}) 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, Aℓ=∂L/∂hℓA_\ell=\partial L/\partial h_\ell gives the measured directional gain bℓ=∥Aℓ∥2/max⁡(∥Aℓ+1∥2,ϵ)b_\ell=\|A_\ell\|_2/\max(\|A_{\ell+1}\|_2,\epsilon). This localizes attenuation or amplification in the observed loss direction; it is not the separator operator norm itself.

Two distinct distributional calculations

On a fixed comparison space, the drift defect is D(β)=∑i(ri−βλiqi/2)2/λiD(\beta)=\sum_i(r_i-\beta\lambda_iq_i/2)^2/\lambda_i. 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 KL(Q∥P)\mathrm{KL}(Q\|P) and an independent certificate sample. A frozen checkpoint defect is not substituted for that prior KL.

Supporting code
# 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'
Supporting code
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))
Supporting code
state = {}
Supporting code
# 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))

1. Reproduction and mathematical checks

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

Checkpoints and the training switch

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.

Supporting code
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.')
Checkpoint inventory (optional replay)

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.

2. Criticality coordinates from recorded checkpoints

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.

1. Actual optimizer-state scalar step

At checkpoint tt, let θt\theta_t be the parameters, gtg_t the current training gradient in the coordinate being tested, and Δθt\Delta\theta_t the next optimizer update reconstructed from the saved optimizer state. The scalar step used in the upper-band comparison is

η∥,t=−Δθt⊤gt∥gt∥22. \eta_{\parallel,t} =-\frac{\Delta\theta_t^\top g_t}{\|g_t\|_2^2}.

This scalar is the component of the actual update parallel to the chosen gradient; an orthogonal update component may remain. For SGD with momentum, Δθt\Delta\theta_t 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.

2. Upper-edge curvature from a Gram matrix

The dense reduced curvature proxy is not formed. With mm probe gradients stacked as

Gt=[gt,1⊤⋮gt,m⊤]∈ℝm×p, G_t=\begin{bmatrix}g_{t,1}^\top\\ \vdots\\ g_{t,m}^\top\end{bmatrix}\in\mathbb R^{m\times p},

the observed-gradient outer-product proxy is

F̂t=1mGt⊤Gt. \widehat F_t=\frac{1}{m}G_t^\top G_t.

The nonzero eigenvalues of F̂t\widehat F_t equal those of the smaller row Gram matrix

K̂t=1mGtGt⊤∈ℝm×m. \widehat K_t=\frac{1}{m}G_tG_t^\top\in\mathbb R^{m\times m}.

The measured scalar edge proxy is therefore

η̂edge,t=2λmax(K̂t). \widehat\eta_{\mathrm{edge},t}=\frac{2}{\lambda_{\max}(\widehat K_t)}.

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:

ηmomentumedge,t=(1+μ)2λmax,ρupper,t=|ηeff,t|ηmomentumedge,t. \eta_{\mathrm{momentum\ edge},t}=(1+\mu)\frac{2}{\lambda_{\max}}, \qquad \rho_{\mathrm{upper},t}=\frac{|\eta_\mathrm{eff,t}|}{\eta_{\mathrm{momentum\ edge},t}}.

For AdamW/GPT, ηeff,t\eta_\mathrm{eff,t} is already reconstructed from the optimizer state, so the coordinate is reported directly in the measured state-effective units.

3. Active subspace and lower-side plasticity

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 Ut∈ℝp×rU_t\in\mathbb R^{p\times r} have orthonormal columns spanning a small active subspace, typically built from recent or probe gradient directions. Given a probe-gradient matrix GtG_t, define the centered version

Xt=Gt−𝟏g‾t⊤,g‾t=1m∑s=1mgt,s. X_t=G_t-\mathbf 1\bar g_t^\top, \qquad \bar g_t=\frac1m\sum_{s=1}^m g_{t,s}.

The centered active-space proxy used in this implementation is

F̂act,t=Ut⊤(1m−1Xt⊤Xt)Ut=1m−1(XtUt)⊤(XtUt). \widehat F_{\mathrm{act},t} =U_t^\top\left(\frac{1}{m-1}X_t^\top X_t\right)U_t =\frac{1}{m-1}(X_tU_t)^\top(X_tU_t).

The helper active_subspace_lower_eigenvalue computes

λact,t=λmin(F̂act,t). \lambda_{\mathrm{act},t}=\lambda_{\min}(\widehat F_{\mathrm{act},t}).

The paper-facing active-plasticity coordinate is

ρact,t=|ηeff,t|λact,t. \rho_{\mathrm{act},t}=|\eta_{\mathrm{eff},t}|\lambda_{\mathrm{act},t}.

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.

4. Checkpoint replay paths

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.

Supporting code
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))
Supporting code
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

3. Backward-gain diagnostics from retained boundaries

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.

1. Boundary adjoints and local gains

At checkpoint θj\theta_j, choose architecture-native retained boundaries

h0(θj;x),h1(θj;x),…,hL(θj;x), h_0(\theta_j;x),h_1(\theta_j;x),\ldots,h_L(\theta_j;x),

such as an input boundary, residual block outputs, DenseNet transition outputs, GPT block outputs, or SSM scan/state boundaries. For a probe minibatch ℬj\mathcal B_j, define the training loss

ℒj(θj)=1|ℬj|∑(x,y)∈ℬjℓ(y,fθj(x)), \mathcal L_j(\theta_j) =\frac{1}{|\mathcal B_j|}\sum_{(x,y)\in\mathcal B_j} \ell(y,f_{\theta_j}(x)),

and retain the boundary adjoints

Aj,ℓ=∂ℒj∂hℓ. A_{j,\ell}=\frac{\partial \mathcal L_j}{\partial h_\ell}.

The local backward gain is

bj,ℓ=∥Aj,ℓ∥2max⁡{∥Aj,ℓ+1∥2,ε}. b_{j,\ell} =\frac{\|A_{j,\ell}\|_2}{\max\{\|A_{j,\ell+1}\|_2,\varepsilon\}}.

The helper boundary_gradient_l2_norm computes ∥Aj,ℓ∥2\|A_{j,\ell}\|_2, 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.

2. Relation to separator transfers

The theorem-level separator transfer for eliminating internal variables II from a clique CC to a separator SS can be written schematically as

TC→S=QSItot(QIItot)−1,gC→S=∥TC→S∥op. T_{C\to S}=Q^\mathrm{tot}_{SI}(Q^\mathrm{tot}_{II})^{-1}, \qquad g_{C\to S}=\|T_{C\to S}\|_\mathrm{op}.

The measured bj,ℓb_{j,\ell} is not a full operator-norm proof of gC→Sg_{C\to S}. 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

Bj,path=∏ℓ=0L−1bj,ℓ=exp⁡(∑ℓ=0L−1logbj,ℓ), B_{j,\mathrm{path}}=\prod_{\ell=0}^{L-1} b_{j,\ell} =\exp\left(\sum_{\ell=0}^{L-1}\log b_{j,\ell}\right),

but the paper-facing figure emphasizes layer/block-local gains because they localize which architectural interface is responsible.

3. Implementation map

The displayed source functions are the math-facing part:

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.

Supporting code
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)))
Supporting code
# 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
Supporting code
# 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
Supporting code
# The measured direction tables are loaded in Section 7.

4. Resolved KL dynamics and the split-certified PAC-Bayes table

4.1 The fixed-space KL-to-Gibbs calculation

Fix a comparison space EE and positive diffusion eigenvalues λi\lambda_i on it. Let rir_i be the drift-mismatch coordinate at β=0\beta=0, and qiq_i the bounded-loss score coordinate. Expanding each square gives DE(β)=∑i∈E(ri−βλiqi/2)2λi=d0+βd1+β2d2,d0=∑iri2λi,d1=−∑iriqi,d2=14∑iλiqi2. D_E(\beta)=\sum_{i\in E}\frac{(r_i-\beta\lambda_iq_i/2)^2}{\lambda_i} =d_0+\beta d_1+\beta^2d_2, \qquad d_0=\sum_i\frac{r_i^2}{\lambda_i},\quad d_1=-\sum_i r_iq_i,\quad d_2=\tfrac14\sum_i\lambda_iq_i^2. 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 K̇≤−αK+D/(2ε)\dot K\le-\alpha K+D/(2\varepsilon). Multiplication by the integrating factor eαte^{\alpha t} and integration over an interval gives K(t+Δt)≤e−αΔtK(t)+1−e−αΔt2εαD. K(t+\Delta t)\le e^{-\alpha\Delta t}K(t) +\frac{1-e^{-\alpha\Delta t}}{2\varepsilon\alpha}D. For α→0\alpha\to0, the forcing term is DΔt/(2ε)D\Delta t/(2\varepsilon). The code also integrates piecewise-varying coefficients. A numerical checkpoint estimate of DD is not automatically an upper bound along the entire path, and an assumed contraction rate is not an empirically established log-Sobolev constant.

4.2 The independent build and certificate samples

Table 1 uses a separate static construction. Conditional on build data, freeze the checkpoint θ̂\widehat\theta, orthonormal retained basis V∈ℝp×kV\in\mathbb R^{p\times k}, and predictor hw(x)=fθ̂+Vw(x)h_w(x)=f_{\widehat\theta+Vw}(x). Freeze Q=𝒩(0,σQ2Ik)Q=\mathcal N(0,\sigma_Q^2I_k) and P=𝒩(0,σP2Ik)P=\mathcal N(0,\sigma_P^2I_k) with σP=2σQ\sigma_P=2\sigma_Q and σQ=5×10−4∥θ̂∥2/k\sigma_Q=5\times10^{-4}\|\widehat\theta\|_2/\sqrt{k} (on the selected parameter blocks). Both laws have the same support.

KL derivation. In kk dimensions, log⁡(q/p)=klog⁡(σP/σQ)+∥w∥2(σP−2−σQ−2)/2\log(q/p)=k\log(\sigma_P/\sigma_Q) +\|w\|^2(\sigma_P^{-2}-\sigma_Q^{-2})/2. Taking 𝔼Q∥w∥2=kσQ2\mathbb E_Q\|w\|^2=k\sigma_Q^2 yields KL(Q∥P)=k2[σQ2σP2−1+logσP2σQ2]=k2[14−1+log4]. \mathrm{KL}(Q\|P)=\frac{k}{2} \left[\frac{\sigma_Q^2}{\sigma_P^2}-1+ \log\frac{\sigma_P^2}{\sigma_Q^2}\right] =\frac{k}{2}\left[\frac14-1+\log4\right]. This is an exact Gaussian KL, not a frozen drift-defect proxy.

The loss is ℓ(θ;x,y)=min⁡{−log⁡pθ(y∣x),5}/5∈[0,1]\ell(\theta;x,y)=\min\{-\log p_\theta(y\mid x),5\}/5\in[0,1]. 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.

4.3 Statistical terms and their calculation

For posterior draw ws∼Qw_s\sim Q, let rs=n−1∑i=1nℓ(hws;xi,yi)r_s=n^{-1}\sum_{i=1}^n\ell(h_{w_s};x_i,y_i). With S=4096S=4096, r‾=S−1∑srs\bar r=S^{-1}\sum_s r_s, and unbiased across-draw variance v̂\widehat v, the one-sided empirical-Bernstein correction is ϵMC=2v̂log⁡(2/δMC)S+7log⁡(2/δMC)3(S−1). \epsilon_\mathrm{MC}= \sqrt{\frac{2\widehat v\log(2/\delta_\mathrm{MC})}{S}} +\frac{7\log(2/\delta_\mathrm{MC})}{3(S-1)}. 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 λ>0\lambda>0, the bounded-loss exponential inequality and change of measure give R(Q)≤R̂(Q)+[KL(Q∥P)+log⁡(1/δPB)]/λ+λ/(8n)R(Q)\le\widehat R(Q)+[\mathrm{KL}(Q\|P)+\log(1/\delta_\mathrm{PB})]/\lambda+\lambda/(8n) with the stated confidence. Conditional on build data, QQ and its KL are fixed, so λ=8n[KL(Q∥P)+log⁡(1/δPB)]\lambda=\sqrt{8n[\mathrm{KL}(Q\|P)+\log(1/\delta_\mathrm{PB})]} can be chosen before certificate access. Substitution and the MC upper bound yield R(Q)≤r‾+ϵMC+KL(Q∥P)+log⁡(1/δPB)2n. R(Q)\le\bar r+\epsilon_\mathrm{MC} +\sqrt{\frac{\mathrm{KL}(Q\|P)+\log(1/\delta_\mathrm{PB})}{2n}}. Each row uses δPB=0.008\delta_\mathrm{PB}=0.008 and δMC=0.002\delta_\mathrm{MC}=0.002; a union bound over five rows gives simultaneous confidence at least 1−5(0.008+0.002)=0.951-5(0.008+0.002)=0.95. 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.

Supporting code
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 kk; 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.

5. Stability and active response over training

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.

Supporting code
# Plotting entry point: code/criticality_coordinates.py
Supporting code
criticality_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')

Download figure PDF

Localizing the affected interface

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.

Supporting code
# Numerical inputs: paper_data/criticality/backward_gain_tables/
Supporting code
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)

Download figure PDF

6. Architecture-visible precision

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.

1. Local factors and lifted precision support

The lifted state is z=(θ,u)z=(\theta,u), where θ\theta are parameters and uu are intermediate states already present in the forward computation. Each local factor ff touches a small scope SfS_f of these variables. At a checkpoint, a residual-form factor has first variation

rf(z0+ΔzSf)=rf(z0)+Jf(z0)ΔzSf+o(∥ΔzSf∥). r_f(z_0+\Delta z_{S_f}) = r_f(z_0)+J_f(z_0)\Delta z_{S_f}+o(\|\Delta z_{S_f}\|).

With local weight Wf≽0W_f\succeq0, this factor contributes the embedded information block

EmbedSf(Jf(z0)⊤WfJf(z0)) \mathrm{Embed}_{S_f}\left(J_f(z_0)^\top W_fJ_f(z_0)\right)

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.

2. Activation elimination

After assembling the lifted precision,

Pθ,u=Λθ⊕τIu+∑fEmbedSf(Jf⊤WfJf), P_{\theta,u}=\Lambda_\theta\oplus\tau I_u+ \sum_f \mathrm{Embed}_{S_f}\left(J_f^\top W_fJ_f\right),

partition it into parameter and state blocks. Eliminating intermediate states gives

Fκ,τ=Pθθ−PθuPuu†Puθ. F_{\kappa,\tau} =P_{\theta\theta}-P_{\theta u}P_{uu}^{\dagger}P_{u\theta}.

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.

3. Implementation map

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:

The 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.

Supporting code
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 written

Exact support builders available for inspection

Supporting code
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)

Download figure PDF

Download figure PDF

Download figure PDF

Supporting code
# 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)

Download figure PDF

Download figure PDF

7. Stochastic geometry and predictive relevance

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.

1. Direction definitions

Let fθ(X)f_\theta(X) be the vector of logits on a measured batch XX, and let Jf(θ;X)J_f(\theta;X) be its parameter Jacobian.

A symmetry direction is a parameter displacement vv for which Jf(θ;X)v≈0J_f(\theta;X)v\approx0 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 vv whose output tangent qv=Jf(θ;X)vq_v=J_f(\theta;X)v has small bounded-loss curvature, for example

∥Hℓ1/2qv∥≪∥qv∥, \|H_\ell^{1/2}q_v\|\ll\|q_v\|,

where HℓH_\ell 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 Jf(θ;X)vJ_f(\theta;X)v with a data-transformation response fθ(TX)−fθ(X)f_\theta(TX)-f_\theta(X) 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.

2. Direction-level normalization

For each condition and direction ii, the direction table provides a minibatch-gradient covariance eigenvalue λi\lambda_i and an inverse-metric Gibbs-defect contribution aia_i, such as a directionwise d0,id_{0,i}. Normalize these into

si=ai∑jaj,mi=λi∑jλj. s_i=\frac{a_i}{\sum_j a_j}, \qquad m_i=\frac{\lambda_i}{\sum_j \lambda_j}.

When a GGN/train-Fisher curvature κi\kappa_i is available, the ordinary-geometry mass is

fi=max⁡(κi,0)∑jmax⁡(κj,0). f_i=\frac{\max(\kappa_i,0)}{\sum_j \max(\kappa_j,0)}.

Here λi\lambda_i is the minibatch-gradient covariance eigenvalue in direction viv_i. If ri=⟨b−brev,vi⟩r_i=\langle b-b_\mathrm{rev},v_i\rangle is the drift/reference mismatch coordinate, then

d0,i=ri2λi d_{0,i}=\frac{r_i^2}{\lambda_i}

is the directionwise inverse-metric contribution to the Gibbs defect at β=0\beta=0. When available, κi=vi⊤F̂trainvi\kappa_i=v_i^\top\widehat F_\mathrm{train}v_i is the train Fisher/GGN Rayleigh value used as ordinary curvature mass.

For a low-covariance tail BB, the aggregate comparison is

SB=∑i∈Bsi,MB=∑i∈Bmi,FB=∑i∈Bfi. S_B=\sum_{i\in B}s_i, \qquad M_B=\sum_{i\in B}m_i, \qquad F_B=\sum_{i\in B}f_i.

Large SBS_B with small MBM_B and FBF_B means that the ambient full-parameter Gibbs defect is dominated by directions that carry little ordinary covariance or train-Fisher mass.

3. Prediction and augmentation diagnostics

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 hi=Jf(θ;X)vih_i=J_f(\theta;X)v_i with transformation tangents ta=fθ(TaX)−fθ(X)t_a=f_\theta(T_aX)-f_\theta(X) using

ci(a)=|⟨hi,ta⟩|∥hi∥∥ta∥. c_i(a)=\frac{|\langle h_i,t_a\rangle|}{\|h_i\|\,\|t_a\|}.

The spectrum overlays and retained train/validation alignment plot use these direction-level quantities to explain how augmentation changes the local probability geometry.

4. Reading the measured panels

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.

Supporting code
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,
    }
Supporting code
# 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

Download figure PDF

Download figure PDF

Download figure PDF

8. Code reading and reproduction scope

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

Read, recompute, or replay

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.

Supporting code
# 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)
Checkpoint inventory (optional replay)
Completed: mathematical checks, verified Table 1, and saved-data diagnostic figures.
Training launched: False
Checkpoint measurements recomputed: False