QA defects D314-1 and D314-2 on the integrated Train A tree. D314-1: the golden runner had no branch for the raw_text malformed-input case (malformed_input_exit3); it now parses raw_text itself and expects exit 3 as the golden file states. D314-2: expected keys the tool did not compute were skipped but the case was counted as passed. Now every expected key is checked or the case is SKIPPED and counted separately; the summary prints "cases: N passed: P skipped: S failed: F" and `golden` exits 1 when a case is skipped unless --allow-skips is given. Newly computed: forbidden_tokens (on the printed output), mention (refusal message), blind_sd + forbidden_key_prefixes (new blind-sd sub-command, first 6 valid pairs, no mean), null_simulation (new simulate-null sub-command, own float path, seeded), --look K, series_b variants (permutation / unit-scale invariance). Unknown argv flags and unknown expected keys make a case SKIPPED. Still independent of series_eval.py and component_class.py; the golden file is only read, not committed here. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
855 lines
36 KiB
Python
855 lines
36 KiB
Python
#!/usr/bin/env python3
|
|
"""Independent recomputation of the E3/E5 series verdict (STRA-314, SDET).
|
|
|
|
A second, separately written implementation of the series verdict of the
|
|
STRA-245 evaluation rule (E3 statistic, E5 verdict classes, E6 screening, E8
|
|
independent verification). It deliberately shares NO code with the production
|
|
evaluator: it has its own Student-t quantile (regularised incomplete beta and a
|
|
bisection solve, cross-checked in the tests against published tables and
|
|
closed forms), its own lag-1 autocorrelation, and it accumulates the mean and
|
|
the sum of squares in exact fractions.
|
|
|
|
Sub-commands
|
|
series <series.json> print the recomputed verdicts
|
|
compare <evaluator_output.json> <series.json>
|
|
exit 0 when the evaluator output
|
|
agrees (n, mean_l, CI bounds to
|
|
1e-9, verdict class) for every
|
|
(metric, row); exit 1 naming the
|
|
first disagreement
|
|
golden <series_cases.json> [--allow-skips] run golden cases against this
|
|
implementation; prints
|
|
"cases: N passed: P skipped: S failed: F"
|
|
blind-sd <series.json> sample sd of l of the first 6 valid
|
|
pairs, no mean (E1)
|
|
simulate-null <series.json> --runs R --seed S
|
|
false-SLOWER rate of the design under
|
|
the null, interim looks included (E8)
|
|
|
|
A golden case counts as passed only when EVERY expected key (and every argv
|
|
flag) of the case was actually checked. A case that carries an expectation this
|
|
tool does not check is reported SKIPPED and counted separately, never as a pass;
|
|
`golden` then exits 1 (not fully verified) unless --allow-skips is given.
|
|
|
|
Exit codes: 0 ok, 1 disagreement / failed case / skipped case, 2 refused input
|
|
(mixed build id or cache state), 3 malformed input.
|
|
|
|
Rules implemented (see the STRA-245 acceptance text):
|
|
l_i = ln(V_i / O_i) for wall_norm and ttft_sum (lower is better),
|
|
l_i = ln(O_i / V_i) for decode_tps (higher is better); positive = ours better.
|
|
Two-sided 95 percent Student-t CI of the mean l. When the lag-1
|
|
autocorrelation r of the l_i (in pair order) is > 0 the effective size
|
|
n_eff = n (1 - r) / (1 + r) is used with dof = max(1, floor(n_eff - 1)).
|
|
STRICT rule (wall_norm): PASS iff CI lower bound > 0; SLOWER iff upper < 0;
|
|
TIE iff the CI contains 0 and lies inside [ln 0.99, ln 1.01]; else
|
|
INCONCLUSIVE.
|
|
NON-NEGATIVE rule (ttft_sum, decode_tps): PASS iff lower > ln 0.99; SLOWER
|
|
iff upper < ln 0.99; else INCONCLUSIVE (never TIE).
|
|
Interim looks at 40 and 80 percent of N (rounded down to a multiple of 6) at
|
|
the two-sided level 0.0221, SLOWER test only; an early exit is only FAILED.
|
|
Fewer than N valid pairs: SCREENING, no PASS.
|
|
|
|
Python >= 3.9, standard library only.
|
|
"""
|
|
|
|
import argparse
|
|
import json
|
|
import math
|
|
import random
|
|
import re
|
|
import sys
|
|
from fractions import Fraction
|
|
|
|
# ---------------------------------------------------------------- constants
|
|
|
|
METRICS = ("wall_norm", "ttft_sum", "decode_tps")
|
|
STRICT_METRICS = ("wall_norm",)
|
|
RATE_METRICS = ("decode_tps",) # higher is better: l = ln(O / V)
|
|
VANILLA_ROWS = ("vanilla_default", "vanilla_noskip")
|
|
|
|
LN_099 = math.log(0.99)
|
|
LN_101 = math.log(1.01)
|
|
|
|
CONFIDENCE_ALPHA = 0.05 # two-sided 95 percent
|
|
POCOCK_ALPHA = 0.0221 # two-sided, three looks (E5)
|
|
MDE_FACTOR = 2.8 # 95 percent confidence, 80 percent power
|
|
BOUND_EPS = 1e-12 # a bound within this of a threshold counts as exactly on it
|
|
COMPARE_TOL = 1e-9 # agreement tolerance of `compare`
|
|
|
|
# TL detail of the n_eff rule (BA may overrule): keep these two switches named.
|
|
NEFF_RULE_ENABLED = True # apply the n_eff correction when r > 0
|
|
NEFF_SCALES_STANDARD_ERROR = True # se = sd / sqrt(n_eff) (else sd / sqrt(n)) when r > 0
|
|
|
|
SERIES_LEVEL_KEYS = ("ours_build_id", "cache_state")
|
|
PAIR_LEVEL_IDENTITY_KEYS = ("ours_build_id", "build_id", "cache_state")
|
|
|
|
|
|
class Refused(Exception):
|
|
"""Pairs of different builds or cache states (exit 2)."""
|
|
|
|
|
|
class Malformed(Exception):
|
|
"""Unusable input (exit 3)."""
|
|
|
|
|
|
# ------------------------------------------------------- Student t quantile
|
|
|
|
|
|
def _betacf(a, b, x):
|
|
"""Continued fraction of the incomplete beta function (modified Lentz)."""
|
|
tiny = 1e-300
|
|
qab, qap, qam = a + b, a + 1.0, a - 1.0
|
|
c = 1.0
|
|
d = 1.0 - qab * x / qap
|
|
if abs(d) < tiny:
|
|
d = tiny
|
|
d = 1.0 / d
|
|
h = d
|
|
for m in range(1, 2000):
|
|
m2 = 2 * m
|
|
aa = m * (b - m) * x / ((qam + m2) * (a + m2))
|
|
d = 1.0 + aa * d
|
|
if abs(d) < tiny:
|
|
d = tiny
|
|
c = 1.0 + aa / c
|
|
if abs(c) < tiny:
|
|
c = tiny
|
|
d = 1.0 / d
|
|
h *= d * c
|
|
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
|
|
d = 1.0 + aa * d
|
|
if abs(d) < tiny:
|
|
d = tiny
|
|
c = 1.0 + aa / c
|
|
if abs(c) < tiny:
|
|
c = tiny
|
|
d = 1.0 / d
|
|
delta = d * c
|
|
h *= delta
|
|
if abs(delta - 1.0) < 1e-16:
|
|
break
|
|
return h
|
|
|
|
|
|
def betainc_reg(a, b, x):
|
|
"""Regularised incomplete beta function I_x(a, b)."""
|
|
if x <= 0.0:
|
|
return 0.0
|
|
if x >= 1.0:
|
|
return 1.0
|
|
ln_front = (math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
|
|
+ a * math.log(x) + b * math.log1p(-x))
|
|
front = math.exp(ln_front)
|
|
if x < (a + 1.0) / (a + b + 2.0):
|
|
return front * _betacf(a, b, x) / a
|
|
return 1.0 - front * _betacf(b, a, 1.0 - x) / b
|
|
|
|
|
|
def t_two_sided_tail(t, dof):
|
|
"""P(|T| > t) for a Student-t variable with `dof` degrees of freedom."""
|
|
if t <= 0.0:
|
|
return 1.0
|
|
return betainc_reg(dof / 2.0, 0.5, dof / (dof + t * t))
|
|
|
|
|
|
_T_CACHE = {}
|
|
|
|
|
|
def t_quantile_two_sided(dof, alpha):
|
|
"""Smallest t with P(|T| > t) = alpha (the 1 - alpha/2 quantile)."""
|
|
key = (dof, alpha)
|
|
if key in _T_CACHE:
|
|
return _T_CACHE[key]
|
|
if dof < 1:
|
|
raise ValueError("dof must be >= 1")
|
|
lo, hi = 0.0, 1.0
|
|
while t_two_sided_tail(hi, dof) > alpha:
|
|
hi *= 2.0
|
|
if hi > 1e12:
|
|
break
|
|
for _ in range(200):
|
|
mid = 0.5 * (lo + hi)
|
|
if t_two_sided_tail(mid, dof) > alpha:
|
|
lo = mid
|
|
else:
|
|
hi = mid
|
|
if hi - lo <= 1e-15 * max(1.0, hi):
|
|
break
|
|
value = 0.5 * (lo + hi)
|
|
_T_CACHE[key] = value
|
|
return value
|
|
|
|
|
|
# ------------------------------------------------------------ statistics
|
|
|
|
|
|
def log_ratio(metric, ours, vanilla):
|
|
"""l_i with positive = ours better; computed from the exact ratio."""
|
|
if metric in RATE_METRICS:
|
|
ratio = Fraction(ours) / Fraction(vanilla)
|
|
else:
|
|
ratio = Fraction(vanilla) / Fraction(ours)
|
|
return math.log(ratio.numerator) - math.log(ratio.denominator)
|
|
|
|
|
|
def mean_sd_r1(values, exact=True):
|
|
"""Exact mean, sample sd and lag-1 autocorrelation of `values`.
|
|
|
|
Sums are accumulated as exact fractions of the float inputs. Returns
|
|
(mean, sd, r1) as floats; sd is 0.0 exactly when all values are equal.
|
|
`exact=False` uses plain floats (only the null simulation, which needs speed).
|
|
"""
|
|
n = len(values)
|
|
if not exact:
|
|
mean = math.fsum(values) / n
|
|
dev = [v - mean for v in values]
|
|
ss = math.fsum(d * d for d in dev)
|
|
sd = math.sqrt(ss / (n - 1)) if n > 1 else float("nan")
|
|
r1 = math.fsum(dev[i] * dev[i + 1] for i in range(n - 1)) / ss if (n > 2 and ss > 0) else 0.0
|
|
return mean, sd, r1
|
|
fr = [Fraction(v) for v in values]
|
|
mean = sum(fr, Fraction(0)) / n
|
|
dev = [v - mean for v in fr]
|
|
ss = sum((d * d for d in dev), Fraction(0))
|
|
sd = math.sqrt(float(ss / (n - 1))) if n > 1 else float("nan")
|
|
if n > 2 and ss != 0:
|
|
cross = sum((dev[i] * dev[i + 1] for i in range(n - 1)), Fraction(0))
|
|
r1 = float(cross / ss)
|
|
else:
|
|
r1 = 0.0
|
|
return float(mean), sd, r1
|
|
|
|
|
|
def confidence_interval(values, alpha, exact=True):
|
|
"""Mean, bounds, r1, n_eff, dof, sd of the t interval at two-sided `alpha`."""
|
|
n = len(values)
|
|
mean, sd, r1 = mean_sd_r1(values, exact)
|
|
n_eff = float(n)
|
|
dof = n - 1
|
|
if NEFF_RULE_ENABLED and r1 > 0:
|
|
n_eff = n * (1.0 - r1) / (1.0 + r1)
|
|
dof = max(1, int(math.floor(n_eff - 1.0)))
|
|
if sd == 0.0:
|
|
half = 0.0
|
|
else:
|
|
size = n_eff if (r1 > 0 and NEFF_SCALES_STANDARD_ERROR and NEFF_RULE_ENABLED) else float(n)
|
|
half = t_quantile_two_sided(dof, alpha) * sd / math.sqrt(size)
|
|
return {"n": n, "mean_l": mean, "sd": sd, "r1": r1, "n_eff": n_eff, "dof": dof,
|
|
"ci_lo": mean - half, "ci_hi": mean + half,
|
|
"mde": MDE_FACTOR * sd / math.sqrt(n)}
|
|
|
|
|
|
def classify(metric, ci_lo, ci_hi):
|
|
"""Verdict class of an interval under the strict or non-negative rule."""
|
|
if metric in STRICT_METRICS:
|
|
bound = 0.0
|
|
else:
|
|
bound = LN_099
|
|
if ci_lo > bound + BOUND_EPS:
|
|
return "PASS"
|
|
if ci_hi < bound - BOUND_EPS:
|
|
return "SLOWER"
|
|
if metric in STRICT_METRICS:
|
|
contains_zero = ci_lo <= BOUND_EPS and ci_hi >= -BOUND_EPS
|
|
inside = ci_lo >= LN_099 - BOUND_EPS and ci_hi <= LN_101 + BOUND_EPS
|
|
if contains_zero and inside:
|
|
return "TIE"
|
|
return "INCONCLUSIVE"
|
|
|
|
|
|
def look_points(n_planned):
|
|
"""Interim look sizes: 40 and 80 percent of N, rounded down to a multiple of 6."""
|
|
points = []
|
|
for num in (2, 4): # 2/5 and 4/5 of N, exact integer arithmetic
|
|
k = (num * n_planned) // 5
|
|
k = (k // 6) * 6
|
|
if 0 < k < n_planned and k not in points:
|
|
points.append(k)
|
|
return points
|
|
|
|
|
|
# ---------------------------------------------------------- input handling
|
|
|
|
|
|
def _number(value, where):
|
|
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
raise Malformed("%s is not a number" % where)
|
|
if not math.isfinite(value) or value <= 0:
|
|
raise Malformed("%s must be a finite positive number, got %r" % (where, value))
|
|
return value
|
|
|
|
|
|
def load_json(path):
|
|
try:
|
|
with open(path, "r", encoding="utf-8") as handle:
|
|
return json.load(handle)
|
|
except (OSError, ValueError) as exc:
|
|
raise Malformed("cannot read %s: %s" % (path, exc))
|
|
|
|
|
|
def check_identity(series):
|
|
"""Refuse pairs of two build ids or two cache states."""
|
|
pairs = series.get("pairs")
|
|
for key in PAIR_LEVEL_IDENTITY_KEYS:
|
|
seen = {}
|
|
if key in series:
|
|
seen[json.dumps(series[key], sort_keys=True)] = "series header"
|
|
for pair in pairs:
|
|
if key in pair and pair.get("valid") is True:
|
|
seen.setdefault(json.dumps(pair[key], sort_keys=True),
|
|
"pair %s" % pair.get("pair"))
|
|
if len(seen) > 1:
|
|
raise Refused("mixed %s: %s" % (key, ", ".join(
|
|
"%s (%s)" % (value, where) for value, where in sorted(seen.items()))))
|
|
|
|
|
|
def rows_of(series):
|
|
"""Vanilla rows to evaluate: both rows, or one when rows_coincide."""
|
|
coincide = bool(series.get("rows_coincide", False))
|
|
present = [row for row in VANILLA_ROWS
|
|
if any(row in (p.get("arms") or {}) for p in series["pairs"])]
|
|
if not present:
|
|
raise Malformed("no vanilla row in any pair")
|
|
return present[:1] if coincide else present
|
|
|
|
|
|
def validate_series(series):
|
|
if not isinstance(series, dict) or not isinstance(series.get("pairs"), list):
|
|
raise Malformed("series.json must be an object with a 'pairs' list")
|
|
n_planned = series.get("N")
|
|
if isinstance(n_planned, bool) or not isinstance(n_planned, int) or n_planned < 1:
|
|
raise Malformed("N must be a positive integer")
|
|
seen = set()
|
|
for pair in series["pairs"]:
|
|
if not isinstance(pair, dict) or "pair" not in pair:
|
|
raise Malformed("every pair needs a 'pair' number")
|
|
if pair["pair"] in seen:
|
|
raise Malformed("duplicate pair number %r" % (pair["pair"],))
|
|
seen.add(pair["pair"])
|
|
|
|
|
|
def valid_pairs(series):
|
|
pairs = [p for p in series["pairs"] if p.get("valid") is True]
|
|
return sorted(pairs, key=lambda p: p["pair"])
|
|
|
|
|
|
def pair_values(pair, metric, row):
|
|
arms = pair.get("arms")
|
|
if not isinstance(arms, dict) or "ours" not in arms or row not in arms:
|
|
raise Malformed("pair %s lacks the arms ours/%s" % (pair["pair"], row))
|
|
try:
|
|
ours = _number(arms["ours"][metric], "pair %s ours.%s" % (pair["pair"], metric))
|
|
other = _number(arms[row][metric], "pair %s %s.%s" % (pair["pair"], row, metric))
|
|
except (KeyError, TypeError):
|
|
raise Malformed("pair %s lacks metric %s for ours/%s" % (pair["pair"], metric, row))
|
|
return ours, other
|
|
|
|
|
|
def log_ratios(pairs, metric, row):
|
|
return [log_ratio(metric, *pair_values(p, metric, row)) for p in pairs]
|
|
|
|
|
|
# ------------------------------------------------------------- evaluation
|
|
|
|
|
|
def recompute(series, look=None):
|
|
"""Full recomputation of one series.json (a dict); raises Refused/Malformed.
|
|
|
|
`look` (1 or 2) restricts the series to the pairs available at that interim
|
|
look (40 or 80 percent of N, rounded down to a multiple of 6).
|
|
"""
|
|
validate_series(series)
|
|
check_identity(series)
|
|
n_planned = series["N"]
|
|
valid_all = valid_pairs(series)
|
|
if look is not None:
|
|
points = look_points(n_planned)
|
|
if not 1 <= look <= len(points):
|
|
raise Malformed("--look %r: N = %d has %d interim looks" % (look, n_planned, len(points)))
|
|
if len(valid_all) < points[look - 1]:
|
|
raise Malformed("--look %d needs %d valid pairs, series has %d"
|
|
% (look, points[look - 1], len(valid_all)))
|
|
valid_all = valid_all[:points[look - 1]]
|
|
used = valid_all[:n_planned]
|
|
n_valid = len(valid_all)
|
|
rows = rows_of(series)
|
|
screening = len(used) < n_planned
|
|
|
|
metrics = {}
|
|
for metric in METRICS:
|
|
metrics[metric] = {}
|
|
for row in rows:
|
|
values = log_ratios(used, metric, row) if len(used) >= 2 else []
|
|
if len(values) < 2:
|
|
cell = {"n": len(used), "mean_l": None, "ci_lo": None, "ci_hi": None,
|
|
"r1": None, "n_eff": None, "mde": None, "dof": None,
|
|
"raw_verdict": "INCONCLUSIVE"}
|
|
else:
|
|
cell = confidence_interval(values, CONFIDENCE_ALPHA)
|
|
cell["raw_verdict"] = classify(metric, cell["ci_lo"], cell["ci_hi"])
|
|
verdict = cell["raw_verdict"]
|
|
if screening and verdict == "PASS":
|
|
# E6: a screening set never carries a PASS token, not even as a raw class.
|
|
verdict = "SCREENING"
|
|
cell["raw_verdict"] = "ABOVE_BOUND"
|
|
cell["verdict"] = verdict
|
|
metrics[metric][row] = cell
|
|
|
|
looks = []
|
|
early_slower = None
|
|
for k in look_points(n_planned):
|
|
if len(valid_all) < k:
|
|
continue
|
|
prefix = valid_all[:k]
|
|
slower = []
|
|
for metric in METRICS:
|
|
for row in rows:
|
|
interval = confidence_interval(log_ratios(prefix, metric, row), POCOCK_ALPHA)
|
|
if classify(metric, interval["ci_lo"], interval["ci_hi"]) == "SLOWER":
|
|
slower.append({"metric": metric, "row": row,
|
|
"ci_lo": interval["ci_lo"], "ci_hi": interval["ci_hi"]})
|
|
looks.append({"look_pairs": k, "level": POCOCK_ALPHA, "slower": slower})
|
|
if slower and early_slower is None:
|
|
early_slower = k
|
|
|
|
cells = [(m, r) for m in METRICS for r in rows]
|
|
if early_slower is not None:
|
|
verdict = "FAILED"
|
|
elif screening:
|
|
verdict = "SCREENING"
|
|
elif any(metrics[m][r]["raw_verdict"] == "SLOWER" for m, r in cells):
|
|
verdict = "FAILED"
|
|
elif all(metrics[m][r]["raw_verdict"] == "PASS" for m, r in cells):
|
|
verdict = "MET"
|
|
else:
|
|
verdict = "NOT_MET"
|
|
|
|
return {"machine": series.get("machine"), "N": n_planned, "n_valid": n_valid,
|
|
"n_used": len(used), "rows": list(rows), "metrics": metrics,
|
|
"series_verdict": verdict, "early_exit_look": early_slower, "looks": looks,
|
|
"rule": {"neff_rule_enabled": NEFF_RULE_ENABLED,
|
|
"neff_scales_standard_error": NEFF_SCALES_STANDARD_ERROR}}
|
|
|
|
|
|
# ------------------------------------------------------------------ compare
|
|
|
|
COMPARED_NUMERIC = ("mean_l", "ci_lo", "ci_hi")
|
|
|
|
|
|
def _close(a, b, tol):
|
|
if a is None or b is None:
|
|
return a is None and b is None
|
|
return isinstance(a, (int, float)) and isinstance(b, (int, float)) and abs(a - b) <= tol
|
|
|
|
|
|
def first_disagreement(evaluator, mine, series, tol=COMPARE_TOL):
|
|
"""Return a message naming the first disagreement, or None when all agree."""
|
|
if not isinstance(evaluator, dict) or not isinstance(evaluator.get("metrics"), dict):
|
|
raise Malformed("evaluator output has no 'metrics' object")
|
|
screening = mine["series_verdict"] == "SCREENING" or mine["n_used"] < mine["N"]
|
|
expected_rows = len(mine["rows"])
|
|
for metric in METRICS:
|
|
ev_rows = evaluator["metrics"].get(metric)
|
|
if not isinstance(ev_rows, dict):
|
|
return "metric=%s field=<metric block> evaluator=missing recompute=present" % metric
|
|
if len(ev_rows) != expected_rows:
|
|
return ("metric=%s field=<row count> evaluator=%d recompute=%d"
|
|
% (metric, len(ev_rows), expected_rows))
|
|
for row, ev_cell in ev_rows.items():
|
|
if row in mine["metrics"][metric]:
|
|
my_cell = mine["metrics"][metric][row]
|
|
elif mine["rows"] and len(mine["rows"]) == 1 and len(ev_rows) == 1:
|
|
my_cell = mine["metrics"][metric][mine["rows"][0]] # coinciding rows, other name
|
|
else:
|
|
return "metric=%s row=%s field=<row> evaluator=present recompute=absent" % (metric, row)
|
|
if not isinstance(ev_cell, dict):
|
|
return "metric=%s row=%s field=<cell> evaluator=malformed" % (metric, row)
|
|
if ev_cell.get("n") != my_cell["n"]:
|
|
return ("metric=%s row=%s field=n evaluator=%r recompute=%r"
|
|
% (metric, row, ev_cell.get("n"), my_cell["n"]))
|
|
for field in COMPARED_NUMERIC:
|
|
if field not in ev_cell:
|
|
return "metric=%s row=%s field=%s evaluator=missing" % (metric, row, field)
|
|
if not _close(ev_cell[field], my_cell[field], tol):
|
|
diff = (abs(ev_cell[field] - my_cell[field])
|
|
if isinstance(ev_cell[field], (int, float)) and my_cell[field] is not None
|
|
else float("nan"))
|
|
return ("metric=%s row=%s field=%s evaluator=%r recompute=%r abs_diff=%.3e tol=%.1e"
|
|
% (metric, row, field, ev_cell[field], my_cell[field], diff, tol))
|
|
ev_verdict = str(ev_cell.get("verdict", "")).upper()
|
|
if screening:
|
|
ok = ev_verdict in (my_cell["verdict"], my_cell["raw_verdict"], "SCREENING") \
|
|
and ev_verdict != "PASS"
|
|
else:
|
|
ok = ev_verdict == my_cell["verdict"]
|
|
if not ok:
|
|
return ("metric=%s row=%s field=verdict evaluator=%r recompute=%r"
|
|
% (metric, row, ev_cell.get("verdict"), my_cell["verdict"]))
|
|
if "series_verdict" in evaluator and str(evaluator["series_verdict"]).upper() != mine["series_verdict"]:
|
|
return ("metric=<series> row=<series> field=series_verdict evaluator=%r recompute=%r"
|
|
% (evaluator["series_verdict"], mine["series_verdict"]))
|
|
return None
|
|
|
|
|
|
def cmd_compare(evaluator_path, series_path, tol):
|
|
evaluator = load_json(evaluator_path)
|
|
series = load_json(series_path)
|
|
try:
|
|
mine = recompute(series)
|
|
except Refused as exc:
|
|
if isinstance(evaluator, dict) and str(evaluator.get("series_verdict", "")).upper() == "REFUSED":
|
|
print("AGREE: both sides refuse the series (%s)" % exc)
|
|
return 0
|
|
print("DISAGREE: recomputation refuses the series (%s) but the evaluator produced a result" % exc)
|
|
return 1
|
|
message = first_disagreement(evaluator, mine, series, tol)
|
|
if message is None:
|
|
cells = sum(len(v) for v in mine["metrics"].values())
|
|
print("AGREE: %d (metric,row) cells, series_verdict=%s, tol=%.1e"
|
|
% (cells, mine["series_verdict"], tol))
|
|
return 0
|
|
print("DISAGREE: " + message)
|
|
return 1
|
|
|
|
|
|
# ------------------------------------------------------- blind sd, null simulation
|
|
|
|
BLIND_PAIRS = 6 # E1: N is fixed from the sd of the first 6 valid pairs
|
|
|
|
|
|
def blind_sd(series):
|
|
"""Sample sd (n - 1) of l of the first 6 valid pairs; deliberately no mean (E1)."""
|
|
validate_series(series)
|
|
check_identity(series)
|
|
first = valid_pairs(series)[:BLIND_PAIRS]
|
|
if len(first) < BLIND_PAIRS:
|
|
raise Malformed("blind sd needs %d valid pairs, series has %d" % (BLIND_PAIRS, len(first)))
|
|
sd = {}
|
|
for metric in METRICS:
|
|
sd[metric] = {}
|
|
for row in rows_of(series):
|
|
sd[metric][row] = mean_sd_r1(log_ratios(first, metric, row))[1]
|
|
return {"pairs_used": BLIND_PAIRS, "sd": sd}
|
|
|
|
|
|
def simulate_null(series, runs, seed):
|
|
"""False-SLOWER rate of one strict-rule cell under the null (E8).
|
|
|
|
l_i ~ Normal(0, sd) with sd of wall_norm / first vanilla row of `series`, N
|
|
pairs per run, the interim looks at the two-sided level 0.0221 and the final
|
|
look at 0.05; a run counts when any look classifies the cell SLOWER.
|
|
"""
|
|
validate_series(series)
|
|
check_identity(series)
|
|
n_planned = series["N"]
|
|
row = rows_of(series)[0]
|
|
used = valid_pairs(series)[:n_planned]
|
|
if len(used) < 3:
|
|
raise Malformed("null simulation needs at least 3 valid pairs")
|
|
sd = mean_sd_r1(log_ratios(used, "wall_norm", row))[1]
|
|
if not sd > 0:
|
|
raise Malformed("null simulation needs a positive sd of l")
|
|
plan = [(k, POCOCK_ALPHA) for k in look_points(n_planned)] + [(n_planned, CONFIDENCE_ALPHA)]
|
|
rng = random.Random(seed)
|
|
false_slower = 0
|
|
for _ in range(runs):
|
|
draws = [rng.gauss(0.0, sd) for _ in range(n_planned)]
|
|
for size, alpha in plan:
|
|
interval = confidence_interval(draws[:size], alpha, exact=False)
|
|
if classify("wall_norm", interval["ci_lo"], interval["ci_hi"]) == "SLOWER":
|
|
false_slower += 1
|
|
break
|
|
return {"runs": runs, "seed": seed, "n": n_planned, "sd_used": sd,
|
|
"looks": [size for size, _ in plan], "false_slower": false_slower,
|
|
"false_slower_rate": false_slower / runs if runs else float("nan")}
|
|
|
|
|
|
# ------------------------------------------------------------------- golden
|
|
|
|
# Expected keys the runner can check, per kind of output. Any other key of a case is
|
|
# NOT checked and makes the case SKIPPED.
|
|
ALWAYS_CHECKED = ("exit", "message_contains", "mention")
|
|
RECOMPUTE_CHECKED = ("series_verdict", "metrics", "rows", "forbidden_tokens")
|
|
BLIND_CHECKED = ("blind_sd", "forbidden_key_prefixes", "forbidden_tokens")
|
|
SIM_CHECKED = ("max_false_slower_rate", "runs", "seed")
|
|
|
|
|
|
def _case_list(doc):
|
|
cases = doc.get("cases", doc) if isinstance(doc, dict) else doc
|
|
if isinstance(cases, dict):
|
|
return [(name, case) for name, case in cases.items() if isinstance(case, dict)]
|
|
if isinstance(cases, list):
|
|
return [(case.get("name", "case-%d" % i), case) for i, case in enumerate(cases)
|
|
if isinstance(case, dict)]
|
|
raise Malformed("golden file has no cases")
|
|
|
|
|
|
def _pick(case, keys):
|
|
for key in keys:
|
|
if key in case:
|
|
return case[key]
|
|
return None
|
|
|
|
|
|
def _check_value(path, expected, actual, tol, problems):
|
|
if isinstance(expected, dict):
|
|
if not isinstance(actual, dict):
|
|
problems.append("%s: expected an object" % path)
|
|
return
|
|
for key, value in expected.items():
|
|
if key not in actual:
|
|
problems.append("%s.%s: missing in recomputation" % (path, key))
|
|
else:
|
|
_check_value("%s.%s" % (path, key), value, actual[key], tol, problems)
|
|
elif isinstance(expected, (int, float)) and not isinstance(expected, bool):
|
|
if not isinstance(actual, (int, float)) or abs(expected - actual) > tol:
|
|
problems.append("%s: expected %r, recomputed %r" % (path, expected, actual))
|
|
elif isinstance(expected, str):
|
|
if str(actual).upper() != expected.upper():
|
|
problems.append("%s: expected %r, recomputed %r" % (path, expected, actual))
|
|
elif expected is None:
|
|
if actual is not None:
|
|
problems.append("%s: expected null, recomputed %r" % (path, actual))
|
|
elif expected != actual:
|
|
problems.append("%s: expected %r, recomputed %r" % (path, expected, actual))
|
|
|
|
|
|
def parse_case_argv(argv):
|
|
"""Understood flags of a golden case's argv; returns (options, unknown tokens)."""
|
|
opts = {"look": None, "blind_sd": False, "simulate_null": False, "runs": None, "seed": None}
|
|
unknown = []
|
|
i = 0
|
|
argv = list(argv or [])
|
|
while i < len(argv):
|
|
token = argv[i]
|
|
if token in ("--look", "--runs", "--seed") and i + 1 < len(argv):
|
|
try:
|
|
opts[token[2:]] = int(argv[i + 1])
|
|
except ValueError:
|
|
unknown.append("%s %s" % (token, argv[i + 1]))
|
|
i += 2
|
|
elif token == "--blind-sd":
|
|
opts["blind_sd"] = True
|
|
i += 1
|
|
elif token == "--simulate-null":
|
|
opts["simulate_null"] = True
|
|
i += 1
|
|
else:
|
|
unknown.append(token)
|
|
i += 1
|
|
return opts, unknown
|
|
|
|
|
|
def _numbers(value):
|
|
"""All numeric leaves of a JSON-like value."""
|
|
if isinstance(value, bool):
|
|
return []
|
|
if isinstance(value, (int, float)):
|
|
return [value]
|
|
if isinstance(value, dict):
|
|
return [x for v in value.values() for x in _numbers(v)]
|
|
if isinstance(value, list):
|
|
return [x for v in value for x in _numbers(v)]
|
|
return []
|
|
|
|
|
|
def _keys(value):
|
|
if isinstance(value, dict):
|
|
for key, sub in value.items():
|
|
yield key
|
|
for inner in _keys(sub):
|
|
yield inner
|
|
elif isinstance(value, list):
|
|
for sub in value:
|
|
for inner in _keys(sub):
|
|
yield inner
|
|
|
|
|
|
def _evaluate(series, opts):
|
|
"""Run the recomputation a case asks for.
|
|
|
|
Returns (mode, output, exit_code, message): mode is 'recompute', 'blind' or 'sim';
|
|
output is None for a refused or malformed input.
|
|
"""
|
|
if isinstance(series, str): # raw_text: the document as a string
|
|
try:
|
|
series = json.loads(series)
|
|
except ValueError as exc:
|
|
return "recompute", None, 3, "cannot parse raw_text: %s" % exc
|
|
try:
|
|
if opts["blind_sd"]:
|
|
return "blind", blind_sd(series), 0, ""
|
|
if opts["simulate_null"]:
|
|
if opts["runs"] is None or opts["seed"] is None:
|
|
raise Malformed("--simulate-null needs --runs and --seed")
|
|
return "sim", simulate_null(series, opts["runs"], opts["seed"]), 0, ""
|
|
return "recompute", recompute(series, opts["look"]), 0, ""
|
|
except Refused as exc:
|
|
return "recompute", None, 2, str(exc)
|
|
except Malformed as exc:
|
|
return "recompute", None, 3, str(exc)
|
|
|
|
|
|
def _check_expected(expected, mode, output, got_exit, message, tol, problems, skipped):
|
|
"""Check every expected key; keys that cannot be checked go to `skipped`."""
|
|
want_exit = expected.get("exit", 0)
|
|
if got_exit != want_exit:
|
|
problems.append("exit: expected %r, recomputed %r" % (want_exit, got_exit))
|
|
if "message_contains" in expected and expected["message_contains"] not in message:
|
|
problems.append("message: expected to contain %r, got %r" % (expected["message_contains"], message))
|
|
if "mention" in expected and expected["mention"] not in message:
|
|
problems.append("mention: expected the message to mention %r, got %r" % (expected["mention"], message))
|
|
if output is None:
|
|
if "series_verdict" in expected and str(expected["series_verdict"]).upper() not in ("REFUSED", "MALFORMED"):
|
|
problems.append("series_verdict: expected %r on a refused input" % expected["series_verdict"])
|
|
checked = ALWAYS_CHECKED + ("series_verdict",)
|
|
else:
|
|
checked = ALWAYS_CHECKED + {"recompute": RECOMPUTE_CHECKED, "blind": BLIND_CHECKED,
|
|
"sim": SIM_CHECKED}[mode]
|
|
rendered = json.dumps(output, sort_keys=True)
|
|
if "forbidden_tokens" in expected and mode in ("recompute", "blind"):
|
|
for token in expected["forbidden_tokens"]:
|
|
if re.search(r"\b%s\b" % re.escape(token), rendered):
|
|
problems.append("forbidden_tokens: %r appears in the output" % token)
|
|
if mode == "recompute":
|
|
if "series_verdict" in expected:
|
|
_check_value("series_verdict", expected["series_verdict"], output["series_verdict"], tol, problems)
|
|
if "metrics" in expected:
|
|
_check_value("metrics", expected["metrics"], output["metrics"], tol, problems)
|
|
if isinstance(expected.get("rows"), list):
|
|
_check_value("rows", sorted(expected["rows"]), sorted(output["rows"]), tol, problems)
|
|
elif "rows" in expected:
|
|
problems.append("rows: expected a list")
|
|
elif mode == "blind":
|
|
if "blind_sd" in expected:
|
|
if not any(abs(x - expected["blind_sd"]) <= tol for x in _numbers(output)):
|
|
problems.append("blind_sd: %r is not among the numeric values of the output"
|
|
% expected["blind_sd"])
|
|
for prefix in expected.get("forbidden_key_prefixes", []):
|
|
bad = sorted({k for k in _keys(output) if str(k).startswith(prefix)})
|
|
if bad:
|
|
problems.append("forbidden_key_prefixes: keys %s start with %r" % (bad, prefix))
|
|
else:
|
|
rate = output["false_slower_rate"]
|
|
if "max_false_slower_rate" in expected and not rate <= expected["max_false_slower_rate"]:
|
|
problems.append("max_false_slower_rate: simulated %.5f > %r"
|
|
% (rate, expected["max_false_slower_rate"]))
|
|
for key in ("runs", "seed"):
|
|
if key in expected and expected[key] != output[key]:
|
|
problems.append("%s: expected %r, simulation ran with %r" % (key, expected[key], output[key]))
|
|
for key in expected:
|
|
if key not in checked:
|
|
skipped.append("expected key %r not checked (%s)"
|
|
% (key, mode if output is not None else "refused or malformed input"))
|
|
|
|
|
|
def run_case(case, tol):
|
|
"""Return (problems, skipped) for one golden case.
|
|
|
|
problems: reasons the case FAILED. skipped: expectations or argv flags this
|
|
tool did not check; a case without problems but with skipped entries is
|
|
SKIPPED, not passed.
|
|
"""
|
|
problems, skipped = [], []
|
|
expected = _pick(case, ("expected", "expect")) or {}
|
|
tol = case.get("tol", tol)
|
|
opts, unknown = parse_case_argv(case.get("argv"))
|
|
for token in unknown:
|
|
skipped.append("argv %r not understood" % token)
|
|
primary = case["raw_text"] if "raw_text" in case else _pick(case, ("input", "series", "series_json"))
|
|
if primary is None:
|
|
return ["case has no 'input'/'series'/'raw_text' (unrecognised case format)"], skipped
|
|
inputs = [("", primary)]
|
|
if "series_b" in case:
|
|
inputs.append(("series_b (%s): " % case.get("series_b_label", "variant"), case["series_b"]))
|
|
for label, series in inputs:
|
|
local_problems, local_skipped = [], []
|
|
mode, output, got_exit, message = _evaluate(series, opts)
|
|
_check_expected(expected, mode, output, got_exit, message, tol, local_problems, local_skipped)
|
|
problems.extend(label + p for p in local_problems)
|
|
for item in local_skipped:
|
|
if item not in skipped:
|
|
skipped.append(item)
|
|
return problems, skipped
|
|
|
|
|
|
def cmd_golden(path, tol, allow_skips=False):
|
|
doc = load_json(path)
|
|
cases = _case_list(doc)
|
|
passed = skipped_count = failed = 0
|
|
for name, case in cases:
|
|
problems, skipped = run_case(case, tol)
|
|
if problems:
|
|
failed += 1
|
|
print("FAIL %s: %s" % (name, "; ".join(problems)))
|
|
elif skipped:
|
|
skipped_count += 1
|
|
print("SKIPPED %s: %s" % (name, "; ".join(skipped)))
|
|
else:
|
|
passed += 1
|
|
print("cases: %d passed: %d skipped: %d failed: %d" % (len(cases), passed, skipped_count, failed))
|
|
if skipped_count:
|
|
print("NOT FULLY VERIFIED: %d case(s) carry expectations this tool does not check%s"
|
|
% (skipped_count, " (allowed by --allow-skips)" if allow_skips else ""))
|
|
ok = bool(cases) and failed == 0 and (skipped_count == 0 or allow_skips)
|
|
return 0 if ok else 1
|
|
|
|
|
|
# --------------------------------------------------------------------- main
|
|
|
|
|
|
def build_parser():
|
|
parser = argparse.ArgumentParser(
|
|
prog="recompute_verdict.py",
|
|
description="Independent recomputation of the E3/E5 series verdict (STRA-314).")
|
|
sub = parser.add_subparsers(dest="command")
|
|
p_series = sub.add_parser("series", help="print the recomputed verdicts of a series.json")
|
|
p_series.add_argument("series_json")
|
|
p_compare = sub.add_parser("compare", help="compare an evaluator output with the recomputation")
|
|
p_compare.add_argument("evaluator_output")
|
|
p_compare.add_argument("series_json")
|
|
p_compare.add_argument("--tol", type=float, default=COMPARE_TOL)
|
|
p_golden = sub.add_parser("golden", help="run golden series cases against this implementation")
|
|
p_golden.add_argument("series_cases")
|
|
p_golden.add_argument("--tol", type=float, default=COMPARE_TOL)
|
|
p_golden.add_argument("--allow-skips", action="store_true",
|
|
help="exit 0 although some cases carry unchecked expectations")
|
|
p_blind = sub.add_parser("blind-sd", help="sd of l of the first 6 valid pairs, no mean")
|
|
p_blind.add_argument("series_json")
|
|
p_sim = sub.add_parser("simulate-null", help="false-SLOWER rate under the null (E8)")
|
|
p_sim.add_argument("series_json")
|
|
p_sim.add_argument("--runs", type=int, default=20000)
|
|
p_sim.add_argument("--seed", type=int, default=1)
|
|
return parser
|
|
|
|
|
|
def main(argv=None):
|
|
args = build_parser().parse_args(argv)
|
|
if args.command is None:
|
|
build_parser().print_usage(sys.stderr)
|
|
return 3
|
|
try:
|
|
if args.command == "series":
|
|
print(json.dumps(recompute(load_json(args.series_json)), indent=2, sort_keys=True))
|
|
return 0
|
|
if args.command == "compare":
|
|
return cmd_compare(args.evaluator_output, args.series_json, args.tol)
|
|
if args.command == "blind-sd":
|
|
print(json.dumps(blind_sd(load_json(args.series_json)), indent=2, sort_keys=True))
|
|
return 0
|
|
if args.command == "simulate-null":
|
|
print(json.dumps(simulate_null(load_json(args.series_json), args.runs, args.seed),
|
|
indent=2, sort_keys=True))
|
|
return 0
|
|
return cmd_golden(args.series_cases, args.tol, args.allow_skips)
|
|
except Refused as exc:
|
|
print("REFUSED: %s" % exc, file=sys.stderr)
|
|
return 2
|
|
except Malformed as exc:
|
|
print("MALFORMED: %s" % exc, file=sys.stderr)
|
|
return 3
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|