#!/usr/bin/env python3
"""Mathematical core used by the compact retained pipeline.

This file intentionally contains formulas rather than experiment plumbing.
Every downstream compact script should call these functions instead of hiding
the theorem implementation inside plotting or training code.

resolved KL-to-Gibbs theorem retained-space defect:

    D_tau(beta) = sum_i (<u,v_i> - beta/2 lambda_i <z,v_i>)^2 / lambda_i
                = d0 + beta d1 + beta^2 d2.

Finite-time KL certificate:

    KL_t <= exp(-alpha t) KL_0
            + (1/(2 epsilon)) int_0^t exp(-alpha(t-s)) D_s ds.

When a checkpoint uses locally frozen coefficients:

    KL_t <= exp(-alpha t) KL_0
            + D (1 - exp(-alpha t)) / (2 epsilon alpha).

Paper-prefix bounded-loss PAC-Bayes screening form:

    R(rho) <= rhat(rho)
              + sqrt((KL(rho||pi) + log(M / delta)) / (2n)).

The older localized Catoni audit uses a separate (lambda, xi) grid.  Both
forms are implemented below and named explicitly so a table cannot silently use
one when the paper describes the other.
"""

from __future__ import annotations

from dataclasses import dataclass

import numpy as np


EPS = 1e-30


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)


@dataclass(frozen=True)
class DefectCoefficients:
    """Quadratic coefficients for D_tau(beta).

    Math:
        D_tau(beta) = d0 + beta d1 + beta^2 d2.

    Here D_tau is the retained-subspace Fisher/inverse-diffusion norm of
    the mismatch between the SGD drift and the reversible Gibbs drift.
    """

    d0: float
    d1: float
    d2: float

    def value(self, beta: float) -> float:
        # Direct evaluation of the quadratic defect source:
        #   D_tau(beta) = d0 + beta d1 + beta^2 d2.
        return float(self.d0 + beta * self.d1 + beta * beta * self.d2)


@dataclass(frozen=True)
class CriticalityProbeSummary:
    """Local LR-cliff rollout summary, not the paper active-lower signal."""

    upper_edge: float
    plasticity: float
    stable_count: int
    near_one_index: int


def bounded_losses(prob_true: np.ndarray, clip_nll_at: float) -> dict[str, np.ndarray]:
    """Return theorem-compatible losses in [0,1].

    Math:
        r_py(theta) = (1/N) sum_i [1 - p_theta(y_i | x_i)].

        r_clip(theta) = (1/N) sum_i min{-log p_theta(y_i | x_i)/c, 1}.

    These are the bounded losses used by the PAC-Bayes endpoint.  The raw
    NLL training objective can differ from the bounded loss used for the
    Gibbs reference, which is why the defect term is nonzero.
    """

    p = np.clip(np.asarray(prob_true, dtype=float), 1e-12, 1.0)
    return {
        "one_minus_py": 1.0 - p,
        "clipped_nll": np.minimum(-np.log(p) / float(clip_nll_at), 1.0),
    }


def centered_sample_matrix(samples: np.ndarray, center: bool = True) -> np.ndarray:
    """Rows are gradient samples; optional centering gives SGD covariance noise.

    Math:
        X_s = g_s(theta) for sampled minibatches/examples.
        X_c = X - 1 mean(X)^T.

    Centering estimates the covariance of stochastic update fluctuations, not
    the second moment of gradients.
    """

    X = np.asarray(samples, dtype=float)
    if X.ndim != 2:
        raise ValueError("samples must have shape (num_samples, dimension)")
    return X - X.mean(axis=0, keepdims=True) if center else X


def covariance_eigh_from_gram(samples: np.ndarray, center: bool = True) -> tuple[np.ndarray, np.ndarray]:
    """Eigenpairs of X.T X / denom without constructing the d-by-d matrix.

    Returns nonnegative eigenvalues and parameter-space eigenvectors as rows.
    This is the scalable blockwise route used for CNN/Transformer diagnostics.

    Math:
        C = X_c^T X_c / denom in R^{d x d}.
        G = X_c X_c^T / denom in R^{m x m}.

    The nonzero eigenvalues of C and G agree.  If G q_i = lambda_i q_i,
    then v_i = X_c^T q_i / sqrt(denom lambda_i) is the matching
    parameter-space eigenvector of C.  This avoids forming C when d is large.
    """

    X = centered_sample_matrix(samples, center=center)
    denom = max(1, X.shape[0] - int(center))
    # Gram reduction: diagonalize the sample-size matrix instead of the
    # parameter-size covariance.
    gram = (X @ X.T) / denom
    vals, sample_vecs = np.linalg.eigh(gram)
    order = np.argsort(vals)[::-1]
    vals = np.maximum(vals[order], 0.0)
    sample_vecs = sample_vecs[:, order]
    param_vecs = np.zeros((len(vals), X.shape[1]), dtype=float)
    for i, (lam, q) in enumerate(zip(vals, sample_vecs.T)):
        if lam > EPS:
            # Lift q_i from sample space to parameter space:
            #   v_i = X_c^T q_i / sqrt(denom lambda_i).
            param_vecs[i] = (X.T @ q) / np.sqrt(denom * lam)
    return vals, param_vecs


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)


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)


def elbow_keep_count(eigenvalues: np.ndarray, min_keep: int = 1) -> int:
    """Pick the log-spectrum reflection point as a one-knob retained dimension.

    Math:
        y_i = log(lambda_i/lambda_1), x_i = i/(r-1).
        Draw the chord from (x_1,y_1) to (x_r,y_r).  The elbow is the
        index maximizing chord_i - y_i, i.e. the largest downward bend in
        the log spectrum.

    This replaces a two-knob q/tau selection with a single deterministic
    spectrum rule.
    """

    vals = np.sort(np.maximum(np.asarray(eigenvalues, dtype=float), 0.0))[::-1]
    vals = vals[vals > 0]
    if len(vals) <= max(2, min_keep):
        return int(len(vals))
    y = np.log(vals / vals[0])
    x = np.linspace(0.0, 1.0, len(vals))
    chord = y[0] + (y[-1] - y[0]) * x
    return int(max(min_keep, np.argmax(chord - y) + 1))


def retained_by_elbow(eigenvalues: np.ndarray, min_keep: int = 1) -> np.ndarray:
    """Indices of the largest eigenvalues retained by the elbow rule."""

    vals = np.asarray(eigenvalues, dtype=float)
    k = elbow_keep_count(vals, min_keep=min_keep)
    return np.sort(np.argsort(vals)[::-1][:k])


def retained_by_energy(eigenvalues: np.ndarray, fraction: float) -> np.ndarray:
    """Indices of largest directions retaining a predeclared spectral fraction.

    Math:
        retain the smallest top-k set I such that
        sum_{i in I} lambda_i >= fraction * sum_{lambda_i > 0} lambda_i.

    If this knob is chosen after seeing results, the final PB report must pay
    a union/grid-selection penalty.  The compact paper path prefers the elbow
    rule when possible.
    """

    vals = np.maximum(np.asarray(eigenvalues, dtype=float), 0.0)
    if vals.ndim != 1:
        raise ValueError("eigenvalues must be one-dimensional")
    if not (0.0 < float(fraction) <= 1.0):
        raise ValueError("fraction must be in (0,1]")
    order = np.argsort(vals)[::-1]
    total = float(vals.sum())
    if total <= EPS:
        return np.array([], dtype=int)
    cumulative = np.cumsum(vals[order])
    k = int(np.searchsorted(cumulative, float(fraction) * total, side="left")) + 1
    return np.sort(order[:k])


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)),
    )


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,
    }


def optimal_beta_for_defect(coeff: DefectCoefficients, beta_min: float = 0.0) -> float:
    """Minimize the quadratic D(beta) over beta >= beta_min.

    Math:
        D(beta) = d0 + beta d1 + beta^2 d2.
        dD/dbeta = d1 + 2 beta d2.
        beta_star = -d1/(2 d2), clipped to beta >= beta_min.

    This optimizes the local defect value itself.  The asymptotic floor
    KL_infty(beta) = [d0/beta + d1 + beta d2]/alpha_base has the related
    optimizer beta_star = sqrt(d0/d2).
    """

    if coeff.d2 <= EPS:
        return float(beta_min)
    return float(max(beta_min, -coeff.d1 / (2.0 * coeff.d2)))


def contraction_alpha_base(weight_decay: float, lambda_min_retained: float, epsilon: float) -> float:
    """Local retained-space contraction scale before multiplying by beta.

    Math:
        alpha_base = (1 - epsilon) lambda_reg lambda_min^+(a_tau),
        alpha(beta) = beta alpha_base.

    The retained minimum eigenvalue is the smallest diffusion eigenvalue kept
    in the resolved subspace.  If it is tiny, the finite-time and asymptotic KL
    bounds are loose even when D_tau is modest.
    """

    return float((1.0 - float(epsilon)) * float(weight_decay) * max(0.0, float(lambda_min_retained)))


def exponential_integral_multiplier(alpha: float, time: float) -> float:
    """Integral_0^t exp(-alpha(t-s)) ds with stable alpha -> 0 limit.

    Math:
        int_0^t exp[-alpha(t-s)] ds = (1 - exp(-alpha t))/alpha.
        As alpha -> 0, the integral tends to t.
    """

    alpha = float(alpha)
    time = float(time)
    if abs(alpha) < 1e-12:
        return time
    return float((1.0 - np.exp(-alpha * time)) / alpha)


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)


def finite_time_kl_path_bound(
    times: np.ndarray,
    defect_values: np.ndarray,
    alphas: np.ndarray,
    kl_initial: float = 0.0,
    epsilon: float = 1.0,
    substeps: int = 8,
) -> np.ndarray:
    """Numerical resolved KL-to-Gibbs theorem path integration over checkpoint-varying curves.

    The finite-time inequality is a linear differential inequality:

        dK_t/dt <= -alpha_t K_t + D_t/(2 epsilon).

    Equivalently,

        K_t <= exp(-int_0^t alpha_r dr) K_0
               + int_0^t exp(-int_s^t alpha_r dr) D_s/(2 epsilon) ds.

    The code evaluates this integral by an exponential midpoint integrator.
    The initial condition is K(times[0])=kl_initial.  If the intended certificate
    starts at training initialization, the caller must include or prepend the
    initialization row with time 0; otherwise the returned curve is certified
    only from the first supplied checkpoint.
    Between adjacent checkpoints t_j and t_{j+1}, alpha_t and D_t are linearly
    interpolated and integrated over substeps.  For one interval with frozen
    alpha and D, this recurrence exactly reduces to finite_time_kl_bound.
    """

    times = np.asarray(times, dtype=float)
    defects = np.asarray(defect_values, dtype=float)
    alphas = np.asarray(alphas, dtype=float)
    if times.ndim != 1 or defects.ndim != 1 or alphas.ndim != 1:
        raise ValueError("times, defect_values, and alphas must be one-dimensional arrays")
    if not (len(times) == len(defects) == len(alphas)):
        raise ValueError("times, defect_values, and alphas must have the same length")
    if len(times) == 0:
        return np.asarray([], dtype=float)
    if np.any(np.diff(times) <= 0.0):
        raise ValueError("times must be strictly increasing")
    substeps = max(1, int(substeps))
    eps = max(float(epsilon), EPS)

    out = np.zeros_like(times, dtype=float)
    state = float(kl_initial)
    out[0] = state
    for j in range(len(times) - 1):
        dt = float(times[j + 1] - times[j])
        dt_sub = dt / substeps
        for s in range(substeps):
            frac = (s + 0.5) / substeps
            alpha_mid = float((1.0 - frac) * alphas[j] + frac * alphas[j + 1])
            defect_mid = float((1.0 - frac) * defects[j] + frac * defects[j + 1])
            decay = float(np.exp(-alpha_mid * dt_sub))
            if abs(alpha_mid) < 1e-12:
                source = dt_sub * defect_mid / (2.0 * eps)
            else:
                source = (1.0 - decay) * defect_mid / (2.0 * eps * alpha_mid)
            # Exponential integrator for K'=-alpha K + D/(2 epsilon).
            state = decay * state + source
        out[j + 1] = state
    return out


def asymptotic_kl_floor(defect_value: float, alpha: float, epsilon: float = 1.0) -> float:
    """Limit of the frozen-coefficient KL bound as t -> infinity.

    Math:
        KL_infty <= D / (2 epsilon alpha).

    This is a diagnostic of endpoint geometry, not a substitute for the
    finite-time certificate when transient path contribution is still large.
    """

    return float(float(defect_value) / (2.0 * max(float(epsilon), EPS) * max(float(alpha), EPS)))


def kl_proxy_from_defect(defect_value: float, beta: float, alpha_base: float, epsilon: float = 0.5) -> float:
    """Stationary/asymptotic KL proxy from a fitted retained defect.

    Math:
        alpha(beta) = beta alpha_base,
        KL_proxy = D(beta) / (2 epsilon beta alpha_base).

    The paper-ready prefix scripts historically used eps=0.5, for which the
    factor 2 epsilon equals one and this reduces to D/(beta alpha_base).  The
    epsilon argument is kept explicit to prevent the same omission from
    becoming an implementation bug when eps != 0.5.
    """

    denom = 2.0 * max(float(epsilon), EPS) * max(float(beta), EPS) * max(float(alpha_base), EPS)
    return float(float(defect_value) / denom)


def localized_pb_sqrt_bound(
    empirical_risk: float,
    kl_bound: float,
    n: int,
    delta: float,
    union_count: int = 1,
) -> float:
    """Classical bounded-loss square-root PAC-Bayes display bound.

    Math for bounded losses ell in [0,1]:
        R(rho) <= rhat(rho)
                  + sqrt((KL(rho||pi) + log(2 sqrt(n) M / delta))/(2n)).

    M is an explicit union-count multiplier for choices such as loss family,
    checkpoint, retained-subspace rule, beta/lambda grid, or configuration.
    The empirical term must be posterior empirical risk when rho is not a
    point mass.
    """

    # Complexity penalty paid by KL plus the explicit union/deviation term.
    penalty = (float(kl_bound) + np.log(2.0 * np.sqrt(int(n)) * int(union_count) / float(delta))) / (2.0 * int(n))
    return float(min(1.0, float(empirical_risk) + np.sqrt(max(0.0, penalty))))


def paper_prefix_pb_sqrt_bound(
    empirical_risk: float,
    kl_bound: float,
    n: int,
    delta: float,
    union_count: int,
) -> tuple[float, float]:
    """Square-root PB screening bound used by the paper prefix tables.

    Production match:
        select_prefix_paper_ready_pb.py::pb_sqrt,
        evaluate_paper_ready_resnet_pb.py::pb_sqrt,
        evaluate_paper_ready_mnist_pb.py::pb_sqrt.

    Math:
        penalty = sqrt((KL + log(M/delta))/(2n)),
        PB = min(1, empirical_risk + penalty).

    M is the number of predeclared prefixes/families checked by the selection
    rule.  This is the paper table's screening/certificate display, distinct
    from the older localized Catoni grid below.
    """

    penalty = np.sqrt(
        max(0.0, float(kl_bound) + np.log(float(max(1, union_count)) / float(delta)))
        / (2.0 * float(n))
    )
    return float(min(1.0, float(empirical_risk) + penalty)), float(penalty)


def validation_safe_prefix_pb_curve(
    lambdas: np.ndarray,
    d0_contrib: np.ndarray,
    d1_contrib: np.ndarray,
    d2_contrib: np.ndarray,
    empirical_train_risk: float,
    validation_risk: float,
    n: int,
    delta: float,
    weight_decay: float,
    epsilon: float = 0.5,
    union_count: int | None = None,
    close_abs: float = 0.03,
    close_mult: float = 1.6,
) -> tuple[list[dict[str, float | int | bool]], int]:
    """Scan nested spectral-prefix subspaces and select a validation-safe prefix.

    The candidate subspaces are deterministic once the checkpoint is fixed:
        E_k = span{v_1,...,v_k},
        lambda_1 >= lambda_2 >= ... > 0.

    For each prefix E_k:
        d_m(k) = sum_{i<=k} d_{m,i},  m in {0,1,2},
        beta_k = max(0, -d1(k)/(2 d2(k))),
        D_k = d0(k) + beta_k d1(k) + beta_k^2 d2(k),
        alpha_base,k = (1-epsilon) lambda_reg lambda_k,
        KL_k = D_k / (2 epsilon beta_k alpha_base,k),
        PB_k = rhat_train + sqrt((KL_k + log(M/delta))/(2n)).

    The selected subspace is the first prefix satisfying both:
        PB_k >= validation_risk,
        PB_k <= validation_risk + close_abs  or  PB_k <= close_mult validation_risk.

    If no prefix passes the gate, the fallback is the prefix with the smallest
    absolute validation gap, and ``paper_ready_screen`` is false.
    """

    lam = np.asarray(lambdas, dtype=float)
    d0_arr = np.asarray(d0_contrib, dtype=float)
    d1_arr = np.asarray(d1_contrib, dtype=float)
    d2_arr = np.asarray(d2_contrib, dtype=float)
    if not (lam.ndim == d0_arr.ndim == d1_arr.ndim == d2_arr.ndim == 1):
        raise ValueError("prefix inputs must be one-dimensional arrays")
    if not (lam.shape == d0_arr.shape == d1_arr.shape == d2_arr.shape):
        raise ValueError("prefix inputs must have the same length")
    if len(lam) == 0:
        raise ValueError("cannot select a prefix from an empty spectrum")

    order = np.argsort(lam)[::-1]
    lam = lam[order]
    d0_arr = d0_arr[order]
    d1_arr = d1_arr[order]
    d2_arr = d2_arr[order]
    total_lambda = max(float(np.sum(lam)), EPS)
    union = int(union_count or len(lam))

    rows: list[dict[str, float | int | bool]] = []
    selected_index: int | None = None
    for k in range(1, len(lam) + 1):
        d0 = float(np.sum(d0_arr[:k]))
        d1 = float(np.sum(d1_arr[:k]))
        d2 = float(np.sum(d2_arr[:k]))
        beta = max(0.0, -d1 / (2.0 * d2)) if d2 > EPS else 0.0
        defect = float(d0 + beta * d1 + beta * beta * d2)
        lambda_min = float(lam[k - 1])
        alpha_base = contraction_alpha_base(weight_decay, lambda_min, epsilon)
        kl_proxy = kl_proxy_from_defect(defect, beta, alpha_base, epsilon)
        pb, penalty = paper_prefix_pb_sqrt_bound(empirical_train_risk, kl_proxy, n, delta, union)
        close_gate = bool((pb <= float(validation_risk) + float(close_abs)) or (pb <= float(close_mult) * float(validation_risk)))
        not_below_gate = bool(pb >= float(validation_risk))
        row: dict[str, float | int | bool] = {
            "k": int(k),
            "energy_fraction": float(np.sum(lam[:k]) / total_lambda),
            "union_factor": int(union),
            "d0": d0,
            "d1": d1,
            "d2": d2,
            "beta": float(beta),
            "D_after": defect,
            "lambda_min": lambda_min,
            "alpha_base": alpha_base,
            "KL_proxy": kl_proxy,
            "PB_sqrt": pb,
            "PB_penalty": penalty,
            "PB_minus_val_clip": float(pb - float(validation_risk)),
            "close_gate": close_gate,
            "not_below_val_gate": not_below_gate,
            "paper_ready_screen": bool(close_gate and not_below_gate),
            "selected": False,
        }
        rows.append(row)
        if selected_index is None and row["paper_ready_screen"]:
            selected_index = k - 1

    if selected_index is None:
        selected_index = int(np.argmin([abs(float(row["PB_minus_val_clip"])) for row in rows]))
        rows[selected_index]["paper_ready_screen"] = False
    rows[selected_index]["selected"] = True
    return rows, selected_index


def catoni_g(x: np.ndarray | float) -> np.ndarray | float:
    """Catoni helper g(x)=(exp(x)-x-1)/x^2 with stable x -> 0 limit."""

    arr = np.asarray(x, dtype=float)
    out = np.empty_like(arr)
    small = np.abs(arr) < 1e-6
    xs = arr[small]
    out[small] = 0.5 + xs / 6.0 + xs * xs / 24.0
    xb = arr[~small]
    out[~small] = (np.exp(xb) - xb - 1.0) / (xb * xb)
    return float(out) if np.ndim(x) == 0 else out


def localized_catoni_bound(
    empirical_risk: np.ndarray | float,
    kl_bound: np.ndarray | float,
    lambda_pb: np.ndarray | float,
    xi: np.ndarray | float,
    n: int,
    penalty: float,
) -> np.ndarray | float:
    """Localized Catoni grid expression used in the older finite-time audit.

    Math from phaseA_resolved_kl_math:
        beta = xi lambda,
        bound = [(1-xi) lambda rhat + KL + (1+xi) penalty]
                / [(1-xi) lambda - (1+xi) g(lambda/n) lambda^2/n].

    The denominator must be positive.  This is vectorized so lambda and xi can
    be supplied as a mesh grid.
    """

    lam = np.asarray(lambda_pb, dtype=float)
    xi_arr = np.asarray(xi, dtype=float)
    numer = (1.0 - xi_arr) * lam * np.asarray(empirical_risk, dtype=float) + np.asarray(kl_bound, dtype=float) + (1.0 + xi_arr) * float(penalty)
    denom = (1.0 - xi_arr) * lam - (1.0 + xi_arr) * catoni_g(lam / float(n)) * lam * lam / float(n)
    bound = np.where(denom > 1e-12, numer / denom, np.inf)
    return float(bound) if np.ndim(bound) == 0 else bound


def rollout_stability_summary(losses_by_scale: dict[float, list[float]], tolerance: float = 0.05) -> CriticalityProbeSummary:
    """LR-cliff upper edge and rollout loss-slope diagnostic.

    Math:
        For each LR multiplier m, run a local rollout from the same checkpoint.
        Mark m stable if
            L_end(m) <= L_start(m) + tol * max(1, |L_start(m)|).

        upper_edge = max stable m.

        rollout_loss_slope = - d L_end(m) / dm at m near 1.

    This function supports LR-cliff calibration.  It is not the active
    plasticity quantity plotted in the paper.  The paper active lower signal is
    actual optimizer step times a restricted lower curvature scale; see
    criticality_coordinates below.
    """

    scales = np.array(sorted(losses_by_scale), dtype=float)
    start = np.array([losses_by_scale[s][0] for s in scales], dtype=float)
    end = np.array([losses_by_scale[s][-1] for s in scales], dtype=float)
    # Stable local rollouts stay inside the predeclared loss-increase tolerance.
    stable = np.isfinite(end) & (end <= start + float(tolerance) * np.maximum(1.0, np.abs(start)))
    upper = float(scales[stable].max()) if np.any(stable) else float(scales.min())
    # Plasticity is the negative local slope of final loss near multiplier 1.
    slopes = np.gradient(end, scales, edge_order=1) if len(scales) > 1 else np.zeros_like(scales)
    near_one = int(np.argmin(np.abs(scales - 1.0)))
    return CriticalityProbeSummary(
        upper_edge=upper,
        plasticity=float(-slopes[near_one]),
        stable_count=int(stable.sum()),
        near_one_index=near_one,
    )


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


def criticality_coordinates(
    lambda_max: float,
    eta_effective: float,
    active_lower: float,
    momentum: float = 0.0,
) -> dict[str, float]:
    """Paper criticality table coordinates from curvature and optimizer state.

    Compact criticality/checkpoint probes use this same coordinate map.

    Math:
        eta_plain_edge = 2 / lambda_max,
        eta_momentum_edge = (1 + momentum) eta_plain_edge,
        upper_coordinate = |eta_eff| / eta_momentum_edge,
        active_lower_coordinate = |eta_eff| * lambda_min(F_active).

    For AdamW/GPT/SSM, momentum is normally zero here because eta_effective is
    already reconstructed from the optimizer state.  For SGD+momentum vision
    runs, production uses the heavy-ball stability heuristic (1+momentum).
    """

    lam = max(float(lambda_max), EPS)
    eta_plain = 2.0 / lam
    eta_edge = eta_plain * (1.0 + float(momentum))
    eta_abs = abs(float(eta_effective))
    active = max(float(active_lower), 0.0)
    return {
        "eta_plain_edge": float(eta_plain),
        "eta_momentum_edge": float(eta_edge),
        "actual_effective_lr": float(eta_abs),
        "upper_coordinate": float(eta_abs / max(eta_edge, EPS)),
        "active_lower": float(active),
        "active_lower_coordinate": float(eta_abs * active),
    }


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")


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


def cosine_with_descent(update_delta: np.ndarray, gradient: np.ndarray) -> float:
    """Cosine between the actual update and negative gradient direction.

    Math:
        cos = - <Delta theta, g> / (||Delta theta|| ||g||).

    This is a sanity check that the optimizer-state update is actually aligned
    with descent before interpreting eta_eff_parallel.
    """

    delta = np.asarray(update_delta, dtype=float).reshape(-1)
    grad = np.asarray(gradient, dtype=float).reshape(-1)
    denom = max(np.linalg.norm(delta) * np.linalg.norm(grad), EPS)
    return float(-np.dot(delta, grad) / denom)
