Two research loops

Companion to Mathematics on Tap: Agents, Lean, and the Research Loop. Download check.py and run it with Python 3; no packages or API access are needed:

python3 check.py

RL: question → prediction → check → next question. Does adding a constant to every response’s training coefficient change the expected update? Model a response as a Bernoulli outcome, with student success probability \(p=1/4\) and logit score \(r-p\). Draw two independent responses from success probability \(q\), use GRPO coefficients \((r_1-r_2,r_2-r_1)\), and average their score updates. Adding \(\lambda=1/2\) predicts a change \(\lambda(q-p)\). Exact enumeration gives zero when \(q=p\) and \(1/4\) when \(q=3/4\).

Now change the question: add the coefficient only to all-wrong pairs. Enumeration gives \(-\lambda p(1-q)^2\), including a nonzero change on policy. Conditioning changes the intervention. These are finite-model checks, not measurements of LLM training performance.

Sampling: modification → proof obligations → budget → next question. Replace an exact drift with an inner-sample average. With common initialization, total outer time 1, coefficient 1, averaged squared conditional bias bounded by \(0.02^2\), averaged trace variance bounded by 4, and \(N=256\), the script checks

\[\frac{0.02^2+4/256}{8}\leq 0.05^2.\]

A reference TV bound of 0.01 then gives a total budget of 0.06. The public Lean theorem supplies the bound. Bias, moment, integrability, and conditional-independence premises must still be established for the proposed sampler. The next question is which estimator satisfies them; increasing \(N\) only reduces the variance term.

The script

Download check.py

#!/usr/bin/env python3
"""Run the blog's finite RL examples and sampling-budget arithmetic.

Standard library only. Exact enumeration checks a finite model; it does not
measure LLM training performance or establish a sampler's input assumptions.
"""

from fractions import Fraction
from itertools import product
from math import sqrt


def expected_update(p, q, weight_shift, shift_on_all_wrong=False):
    """Average the two-response update over all four IID Bernoulli pairs."""
    expectation = Fraction(0)
    total_probability = Fraction(0)
    for r1, r2 in product((0, 1), repeat=2):
        probability = (q if r1 else 1 - q) * (q if r2 else 1 - q)
        a1, a2 = Fraction(r1 - r2), Fraction(r2 - r1)
        if not shift_on_all_wrong or (r1 == 0 and r2 == 0):
            a1 += weight_shift
            a2 += weight_shift
        # The Bernoulli-logit score at outcome r is r - p.
        update = (a1 * (r1 - p) + a2 * (r2 - p)) / 2
        expectation += probability * update
        total_probability += probability
    if total_probability != 1:
        raise AssertionError("Pair probabilities do not sum to one")
    return expectation


def check_equal(actual, predicted):
    if actual != predicted:
        raise AssertionError(f"Enumerated {actual}; predicted {predicted}")


def main():
    p = Fraction(1, 4)
    weight_shift = Fraction(1, 2)
    print("RL: exact group enumeration; p = 1/4, lambda = 1/2")
    print(f"{'Intervention':<22} {'q':>5} {'Base':>8} {'Shifted':>8} {'Delta':>8} {'Prediction':>11}")
    for intervention, all_wrong_only in (("Every response", False), ("All-wrong pairs only", True)):
        for q in (p, Fraction(3, 4)):
            baseline = expected_update(p, q, Fraction(0))
            shifted = expected_update(p, q, weight_shift, all_wrong_only)
            difference = shifted - baseline
            prediction = (
                weight_shift * (1 - q) ** 2 * (-p)
                if all_wrong_only
                else weight_shift * (q - p)
            )
            check_equal(difference, prediction)
            print(f"{intervention:<22} {str(q):>5} {str(baseline):>8} {str(shifted):>8} {str(difference):>8} {str(prediction):>11}")

    # Inputs to the public theorem, assumed to hold at every outer step:
    # common initialization, total outer time 1, c = 1, averaged squared
    # conditional bias <= .02^2, averaged trace variance <= 4, and N = 256
    # conditionally independent inner samples. All moment/integrability and
    # Gaussian-chain premises remain inputs; this checks only the arithmetic.
    total_time = Fraction(1)
    coefficient = Fraction(1)
    squared_bias_bound = Fraction(2, 100) ** 2
    trace_variance_bound = Fraction(4)
    inner_samples = 256
    approximation_budget = Fraction(5, 100)
    reference_tv_bound = Fraction(1, 100)
    squared_approximation_bound = (
        total_time * coefficient**2
        * (squared_bias_bound + trace_variance_bound / inner_samples) / 8
    )
    if squared_approximation_bound > approximation_budget**2:
        raise AssertionError("The approximation budget is exceeded")
    total_tv_budget = reference_tv_bound + approximation_budget
    check_equal(total_tv_budget, Fraction(6, 100))
    print("\nSampling: arithmetic with the theorem's assumptions supplied")
    print(f"Squared approximation bound: {squared_approximation_bound} <= {approximation_budget**2}")
    print(f"Approximation TV bound: {sqrt(float(squared_approximation_bound)):.6f} <= {float(approximation_budget):.2f}")
    print(f"Target TV budget: {float(reference_tv_bound):.2f} + {float(approximation_budget):.2f} = {float(total_tv_budget):.2f}")
    print("\nPASS: finite RL enumeration and sampling-budget arithmetic")


if __name__ == "__main__":
    main()

Output:

RL: exact group enumeration; p = 1/4, lambda = 1/2
Intervention               q     Base  Shifted    Delta  Prediction
Every response           1/4     3/16     3/16        0           0
Every response           3/4     3/16     7/16      1/4         1/4
All-wrong pairs only     1/4     3/16   15/128   -9/128      -9/128
All-wrong pairs only     3/4     3/16   23/128   -1/128      -1/128

Sampling: arithmetic with the theorem's assumptions supplied
Squared approximation bound: 641/320000 <= 1/400
Approximation TV bound: 0.044756 <= 0.05
Target TV budget: 0.01 + 0.05 = 0.06

PASS: finite RL enumeration and sampling-budget arithmetic