Merge claude/stra-314 into Train A (STRA-245)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,618 @@
|
||||
#!/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> run golden cases against this
|
||||
implementation
|
||||
|
||||
Exit codes: 0 ok, 1 disagreement / failed 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 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 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.
|
||||
"""
|
||||
n = len(values)
|
||||
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):
|
||||
"""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)
|
||||
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):
|
||||
"""Full recomputation of one series.json (a dict); raises Refused/Malformed."""
|
||||
validate_series(series)
|
||||
check_identity(series)
|
||||
n_planned = series["N"]
|
||||
valid_all = valid_pairs(series)
|
||||
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
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- golden
|
||||
|
||||
|
||||
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 run_case(case, tol):
|
||||
"""Return a list of problems for one golden case (empty list = pass)."""
|
||||
series = _pick(case, ("input", "series", "series_json"))
|
||||
expected = _pick(case, ("expected", "expect")) or {}
|
||||
if series is None:
|
||||
return ["case has no 'input'/'series' object (unrecognised case format)"]
|
||||
tol = case.get("tol", tol)
|
||||
want_exit = expected.get("exit", 0)
|
||||
try:
|
||||
mine = recompute(series)
|
||||
got_exit = 0
|
||||
except Refused as exc:
|
||||
mine, got_exit, refusal = None, 2, str(exc)
|
||||
except Malformed as exc:
|
||||
mine, got_exit, refusal = None, 3, str(exc)
|
||||
problems = []
|
||||
if got_exit != want_exit:
|
||||
problems.append("exit: expected %r, recomputed %r" % (want_exit, got_exit))
|
||||
if mine is None:
|
||||
contains = expected.get("message_contains")
|
||||
if contains and contains not in refusal:
|
||||
problems.append("message: expected to contain %r, got %r" % (contains, refusal))
|
||||
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"])
|
||||
return problems
|
||||
for key, value in expected.items():
|
||||
if key in ("exit", "message_contains"):
|
||||
continue
|
||||
if key == "metrics":
|
||||
_check_value("metrics", value, mine["metrics"], tol, problems)
|
||||
elif key == "rows":
|
||||
_check_value("rows", sorted(value), sorted(mine["rows"]), tol, problems) \
|
||||
if isinstance(value, list) else None
|
||||
elif key in mine:
|
||||
_check_value(key, value, mine[key], tol, problems)
|
||||
return problems
|
||||
|
||||
|
||||
def cmd_golden(path, tol):
|
||||
doc = load_json(path)
|
||||
cases = _case_list(doc)
|
||||
passed = 0
|
||||
for name, case in cases:
|
||||
problems = run_case(case, tol)
|
||||
if problems:
|
||||
print("FAIL %s: %s" % (name, "; ".join(problems)))
|
||||
else:
|
||||
passed += 1
|
||||
print("cases: %d passed: %d" % (len(cases), passed))
|
||||
return 0 if passed == len(cases) and cases 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)
|
||||
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)
|
||||
return cmd_golden(args.series_cases, args.tol)
|
||||
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())
|
||||
@@ -0,0 +1,363 @@
|
||||
"""Tests of the independent verdict recomputation (STRA-314, SDET).
|
||||
|
||||
Run from the repository root:
|
||||
python -m unittest scripts.e2e.evidence.test_recompute_verdict -v
|
||||
|
||||
Expected values here come from three routes that do not use the code under test:
|
||||
published Student-t table values, the closed-form t distribution for integer
|
||||
dof (Abramowitz-Stegun 26.7.3/4) and the stdlib `statistics` module.
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
SCRIPT = os.path.join(HERE, "recompute_verdict.py")
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("recompute_verdict", SCRIPT)
|
||||
rv = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["recompute_verdict"] = rv
|
||||
_spec.loader.exec_module(rv)
|
||||
|
||||
# Published t(0.975, dof) for dof 1..30 (four decimals).
|
||||
T975 = [12.7062, 4.3027, 3.1824, 2.7764, 2.5706, 2.4469, 2.3646, 2.3060, 2.2622, 2.2281,
|
||||
2.2010, 2.1788, 2.1604, 2.1448, 2.1315, 2.1199, 2.1098, 2.1009, 2.0930, 2.0860,
|
||||
2.0796, 2.0739, 2.0687, 2.0639, 2.0595, 2.0555, 2.0518, 2.0484, 2.0452, 2.0423]
|
||||
|
||||
|
||||
def cdf_abs_closed_form(t, dof):
|
||||
"""P(|T| < t) for integer dof, Abramowitz-Stegun 26.7.3 (odd) / 26.7.4 (even)."""
|
||||
theta = math.atan(t / math.sqrt(dof))
|
||||
c2 = math.cos(theta) ** 2
|
||||
if dof == 1:
|
||||
return 2.0 * theta / math.pi
|
||||
if dof % 2 == 1:
|
||||
total, term = 0.0, 1.0
|
||||
for k in range((dof - 3) // 2 + 1):
|
||||
if k > 0:
|
||||
term *= (2.0 * k) / (2.0 * k + 1.0) * c2
|
||||
total += term
|
||||
return 2.0 / math.pi * (theta + math.sin(theta) * math.cos(theta) * total)
|
||||
total, term = 0.0, 1.0
|
||||
for k in range((dof - 2) // 2 + 1):
|
||||
if k > 0:
|
||||
term *= (2.0 * k - 1.0) / (2.0 * k) * c2
|
||||
total += term
|
||||
return math.sin(theta) * total
|
||||
|
||||
|
||||
def make_series(ratios_by_metric, n_planned=None, rows=("vanilla_default", "vanilla_noskip"),
|
||||
coincide=False, **extra):
|
||||
"""series.json where ours is 100 and vanilla is 100*ratio (rate: 100/ratio).
|
||||
|
||||
ratios_by_metric: {metric: [exp(l_i) ...]} with l positive = ours better.
|
||||
"""
|
||||
n = len(next(iter(ratios_by_metric.values())))
|
||||
pairs = []
|
||||
for i in range(n):
|
||||
arms = {"ours": {m: 100.0 for m in ("wall_norm", "ttft_sum", "decode_tps")}}
|
||||
for row in rows:
|
||||
arms[row] = {}
|
||||
for metric, ratios in ratios_by_metric.items():
|
||||
ratio = ratios[i]
|
||||
arms[row][metric] = 100.0 / ratio if metric == "decode_tps" else 100.0 * ratio
|
||||
pairs.append({"pair": i + 1, "valid": True, "reasons": [], "arms": arms})
|
||||
series = {"machine": "server", "ours_build_id": "b1", "cache_state": "WARM-OS/EMPTY-ENGINE",
|
||||
"schedule_hash": "h", "N": n_planned or n, "rows_coincide": coincide, "pairs": pairs}
|
||||
series.update(extra)
|
||||
return series
|
||||
|
||||
|
||||
def uniform(ratios):
|
||||
return {"wall_norm": ratios, "ttft_sum": ratios, "decode_tps": ratios}
|
||||
|
||||
|
||||
def alternating(center, amp, n):
|
||||
"""ratios whose logs alternate around `center` (negative lag-1 autocorrelation)."""
|
||||
return [math.exp(center + (amp if i % 2 == 0 else -amp)) for i in range(n)]
|
||||
|
||||
|
||||
def run_cli(*args):
|
||||
proc = subprocess.run([sys.executable, SCRIPT] + list(args), stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, universal_newlines=True)
|
||||
return proc.returncode, proc.stdout, proc.stderr
|
||||
|
||||
|
||||
class TempFiles(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self._tmp.cleanup)
|
||||
|
||||
def write(self, name, obj):
|
||||
path = os.path.join(self._tmp.name, name)
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
json.dump(obj, handle)
|
||||
return path
|
||||
|
||||
|
||||
class StudentTTests(unittest.TestCase):
|
||||
def test_quantile_matches_published_table_dof_1_to_30(self):
|
||||
for dof, expected in enumerate(T975, start=1):
|
||||
got = rv.t_quantile_two_sided(dof, 0.05)
|
||||
self.assertAlmostEqual(got, expected, delta=6e-5, msg="dof %d" % dof) # table is rounded to 4 decimals
|
||||
self.assertAlmostEqual(rv.t_quantile_two_sided(29, 0.05), 2.0452, delta=5e-5)
|
||||
|
||||
def test_quantile_matches_closed_form_distribution(self):
|
||||
for dof in (1, 2, 3, 4, 5, 8, 11, 12, 23, 24):
|
||||
for alpha in (0.05, 0.0221, 0.0158):
|
||||
t = rv.t_quantile_two_sided(dof, alpha)
|
||||
self.assertAlmostEqual(cdf_abs_closed_form(t, dof), 1.0 - alpha, delta=1e-10,
|
||||
msg="dof %d alpha %s" % (dof, alpha))
|
||||
|
||||
def test_quantile_exact_for_dof_1_and_2(self):
|
||||
# dof 1 is the Cauchy law: t = tan(pi (1 - alpha / 2 - 1/2)); dof 2: t = (1 - alpha) / sqrt(alpha (1 - alpha / 2)) ... use p form
|
||||
alpha = 0.05
|
||||
self.assertAlmostEqual(rv.t_quantile_two_sided(1, alpha), math.tan(math.pi * (1 - alpha) / 2),
|
||||
delta=1e-11)
|
||||
p = 1 - alpha / 2
|
||||
self.assertAlmostEqual(rv.t_quantile_two_sided(2, alpha),
|
||||
(2 * p - 1) / math.sqrt(2 * p * (1 - p)), delta=1e-11)
|
||||
|
||||
|
||||
class SeriesTests(TempFiles):
|
||||
def test_hand_computed_interval_against_stdlib_statistics(self):
|
||||
ratios = [1.02, 1.05, 1.01, 1.04, 1.03, 1.06]
|
||||
# The rate metric is the same l (decode_tps built as 100/ratio -> ln(O/V) = ln(ratio)).
|
||||
out = rv.recompute(make_series(uniform(ratios), n_planned=6))
|
||||
logs = [math.log(r) for r in ratios]
|
||||
mean, sd = statistics.mean(logs), statistics.stdev(logs)
|
||||
# lag-1 autocorrelation by hand, to know which rule applies
|
||||
dev = [x - mean for x in logs]
|
||||
r1 = sum(dev[i] * dev[i + 1] for i in range(5)) / sum(d * d for d in dev)
|
||||
n_eff = 6 * (1 - r1) / (1 + r1) if r1 > 0 else 6.0
|
||||
dof = max(1, math.floor(n_eff - 1)) if r1 > 0 else 5
|
||||
half = T975[dof - 1] * sd / math.sqrt(n_eff if r1 > 0 else 6)
|
||||
cell = out["metrics"]["wall_norm"]["vanilla_default"]
|
||||
self.assertEqual(cell["n"], 6)
|
||||
self.assertAlmostEqual(cell["mean_l"], mean, places=14)
|
||||
self.assertAlmostEqual(cell["r1"], r1, places=12)
|
||||
self.assertAlmostEqual(cell["ci_lo"], mean - half, delta=1e-4 * sd)
|
||||
self.assertAlmostEqual(cell["ci_hi"], mean + half, delta=1e-4 * sd)
|
||||
self.assertAlmostEqual(cell["mde"], 2.8 * sd / math.sqrt(6), places=12)
|
||||
|
||||
def test_all_zero_series_is_tie_strict_and_pass_nonnegative(self):
|
||||
out = rv.recompute(make_series(uniform([1.0] * 30)))
|
||||
for row in ("vanilla_default", "vanilla_noskip"):
|
||||
self.assertEqual(out["metrics"]["wall_norm"][row]["verdict"], "TIE")
|
||||
self.assertEqual(out["metrics"]["ttft_sum"][row]["verdict"], "PASS")
|
||||
self.assertEqual(out["metrics"]["decode_tps"][row]["verdict"], "PASS")
|
||||
self.assertEqual(out["metrics"]["wall_norm"][row]["mean_l"], 0.0)
|
||||
self.assertEqual(out["series_verdict"], "NOT_MET")
|
||||
|
||||
def test_bound_exactly_at_ln_099_is_not_a_pass_and_not_slower(self):
|
||||
# sd = 0 makes the bound exact: every l_i = ln(100/99).. here ours is 1 percent slower
|
||||
ratios = [0.99] * 30
|
||||
out = rv.recompute(make_series({"wall_norm": [1.01] * 30, "ttft_sum": ratios,
|
||||
"decode_tps": ratios}))
|
||||
cell = out["metrics"]["ttft_sum"]["vanilla_default"]
|
||||
self.assertEqual(cell["ci_lo"], cell["ci_hi"])
|
||||
self.assertAlmostEqual(cell["ci_lo"], math.log(0.99), delta=1e-13)
|
||||
self.assertEqual(cell["verdict"], "INCONCLUSIVE")
|
||||
|
||||
def test_clear_pass_slower_and_inconclusive(self):
|
||||
good = alternating(0.05, 0.002, 30)
|
||||
out = rv.recompute(make_series(uniform(good)))
|
||||
self.assertEqual(out["series_verdict"], "MET")
|
||||
self.assertTrue(all(c["verdict"] == "PASS" for m in out["metrics"].values() for c in m.values()))
|
||||
bad = alternating(-0.05, 0.002, 30)
|
||||
out = rv.recompute(make_series(uniform(bad)))
|
||||
self.assertEqual(out["series_verdict"], "FAILED")
|
||||
self.assertEqual(out["metrics"]["wall_norm"]["vanilla_default"]["verdict"], "SLOWER")
|
||||
noisy = alternating(0.001, 0.2, 30)
|
||||
out = rv.recompute(make_series(uniform(noisy)))
|
||||
self.assertEqual(out["metrics"]["wall_norm"]["vanilla_default"]["verdict"], "INCONCLUSIVE")
|
||||
self.assertEqual(out["series_verdict"], "NOT_MET")
|
||||
|
||||
def test_n29_is_screening_without_a_pass_token_and_n30_is_not(self):
|
||||
good = alternating(0.05, 0.002, 30)
|
||||
s29 = make_series(uniform(good[:29]), n_planned=30)
|
||||
code, stdout, _ = run_cli("series", self.write("s29.json", s29))
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(json.loads(stdout)["series_verdict"], "SCREENING")
|
||||
self.assertEqual(len(re.findall("PASS", stdout)), 0)
|
||||
self.assertEqual(rv.recompute(make_series(uniform(good)))["series_verdict"], "MET")
|
||||
|
||||
def test_invalid_pairs_are_excluded(self):
|
||||
series = make_series(uniform(alternating(0.05, 0.002, 31)), n_planned=30)
|
||||
series["pairs"][3]["valid"] = False
|
||||
series["pairs"][3]["reasons"] = ["power band"]
|
||||
series["pairs"][3]["arms"]["ours"]["wall_norm"] = 1e9
|
||||
out = rv.recompute(series)
|
||||
self.assertEqual(out["n_valid"], 30)
|
||||
self.assertEqual(out["series_verdict"], "MET")
|
||||
|
||||
def test_mixed_build_or_cache_state_is_refused_exit_2(self):
|
||||
base = make_series(uniform(alternating(0.05, 0.002, 30)))
|
||||
for key, other in (("ours_build_id", "b2"), ("cache_state", "COLD")):
|
||||
series = json.loads(json.dumps(base))
|
||||
series["pairs"][7][key] = other
|
||||
series["pairs"][0][key] = series[key]
|
||||
code, _, stderr = run_cli("series", self.write("mixed.json", series))
|
||||
self.assertEqual(code, 2, key)
|
||||
self.assertIn(key, stderr)
|
||||
|
||||
def test_malformed_input_exit_3(self):
|
||||
code, _, _ = run_cli("series", self.write("bad.json", {"pairs": "x"}))
|
||||
self.assertEqual(code, 3)
|
||||
series = make_series(uniform([1.01] * 30))
|
||||
series["pairs"][0]["arms"]["ours"]["wall_norm"] = 0
|
||||
code, _, _ = run_cli("series", self.write("zero.json", series))
|
||||
self.assertEqual(code, 3)
|
||||
|
||||
def test_unit_scale_and_pair_order_invariance(self):
|
||||
ratios = alternating(0.03, 0.004, 30)
|
||||
base = rv.recompute(make_series(uniform(ratios)))
|
||||
scaled = make_series(uniform(ratios))
|
||||
for pair in scaled["pairs"]:
|
||||
for arm in pair["arms"].values():
|
||||
for key in arm:
|
||||
arm[key] *= 1000.0
|
||||
out = rv.recompute(scaled)
|
||||
for metric in rv.METRICS:
|
||||
a = base["metrics"][metric]["vanilla_default"]
|
||||
b = out["metrics"][metric]["vanilla_default"]
|
||||
for field in ("mean_l", "ci_lo", "ci_hi"):
|
||||
self.assertAlmostEqual(a[field], b[field], places=12)
|
||||
# The pair order inside the file does not matter (pairs are ordered by number).
|
||||
shuffled = make_series(uniform(ratios))
|
||||
shuffled["pairs"].reverse()
|
||||
out = rv.recompute(shuffled)
|
||||
self.assertEqual(out["metrics"]["wall_norm"]["vanilla_default"]["ci_lo"],
|
||||
base["metrics"]["wall_norm"]["vanilla_default"]["ci_lo"])
|
||||
|
||||
def test_rows_coincide_gives_one_row(self):
|
||||
out = rv.recompute(make_series(uniform(alternating(0.05, 0.002, 30)), coincide=True))
|
||||
self.assertEqual(len(out["metrics"]["wall_norm"]), 1)
|
||||
out = rv.recompute(make_series(uniform(alternating(0.05, 0.002, 30))))
|
||||
self.assertEqual(len(out["metrics"]["wall_norm"]), 2)
|
||||
|
||||
def test_positive_autocorrelation_widens_the_interval(self):
|
||||
drift = [math.exp(0.002 * i) for i in range(30)] # trend: strong positive r1
|
||||
out = rv.recompute(make_series(uniform(drift)))
|
||||
cell = out["metrics"]["wall_norm"]["vanilla_default"]
|
||||
self.assertGreater(cell["r1"], 0.5)
|
||||
self.assertLess(cell["n_eff"], 30)
|
||||
logs = [math.log(r) for r in drift]
|
||||
plain_half = T975[28] * statistics.stdev(logs) / math.sqrt(30)
|
||||
self.assertGreater(cell["ci_hi"] - cell["ci_lo"], 2 * plain_half)
|
||||
|
||||
def test_interim_look_can_only_end_as_failed_never_pass(self):
|
||||
# 12 clearly slower pairs, then 18 clearly faster pairs: the look at 12 ends it.
|
||||
ratios = alternating(-0.05, 0.002, 12) + alternating(0.30, 0.002, 18)
|
||||
out = rv.recompute(make_series(uniform(ratios)))
|
||||
self.assertEqual(out["early_exit_look"], 12)
|
||||
self.assertEqual(out["series_verdict"], "FAILED")
|
||||
# A strong early lead never produces PASS before the end.
|
||||
out = rv.recompute(make_series(uniform(alternating(0.05, 0.002, 30)[:24]), n_planned=30))
|
||||
self.assertEqual(out["series_verdict"], "SCREENING")
|
||||
self.assertNotIn("PASS", [c["verdict"] for m in out["metrics"].values() for c in m.values()])
|
||||
self.assertEqual([k["look_pairs"] for k in out["looks"]], [12, 24])
|
||||
self.assertEqual(rv.look_points(30), [12, 24])
|
||||
self.assertEqual(rv.look_points(36), [12, 24])
|
||||
|
||||
|
||||
class CompareTests(TempFiles):
|
||||
def evaluator_output(self, series):
|
||||
"""What a correct evaluator prints (here: the recomputation in INTERFACE v1 shape)."""
|
||||
mine = rv.recompute(series)
|
||||
return {"metrics": {m: {r: {k: c[k] for k in ("n", "mean_l", "ci_lo", "ci_hi", "r1",
|
||||
"n_eff", "mde", "verdict")}
|
||||
for r, c in rows.items()} for m, rows in mine["metrics"].items()},
|
||||
"series_verdict": mine["series_verdict"], "looks": []}
|
||||
|
||||
def test_agreeing_evaluator_exits_0(self):
|
||||
series = make_series(uniform(alternating(0.05, 0.002, 30)))
|
||||
code, stdout, _ = run_cli("compare", self.write("ev.json", self.evaluator_output(series)),
|
||||
self.write("s.json", series))
|
||||
self.assertEqual(code, 0, stdout)
|
||||
self.assertIn("AGREE", stdout)
|
||||
|
||||
def test_mean_l_perturbed_by_0_005_exits_1_naming_metric_row_field(self):
|
||||
series = make_series(uniform(alternating(0.05, 0.002, 30)))
|
||||
evaluator = self.evaluator_output(series)
|
||||
evaluator["metrics"]["ttft_sum"]["vanilla_noskip"]["mean_l"] += 0.005
|
||||
code, stdout, _ = run_cli("compare", self.write("ev.json", evaluator),
|
||||
self.write("s.json", series))
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("metric=ttft_sum", stdout)
|
||||
self.assertIn("row=vanilla_noskip", stdout)
|
||||
self.assertIn("field=mean_l", stdout)
|
||||
|
||||
def test_ci_bound_just_over_tolerance_is_caught_and_under_is_accepted(self):
|
||||
series = make_series(uniform(alternating(0.05, 0.002, 30)))
|
||||
evaluator = self.evaluator_output(series)
|
||||
evaluator["metrics"]["wall_norm"]["vanilla_default"]["ci_lo"] += 5e-10
|
||||
self.assertEqual(run_cli("compare", self.write("a.json", evaluator),
|
||||
self.write("s.json", series))[0], 0)
|
||||
evaluator["metrics"]["wall_norm"]["vanilla_default"]["ci_lo"] += 1e-8
|
||||
code, stdout, _ = run_cli("compare", self.write("b.json", evaluator),
|
||||
self.write("s.json", series))
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("field=ci_lo", stdout)
|
||||
|
||||
def test_verdict_class_and_n_disagreement(self):
|
||||
series = make_series(uniform(alternating(0.05, 0.002, 30)))
|
||||
evaluator = self.evaluator_output(series)
|
||||
evaluator["metrics"]["decode_tps"]["vanilla_default"]["verdict"] = "INCONCLUSIVE"
|
||||
code, stdout, _ = run_cli("compare", self.write("ev.json", evaluator),
|
||||
self.write("s.json", series))
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("field=verdict", stdout)
|
||||
evaluator = self.evaluator_output(series)
|
||||
evaluator["metrics"]["wall_norm"]["vanilla_default"]["n"] = 29
|
||||
code, stdout, _ = run_cli("compare", self.write("ev2.json", evaluator),
|
||||
self.write("s.json", series))
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("field=n", stdout)
|
||||
|
||||
|
||||
class GoldenTests(TempFiles):
|
||||
def test_golden_runner_prints_counts_and_detects_a_wrong_expectation(self):
|
||||
# Expected values below are written by hand from the definitions, not read from the code.
|
||||
ratios_zero = uniform([1.0] * 30)
|
||||
cases = {"cases": {
|
||||
"all_zero": {"input": make_series(ratios_zero), "basis": "l_i = ln(1) = 0, sd = 0",
|
||||
"expected": {"series_verdict": "NOT_MET", "metrics": {
|
||||
"wall_norm": {"vanilla_default": {"n": 30, "mean_l": 0.0, "ci_lo": 0.0,
|
||||
"ci_hi": 0.0, "verdict": "TIE"}},
|
||||
"ttft_sum": {"vanilla_default": {"verdict": "PASS"}}}}},
|
||||
"mixed_build": {"input": dict(make_series(ratios_zero), pairs=[
|
||||
dict(p, ours_build_id="b%d" % (p["pair"] % 2)) for p in make_series(ratios_zero)["pairs"]]),
|
||||
"basis": "two build ids", "expected": {"exit": 2}},
|
||||
}}
|
||||
code, stdout, _ = run_cli("golden", self.write("g.json", cases))
|
||||
self.assertEqual(code, 0, stdout)
|
||||
self.assertIn("cases: 2 passed: 2", stdout)
|
||||
cases["cases"]["all_zero"]["expected"]["metrics"]["wall_norm"]["vanilla_default"]["verdict"] = "PASS"
|
||||
code, stdout, _ = run_cli("golden", self.write("g2.json", cases))
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("cases: 2 passed: 1", stdout)
|
||||
|
||||
|
||||
class IndependenceTests(unittest.TestCase):
|
||||
def test_no_import_of_the_evaluator_modules(self):
|
||||
with open(SCRIPT, "r", encoding="utf-8") as handle:
|
||||
lines = handle.read().splitlines()
|
||||
imports = [ln for ln in lines if re.match(r"^(import|from)\s", ln)]
|
||||
self.assertTrue(imports)
|
||||
for line in imports:
|
||||
self.assertNotRegex(line, "series_eval|component_class")
|
||||
# nothing imports lazily either
|
||||
self.assertFalse([ln for ln in lines if re.search(r"__import__|importlib", ln)])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user