"""
Numerical checks of the relearning limit (Theorems 1, 2 and 3 of the note).

What this script does, in plain words
-------------------------------------
The note proves three inequalities of the form  left side <= right side.
For each one this script builds many random test cases, computes both sides,
and prints the largest value of  left / right  that it found.
A value above 1 would be a counterexample. No pass/fail threshold is used:
the measured numbers are printed and the reader compares them with 1.

Terms
-----
weights        : the vector w that an attack changes
L_A            : the attacker's training loss (error on the attacker's data)
L_F            : the capability loss (error on a test of the removed capability)
gradient       : the vector of slopes of a loss with respect to the weights
learning rate  : eta, the size of each training step
noise level    : T, how strong the random kicks are in noisy training
Lipschitz constant b of the gradient of L_A : an upper bound on its curvature
"""

import sys
import numpy as np

# ---------------------------------------------------------------------------
# 0. SETTINGS (every number that controls the run is set here)
# ---------------------------------------------------------------------------
SMOKE = "--smoke" in sys.argv        # tiny end-to-end run, a few seconds
SEED = 20261127                      # seed of the random number generator
MAX_DIM = 4 if SMOKE else 20         # largest number of weights in a test case
GD_TRIALS = 50 if SMOKE else 4000    # test cases for Theorem 2 (gradient descent)
GD_MAX_STEPS = 30 if SMOKE else 300  # largest number of training steps
FLOW_TRIALS = 5 if SMOKE else 300    # test cases for Theorem 1 (continuous time)
FLOW_STEPS = 400 if SMOKE else 2000  # integration steps per test case
OU_TRIALS = 50 if SMOKE else 20000   # test cases for Theorem 3 (noise, Gaussian case)
OU_GRID = 401 if SMOKE else 4001     # time points used to find the largest sensitivity
MC_PARTICLES = 20000 if SMOKE else 200000  # simulated runs in the direct simulation
MC_STEPS = 200 if SMOKE else 2000    # time steps in the direct simulation

rng = np.random.default_rng(SEED)


# ---------------------------------------------------------------------------
# 1. Building blocks: a random attacker loss and a random capability loss
# ---------------------------------------------------------------------------
def make_attacker_loss(d):
    """Non-convex smooth loss: positive quadratic bowl plus cosine ripples.
    Returns the loss, its gradient and a true upper bound b on its curvature."""
    q = np.linalg.qr(rng.normal(size=(d, d)))[0]
    eig = 10.0 ** rng.uniform(-2, 1, size=d)          # curvatures of the bowl
    H = (q * eig) @ q.T
    lin = rng.normal(size=d)
    n_cos = int(rng.integers(0, 4))
    U = rng.normal(size=(n_cos, d))
    phase = rng.uniform(0, 2 * np.pi, size=n_cos)
    amp = rng.uniform(0, 2.0)

    def loss(w):
        return 0.5 * w @ H @ w - lin @ w + amp * np.sum(np.cos(U @ w + phase))

    def grad(w):
        return H @ w - lin - amp * (np.sin(U @ w + phase) @ U)

    b = eig.max() + amp * np.sum(U ** 2)              # bound on the largest curvature
    return loss, grad, b, n_cos


def make_capability_loss(d):
    """Quadratic loss with curvature of either sign. Its gradient is a straight-line
    function of w, so on a straight segment its size is largest at an end point."""
    K = rng.normal(size=(d, d))
    K = 0.5 * (K + K.T) * rng.uniform(0, 1.5)
    g = rng.normal(size=d) * rng.uniform(0, 3.0)

    def loss(w):
        return g @ w + 0.5 * w @ K @ w

    def grad(w):
        return g + K @ w

    return loss, grad


# ---------------------------------------------------------------------------
# 2. Theorem 2: gradient descent in steps
#    claim (2):  D_F^2 <= eta * n * G^2 * D_A / (1 - eta*b/2)
#    claim (ball): |w_m - w_0|^2 <= eta * m * (L_A(w_0) - L_A(w_m)) / (1 - eta*b/2)
# ---------------------------------------------------------------------------
def check_gradient_descent():
    worst_ratio, worst_ball, n_above, n_ball_above, min_DA = 0.0, 0.0, 0, 0, np.inf
    worst_sharp, n_sharp_above = 0.0, 0
    above_kinds = set()   # (number of weights, number of cosine ripples, step) of each ball check above 1
    for _ in range(GD_TRIALS):
        d = int(rng.integers(1, MAX_DIM + 1))
        LA, gA, b, n_cos = make_attacker_loss(d)
        LF, gF = make_capability_loss(d)
        frac = rng.choice([rng.uniform(0.01, 0.99), rng.uniform(0.99, 0.9999)])
        eta = frac * 2.0 / b
        c = 1.0 - eta * b / 2.0
        n = int(rng.integers(1, GD_MAX_STEPS + 1))
        w0 = rng.normal(size=d) * rng.uniform(0.1, 5.0)
        w = w0.copy()
        G = np.linalg.norm(gF(w))
        prev_norm, sum_Gk_sq = G, 0.0
        for m in range(1, n + 1):
            w = w - eta * gA(w)
            new_norm = np.linalg.norm(gF(w))
            sum_Gk_sq += max(prev_norm, new_norm) ** 2      # largest sensitivity on this segment, squared
            prev_norm = new_norm
            G = max(G, new_norm)
            DA_m = LA(w0) - LA(w)
            if DA_m > 0:
                ball = np.sum((w - w0) ** 2) / (eta * m * DA_m / c)
                worst_ball = max(worst_ball, ball)
                n_ball_above += ball > 1.0
                if ball > 1.0:
                    above_kinds.add((d, n_cos, m))
        DF = LF(w0) - LF(w)
        DA = LA(w0) - LA(w)
        min_DA = min(min_DA, DA)
        if DA > 0 and G > 0:
            ratio = DF ** 2 / (eta * n * G ** 2 * DA / c)
            worst_ratio = max(worst_ratio, ratio)
            n_above += ratio > 1.0
            sharp = DF ** 2 / (eta * sum_Gk_sq * DA / c)
            worst_sharp = max(worst_sharp, sharp)
            n_sharp_above += sharp > 1.0
    print("THEOREM 2 (gradient descent)")
    print(f"  test cases                         : {GD_TRIALS}")
    print(f"  largest left/right of (2)          : {worst_ratio:.6f}   (minus 1: {worst_ratio - 1:+.2e})")
    print(f"  cases with left/right above 1      : {n_above}")
    print(f"  largest left/right of ball claim   : {worst_ball:.6f}   (minus 1: {worst_ball - 1:+.2e})")
    print(f"  ball checks above 1                : {n_ball_above}")
    print(f"  kinds of case above 1 (weights, cosine ripples, step): {sorted(above_kinds)}")
    print("    note: with 1 weight, 0 ripples and step 1 the ball claim is an exact equality, so rounding decides the sign")
    print(f"  smallest fall in attacker loss D_A : {min_DA:.3e}  (claim: never negative)")
    print(f"  sharper form (sum of squared sensitivities per step): largest left/right {worst_sharp:.6f} (minus 1: {worst_sharp - 1:+.2e}), cases above 1: {n_sharp_above}")


# ---------------------------------------------------------------------------
# 3. Theorem 1: continuous time
#    claim (1):  D_F^2 <= eta * tau * G^2 * D_A
# ---------------------------------------------------------------------------
def rk4_path(gA, w0, eta, tau, steps):
    """Integrate dw/dt = -eta * gradient with the classical Runge-Kutta method."""
    dt = tau / steps
    f = lambda w: -eta * gA(w)
    path = [w0.copy()]
    w = w0.copy()
    for _ in range(steps):
        k1 = f(w); k2 = f(w + 0.5 * dt * k1); k3 = f(w + 0.5 * dt * k2); k4 = f(w + dt * k3)
        w = w + dt * (k1 + 2 * k2 + 2 * k3 + k4) / 6.0
        path.append(w.copy())
    return np.array(path)


def check_gradient_flow():
    print("THEOREM 1 (continuous time)")
    print("  one-dimensional example: left/right should equal tanh(x/2)/(x/2)")
    h, g, w0, eta = 2.0, 1.5, 3.0, 0.1
    for x in [0.01, 0.1, 1.0, 4.0, 20.0]:
        tau = x / (eta * h)
        path = rk4_path(lambda w: h * w, np.array([w0]), eta, tau, FLOW_STEPS)
        DF = g * (path[0, 0] - path[-1, 0])
        DA = 0.5 * h * (path[0, 0] ** 2 - path[-1, 0] ** 2)
        measured = DF ** 2 / (eta * tau * g ** 2 * DA)
        print(f"    x = {x:6.2f}   measured {measured:.8f}   formula {np.tanh(x / 2) / (x / 2):.8f}")
    worst = 0.0
    n_above = 0
    worst_sharp, n_sharp_above = 0.0, 0
    for _ in range(FLOW_TRIALS):
        d = int(rng.integers(1, MAX_DIM + 1))
        LA, gA, b, n_cos = make_attacker_loss(d)
        LF, gF = make_capability_loss(d)
        eta = 10.0 ** rng.uniform(-2, 0)
        tau = 10.0 ** rng.uniform(-2, 1.5) / (eta * b)
        w0 = rng.normal(size=d) * rng.uniform(0.1, 5.0)
        path = rk4_path(gA, w0, eta, tau, FLOW_STEPS)
        G = max(np.linalg.norm(gF(w)) for w in path)
        DF = LF(path[0]) - LF(path[-1])
        DA = LA(path[0]) - LA(path[-1])
        if DA > 0 and G > 0:
            ratio = DF ** 2 / (eta * tau * G ** 2 * DA)
            worst = max(worst, ratio)
            n_above += ratio > 1.0
            gsq_path = np.array([np.sum(gF(w) ** 2) for w in path])
            integral = (tau / FLOW_STEPS) * (gsq_path.sum() - 0.5 * (gsq_path[0] + gsq_path[-1]))   # trapezoid rule
            sharp = DF ** 2 / (eta * integral * DA)
            worst_sharp = max(worst_sharp, sharp)
            n_sharp_above += sharp > 1.0
    print(f"  random test cases                  : {FLOW_TRIALS}")
    print(f"  largest left/right of (1)          : {worst:.6f}")
    print(f"  cases with left/right above 1      : {n_above}")
    print(f"  sharper form (time integral of squared sensitivity): largest left/right {worst_sharp:.6f} (minus 1: {worst_sharp - 1:+.2e}), cases above 1: {n_sharp_above}")
    print("    (the time integral is computed by the trapezoid rule, so values within about 1e-5 of 1 are within its error)")


# ---------------------------------------------------------------------------
# 4. Theorem 3 in the explicit Gaussian case (Proposition 3a)
#    claim (4):  D_F^2 <= eta * T * tau * G^2 * Sigma
#    also checks the identity  integral of E|v|^2 dt = eta * T * Sigma
# ---------------------------------------------------------------------------
def gaussian_case(h, T, eta, m0, s0sq, g, c, t):
    """Closed forms of Proposition 3a at the times in the array t."""
    e1 = np.exp(-eta * np.outer(t, h))
    m = m0 * e1
    ssq = T / h + (s0sq - T / h) * e1 ** 2
    kl = 0.5 * np.sum(h * (ssq + m ** 2) / T - 1.0 - np.log(h * ssq / T), axis=1)
    mean_LF = np.sum(g * m + 0.5 * c * (m ** 2 + ssq), axis=1)
    mean_gradF_sq = np.sum((g + c * m) ** 2 + c ** 2 * ssq, axis=1)
    mean_v_sq = eta ** 2 * np.sum((T / ssq - h) ** 2 * ssq + h ** 2 * m ** 2, axis=1)
    return kl, mean_LF, mean_gradF_sq, mean_v_sq


def check_noise_gaussian():
    worst, n_above, worst_identity, min_sigma, n_identity = 0.0, 0, 0.0, np.inf, 0
    worst_sharp, n_sharp_above = 0.0, 0
    for _ in range(OU_TRIALS):
        d = int(rng.integers(1, MAX_DIM + 1))
        h = 10.0 ** rng.uniform(-1.5, 1.3, size=d)
        T = 10.0 ** rng.uniform(-2, 0.7)
        eta = 10.0 ** rng.uniform(-3, 0)
        m0 = rng.normal(size=d) * rng.uniform(0, 4.0)
        s0sq = 10.0 ** rng.uniform(-2, 1, size=d)
        g = rng.normal(size=d) * rng.uniform(0, 3.0)
        c = rng.normal(size=d) * rng.uniform(0, 1.5)
        tau = 10.0 ** rng.uniform(-3, 2) / (eta * h.mean())
        t = np.unique(np.concatenate([np.linspace(0.0, tau, OU_GRID), tau * np.logspace(-9, 0, OU_GRID)]))
        kl, mean_LF, gsq, vsq = gaussian_case(h, T, eta, m0, s0sq, g, c, t)
        sigma = kl[0] - kl[-1]
        min_sigma = min(min_sigma, sigma)
        DF = mean_LF[0] - mean_LF[-1]
        Gsq = gsq.max()
        if sigma > 0 and Gsq > 0:
            ratio = DF ** 2 / (eta * T * tau * Gsq * sigma)
            worst = max(worst, ratio)
            n_above += ratio > 1.0
            integral_B = np.sum(0.5 * (gsq[1:] + gsq[:-1]) * np.diff(t))        # trapezoid rule
            sharp = DF ** 2 / (eta * T * sigma * integral_B)
            worst_sharp = max(worst_sharp, sharp)
            n_sharp_above += sharp > 1.0
            # identity of step 1 of the proof, checked at three random times by a finite difference
            for tc in rng.uniform(0.0, tau, size=3):
                # the difference step must be short against every time scale of the problem:
                # the relaxation times 1/(eta*h) and the times s0^2/(eta*T) over which noise widens a narrow start
                delta = 1e-5 * min(1.0 / (eta * h.max()), s0sq.min() / (eta * T))
                tt = np.array([tc - delta, tc, tc + delta]) if tc > delta else np.array([tc, tc + delta, tc + 2 * delta])
                kl3, _, _, v3 = gaussian_case(h, T, eta, m0, s0sq, g, c, tt)
                slope = (kl3[2] - kl3[0]) / (tt[2] - tt[0])
                exact = -v3[1] / (eta * T)
                resolvable = abs(exact) * (tt[2] - tt[0]) > 1e-6 * max(abs(kl3[1]), 1.0)
                if resolvable:
                    n_identity += 1
                    worst_identity = max(worst_identity, abs(slope / exact - 1.0))
    print("THEOREM 3 (noise, explicit Gaussian case)")
    print(f"  test cases                         : {OU_TRIALS}")
    print(f"  largest left/right of (4)          : {worst:.6f}")
    print(f"  cases with left/right above 1      : {n_above}")
    print(f"  smallest dissipation Sigma         : {min_sigma:.3e}  (claim: never negative)")
    print(f"  largest left/right of (4) minus 1  : {worst - 1:+.2e}")
    print(f"  sharper form (time integral of mean squared sensitivity): largest left/right {worst_sharp:.6f} (minus 1: {worst_sharp - 1:+.2e}), cases above 1: {n_sharp_above}")
    print("    (trapezoid rule for the time integral)")
    print(f"  identity 'd/dt KL = -E|v|^2/(eta*T)' by finite difference: {n_identity} checks, largest relative gap {worst_identity:.2e}")
    print("    (checked only at times where the change in KL across the difference step is large enough to resolve)")


# ---------------------------------------------------------------------------
# 5. Direct simulation of noisy training in one dimension, against the closed forms
# ---------------------------------------------------------------------------
def check_simulation():
    h, T, eta, m0, s0sq, g, c, tau = 1.7, 0.4, 0.05, 2.5, 0.3, 1.2, -0.6, 30.0
    dt = tau / MC_STEPS
    w = m0 + np.sqrt(s0sq) * rng.normal(size=MC_PARTICLES)
    for _ in range(MC_STEPS):
        w = w - eta * h * w * dt + np.sqrt(2 * eta * T * dt) * rng.normal(size=MC_PARTICLES)
    kl, mean_LF, gsq, _ = gaussian_case(np.array([h]), T, eta, np.array([m0]), np.array([s0sq]),
                                        np.array([g]), np.array([c]), np.array([0.0, tau]))
    m_th = m0 * np.exp(-eta * h * tau)
    s_th = T / h + (s0sq - T / h) * np.exp(-2 * eta * h * tau)
    print("DIRECT SIMULATION (one dimension, noisy training) against the closed forms")
    print(f"  simulated runs {MC_PARTICLES}, time steps {MC_STEPS}")
    print(f"  mean of weight at the end   : simulated {w.mean():+.5f}   formula {m_th:+.5f}")
    print(f"  variance of weight at end   : simulated {w.var():.5f}   formula {s_th:.5f}")
    print(f"  average capability loss     : simulated {np.mean(g * w + 0.5 * c * w ** 2):+.5f}   formula {mean_LF[-1]:+.5f}")


# ---------------------------------------------------------------------------
# 6. Run everything
# ---------------------------------------------------------------------------
if __name__ == "__main__":
    print(f"mode: {'SMOKE (tiny sample)' if SMOKE else 'FULL'}   seed: {SEED}")
    check_gradient_descent()
    check_gradient_flow()
    check_noise_gaussian()
    check_simulation()
