#!/usr/bin/env python3 """Series evaluator for END_TO_END evidence (STRA-290, S0.10): E3 statistics, E5 verdict classes and interim looks, E6 SCREENING. Implements the evaluation rule of STRA-245 as rewritten by BA round 2 (comment 3eeb53e1, D2-D5; E1, E3, E5, E6, E8). The component classifier is STRA-313 (component_class.py) and imports the statistics functions of THIS file (t_quantile, t_crit, summarize, classify), it does not copy them. The validity of a pair (E2) is NOT derived here: series.json carries `valid` and `reasons`, produced by validity.py (STRA-312) through records_to_series.py. Stdlib only, Python >= 3.9. Offline, no GPU, no network. Writes nothing unless --out is given (run roots live outside Git). INTERFACE v1 series_eval.py [--look K] [--blind-sd] [--simulate-null --runs R --seed S] [--look-alpha A] [--out FILE] series.json {"machine": "laptop|server", "ours_build_id": str, "cache_state": str, "schedule_hash": str, "N": int, "rows_coincide": bool, "pairs": [{"pair": int, "valid": bool, "reasons": [str], "ours_build_id"?: str, "cache_state"?: str, "position": {arm: int}, "predecessor": {arm: str|null}, "arms": {"ours": {wall_norm, ttft_sum, decode_tps}, "vanilla_default": {...}, "vanilla_noskip": {...}}}]} stdout JSON {"metrics": {metric: {row: {n, mean_l, ci_lo, ci_hi, r1, n_eff, mde, verdict, ...}}}, "series_verdict": "MET|NOT_MET|FAILED|SCREENING|REFUSED", "looks": [...], "order_tables": ..., ...} exit 0 result produced; 2 REFUSED (mixed ours_build_id / cache_state / schedule_hash / machine; the message names the field); 3 malformed input (also a command-line usage error and --blind-sd with fewer than 6 valid pairs). DEFINITIONS (the golden vectors of STRA-310 fix what the BA text leaves open; see golden/gen_exact.py) l_i ln(V_i / O_i) for wall_norm and ttft_sum (lower is better), ln(O_i / V_i) for decode_tps (higher is better); positive = ours better. Only valid pairs, ordered by pair number; the first N valid pairs form the series (later pairs are outside the schedule, E6). r1 lag-1 autocorrelation sum_{i 0, else n. dof = max(1, floor(n_eff - 1)) when r1 > 0, else n - 1: the floor of n_eff - 1 is taken first and the result is never below 1 (n_eff < 2 gives dof 1, not 0). se the standard error of the mean is sd / sqrt(n_eff) (sd / sqrt(n) when r1 <= 0, where n_eff = n), NOT sd / sqrt(n): the lag-1 correction acts on the standard error and on the degrees of freedom together (E3; STRA-329 wording fix). CI mean +- t(1 - alpha/2, dof) * se; alpha = 0.05 for the verdicts, 0.0221 for the interim SLOWER test. mde 2.8 * sd / sqrt(n) (log-ratio units, charter 4.3 / E1). EPS 1e-12: a bound within EPS of a threshold counts as ON it (so an sd = 0 CI exactly on 0 or on ln 0.99 is well defined). strict (wall_norm) PASS lo > 0; SLOWER hi < 0; TIE CI contains 0 and lies in [ln 0.99, ln 1.01]; else INCONCLUSIVE. nonneg (ttft_sum, decode_tps) PASS lo > ln 0.99; SLOWER hi < ln 0.99; else INCONCLUSIVE (no TIE). looks at floor(0.4 N / 6) * 6 and floor(0.8 N / 6) * 6 valid pairs (12 and 24 for N = 30), SLOWER test only, two-sided level 0.0221; an early exit is only ever FAILED. --look K evaluates the series on the first (look K size) valid pairs. series fewer than N valid pairs (and no SLOWER exit): SCREENING, no verdict class; N valid pairs: any SLOWER FAILED, all PASS MET, else NOT_MET with the reason. A pair with event FAIL (ours failure not attributable, E2(5)) stops the series FAILED. """ import argparse import json import math import os import random import sys from functools import lru_cache SCHEMA = "series-eval-v1" METRICS = ("wall_norm", "ttft_sum", "decode_tps") STRICT_METRICS = ("wall_norm",) HIGHER_IS_BETTER = ("decode_tps",) ROW_DEFAULT = "vanilla_default" ROW_NOSKIP = "vanilla_noskip" ARMS_ALL = ("ours", ROW_DEFAULT, ROW_NOSKIP) LN_099 = math.log(0.99) LN_101 = math.log(1.01) EPS = 1e-12 # threshold tolerance (golden vectors, gen_exact.py) ALPHA_FINAL = 0.05 # two-sided level of the final verdicts (E5: 95 percent CI) ALPHA_LOOK_TABLE = 0.0221 # Pocock, three looks, normal-approximation table (E5) LOOK_FRACTIONS = ((2, 5), (4, 5)) # 40 and 80 percent of N as exact fractions GROUP = 6 # D5 / E1: N and looks are multiples of 6 MDE_FACTOR = 2.8 # 95 percent confidence, 80 percent power (E1) MDE_TARGET = 0.01 # E1: the MDE must not exceed 1 percent (log-ratio units) MAX_FALSE_SLOWER_RATE = 0.05 # E5 / E8 BLIND_PAIRS = 6 # E1: the sd of the first 6 valid pairs fixes N MISMATCH_FIELDS = ("ours_build_id", "cache_state", "schedule_hash", "machine") class Malformed(Exception): """Input that cannot be interpreted (exit 3).""" class Refused(Exception): """Pairs of different builds / cache states / schedules (exit 2); .field names the mixed field.""" def __init__(self, field, message): Exception.__init__(self, message) self.field = field # -------------------------------------------------------------------------------------------------------------------------------- # Student t quantile: regularised incomplete beta (continued fraction) + bisection. Tail probabilities are formed directly so that the # small levels (0.0158, 0.0221) lose no precision. # -------------------------------------------------------------------------------------------------------------------------------- def _betacf(a, b, x): 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 _betai(a, b, x): """Regularised incomplete beta 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_upper_tail(t, dof): """P(T > t) for t >= 0, Student t with dof degrees of freedom.""" if t <= 0.0: return 0.5 return 0.5 * _betai(dof / 2.0, 0.5, dof / (dof + t * t)) @lru_cache(maxsize=None) def _t_upper_quantile(q, dof): if dof == 1: return math.tan(math.pi * (0.5 - q)) if dof == 2: return (1.0 - 2.0 * q) / math.sqrt(2.0 * q * (1.0 - q)) lo, hi = 0.0, 1.0 while t_upper_tail(hi, dof) > q: lo, hi = hi, hi * 2.0 if hi > 1e12: raise ValueError("t quantile out of range") for _ in range(200): mid = 0.5 * (lo + hi) if t_upper_tail(mid, dof) > q: lo = mid else: hi = mid if hi - lo <= 1e-15 * hi: break return 0.5 * (lo + hi) def t_quantile(p, dof): """Quantile of Student's t for 0.5 < p < 1 (for example t_quantile(0.975, 29) = 2.0452).""" if not (0.5 < p < 1.0) or dof < 1: raise ValueError("t_quantile needs 0.5 < p < 1 and dof >= 1") return _t_upper_quantile(1.0 - p, int(dof)) def t_crit(alpha, dof): """Two-sided critical value: t(1 - alpha/2, dof).""" if not (0.0 < alpha < 1.0) or dof < 1: raise ValueError("t_crit needs 0 < alpha < 1 and dof >= 1") return _t_upper_quantile(alpha / 2.0, int(dof)) # -------------------------------------------------------------------------------------------------------------------------------- # E3 statistics # -------------------------------------------------------------------------------------------------------------------------------- def log_ratio(metric, ours, vanilla): """l = ln(V/O) (lower is better) or ln(O/V) (decode_tps); positive = ours better.""" if metric in HIGHER_IS_BETTER: return math.log(ours / vanilla) return math.log(vanilla / ours) def percent(l): return 100.0 * (math.exp(l) - 1.0) def lag1_autocorr(ls, mean=None): n = len(ls) if n < 2: return 0.0 m = math.fsum(ls) / n if mean is None else mean ss = math.fsum((x - m) ** 2 for x in ls) if ss <= 0.0: return 0.0 return math.fsum((ls[i] - m) * (ls[i + 1] - m) for i in range(n - 1)) / ss def summarize(ls, alpha=ALPHA_FINAL): """mean, sd, lag-1 r, n_eff, dof, t-CI of the mean of the log ratios `ls` (in pair order) at two-sided level alpha, and the MDE.""" n = len(ls) out = {"n": n} if n == 0: return out same = len(set(ls)) == 1 mean = ls[0] if same else math.fsum(ls) / n out["mean_l"] = mean if n < 2: return out ss = 0.0 if same else math.fsum((x - mean) ** 2 for x in ls) sd = math.sqrt(ss / (n - 1)) r1 = lag1_autocorr(ls, mean) if ss > 0.0 else 0.0 if r1 > 0.0: n_eff = n * (1.0 - r1) / (1.0 + r1) dof = max(1, int(math.floor(n_eff - 1.0))) else: n_eff = float(n) dof = n - 1 se = sd / math.sqrt(n_eff) t = t_crit(alpha, dof) out.update({"sd": sd, "r1": r1, "n_eff": n_eff, "dof": dof, "se": se, "t": t, "level": 1.0 - alpha, "ci_lo": mean - t * se, "ci_hi": mean + t * se, "half_width": t * se, "mde": MDE_FACTOR * sd / math.sqrt(n)}) return out def rule_of(metric): return "strict" if metric in STRICT_METRICS else "non_negative" def threshold_of(metric): return 0.0 if metric in STRICT_METRICS else LN_099 def classify(metric, lo, hi): """E5 verdict class of a CI [lo, hi] of the mean log ratio: PASS | SLOWER | TIE (strict only) | INCONCLUSIVE.""" strict = metric in STRICT_METRICS thr = threshold_of(metric) if lo > thr + EPS: return "PASS" if hi < thr - EPS: return "SLOWER" if strict and lo <= EPS and hi >= -EPS and lo >= LN_099 - EPS and hi <= LN_101 + EPS: return "TIE" return "INCONCLUSIVE" def is_slower(metric, ls, alpha): """The SLOWER test of the interim looks (and of the final verdict): CI upper bound below the rule's threshold.""" s = summarize(ls, alpha) return "ci_hi" in s and s["ci_hi"] < threshold_of(metric) - EPS def percentile(sorted_values, q): """Linear interpolation between order statistics (q in [0, 1]).""" n = len(sorted_values) if n == 0: return None pos = q * (n - 1) lo = int(math.floor(pos)) hi = min(lo + 1, n - 1) return sorted_values[lo] + (sorted_values[hi] - sorted_values[lo]) * (pos - lo) def sign_test(ls): """Exact two-sided sign test on the non-zero l_i; zeros are dropped.""" pos = sum(1 for x in ls if x > 0) neg = sum(1 for x in ls if x < 0) n = pos + neg if n == 0: p = 1.0 else: k = min(pos, neg) p = min(1.0, 2.0 * sum(math.comb(n, i) for i in range(k + 1)) / (2.0 ** n)) return {"n_pos": pos, "n_neg": neg, "n_zero": len(ls) - n, "p_two_sided": p} def wilcoxon(ls): """Wilcoxon signed-rank test (two-sided) on the non-zero l_i: exact when there are no ties, else the normal approximation with tie and continuity correction. Shown, never decides (E3).""" d = [x for x in ls if x != 0.0] n = len(d) if n == 0: return {"n": 0, "w_plus": 0.0, "p_two_sided": 1.0, "method": "none"} order = sorted(range(n), key=lambda i: abs(d[i])) ranks = [0.0] * n ties = [] i = 0 while i < n: j = i while j + 1 < n and abs(d[order[j + 1]]) == abs(d[order[i]]): j += 1 for k in range(i, j + 1): ranks[order[k]] = (i + j) / 2.0 + 1.0 ties.append(j - i + 1) i = j + 1 w_plus = math.fsum(ranks[i] for i in range(n) if d[i] > 0) total = n * (n + 1) / 2.0 if max(ties) == 1 and n <= 60: counts = [0] * (n * (n + 1) // 2 + 1) counts[0] = 1 for r in range(1, n + 1): for s in range(len(counts) - 1, r - 1, -1): counts[s] += counts[s - r] w_min = int(min(w_plus, total - w_plus)) p = min(1.0, 2.0 * sum(counts[: w_min + 1]) / (2.0 ** n)) method = "exact" else: mu = total / 2.0 var = n * (n + 1) * (2 * n + 1) / 24.0 - sum(t ** 3 - t for t in ties) / 48.0 z = max(0.0, abs(w_plus - mu) - 0.5) / math.sqrt(var) if var > 0 else 0.0 p = math.erfc(z / math.sqrt(2.0)) method = "normal_approximation" return {"n": n, "w_plus": w_plus, "p_two_sided": p, "method": method} def n_to_resolve(stats, metric, alpha=ALPHA_FINAL, limit=100000): """Smallest N (multiple of 6) at which the CI lower bound would clear the rule's threshold if mean, sd and r1 stayed as observed; None when the observed mean does not exceed the threshold (no N resolves it in favour of ours).""" if "sd" not in stats: return None gap = stats["mean_l"] - threshold_of(metric) if gap <= EPS: return None ratio = (1.0 - stats["r1"]) / (1.0 + stats["r1"]) if stats["r1"] > 0.0 else 1.0 n = max(GROUP, GROUP * int(math.ceil(stats["n"] / float(GROUP)))) while n <= limit: n_eff = n * ratio dof = max(1, int(math.floor(n_eff - 1.0))) if stats["r1"] > 0.0 else n - 1 if stats["sd"] / math.sqrt(n_eff) * t_crit(alpha, dof) < gap - EPS: return n n += GROUP return None def required_n(sd, n_now, target=MDE_TARGET): """E1: smallest multiple of 6 that is >= n_now and gives 2.8 sd / sqrt(N) <= target; N is raised, never lowered.""" need = int(math.ceil((MDE_FACTOR * sd / target) ** 2)) if sd > 0 else 0 return max(n_now, GROUP * int(math.ceil(need / float(GROUP)))) # -------------------------------------------------------------------------------------------------------------------------------- # input # -------------------------------------------------------------------------------------------------------------------------------- def _is_number(x): return isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x) def load_series(path): try: with open(path, "r", encoding="utf-8") as fh: return json.load(fh) except (OSError, ValueError) as exc: raise Malformed("cannot read %s: %s" % (path, exc)) def parse_series(doc): """Validates the document. Returns (series dict, rows, valid pairs sorted by pair number, all pairs sorted).""" if not isinstance(doc, dict): raise Malformed("series.json must be a JSON object") n_reg = doc.get("N") if not isinstance(n_reg, int) or isinstance(n_reg, bool) or n_reg < 2: raise Malformed("N must be an integer >= 2") if doc.get("machine") not in ("laptop", "server"): raise Malformed("machine must be laptop or server") if not isinstance(doc.get("rows_coincide", False), bool): raise Malformed("rows_coincide must be a boolean") pairs = doc.get("pairs") if not isinstance(pairs, list): raise Malformed("pairs must be a list") rows = [ROW_DEFAULT] if doc.get("rows_coincide", False) else [ROW_DEFAULT, ROW_NOSKIP] seen = set() for p in pairs: if not isinstance(p, dict): raise Malformed("every pair must be an object") num = p.get("pair") if not isinstance(num, int) or isinstance(num, bool): raise Malformed("every pair needs an integer 'pair'") if num in seen: raise Malformed("pair %d appears twice" % num) seen.add(num) if not isinstance(p.get("valid"), bool): raise Malformed("pair %d: 'valid' must be a boolean" % num) if not isinstance(p.get("reasons", []), list): raise Malformed("pair %d: 'reasons' must be a list" % num) if p["valid"]: arms = p.get("arms") if not isinstance(arms, dict): raise Malformed("pair %d: a valid pair needs 'arms'" % num) for arm in ("ours",) + tuple(rows): vals = arms.get(arm) if not isinstance(vals, dict): raise Malformed("pair %d: arm %s is missing" % (num, arm)) for metric in METRICS: v = vals.get(metric) if not _is_number(v) or v <= 0: raise Malformed("pair %d: %s.%s must be a finite positive number, got %r" % (num, arm, metric, v)) ordered = sorted(pairs, key=lambda p: p["pair"]) return doc, rows, [p for p in ordered if p["valid"]], ordered def check_mixed(doc, pairs): """E1/E6: pairs of different builds, cache states or schedules are never pooled -> REFUSED. A pair that states no value is skipped.""" for field in MISMATCH_FIELDS: seen = {} top = doc.get(field) if isinstance(top, str): seen.setdefault(top, []).append("series") for p in pairs: v = p.get(field) if isinstance(v, str): seen.setdefault(v, []).append("pair %d" % p["pair"]) if len(seen) > 1: detail = "; ".join("%r in %s" % (v, ", ".join(w[:4]) + (" ..." if len(w) > 4 else "")) for v, w in sorted(seen.items())) raise Refused(field, "REFUSED: mixed %s (%s)" % (field, detail)) def look_sizes(n_reg): """Valid-pair counts of the interim looks: 40 and 80 percent of N rounded down to a multiple of 6 (12 and 24 for N = 30).""" sizes = [] for num, den in LOOK_FRACTIONS: size = (num * n_reg // den) // GROUP * GROUP if 2 <= size < n_reg and size not in sizes: sizes.append(size) return sizes # -------------------------------------------------------------------------------------------------------------------------------- # tables (E1) # -------------------------------------------------------------------------------------------------------------------------------- def _group_mean(items): out = {} for key, value in items: out.setdefault(key, []).append(value) return dict((k, {"n": len(v), "mean_l": math.fsum(v) / len(v)}) for k, v in sorted(out.items())) def order_tables(pairs, rows): """order_tables (golden requirement of STRA-311): mean ln(value) of each arm's own metric by the arm's position and by its predecessor.""" by_pos, by_pred = {}, {} for metric in METRICS: pos_acc, pred_acc = {}, {} for p in pairs: for arm, vals in p["arms"].items(): if not isinstance(vals, dict) or not _is_number(vals.get(metric)) or vals[metric] <= 0: continue value = math.log(vals[metric]) position = (p.get("position") or {}).get(arm) if position is not None: pos_acc.setdefault(arm, {}).setdefault(str(position), []).append(value) if arm in (p.get("predecessor") or {}): pred_acc.setdefault(arm, {}).setdefault((p["predecessor"][arm] or "none"), []).append(value) by_pos[metric] = dict((a, dict((k, math.fsum(v) / len(v)) for k, v in sorted(d.items()))) for a, d in sorted(pos_acc.items())) by_pred[metric] = dict((a, dict((k, math.fsum(v) / len(v)) for k, v in sorted(d.items()))) for a, d in sorted(pred_acc.items())) return {"by_position": by_pos, "by_predecessor": by_pred} def l_tables(pairs, rows): """E1: mean l by the position and by the predecessor of ours and of the compared vanilla row.""" out = {"by_position_of_ours": {}, "by_position_of_row": {}, "by_predecessor_of_ours": {}, "by_predecessor_of_row": {}} for metric in METRICS: for key in out: out[key][metric] = {} for row in rows: acc = dict((key, []) for key in out) for p in pairs: l = log_ratio(metric, p["arms"]["ours"][metric], p["arms"][row][metric]) pos, pred = p.get("position") or {}, p.get("predecessor") or {} if pos.get("ours") is not None: acc["by_position_of_ours"].append((str(pos["ours"]), l)) if pos.get(row) is not None: acc["by_position_of_row"].append((str(pos[row]), l)) if "ours" in pred: acc["by_predecessor_of_ours"].append((pred["ours"] or "none", l)) if row in pred: acc["by_predecessor_of_row"].append((pred[row] or "none", l)) for key in out: out[key][metric][row] = _group_mean(acc[key]) return out # -------------------------------------------------------------------------------------------------------------------------------- # evaluation # -------------------------------------------------------------------------------------------------------------------------------- def cell_logs(pairs, metric, row): return [log_ratio(metric, p["arms"]["ours"][metric], p["arms"][row][metric]) for p in pairs] def build_cell(metric, ls, verdict): s = summarize(ls, ALPHA_FINAL) cell = dict(s) cell["rule"] = rule_of(metric) cell["threshold"] = threshold_of(metric) cell["verdict"] = verdict srt = sorted(ls) cell["median_l"] = percentile(srt, 0.5) cell["percentiles"] = dict((("p%02d" % round(q * 100)), percentile(srt, q)) for q in (0.05, 0.25, 0.5, 0.75, 0.95)) cell["l"] = list(ls) cell["count_le0"] = sum(1 for x in ls if x <= 0.0) cell["sign_test"] = sign_test(ls) cell["wilcoxon"] = wilcoxon(ls) if "mean_l" in s: cell["mean_pct"] = percent(s["mean_l"]) if "ci_lo" in s: cell["ci_lo_pct"] = percent(s["ci_lo"]) cell["ci_hi_pct"] = percent(s["ci_hi"]) return cell def evaluate(doc, look=None, alpha_look=ALPHA_LOOK_TABLE): series, rows, valid, ordered = parse_series(doc) check_mixed(series, ordered) n_reg = series["N"] sizes = look_sizes(n_reg) if look is not None and not (1 <= look <= len(sizes)): raise Malformed("--look %r: N = %d has %d interim looks (sizes %s)" % (look, n_reg, len(sizes), sizes)) used = valid[:sizes[look - 1]] if look is not None else valid[:n_reg] look_reached = look is None or len(valid) >= sizes[look - 1] # interim looks: SLOWER test at level alpha_look on the first `size` valid pairs of every look reached looks = [] stop = None for k, size in enumerate(sizes, 1): if size > len(used): looks.append({"look": k, "pairs": size, "reached": False, "slower": None, "cells": {}}) continue sub = used[:size] cells = {} slower_cells = [] for metric in METRICS: for row in rows: hit = is_slower(metric, cell_logs(sub, metric, row), alpha_look) cells["%s/%s" % (metric, row)] = hit if hit: slower_cells.append("%s/%s" % (metric, row)) entry = {"look": k, "pairs": size, "reached": True, "alpha": alpha_look, "slower": bool(slower_cells), "slower_cells": slower_cells, "cells": cells} looks.append(entry) if slower_cells and stop is None: stop = k # a cell is labelled SLOWER while the series is not final only when the look that flagged it is the point of evaluation (n_used pairs); # a cell flagged by an EARLIER look carries that in slower_at_looks and keeps the SCREENING label (its 95 percent CI says otherwise) stopped_cells = set() flagged_at = {} for entry in looks: if entry["reached"]: for name in entry["slower_cells"]: flagged_at.setdefault(name, []).append(entry["look"]) if entry["pairs"] == len(used): stopped_cells.add(name) fail_events = [p["pair"] for p in ordered if p.get("event") == "FAIL"] owner_events = [p["pair"] for p in ordered if p.get("event") == "OWNER"] final = look is None and len(used) >= n_reg metrics = {} verdicts = {} for metric in METRICS: metrics[metric] = {} for row in rows: ls = cell_logs(used, metric, row) if final: s = summarize(ls, ALPHA_FINAL) verdict = classify(metric, s["ci_lo"], s["ci_hi"]) if "ci_lo" in s else "INCONCLUSIVE" elif ("%s/%s" % (metric, row)) in stopped_cells: verdict = "SLOWER" else: verdict = "SCREENING" cell = build_cell(metric, ls, verdict) if ("%s/%s" % (metric, row)) in flagged_at: cell["slower_at_looks"] = flagged_at["%s/%s" % (metric, row)] if final and verdict in ("INCONCLUSIVE", "TIE"): cell["n_to_resolve"] = n_to_resolve(cell, metric) metrics[metric][row] = cell verdicts[(metric, row)] = verdict reasons = [] if fail_events: verdict = "FAILED" reasons.append("pair(s) %s: event FAIL (ours failure not attributable to infrastructure, E2(5)); the series stops" % fail_events) elif stop is not None: verdict = "FAILED" reasons.append("interim look %d (%d valid pairs, level %g): SLOWER in %s; an early exit is only ever FAILED" % ( stop, sizes[stop - 1], alpha_look, ", ".join(looks[stop - 1]["slower_cells"]))) elif final: slower = sorted("%s/%s" % k for k, v in verdicts.items() if v == "SLOWER") if slower: verdict = "FAILED" reasons.append("SLOWER: " + ", ".join(slower)) elif all(v == "PASS" for v in verdicts.values()): verdict = "MET" else: verdict = "NOT_MET" for (metric, row), v in sorted(verdicts.items()): if v != "PASS": c = metrics[metric][row] extra = ", half-width %.6g, N that would resolve it: %s" % (c.get("half_width", float("nan")), c.get("n_to_resolve", "none")) reasons.append("%s/%s: %s (not a PASS)%s" % (metric, row, v, extra)) else: verdict = "SCREENING" if look is not None: reasons.append("look %d: %d valid pairs present of the %d the look needs (N = %d); screening only, E6" % ( look, len(valid), sizes[look - 1], n_reg) if not look_reached else "look %d (%d valid pairs of N = %d): no SLOWER exit; screening only, E6" % (look, sizes[look - 1], n_reg)) else: reasons.append("%d valid pairs of N = %d: screening only, no verdict (E6)" % (len(used), n_reg)) if owner_events: reasons.append("pair(s) %s: event OWNER, reported to the owner (E2)" % owner_events) invalid = [p for p in ordered if not p["valid"]] result = { "schema": SCHEMA, "machine": series["machine"], "ours_build_id": series.get("ours_build_id"), "cache_state": series.get("cache_state"), "schedule_hash": series.get("schedule_hash"), "N": n_reg, "rows_coincide": bool(series.get("rows_coincide", False)), "rows": rows, "n_valid": len(valid), "n_used": len(used), "n_outside_schedule": max(0, len(valid) - n_reg) if look is None else 0, "n_invalid": len(invalid), "invalid_rate": (float(len(invalid)) / len(ordered)) if ordered else 0.0, "series_verdict": verdict, "reasons": reasons, "look_requested": look, "stopped_at_look": stop, "metrics": metrics, "looks": looks, "order_tables": order_tables(used, rows), "order_tables_l": l_tables(used, rows), "pairs": [{"pair": p["pair"], "valid": p["valid"], "reasons": list(p.get("reasons") or []), "event": p.get("event"), "counted": p in used} for p in ordered], } return result # -------------------------------------------------------------------------------------------------------------------------------- # --blind-sd (E1) # -------------------------------------------------------------------------------------------------------------------------------- def blind_sd(doc): series, rows, valid, ordered = parse_series(doc) check_mixed(series, ordered) if len(valid) < BLIND_PAIRS: raise Malformed("--blind-sd needs %d valid pairs, the series has %d" % (BLIND_PAIRS, len(valid))) first = valid[:BLIND_PAIRS] n_reg = series["N"] sd, mde_now, n_cell = {}, {}, {} worst = 0.0 for metric in METRICS: sd[metric], mde_now[metric], n_cell[metric] = {}, {}, {} for row in rows: s = summarize(cell_logs(first, metric, row), ALPHA_FINAL) sd[metric][row] = s["sd"] mde_now[metric][row] = MDE_FACTOR * s["sd"] / math.sqrt(n_reg) n_cell[metric][row] = required_n(s["sd"], n_reg) worst = max(worst, s["sd"]) return { "schema": SCHEMA, "mode": "blind-sd", "machine": series["machine"], "N": n_reg, "pairs_used": [p["pair"] for p in first], "sd": sd, "mde_at_registered_N": mde_now, "mde_target": MDE_TARGET, "N_required_per_cell": n_cell, "N_recommended": required_n(worst, n_reg), "note": "sample sd (n-1) of the log ratios of the first %d valid pairs; no location statistic is printed (E1)" % BLIND_PAIRS, } # -------------------------------------------------------------------------------------------------------------------------------- # --simulate-null (E8) # -------------------------------------------------------------------------------------------------------------------------------- def _draw(rng, n_reg, phi): if phi <= 0.0: return [rng.gauss(0.0, 1.0) for _ in range(n_reg)] xs = [rng.gauss(0.0, 1.0)] scale = math.sqrt(1.0 - phi * phi) for _ in range(n_reg - 1): xs.append(phi * xs[-1] + scale * rng.gauss(0.0, 1.0)) return xs def _slower_any(xs, sizes, n_reg, alpha_look): """One simulated series at the null boundary (true mean = the rule's threshold, shifted to 0): did a look or the final test say SLOWER?""" for size in sizes: if is_slower("wall_norm", xs[:size], alpha_look): return True return is_slower("wall_norm", xs[:n_reg], ALPHA_FINAL) def false_slower_rate(runs, seed, n_reg, alpha_look, phi): rng = random.Random(seed) sizes = look_sizes(n_reg) hits = 0 for _ in range(runs): if _slower_any(_draw(rng, n_reg, phi), sizes, n_reg, alpha_look): hits += 1 return hits / float(runs) def simulate_null(doc, runs, seed, alpha_look=ALPHA_LOOK_TABLE): series, rows, valid, ordered = parse_series(doc) check_mixed(series, ordered) n_reg = series["N"] if runs < 1: raise Malformed("--runs must be >= 1") # AR(1) stress null: the mean lag-1 r of the series' own cells (clamped), so the n_eff correction is exercised r_obs = [] for metric in METRICS: for row in rows: ls = cell_logs(valid[:n_reg], metric, row) if len(ls) >= 3: r_obs.append(summarize(ls)["r1"]) phi = min(0.9, max(0.0, math.fsum(r_obs) / len(r_obs))) if r_obs else 0.0 rate_iid = false_slower_rate(runs, seed, n_reg, alpha_look, 0.0) rate_ar1 = false_slower_rate(runs, seed + 1, n_reg, alpha_look, phi) if phi > 0.0 else rate_iid rate = max(rate_iid, rate_ar1) out = { "schema": SCHEMA, "mode": "simulate-null", "runs": runs, "seed": seed, "N": n_reg, "look_sizes": look_sizes(n_reg), "alpha_look_table": ALPHA_LOOK_TABLE, "alpha_look_used": alpha_look, "alpha_final": ALPHA_FINAL, "ar1_phi_stress": phi, "false_slower_rate_iid": rate_iid, "false_slower_rate_ar1": rate_ar1, "false_slower_rate": rate, "max_false_slower_rate": MAX_FALSE_SLOWER_RATE, "critical_level_replaced": False, "scope": "one (metric,row) cell at its null boundary, interim looks included; a series has %d cells" % (3 * len(rows)), } if rate > MAX_FALSE_SLOWER_RATE: lo, hi = 1e-5, alpha_look for _ in range(14): mid = 0.5 * (lo + hi) r = max(false_slower_rate(runs, seed, n_reg, mid, 0.0), false_slower_rate(runs, seed + 1, n_reg, mid, phi) if phi > 0 else 0.0) if r > MAX_FALSE_SLOWER_RATE: hi = mid else: lo = mid out["critical_level_replaced"] = True out["simulated_alpha_look"] = lo out["false_slower_rate_at_simulated_level"] = max( false_slower_rate(runs, seed, n_reg, lo, 0.0), false_slower_rate(runs, seed + 1, n_reg, lo, phi) if phi > 0 else 0.0) return out # -------------------------------------------------------------------------------------------------------------------------------- # command line # -------------------------------------------------------------------------------------------------------------------------------- class _Parser(argparse.ArgumentParser): def error(self, message): # argparse exits 2 by default; 2 is the REFUSED code of this interface sys.stderr.write("%s: error: %s\n" % (self.prog, message)) raise SystemExit(3) def _emit(result, out_path): text = json.dumps(result, indent=2, allow_nan=False) + "\n" sys.stdout.write(text) if out_path: with open(out_path, "w", encoding="utf-8", newline="\n") as fh: fh.write(text) def main(argv=None): parser = _Parser(prog="series_eval.py", description="Series evaluator (STRA-290)") parser.add_argument("series", help="series.json") parser.add_argument("--look", type=int, default=None, help="evaluate the interim SLOWER test of look K (1-based) on the valid pairs present") parser.add_argument("--blind-sd", action="store_true", help="print only the sd of the first 6 valid pairs (E1)") parser.add_argument("--simulate-null", action="store_true", help="null simulation of the looks (E8)") parser.add_argument("--runs", type=int, default=20000) parser.add_argument("--seed", type=int, default=1) parser.add_argument("--look-alpha", type=float, default=ALPHA_LOOK_TABLE, help="two-sided level of the interim looks (default: Pocock 0.0221)") parser.add_argument("--out", help="also write the JSON result here (run roots outside Git)") args = parser.parse_args(argv) try: if not (0.0 < args.look_alpha < 1.0): raise Malformed("--look-alpha must be in (0, 1)") doc = load_series(args.series) if args.blind_sd: result = blind_sd(doc) elif args.simulate_null: result = simulate_null(doc, args.runs, args.seed, args.look_alpha) else: result = evaluate(doc, args.look, args.look_alpha) _emit(result, args.out) return 0 except Refused as exc: sys.stderr.write("%s\n" % exc) sys.stdout.write(json.dumps({"schema": SCHEMA, "series_verdict": "REFUSED", "field": exc.field, "message": str(exc)}) + "\n") return 2 except Malformed as exc: sys.stderr.write("MALFORMED INPUT: %s\n" % exc) return 3 if __name__ == "__main__": sys.exit(main())