#!/usr/bin/env python3
"""Scratch Davidson / Bradley-Terry MLE with Ties, Length-Controlled Win Rate (LC-WR), and Swap-and-Tie Arena.
Pure Python stdlib (IEEE-754 FP64) implementation with partial-pivoting Newton-Raphson MLE,
Zermelo Minorization-Maximization cross-check, online Elo order-sensitivity proof, and Bootstrap CIs.
"""
from __future__ import annotations
import math
import random
from typing import Sequence
ELO_BASE = 1000.0
ELO_SCALE = 400.0 / math.log(10.0)
def extract_style_features(resp_a: str, resp_b: str) -> list[float]:
"""Compute antisymmetric style covariates x(A, B) = -x(B, A): [tanh_char_diff, md_ornament_diff]."""
len_diff = math.tanh((len(resp_a) - len(resp_b)) / 360.0)
def md_density(txt: str) -> float:
lines = txt.splitlines() or [txt]
headers = sum(1 for ln in lines if ln.lstrip().startswith("#"))
bullets = sum(1 for ln in lines if ln.lstrip().startswith(("- ", "* ", "1.", "2.", "3.", "4.")))
bolds = txt.count("**") // 2
return (headers * 1.5 + bullets * 0.6 + bolds * 0.5) / max(1.0, len(txt) / 120.0)
md_diff = math.tanh(md_density(resp_a) - md_density(resp_b))
return [len_diff, md_diff]
def swap_and_tie_adjudicate(verdict_ab: str, verdict_ba: str) -> dict[str, object]:
"""Bidirectional position-swap protocol: keep only swap-consistent wins; map reversals to TIE."""
map_ba = {"A": "B", "B": "A", "TIE": "TIE"}
implied_from_ba = map_ba[verdict_ba]
if verdict_ab == implied_from_ba:
return {"outcome": verdict_ab, "position_consistent": True, "bias_type": "none"}
if verdict_ab == "A" and verdict_ba == "A":
return {"outcome": "TIE", "position_consistent": False, "bias_type": "slot_1_primacy"}
if verdict_ab == "B" and verdict_ba == "B":
return {"outcome": "TIE", "position_consistent": False, "bias_type": "slot_2_recency"}
return {"outcome": "TIE", "position_consistent": False, "bias_type": "tie_asymmetry"}
def sequential_online_elo(
n_models: int,
matches: Sequence[tuple[int, int, str]],
k_factor: float = 32.0,
init_elo: float = ELO_BASE,
) -> list[float]:
"""Order-dependent incremental Elo updater demonstrating arrival-sequence sensitivity."""
ratings = [init_elo for _ in range(n_models)]
for i, j, outcome in matches:
exp_i = 1.0 / (1.0 + 10.0 ** ((ratings[j] - ratings[i]) / 400.0))
score_i = 1.0 if outcome == "A" else (0.0 if outcome == "B" else 0.5)
ratings[i] += k_factor * (score_i - exp_i)
ratings[j] += k_factor * ((1.0 - score_i) - (1.0 - exp_i))
return ratings
def solve_linear_system(mat: list[list[float]], rhs: list[float]) -> list[float]:
"""Gaussian elimination with partial pivoting for small SPD Newton Hessian systems."""
n = len(rhs)
aug = [row[:] + [rhs[r]] for r, row in enumerate(mat)]
for col in range(n):
pivot = max(range(col, n), key=lambda r: abs(aug[r][col]))
aug[col], aug[pivot] = aug[pivot], aug[col]
diag = aug[col][col]
if abs(diag) < 1e-15:
diag = 1e-15
for r in range(col + 1, n):
factor = aug[r][col] / diag
for c in range(col, n + 1):
aug[r][c] -= factor * aug[col][c]
sol = [0.0] * n
for r in range(n - 1, -1, -1):
acc = aug[r][n] - sum(aug[r][c] * sol[c] for c in range(r + 1, n))
sol[r] = acc / aug[r][r]
return sol
def fit_davidson_bt_mle(
n_models: int,
matches: Sequence[tuple[int, int, str, Sequence[float] | None]],
allow_ties: bool = True,
n_covariates: int = 0,
l2_reg: float = 1e-4,
max_iter: int = 60,
tol: float = 1e-12,
) -> dict[str, object]:
"""Damped Newton-Raphson MLE for Davidson-Bradley-Terry with ties and style covariates (~75 lines)."""
dim_theta = n_models - 1
idx_eta = dim_theta if allow_ties else -1
idx_gamma = dim_theta + (1 if allow_ties else 0)
total_dim = idx_gamma + n_covariates
outcome_map = {"A": 0, "B": 1, "TIE": 2}
inv_m = 1.0 / max(1, len(matches))
def nll_grad_hess(w: list[float]) -> tuple[float, list[float], list[list[float]]]:
nll = 0.0
grad = [0.0] * total_dim
hess = [[0.0] * total_dim for _ in range(total_dim)]
for i, j, outcome, cov in matches:
th_i = 0.0 if i == 0 else w[i - 1]
th_j = 0.0 if j == 0 else w[j - 1]
delta = th_i - th_j
if n_covariates > 0 and cov is not None:
for k in range(n_covariates):
delta += w[idx_gamma + k] * cov[k]
z0, z1 = 0.5 * delta, -0.5 * delta
z2 = w[idx_eta] if allow_ties else -1e9
m_z = max(z0, z1, z2) if allow_ties else max(z0, z1)
e0, e1 = math.exp(z0 - m_z), math.exp(z1 - m_z)
e2 = math.exp(z2 - m_z) if allow_ties else 0.0
inv_s = 1.0 / (e0 + e1 + e2)
probs = [e0 * inv_s, e1 * inv_s, e2 * inv_s]
y_col = outcome_map[outcome]
nll -= inv_m * math.log(max(probs[y_col], 1e-300))
# Sparse Jacobian columns active in this match: (param_idx, J[0,p], J[1,p], J[2,p])
active: list[tuple[int, float, float, float]] = []
if i > 0:
active.append((i - 1, 0.5, -0.5, 0.0))
if j > 0:
active.append((j - 1, -0.5, 0.5, 0.0))
if allow_ties:
active.append((idx_eta, 0.0, 0.0, 1.0))
if n_covariates > 0 and cov is not None:
for k in range(n_covariates):
ck = 0.5 * float(cov[k])
active.append((idx_gamma + k, ck, -ck, 0.0))
d0, d1, d2 = probs[0] - (1.0 if y_col == 0 else 0.0), probs[1] - (1.0 if y_col == 1 else 0.0), probs[2] - (1.0 if y_col == 2 else 0.0)
pj_list: list[tuple[int, float, tuple[float, float, float]]] = []
for p_idx, j0, j1, j2 in active:
grad[p_idx] += inv_m * (d0 * j0 + d1 * j1 + d2 * j2)
pj = probs[0] * j0 + probs[1] * j1 + probs[2] * j2
pj_list.append((p_idx, pj, (j0, j1, j2)))
for idx_a, pj_a, ja in pj_list:
for idx_b, pj_b, jb in pj_list:
dot_p = probs[0] * ja[0] * jb[0] + probs[1] * ja[1] * jb[1] + probs[2] * ja[2] * jb[2]
hess[idx_a][idx_b] += inv_m * (dot_p - pj_a * pj_b)
theta_full = [0.0] + w[:dim_theta]
mean_th = sum(theta_full) / n_models
theta_centered = [t - mean_th for t in theta_full]
nll += 0.5 * l2_reg * (sum(t * t for t in theta_centered) + sum(v * v for v in w[dim_theta:]))
for p in range(dim_theta):
grad[p] += l2_reg * theta_centered[p + 1]
for q in range(dim_theta):
hess[p][q] += l2_reg * ((1.0 if p == q else 0.0) - 1.0 / n_models)
for p in range(dim_theta, total_dim):
grad[p] += l2_reg * w[p]
hess[p][p] += l2_reg
return nll, grad, hess
w = [0.0] * total_dim
nll, grad, hess = nll_grad_hess(w)
steps_used = 0
for step in range(1, max_iter + 1):
steps_used = step
if max((abs(g) for g in grad), default=0.0) < tol:
break
damped = [row[:] for row in hess]
for d in range(total_dim):
damped[d][d] += 1e-12
neg_grad = [-g for g in grad]
delta = solve_linear_system(damped, neg_grad)
directional = sum(g * d for g, d in zip(grad, delta))
alpha = 1.0
while alpha >= 1e-8:
cand_w = [wi + alpha * di for wi, di in zip(w, delta)]
cand_nll, cand_grad, cand_hess = nll_grad_hess(cand_w)
grad_inf = max((abs(g) for g in grad), default=0.0)
cand_grad_inf = max((abs(g) for g in cand_grad), default=0.0)
if cand_nll <= nll + 1e-4 * alpha * directional or (alpha == 1.0 and cand_grad_inf < 0.5 * grad_inf):
w, nll, grad, hess = cand_w, cand_nll, cand_grad, cand_hess
break
alpha *= 0.5
theta_raw = [0.0] + w[:dim_theta]
mean_theta = sum(theta_raw) / n_models
theta = [t - mean_theta for t in theta_raw]
elo = [ELO_BASE + ELO_SCALE * t for t in theta]
nu = math.exp(w[idx_eta]) if allow_ties else 0.0
gamma = w[idx_gamma : idx_gamma + n_covariates] if n_covariates > 0 else []
lc_wr_vs_baseline: list[float] = []
lc_wr_vs_field: list[float] = []
for i in range(n_models):
d0 = theta[i] - theta[0]
lc_wr_vs_baseline.append((math.exp(0.5 * d0) + 0.5 * nu) / (math.exp(0.5 * d0) + math.exp(-0.5 * d0) + nu))
peers = [
(math.exp(0.5 * (theta[i] - theta[j])) + 0.5 * nu)
/ (math.exp(0.5 * (theta[i] - theta[j])) + math.exp(-0.5 * (theta[i] - theta[j])) + nu)
for j in range(n_models) if j != i
]
lc_wr_vs_field.append(sum(peers) / max(1, len(peers)))
return {
"theta": theta,
"elo": elo,
"tie_nu": nu,
"gamma": gamma,
"lc_wr_vs_baseline": lc_wr_vs_baseline,
"lc_wr_vs_field": lc_wr_vs_field,
"grad_inf_norm": max((abs(g) for g in grad), default=0.0),
"nll": nll,
"newton_steps": steps_used,
"_nll_grad_hess_fn": nll_grad_hess,
}
def zermelo_mm_bt_no_ties(
n_models: int,
matches: Sequence[tuple[int, int, str]],
max_iter: int = 6000,
tol: float = 1e-15,
) -> list[float]:
"""Classic Minorization-Maximization (Zermelo 1929 / Hunter 2004) solver for tie-free BT verification."""
wins = [0.0] * n_models
games = [[0.0] * n_models for _ in range(n_models)]
for i, j, outcome in matches:
if outcome == "A":
wins[i] += 1.0
elif outcome == "B":
wins[j] += 1.0
else:
wins[i] += 0.5
wins[j] += 0.5
games[i][j] += 1.0
games[j][i] += 1.0
pi = [1.0] * n_models
for _ in range(max_iter):
pi_next = [1.0] * n_models
for i in range(n_models):
denom = sum(games[i][j] / (pi[i] + pi[j]) for j in range(n_models) if i != j and games[i][j] > 0.0)
pi_next[i] = wins[i] / max(denom, 1e-30)
logs = [math.log(p) for p in pi_next]
mean_log = sum(logs) / n_models
pi_next = [math.exp(lg - mean_log) for lg in logs]
if max(abs(a - b) for a, b in zip(pi_next, pi)) < tol:
pi = pi_next
break
pi = pi_next
logs = [math.log(p) for p in pi]
mean_log = sum(logs) / n_models
return [lg - mean_log for lg in logs]
def bootstrap_arena_ci(
n_models: int,
matches: Sequence[tuple[int, int, str, Sequence[float] | None]],
n_covariates: int = 2,
n_boot: int = 300,
seed: int = 20261122,
) -> dict[str, list[float]]:
"""Nonparametric bootstrap 95% confidence intervals for Davidson-BT Elo and LC-WR."""
rng = random.Random(seed)
m = len(matches)
elos_by_model: list[list[float]] = [[] for _ in range(n_models)]
lc_by_model: list[list[float]] = [[] for _ in range(n_models)]
for _ in range(n_boot):
sample = [matches[rng.randrange(m)] for _ in range(m)]
fit = fit_davidson_bt_mle(
n_models=n_models,
matches=sample,
allow_ties=True,
n_covariates=n_covariates,
l2_reg=1e-3,
)
elo_vec = fit["elo"]
lc_vec = fit["lc_wr_vs_field"]
assert isinstance(elo_vec, list) and isinstance(lc_vec, list)
for idx in range(n_models):
elos_by_model[idx].append(float(elo_vec[idx]))
lc_by_model[idx].append(float(lc_vec[idx]))
def pct(vals: list[float], q: float) -> float:
s = sorted(vals)
pos = q * (len(s) - 1)
lo = int(math.floor(pos))
hi = min(len(s) - 1, lo + 1)
frac = pos - lo
return s[lo] * (1.0 - frac) + s[hi] * frac
return {
"elo_ci95_low": [round(pct(elos_by_model[i], 0.025), 2) for i in range(n_models)],
"elo_ci95_high": [round(pct(elos_by_model[i], 0.975), 2) for i in range(n_models)],
"lc_wr_ci95_low": [round(pct(lc_by_model[i], 0.025), 4) for i in range(n_models)],
"lc_wr_ci95_high": [round(pct(lc_by_model[i], 0.975), 4) for i in range(n_models)],
}
def verify_bt_and_elo_math() -> dict[str, object]:
"""Deterministic <1e-6 verification of Newton gradient, MM parity, Elo order drift, and LC-WR debiasing."""
rng = random.Random(42)
# 1. Exact Newton MLE vs Zermelo MM on tie-free connected tournament (l2_reg = 0.0)
raw_th = [-0.55, -0.10, 0.20, 0.45]
mean_th = sum(raw_th) / 4.0
true_theta = [t - mean_th for t in raw_th]
no_tie_matches: list[tuple[int, int, str, None]] = []
simple_matches: list[tuple[int, int, str]] = []
for _ in range(360):
i, j = rng.sample(range(4), 2)
p_i = 1.0 / (1.0 + math.exp(-(true_theta[i] - true_theta[j])))
out = "A" if rng.random() < p_i else "B"
no_tie_matches.append((i, j, out, None))
simple_matches.append((i, j, out))
newton_no_tie = fit_davidson_bt_mle(4, no_tie_matches, allow_ties=False, n_covariates=0, l2_reg=0.0, tol=1e-14)
mm_theta = zermelo_mm_bt_no_ties(4, simple_matches)
nt_theta = newton_no_tie["theta"]
assert isinstance(nt_theta, list)
mm_vs_newton_max_diff = max(abs(a - b) for a, b in zip(nt_theta, mm_theta))
assert mm_vs_newton_max_diff < 1e-9, f"Newton vs MM mismatch: {mm_vs_newton_max_diff}"
assert float(newton_no_tie["grad_inf_norm"]) < 1e-12
# 2. Central finite-difference gradient check on full Davidson + 2 covariates model
cov_matches: list[tuple[int, int, str, list[float]]] = []
latent_theta = [-0.60, 0.45, 0.05, 0.10] # Model 1 is truly best; Model 2 is mediocre but verbose
true_gamma = [0.85, 0.55]
true_nu = 0.45
style_means = [0.0, -0.25, 1.35, 0.10]
for _ in range(900):
i, j = rng.sample(range(4), 2)
s_i = style_means[i] + rng.gauss(0.0, 0.65)
s_j = style_means[j] + rng.gauss(0.0, 0.65)
m_i = 0.7 * style_means[i] + rng.gauss(0.0, 0.60)
m_j = 0.7 * style_means[j] + rng.gauss(0.0, 0.60)
cov = [math.tanh(s_i - s_j), math.tanh(m_i - m_j)]
delta = latent_theta[i] - latent_theta[j] + true_gamma[0] * cov[0] + true_gamma[1] * cov[1]
wa, wb, wt = math.exp(0.5 * delta), math.exp(-0.5 * delta), true_nu
z = wa + wb + wt
u = rng.random()
out = "A" if u < wa / z else ("B" if u < (wa + wb) / z else "TIE")
cov_matches.append((i, j, out, cov))
full_fit = fit_davidson_bt_mle(4, cov_matches, allow_ties=True, n_covariates=2, l2_reg=1e-4)
test_w = [0.25, -0.35, 0.15, -0.40, 0.60, 0.30]
fn = full_fit["_nll_grad_hess_fn"]
assert callable(fn)
_, analytic_grad, _ = fn(test_w)
eps = 1e-6
fd_grad = []
for d in range(len(test_w)):
wp = test_w[:]
wm = test_w[:]
wp[d] += eps
wm[d] -= eps
fd_grad.append((fn(wp)[0] - fn(wm)[0]) / (2.0 * eps))
fd_grad_max_err = max(abs(a - b) for a, b in zip(analytic_grad, fd_grad))
assert fd_grad_max_err < 1e-7, f"FD gradient error too high: {fd_grad_max_err}"
assert float(full_fit["grad_inf_norm"]) < 1e-12
# 3. Order sensitivity of Online Elo vs exact permutation invariance of Global Davidson-BT MLE
plain_cov_matches = [(i, j, out) for (i, j, out, _) in cov_matches]
elo_runs: list[list[float]] = []
bt_runs: list[list[float]] = []
for perm_idx in range(200):
shuffled_idx = list(range(len(cov_matches)))
rng.shuffle(shuffled_idx)
elo_runs.append(sequential_online_elo(4, [plain_cov_matches[k] for k in shuffled_idx], k_factor=32.0))
if perm_idx < 12:
elo_fit = fit_davidson_bt_mle(4, [cov_matches[k] for k in shuffled_idx], allow_ties=True, n_covariates=2)["elo"]
assert isinstance(elo_fit, list)
bt_runs.append(elo_fit)
elo_max_spread = max(
max(run[m] for run in elo_runs) - min(run[m] for run in elo_runs)
for m in range(4)
)
elo_top1_set = {max(range(4), key=lambda m: run[m]) for run in elo_runs}
bt_perm_max_diff = max(
max(run[m] for run in bt_runs) - min(run[m] for run in bt_runs)
for m in range(4)
)
assert bt_perm_max_diff < 1e-11, f"BT MLE not permutation invariant: {bt_perm_max_diff}"
assert elo_max_spread > 40.0, f"Expected substantial Elo order drift, got {elo_max_spread}"
# 4. Verify LC-WR reverses verbose rank inflation back to true quality #1 (Model 1)
raw_fit = fit_davidson_bt_mle(4, [(i, j, out, None) for (i, j, out, _) in cov_matches], allow_ties=True, n_covariates=0)
raw_elo = raw_fit["elo"]
lc_elo = full_fit["elo"]
rec_gamma = full_fit["gamma"]
assert isinstance(raw_elo, list) and isinstance(lc_elo, list) and isinstance(rec_gamma, list)
raw_winner = max(range(4), key=lambda m: raw_elo[m])
lc_winner = max(range(4), key=lambda m: lc_elo[m])
assert raw_winner == 2 and lc_winner == 1, f"Expected raw=2 (verbose), lc=1 (true expert), got raw={raw_winner}, lc={lc_winner}"
return {
"mm_vs_newton_max_abs_diff": float(f"{mm_vs_newton_max_diff:.3e}"),
"fd_vs_analytic_grad_max_err": float(f"{fd_grad_max_err:.3e}"),
"newton_grad_inf_norm": float(f"{float(full_fit['grad_inf_norm']):.3e}"),
"newton_steps": full_fit["newton_steps"],
"bt_permutation_max_elo_diff": float(f"{bt_perm_max_diff:.3e}"),
"online_elo_200_perm_max_spread_pts": round(elo_max_spread, 2),
"online_elo_distinct_top1_winners": sorted(elo_top1_set),
"synthetic_raw_elo": [round(x, 2) for x in raw_elo],
"synthetic_lc_elo": [round(x, 2) for x in lc_elo],
"synthetic_raw_top1_model": raw_winner,
"synthetic_lc_top1_model": lc_winner,
"recovered_gamma": [round(x, 4) for x in rec_gamma],
"recovered_tie_nu": round(float(full_fit["tie_nu"]), 4),
}
if __name__ == "__main__":
print(verify_bt_and_elo_math())