Merge claude/stra-290 into train-a (STRA-245)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,145 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Turns a directory of END_TO_END records (STRA-246 schema v1) into the series.json that series_eval.py reads (STRA-290).
|
||||
|
||||
The validity of every pair (E2) is decided by validity.py (STRA-312) and only imported here; this file derives nothing about validity. It adds
|
||||
the three aggregates of E7(d) per arm, the arm position / predecessor of E1, and the per-pair build id and cache state that series_eval.py
|
||||
checks for mixing (E1, E6).
|
||||
|
||||
Stdlib only, Python >= 3.9. Offline. Writes nothing unless --out is given (run roots live outside Git).
|
||||
|
||||
records_to_series.py --records <dir> --schedule <schedule.json> --ledger <ledger.jsonl> --machine laptop|server
|
||||
[--n N] [--rows-coincide] [--out series.json]
|
||||
|
||||
Metrics per arm (E7 d): wall_norm = metrics.wall_norm_s; ttft_sum = sum of the per-turn ttft_s; decode_tps = total output tokens / total decode
|
||||
time, decode time of a turn = wall_s - ttft_s (never a mean of per-turn rates).
|
||||
N defaults to schedule.n_pairs and can be raised with --n (E1: N is raised, never lowered). rows_coincide is true when --rows-coincide is given,
|
||||
when the schedule says so, or when the schedule's arms have no vanilla_noskip (two-arm blocks, E4 applies once).
|
||||
Exit codes are those of validity.py: 0 result produced, 2 ledger/manifest refusal, 3 malformed input.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
if HERE not in sys.path:
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
import validity # noqa: E402 (STRA-312; imported, never re-derived)
|
||||
|
||||
Malformed = validity.Malformed
|
||||
|
||||
|
||||
def build_id_string(rec):
|
||||
"""One comparable string for the frozen build id (commit, target triple, feature set, shipped profile hash)."""
|
||||
b = rec.get("ours_build_id_frozen")
|
||||
if not isinstance(b, dict):
|
||||
return None
|
||||
try:
|
||||
return "%s|%s|%s|%s" % (b["commit"], b["target_triple"], "+".join(sorted(b["cargo_features"])), b["profile_value_sha256"][:16])
|
||||
except (KeyError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def record_metrics(rec, run_id):
|
||||
m = rec.get("metrics")
|
||||
if not isinstance(m, dict) or not isinstance(m.get("turns"), list) or not m["turns"]:
|
||||
raise Malformed("record %s has no metrics.turns" % run_id)
|
||||
try:
|
||||
wall_norm = float(m["wall_norm_s"])
|
||||
ttft_sum = sum(float(t["ttft_s"]) for t in m["turns"])
|
||||
decode_time = sum(float(t["wall_s"]) - float(t["ttft_s"]) for t in m["turns"])
|
||||
tokens = sum(int(t["output_tokens"]) for t in m["turns"])
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise Malformed("record %s: metrics incomplete (%s)" % (run_id, exc))
|
||||
if wall_norm <= 0 or ttft_sum <= 0 or decode_time <= 0 or tokens <= 0:
|
||||
raise Malformed("record %s: wall_norm, TTFT sum, decode time and output tokens must be positive" % run_id)
|
||||
return {"wall_norm": wall_norm, "ttft_sum": ttft_sum, "decode_tps": tokens / decode_time}
|
||||
|
||||
|
||||
def build_series(records, sched, last, machine, n_override=None, rows_coincide=False):
|
||||
derived = validity.derive_pairs(records, sched, last, machine)
|
||||
by_number = {}
|
||||
for rid, line in last.items():
|
||||
if rid in records:
|
||||
by_number.setdefault(validity._pair_number(line), {})[line.get("arm")] = (rid, records[rid])
|
||||
n_reg = n_override if n_override is not None else sched.get("n_pairs")
|
||||
if not isinstance(n_reg, int) or isinstance(n_reg, bool) or n_reg < 2:
|
||||
raise Malformed("N must be an integer >= 2 (schedule.n_pairs or --n)")
|
||||
arms = list(sched["arms"])
|
||||
coincide = bool(rows_coincide or sched.get("rows_coincide") is True or "vanilla_noskip" not in arms)
|
||||
pairs = []
|
||||
for p in derived["pairs"]:
|
||||
recs = by_number.get(p["pair"], {})
|
||||
entry = {"pair": p["pair"], "valid": p["valid"], "reasons": p["reasons"], "event": p["event"]}
|
||||
ours = recs.get("ours")
|
||||
ids = [build_id_string(r) for _, r in ([ours] if ours else [])]
|
||||
if ids and ids[0] is not None:
|
||||
entry["ours_build_id"] = ids[0]
|
||||
states = sorted(set(str((r.get("cache") or {}).get("state")) for _, r in recs.values()))
|
||||
if states:
|
||||
entry["cache_state"] = "|".join(states) # an arm with another state makes the pair a mixed one: series_eval.py refuses it
|
||||
arm_ids = [(arm, r.get("arm_identity") or {}) for arm, (_, r) in sorted(recs.items())]
|
||||
entry["position"] = dict((a, i["position"]) for a, i in arm_ids if "position" in i)
|
||||
entry["predecessor"] = dict((a, (None if i.get("predecessor_arm") in (None, "none") else i["predecessor_arm"]))
|
||||
for a, i in arm_ids if "predecessor_arm" in i)
|
||||
entry["arms"] = {}
|
||||
for arm, (rid, rec) in sorted(recs.items()):
|
||||
try:
|
||||
entry["arms"][arm] = record_metrics(rec, rid)
|
||||
except Malformed:
|
||||
if p["valid"]:
|
||||
raise
|
||||
pairs.append(entry)
|
||||
states = sorted(set(e["cache_state"] for e in pairs if "cache_state" in e))
|
||||
builds = sorted(set(e["ours_build_id"] for e in pairs if "ours_build_id" in e))
|
||||
return {
|
||||
"machine": machine,
|
||||
"ours_build_id": builds[0] if len(builds) == 1 else None,
|
||||
"cache_state": states[0] if len(states) == 1 else None,
|
||||
"schedule_hash": validity.schedule_hash(sched),
|
||||
"N": n_reg,
|
||||
"rows_coincide": coincide,
|
||||
"invalid_rate": derived["invalid_rate"],
|
||||
"pairs": pairs,
|
||||
}
|
||||
|
||||
|
||||
class _Parser(argparse.ArgumentParser):
|
||||
def error(self, message):
|
||||
sys.stderr.write("%s: error: %s\n" % (self.prog, message))
|
||||
raise SystemExit(3)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = _Parser(prog="records_to_series.py", description="records directory -> series.json (STRA-290)")
|
||||
parser.add_argument("--records", required=True)
|
||||
parser.add_argument("--schedule", required=True)
|
||||
parser.add_argument("--ledger", required=True)
|
||||
parser.add_argument("--machine", required=True, choices=["laptop", "server"])
|
||||
parser.add_argument("--n", type=int, default=None, help="N valid pairs of the series (default: schedule n_pairs)")
|
||||
parser.add_argument("--rows-coincide", action="store_true")
|
||||
parser.add_argument("--out", help="also write series.json here (run roots outside Git)")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
sched = validity._load_json(args.schedule, "schedule")
|
||||
records = validity.read_records(args.records)
|
||||
last, _ = validity.read_ledger(args.ledger)
|
||||
series = build_series(records, sched, last, args.machine, args.n, args.rows_coincide)
|
||||
text = json.dumps(series, indent=2, allow_nan=False) + "\n"
|
||||
sys.stdout.write(text)
|
||||
if args.out:
|
||||
with open(args.out, "w", encoding="utf-8", newline="\n") as fh:
|
||||
fh.write(text)
|
||||
return 0
|
||||
except validity.Refusal as exc:
|
||||
sys.stderr.write("REFUSED (ledger/manifest): %s\n" % exc)
|
||||
sys.stdout.write(json.dumps({"manifest_ok": False, "run_ids": exc.names}) + "\n")
|
||||
return 2
|
||||
except Malformed as exc:
|
||||
sys.stderr.write("MALFORMED INPUT: %s\n" % exc)
|
||||
return 3
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,786 @@
|
||||
#!/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 <series.json> [--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<n}(l_i - m)(l_{i+1} - m) / sum_i (l_i - m)^2 (0 when the spread is 0).
|
||||
n_eff n (1 - r1) / (1 + r1) when r1 > 0, else n. dof = max(1, floor(n_eff - 1)) when r1 > 0, else n - 1.
|
||||
CI mean +- t(1 - alpha/2, dof) * sd / sqrt(n_eff); 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())
|
||||
@@ -0,0 +1,714 @@
|
||||
"""Tests of series_eval.py and records_to_series.py (STRA-290, S0.10): statistics, verdict classes, interim looks, SCREENING, refusal,
|
||||
--blind-sd, --simulate-null and the acceptance commands AC2-AC6 of the leaf.
|
||||
|
||||
Run: python -m unittest scripts.e2e.evidence.test_series_eval_golden scripts.e2e.evidence.test_series_eval -v (from the repository root)
|
||||
Stdlib only, Python >= 3.9. The golden cases (test_series_eval_golden.py, STRA-310) are NOT edited here. The expected values below are
|
||||
published t tables, closed forms, or hand arithmetic; none comes from series_eval.py.
|
||||
"""
|
||||
import importlib.util
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
|
||||
GOLDEN = os.path.join(HERE, "golden")
|
||||
SERIES_EVAL = os.path.join(HERE, "series_eval.py")
|
||||
RECORDS_TO_SERIES = os.path.join(HERE, "records_to_series.py")
|
||||
|
||||
|
||||
def _load(name, path):
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[name] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
S = _load("series_eval_under_test", SERIES_EVAL)
|
||||
G = _load("gen_validity_for_series_test", os.path.join(GOLDEN, "gen_validity.py"))
|
||||
with open(os.path.join(GOLDEN, "validity_cases.json"), "r", encoding="utf-8") as _fh:
|
||||
VDOC = json.load(_fh)
|
||||
|
||||
BUILD = "test-build-A"
|
||||
CACHE = "WARM-OS/EMPTY-ENGINE"
|
||||
THREE = ("ours", "vanilla_default", "vanilla_noskip")
|
||||
|
||||
|
||||
def run(script, *args):
|
||||
proc = subprocess.run([sys.executable, script] + [str(a) for a in args], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
universal_newlines=True, cwd=REPO, timeout=300)
|
||||
return proc.returncode, proc.stdout, proc.stderr
|
||||
|
||||
|
||||
def make_series(l_wall, l_ttft=None, l_dec=None, n_reg=None, rows_coincide=False, valid=None, extra=None):
|
||||
"""A series whose log ratios are exactly the given lists (ours = 1.0 s, vanilla = exp(l) for time metrics, ours = exp(l) for rates)."""
|
||||
l_ttft = l_ttft if l_ttft is not None else l_wall
|
||||
l_dec = l_dec if l_dec is not None else l_wall
|
||||
pairs = []
|
||||
for i, (a, b, c) in enumerate(zip(l_wall, l_ttft, l_dec), 1):
|
||||
arms = {"ours": {"wall_norm": 100.0, "ttft_sum": 50.0, "decode_tps": 100.0}}
|
||||
for row in (("vanilla_default",) if rows_coincide else ("vanilla_default", "vanilla_noskip")):
|
||||
arms[row] = {"wall_norm": 100.0 * math.exp(a), "ttft_sum": 50.0 * math.exp(b), "decode_tps": 100.0 / math.exp(c)}
|
||||
pairs.append({"pair": i, "valid": True if valid is None else valid[i - 1], "reasons": [], "ours_build_id": BUILD, "cache_state": CACHE,
|
||||
"position": dict((a_, 1 + k) for k, a_ in enumerate(THREE[:2] if rows_coincide else THREE)),
|
||||
"predecessor": {"ours": None, "vanilla_default": "ours", "vanilla_noskip": "vanilla_default"}, "arms": arms})
|
||||
doc = {"machine": "server", "ours_build_id": BUILD, "cache_state": CACHE, "schedule_hash": "test-schedule",
|
||||
"N": n_reg or len(l_wall), "rows_coincide": rows_coincide, "pairs": pairs}
|
||||
if extra:
|
||||
doc.update(extra)
|
||||
return doc
|
||||
|
||||
|
||||
def noisy(n, mean, sd, seed):
|
||||
rng = random.Random(seed)
|
||||
return [rng.gauss(mean, sd) for _ in range(n)]
|
||||
|
||||
|
||||
class Cli(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
|
||||
def write(self, doc, name="series.json"):
|
||||
path = os.path.join(self.tmp.name, name)
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
fh.write(doc if isinstance(doc, str) else json.dumps(doc))
|
||||
return path
|
||||
|
||||
def eval(self, doc, *args):
|
||||
rc, out, err = run(SERIES_EVAL, self.write(doc), *args)
|
||||
return rc, out, err
|
||||
|
||||
|
||||
class Statistics(unittest.TestCase):
|
||||
def test_t_quantile_published_table(self):
|
||||
# t(p, df) from the standard table, 4 decimals
|
||||
table = [(1, 0.975, 12.7062), (2, 0.975, 4.3027), (3, 0.975, 3.1824), (4, 0.975, 2.7764), (5, 0.975, 2.5706),
|
||||
(10, 0.975, 2.2281), (11, 0.975, 2.2010), (29, 0.975, 2.0452), (30, 0.975, 2.0423), (60, 0.975, 2.0003),
|
||||
(120, 0.975, 1.9799), (10, 0.995, 3.1693), (29, 0.995, 2.7564), (11, 0.99, 2.7181), (29, 0.95, 1.6991)]
|
||||
for dof, p, want in table:
|
||||
self.assertAlmostEqual(S.t_quantile(p, dof), want, delta=6e-5, msg="t(%s, %s)" % (p, dof))
|
||||
|
||||
def test_t_quantile_closed_forms(self):
|
||||
for q in (0.0221 / 2, 0.0158 / 2, 0.025):
|
||||
self.assertAlmostEqual(S.t_crit(2 * q, 1), math.tan(math.pi * (0.5 - q)), places=12)
|
||||
self.assertAlmostEqual(S.t_crit(2 * q, 2), (1 - 2 * q) / math.sqrt(2 * q * (1 - q)), places=12)
|
||||
|
||||
def test_t_quantile_round_trip_and_monotone(self):
|
||||
for dof in (3, 7, 11, 29, 59):
|
||||
for alpha in (0.05, 0.0221, 0.0158):
|
||||
self.assertAlmostEqual(S.t_upper_tail(S.t_crit(alpha, dof), dof), alpha / 2, places=13)
|
||||
self.assertGreater(S.t_crit(0.0221, 11), S.t_crit(0.05, 11))
|
||||
self.assertGreater(S.t_crit(0.05, 5), S.t_crit(0.05, 6))
|
||||
self.assertAlmostEqual(S.t_crit(0.0221, 11), 2.66219, delta=2e-5) # value used by the golden basis text (integrated CDF)
|
||||
|
||||
def test_t_quantile_rejects_bad_arguments(self):
|
||||
for args in ((0.4, 5), (1.0, 5), (0.975, 0)):
|
||||
self.assertRaises(ValueError, S.t_quantile, *args)
|
||||
|
||||
def test_summarize_hand_computed(self):
|
||||
s = S.summarize([1.0, 2.0, 3.0, 4.0, 5.0])
|
||||
self.assertEqual(s["n"], 5)
|
||||
self.assertAlmostEqual(s["mean_l"], 3.0, places=14)
|
||||
self.assertAlmostEqual(s["sd"], math.sqrt(2.5), places=14)
|
||||
self.assertAlmostEqual(s["r1"], 0.4, places=14) # (2 + 0 + 0 + 2) / 10
|
||||
self.assertAlmostEqual(s["n_eff"], 5 * 0.6 / 1.4, places=12)
|
||||
self.assertEqual(s["dof"], 1) # floor(2.1428 - 1) = 1
|
||||
self.assertAlmostEqual(s["ci_lo"], 3.0 - 12.7062 * math.sqrt(2.5) / math.sqrt(5 * 0.6 / 1.4), delta=2e-4)
|
||||
self.assertAlmostEqual(s["mde"], 2.8 * math.sqrt(2.5) / math.sqrt(5), places=12)
|
||||
|
||||
def test_no_correction_when_r_not_positive(self):
|
||||
s = S.summarize([1.0, -1.0, 1.0, -1.0, 1.0, -1.0])
|
||||
self.assertLess(s["r1"], 0)
|
||||
self.assertEqual(s["n_eff"], 6.0)
|
||||
self.assertEqual(s["dof"], 5)
|
||||
|
||||
def test_constant_series_has_zero_spread_and_exact_bounds(self):
|
||||
s = S.summarize([math.log(0.99)] * 30)
|
||||
self.assertEqual(s["sd"], 0.0)
|
||||
self.assertEqual(s["ci_lo"], s["ci_hi"])
|
||||
self.assertEqual(s["mean_l"], math.log(0.99))
|
||||
|
||||
def test_short_inputs(self):
|
||||
self.assertEqual(S.summarize([]), {"n": 0})
|
||||
self.assertEqual(sorted(S.summarize([0.1])), ["mean_l", "n"])
|
||||
|
||||
def test_percent_and_log_ratio_directions(self):
|
||||
self.assertAlmostEqual(S.percent(math.log(1.05)), 5.0, places=12)
|
||||
self.assertAlmostEqual(S.log_ratio("wall_norm", 90.0, 100.0), math.log(100 / 90.0), places=15)
|
||||
self.assertAlmostEqual(S.log_ratio("ttft_sum", 90.0, 100.0), math.log(100 / 90.0), places=15)
|
||||
self.assertAlmostEqual(S.log_ratio("decode_tps", 110.0, 100.0), math.log(1.1), places=15)
|
||||
|
||||
def test_classify_strict(self):
|
||||
c = lambda lo, hi: S.classify("wall_norm", lo, hi)
|
||||
self.assertEqual(c(0.001, 0.02), "PASS")
|
||||
self.assertEqual(c(0.0, 0.02), "INCONCLUSIVE") # a bound exactly on 0 is not > 0 (and 0.02 leaves the 1 percent band)
|
||||
self.assertEqual(c(0.0, 0.0), "TIE")
|
||||
self.assertEqual(c(-0.005, 0.005), "TIE")
|
||||
self.assertEqual(c(-0.02, 0.005), "INCONCLUSIVE")
|
||||
self.assertEqual(c(-0.03, -0.001), "SLOWER")
|
||||
self.assertEqual(c(-0.02, 0.0), "INCONCLUSIVE") # upper bound exactly on 0 is not < 0
|
||||
self.assertEqual(c(-0.0100, 0.0099), "TIE") # inside [ln 0.99, ln 1.01]
|
||||
self.assertEqual(c(-0.0102, 0.005), "INCONCLUSIVE")
|
||||
|
||||
def test_classify_non_negative(self):
|
||||
c = lambda m, lo, hi: S.classify(m, lo, hi)
|
||||
ln099 = math.log(0.99)
|
||||
for metric in ("ttft_sum", "decode_tps"):
|
||||
self.assertEqual(c(metric, ln099 + 1e-6, 0.05), "PASS")
|
||||
self.assertEqual(c(metric, ln099, 0.05), "INCONCLUSIVE")
|
||||
self.assertEqual(c(metric, -0.001, 0.001), "PASS") # no TIE class for this rule
|
||||
self.assertEqual(c(metric, -0.05, ln099 - 1e-6), "SLOWER")
|
||||
self.assertEqual(c(metric, -0.05, ln099), "INCONCLUSIVE")
|
||||
self.assertEqual(c(metric, -0.05, 0.0), "INCONCLUSIVE")
|
||||
|
||||
def test_sign_test_exact(self):
|
||||
s = S.sign_test([1, 1, 1, 1, 1, -1, 0])
|
||||
self.assertEqual((s["n_pos"], s["n_neg"], s["n_zero"]), (5, 1, 1))
|
||||
self.assertAlmostEqual(s["p_two_sided"], 2 * (1 + 6) / 64.0, places=14)
|
||||
self.assertEqual(S.sign_test([0, 0])["p_two_sided"], 1.0)
|
||||
self.assertEqual(S.sign_test([1] * 10)["p_two_sided"], 2.0 / 1024)
|
||||
|
||||
def test_wilcoxon_exact_and_normal(self):
|
||||
w = S.wilcoxon([1, 2, 3, 4, 5, -6]) # ranks 1..6, W+ = 15, W- = 6; 14 of 64 subset sums are <= 6
|
||||
self.assertEqual(w["method"], "exact")
|
||||
self.assertAlmostEqual(w["p_two_sided"], 2 * 14 / 64.0, places=14)
|
||||
t = S.wilcoxon([1, 1, 2, 2, 3, -3])
|
||||
self.assertEqual(t["method"], "normal_approximation")
|
||||
self.assertTrue(0.0 < t["p_two_sided"] <= 1.0)
|
||||
self.assertEqual(S.wilcoxon([0.0, 0.0])["n"], 0)
|
||||
|
||||
def test_percentile(self):
|
||||
xs = [1.0, 2.0, 3.0, 4.0]
|
||||
self.assertEqual(S.percentile(xs, 0.5), 2.5)
|
||||
self.assertEqual(S.percentile(xs, 0.0), 1.0)
|
||||
self.assertEqual(S.percentile(xs, 1.0), 4.0)
|
||||
|
||||
def test_look_sizes(self):
|
||||
self.assertEqual(S.look_sizes(30), [12, 24])
|
||||
self.assertEqual(S.look_sizes(36), [12, 24])
|
||||
self.assertEqual(S.look_sizes(60), [24, 48])
|
||||
self.assertEqual(S.look_sizes(6), [])
|
||||
|
||||
def test_required_n_raised_never_lowered(self):
|
||||
self.assertEqual(S.required_n(0.0202807, 30), 36) # (2.8 * 0.0202807 / 0.01)^2 = 32.2 -> 36
|
||||
self.assertEqual(S.required_n(0.001, 30), 30)
|
||||
self.assertEqual(S.required_n(0.0, 30), 30)
|
||||
self.assertEqual(S.required_n(0.1, 30) % 6, 0)
|
||||
|
||||
def test_n_to_resolve(self):
|
||||
s = S.summarize(noisy(30, 0.004, 0.02, 3))
|
||||
n = S.n_to_resolve(s, "wall_norm")
|
||||
self.assertIsNotNone(n)
|
||||
self.assertEqual(n % 6, 0)
|
||||
self.assertGreater(n, 30)
|
||||
self.assertIsNone(S.n_to_resolve(S.summarize([-0.01, 0.0, -0.02, 0.01]), "wall_norm"))
|
||||
|
||||
|
||||
class Verdicts(Cli):
|
||||
def test_ac2_all_zero_strict_tie_nonneg_pass(self):
|
||||
rc, out, err = self.eval(make_series([0.0] * 30))
|
||||
self.assertEqual(rc, 0, err)
|
||||
d = json.loads(out)
|
||||
for row in ("vanilla_default", "vanilla_noskip"):
|
||||
self.assertEqual(d["metrics"]["wall_norm"][row]["verdict"], "TIE")
|
||||
self.assertEqual(d["metrics"]["ttft_sum"][row]["verdict"], "PASS")
|
||||
self.assertEqual(d["metrics"]["decode_tps"][row]["verdict"], "PASS")
|
||||
self.assertEqual(d["series_verdict"], "NOT_MET")
|
||||
self.assertTrue(any("TIE" in r for r in d["reasons"]))
|
||||
|
||||
def test_clear_pass_is_met(self):
|
||||
l = noisy(30, 0.05, 0.01, 1)
|
||||
rc, out, err = self.eval(make_series(l, noisy(30, 0.04, 0.01, 2), noisy(30, 0.03, 0.01, 3)))
|
||||
d = json.loads(out)
|
||||
self.assertEqual(d["series_verdict"], "MET")
|
||||
self.assertEqual(d["metrics"]["wall_norm"]["vanilla_default"]["n"], 30)
|
||||
|
||||
def test_any_margin_counts_and_no_every_pair_condition(self):
|
||||
# a 0.3 percent mean gain with tiny noise is a PASS of the strict rule although several pairs are <= 0
|
||||
l = [0.003 + (0.0004 if i % 2 else -0.0004) for i in range(30)]
|
||||
l[5] = -0.0001
|
||||
d = json.loads(self.eval(make_series(l))[1])
|
||||
self.assertEqual(d["metrics"]["wall_norm"]["vanilla_default"]["verdict"], "PASS")
|
||||
self.assertGreaterEqual(d["metrics"]["wall_norm"]["vanilla_default"]["count_le0"], 1)
|
||||
self.assertEqual(d["series_verdict"], "MET")
|
||||
|
||||
def test_slower_row_fails_the_series_even_if_the_other_row_passes(self):
|
||||
doc = make_series([0.05] * 30)
|
||||
for p in doc["pairs"]:
|
||||
p["arms"]["vanilla_noskip"]["wall_norm"] = 100.0 * math.exp(-0.05) # ours slower than the no-skip row
|
||||
rc, out, _ = self.eval(doc)
|
||||
d = json.loads(out)
|
||||
self.assertEqual(d["metrics"]["wall_norm"]["vanilla_default"]["verdict"], "PASS")
|
||||
self.assertEqual(d["metrics"]["wall_norm"]["vanilla_noskip"]["verdict"], "SLOWER")
|
||||
self.assertEqual(d["series_verdict"], "FAILED")
|
||||
|
||||
def test_inconclusive_reports_half_width_and_n(self):
|
||||
d = json.loads(self.eval(make_series(noisy(30, 0.004, 0.03, 4)))[1])
|
||||
cell = d["metrics"]["wall_norm"]["vanilla_default"]
|
||||
self.assertEqual(cell["verdict"], "INCONCLUSIVE")
|
||||
self.assertGreater(cell["half_width"], 0)
|
||||
self.assertIn("n_to_resolve", cell)
|
||||
self.assertEqual(d["series_verdict"], "NOT_MET")
|
||||
self.assertTrue(any("half-width" in r for r in d["reasons"]))
|
||||
|
||||
def test_extra_valid_pairs_beyond_n_are_not_added(self):
|
||||
l = [0.05] * 33
|
||||
l[31] = -5.0 # would ruin the verdict if it were counted
|
||||
rc, out, _ = self.eval(make_series(l, n_reg=30))
|
||||
d = json.loads(out)
|
||||
self.assertEqual(d["n_used"], 30)
|
||||
self.assertEqual(d["n_outside_schedule"], 3)
|
||||
self.assertEqual(d["metrics"]["wall_norm"]["vanilla_default"]["n"], 30)
|
||||
self.assertEqual(sum(1 for p in d["pairs"] if p["counted"]), 30)
|
||||
|
||||
def test_invalid_pairs_are_listed_with_reasons_and_not_counted(self):
|
||||
doc = make_series([0.05] * 33, valid=[True] * 4 + [False] + [True] * 28, n_reg=30)
|
||||
doc["pairs"][4]["reasons"] = ["POWER"]
|
||||
d = json.loads(self.eval(doc)[1])
|
||||
self.assertEqual(d["n_valid"], 32)
|
||||
self.assertEqual(d["n_invalid"], 1)
|
||||
self.assertAlmostEqual(d["invalid_rate"], 1 / 33.0)
|
||||
bad = [p for p in d["pairs"] if not p["valid"]]
|
||||
self.assertEqual(bad[0]["reasons"], ["POWER"])
|
||||
self.assertFalse(bad[0]["counted"])
|
||||
|
||||
def test_fail_event_stops_the_series_failed(self):
|
||||
doc = make_series([0.05] * 30)
|
||||
doc["pairs"][9]["event"] = "FAIL"
|
||||
d = json.loads(self.eval(doc)[1])
|
||||
self.assertEqual(d["series_verdict"], "FAILED")
|
||||
self.assertTrue(any("FAIL" in r for r in d["reasons"]))
|
||||
|
||||
def test_direction_of_each_metric(self):
|
||||
# ours better on decode, worse on TTFT only
|
||||
d = json.loads(self.eval(make_series([0.05] * 30, [-0.05] * 30, [0.05] * 30))[1])
|
||||
self.assertEqual(d["metrics"]["ttft_sum"]["vanilla_default"]["verdict"], "SLOWER")
|
||||
self.assertEqual(d["metrics"]["decode_tps"]["vanilla_default"]["verdict"], "PASS")
|
||||
self.assertLess(d["metrics"]["ttft_sum"]["vanilla_default"]["mean_l"], 0)
|
||||
|
||||
def test_autocorrelation_widens_the_interval(self):
|
||||
rng = random.Random(9)
|
||||
x, l = 0.0, []
|
||||
for _ in range(30):
|
||||
x = 0.7 * x + rng.gauss(0, 0.01)
|
||||
l.append(0.004 + x)
|
||||
s = S.summarize(l)
|
||||
self.assertGreater(s["r1"], 0)
|
||||
plain = s["t"] and S.t_crit(0.05, 29) * s["sd"] / math.sqrt(30)
|
||||
self.assertGreater(s["half_width"], plain)
|
||||
|
||||
def test_percent_fields(self):
|
||||
d = json.loads(self.eval(make_series([math.log(1.05)] * 30))[1])
|
||||
c = d["metrics"]["wall_norm"]["vanilla_default"]
|
||||
self.assertAlmostEqual(c["mean_pct"], 5.0, places=9)
|
||||
self.assertAlmostEqual(c["ci_lo_pct"], 5.0, places=9)
|
||||
|
||||
|
||||
class Looks(Cli):
|
||||
def slower_then_better(self):
|
||||
return [-0.10 + 0.002 * (i % 3) for i in range(12)] + [0.20 + 0.002 * (i % 3) for i in range(18)]
|
||||
|
||||
def test_early_look_slower_ends_the_series_failed(self):
|
||||
d = json.loads(self.eval(make_series(self.slower_then_better()))[1])
|
||||
self.assertEqual(d["series_verdict"], "FAILED")
|
||||
self.assertEqual(d["stopped_at_look"], 1)
|
||||
self.assertTrue(d["looks"][0]["slower"])
|
||||
self.assertTrue(any("interim look 1" in r for r in d["reasons"]))
|
||||
|
||||
def test_look_never_ends_a_series_as_pass(self):
|
||||
rc, out, _ = self.eval(make_series([0.2 + 0.001 * (i % 4) for i in range(12)], n_reg=30), "--look", 1)
|
||||
d = json.loads(out)
|
||||
self.assertEqual(d["series_verdict"], "SCREENING")
|
||||
self.assertEqual(len(d["pairs"]), 12)
|
||||
for token in ("PASS", "TIE"):
|
||||
self.assertNotIn(token, out)
|
||||
|
||||
def test_look_uses_the_pocock_level_not_the_95_percent_level(self):
|
||||
# mean/se between t(0.975, 11) = 2.201 and t(0.98895, 11) = 2.662: SLOWER at 95 percent, not at 0.0221
|
||||
l = [-0.0210581571426498 + 0.03 * (1 if i % 2 else -1) * 0.9 for i in range(12)]
|
||||
s95 = S.summarize(l, 0.05)
|
||||
s022 = S.summarize(l, 0.0221)
|
||||
if not (s95["ci_hi"] < 0 <= s022["ci_hi"]): # tune the offset rather than trust the constant
|
||||
m = s95["sd"] / math.sqrt(12)
|
||||
l = [x - s022["mean_l"] - 2.4 * m for x in l]
|
||||
s95, s022 = S.summarize(l, 0.05), S.summarize(l, 0.0221)
|
||||
self.assertLess(s95["ci_hi"], 0)
|
||||
self.assertGreaterEqual(s022["ci_hi"], 0)
|
||||
d = json.loads(self.eval(make_series(l, n_reg=30), "--look", 1)[1])
|
||||
self.assertEqual(d["series_verdict"], "SCREENING")
|
||||
|
||||
def test_look_argument_out_of_range_is_malformed(self):
|
||||
for k in (0, 3, -1):
|
||||
rc, out, err = self.eval(make_series([0.05] * 30), "--look", k)
|
||||
self.assertEqual(rc, 3, err)
|
||||
|
||||
def test_look_not_reached_is_screening(self):
|
||||
rc, out, _ = self.eval(make_series([-0.3] * 6, n_reg=30), "--look", 1)
|
||||
d = json.loads(out)
|
||||
self.assertEqual(rc, 0)
|
||||
self.assertEqual(d["series_verdict"], "SCREENING")
|
||||
self.assertFalse(d["looks"][0]["reached"])
|
||||
|
||||
|
||||
class Screening(Cli):
|
||||
def test_ac4_n29_is_screening_without_pass_token(self):
|
||||
l = noisy(29, 0.05, 0.01, 5)
|
||||
rc, out, err = self.eval(make_series(l, n_reg=30))
|
||||
self.assertEqual(rc, 0, err)
|
||||
d = json.loads(out)
|
||||
self.assertEqual(d["series_verdict"], "SCREENING")
|
||||
self.assertEqual(sum(1 for line in out.splitlines() if "PASS" in line), 0) # `| grep -c PASS` prints 0
|
||||
cell = d["metrics"]["wall_norm"]["vanilla_default"]
|
||||
self.assertEqual(cell["n"], 29)
|
||||
self.assertEqual(cell["verdict"], "SCREENING")
|
||||
self.assertIn("ci_lo", cell)
|
||||
self.assertIn("mean_l", cell)
|
||||
|
||||
def test_screening_is_not_a_pass_even_when_every_pair_is_better(self):
|
||||
out = self.eval(make_series([0.3] * 5, n_reg=30))[1]
|
||||
self.assertNotIn("PASS", out)
|
||||
self.assertNotIn("MET", json.loads(out)["series_verdict"].replace("NOT_MET", ""))
|
||||
|
||||
def test_empty_series_is_screening(self):
|
||||
d = json.loads(self.eval(make_series([], n_reg=30))[1])
|
||||
self.assertEqual(d["series_verdict"], "SCREENING")
|
||||
self.assertEqual(d["metrics"]["wall_norm"]["vanilla_default"]["n"], 0)
|
||||
|
||||
|
||||
class Refusal(Cli):
|
||||
def test_ac4_mixed_build_ids_exit_2_names_the_field(self):
|
||||
doc = make_series([0.05] * 30)
|
||||
doc["pairs"][16]["ours_build_id"] = "test-build-B"
|
||||
rc, out, err = self.eval(doc)
|
||||
self.assertEqual(rc, 2)
|
||||
self.assertIn("ours_build_id", out + err)
|
||||
self.assertEqual(json.loads(out)["series_verdict"], "REFUSED")
|
||||
|
||||
def test_ac4_mixed_warm_cold_exit_2_names_the_field(self):
|
||||
doc = make_series([0.05] * 30)
|
||||
doc["pairs"][16]["cache_state"] = "COLD"
|
||||
rc, out, err = self.eval(doc)
|
||||
self.assertEqual(rc, 2)
|
||||
self.assertIn("cache_state", out + err)
|
||||
|
||||
def test_top_level_disagreeing_with_every_pair_is_mixed(self):
|
||||
doc = make_series([0.05] * 30)
|
||||
doc["cache_state"] = "COLD"
|
||||
self.assertEqual(self.eval(doc)[0], 2)
|
||||
|
||||
def test_mixed_schedule_hash_is_refused(self):
|
||||
doc = make_series([0.05] * 30)
|
||||
doc["pairs"][3]["schedule_hash"] = "other"
|
||||
rc, out, err = self.eval(doc)
|
||||
self.assertEqual(rc, 2)
|
||||
self.assertIn("schedule_hash", out + err)
|
||||
|
||||
def test_invalid_pairs_of_another_build_are_refused_too(self):
|
||||
doc = make_series([0.05] * 30, valid=[True] * 29 + [False])
|
||||
doc["pairs"][29]["ours_build_id"] = "test-build-B"
|
||||
self.assertEqual(self.eval(doc)[0], 2)
|
||||
|
||||
def test_pair_without_stated_build_is_not_a_mixture(self):
|
||||
doc = make_series([0.05] * 30)
|
||||
del doc["pairs"][3]["ours_build_id"]
|
||||
self.assertEqual(self.eval(doc)[0], 0)
|
||||
|
||||
|
||||
class Malformed(Cli):
|
||||
def test_truncated_json_exit_3(self):
|
||||
self.assertEqual(self.eval('{"machine": "server", "N": 30, "pairs": [')[0], 3)
|
||||
|
||||
def test_missing_file_exit_3(self):
|
||||
self.assertEqual(run(SERIES_EVAL, os.path.join(self.tmp.name, "nope.json"))[0], 3)
|
||||
|
||||
def test_usage_error_exit_3_not_2(self):
|
||||
self.assertEqual(run(SERIES_EVAL, "--no-such-flag")[0], 3)
|
||||
|
||||
def test_valid_pair_with_missing_arm_or_bad_number(self):
|
||||
doc = make_series([0.05] * 30)
|
||||
del doc["pairs"][2]["arms"]["vanilla_noskip"]
|
||||
self.assertEqual(self.eval(doc)[0], 3)
|
||||
doc = make_series([0.05] * 30)
|
||||
doc["pairs"][2]["arms"]["ours"]["wall_norm"] = 0.0
|
||||
self.assertEqual(self.eval(doc)[0], 3)
|
||||
doc = make_series([0.05] * 30)
|
||||
doc["pairs"][2]["arms"]["ours"]["ttft_sum"] = "fast"
|
||||
self.assertEqual(self.eval(doc)[0], 3)
|
||||
|
||||
def test_duplicate_pair_numbers_and_bad_header(self):
|
||||
doc = make_series([0.05] * 30)
|
||||
doc["pairs"][1]["pair"] = 1
|
||||
self.assertEqual(self.eval(doc)[0], 3)
|
||||
doc = make_series([0.05] * 30)
|
||||
doc["machine"] = "desktop"
|
||||
self.assertEqual(self.eval(doc)[0], 3)
|
||||
doc = make_series([0.05] * 30)
|
||||
doc["N"] = 1
|
||||
self.assertEqual(self.eval(doc)[0], 3)
|
||||
|
||||
def test_invalid_pair_may_lack_arms(self):
|
||||
doc = make_series([0.05] * 31, valid=[True] * 30 + [False], n_reg=30)
|
||||
doc["pairs"][30]["arms"] = {}
|
||||
self.assertEqual(self.eval(doc)[0], 0)
|
||||
|
||||
|
||||
class Rows(Cli):
|
||||
def test_ac5_two_row_blocks_and_one_when_rows_coincide(self):
|
||||
d = json.loads(self.eval(make_series([0.05] * 30))[1])
|
||||
self.assertEqual(sorted(d["metrics"]["wall_norm"]), ["vanilla_default", "vanilla_noskip"])
|
||||
d = json.loads(self.eval(make_series([0.05] * 30, rows_coincide=True))[1])
|
||||
for metric in ("wall_norm", "ttft_sum", "decode_tps"):
|
||||
self.assertEqual(list(d["metrics"][metric]), ["vanilla_default"])
|
||||
self.assertEqual(len(d["metrics"]["wall_norm"]), 1)
|
||||
|
||||
def test_rows_are_evaluated_separately(self):
|
||||
doc = make_series([0.05] * 30)
|
||||
for p in doc["pairs"]:
|
||||
p["arms"]["vanilla_noskip"]["wall_norm"] = 100.0 * math.exp(0.02)
|
||||
d = json.loads(self.eval(doc)[1])
|
||||
self.assertAlmostEqual(d["metrics"]["wall_norm"]["vanilla_default"]["mean_l"], 0.05, places=12)
|
||||
self.assertAlmostEqual(d["metrics"]["wall_norm"]["vanilla_noskip"]["mean_l"], 0.02, places=12)
|
||||
|
||||
|
||||
class BlindSd(Cli):
|
||||
def test_ac6_prints_sd_of_first_six_valid_pairs_and_no_mean(self):
|
||||
l = noisy(30, 0.05, 0.02, 11)
|
||||
doc = make_series(l, valid=[False] + [True] * 29) # pair 1 is invalid: the first 6 VALID pairs are pairs 2..7
|
||||
rc, out, err = self.eval(doc, "--blind-sd")
|
||||
self.assertEqual(rc, 0, err)
|
||||
d = json.loads(out)
|
||||
want = statistics.stdev(l[1:7])
|
||||
self.assertAlmostEqual(d["sd"]["wall_norm"]["vanilla_default"], want, places=12)
|
||||
self.assertEqual(d["pairs_used"], [2, 3, 4, 5, 6, 7])
|
||||
|
||||
def keys(o):
|
||||
if isinstance(o, dict):
|
||||
for k, v in o.items():
|
||||
yield k
|
||||
for sub in keys(v):
|
||||
yield sub
|
||||
elif isinstance(o, list):
|
||||
for v in o:
|
||||
for sub in keys(v):
|
||||
yield sub
|
||||
self.assertEqual([k for k in keys(d) if k.startswith("mean")], [])
|
||||
self.assertNotIn("order_tables", d)
|
||||
self.assertNotIn("metrics", d)
|
||||
|
||||
def test_blind_sd_recommends_a_larger_n_in_multiples_of_6(self):
|
||||
d = json.loads(self.eval(make_series(noisy(30, 0.0, 0.05, 2)), "--blind-sd")[1])
|
||||
self.assertGreater(d["N_recommended"], 30)
|
||||
self.assertEqual(d["N_recommended"] % 6, 0)
|
||||
d = json.loads(self.eval(make_series(noisy(30, 0.0, 0.0005, 2)), "--blind-sd")[1])
|
||||
self.assertEqual(d["N_recommended"], 30)
|
||||
|
||||
def test_blind_sd_needs_six_valid_pairs(self):
|
||||
self.assertEqual(self.eval(make_series([0.05] * 5, n_reg=30), "--blind-sd")[0], 3)
|
||||
|
||||
def test_blind_sd_still_refuses_a_mixed_series(self):
|
||||
doc = make_series([0.05] * 30)
|
||||
doc["pairs"][2]["ours_build_id"] = "x"
|
||||
self.assertEqual(self.eval(doc, "--blind-sd")[0], 2)
|
||||
|
||||
|
||||
class OrderTables(Cli):
|
||||
def test_order_tables_hand_computed(self):
|
||||
# ours at positions 1,2,3,1,2,3 with wall values e^0..e^5; predecessors none / vanilla_default / vanilla_noskip alternate
|
||||
doc = make_series([0.0] * 6, n_reg=6)
|
||||
pos = [1, 2, 3, 1, 2, 3]
|
||||
pred = [None, "vanilla_default", "vanilla_noskip", None, "vanilla_default", "vanilla_noskip"]
|
||||
for i, p in enumerate(doc["pairs"]):
|
||||
p["position"]["ours"] = pos[i]
|
||||
p["predecessor"]["ours"] = pred[i]
|
||||
for arm in p["arms"]:
|
||||
p["arms"][arm]["wall_norm"] = math.exp(i)
|
||||
t = json.loads(self.eval(doc)[1])["order_tables"]
|
||||
self.assertAlmostEqual(t["by_position"]["wall_norm"]["ours"]["1"], 1.5, places=12) # mean(0, 3)
|
||||
self.assertAlmostEqual(t["by_position"]["wall_norm"]["ours"]["2"], 2.5, places=12) # mean(1, 4)
|
||||
self.assertAlmostEqual(t["by_position"]["wall_norm"]["ours"]["3"], 3.5, places=12) # mean(2, 5)
|
||||
self.assertAlmostEqual(t["by_predecessor"]["wall_norm"]["ours"]["none"], 1.5, places=12)
|
||||
self.assertAlmostEqual(t["by_predecessor"]["wall_norm"]["ours"]["vanilla_default"], 2.5, places=12)
|
||||
self.assertAlmostEqual(t["by_predecessor"]["wall_norm"]["ours"]["vanilla_noskip"], 3.5, places=12)
|
||||
|
||||
def test_l_tables_present_per_metric_and_row(self):
|
||||
d = json.loads(self.eval(make_series([0.05] * 12, n_reg=12))[1])
|
||||
t = d["order_tables_l"]
|
||||
self.assertAlmostEqual(t["by_position_of_ours"]["wall_norm"]["vanilla_default"]["1"]["mean_l"], 0.05, places=12)
|
||||
self.assertEqual(t["by_predecessor_of_ours"]["wall_norm"]["vanilla_noskip"]["none"]["n"], 12)
|
||||
|
||||
|
||||
class Output(Cli):
|
||||
def test_out_file_is_written_beside_stdout(self):
|
||||
path = os.path.join(self.tmp.name, "verdict.json")
|
||||
rc, out, err = self.eval(make_series([0.05] * 30), "--out", path)
|
||||
self.assertEqual(rc, 0, err)
|
||||
with open(path, "r", encoding="utf-8") as fh:
|
||||
self.assertEqual(json.load(fh), json.loads(out))
|
||||
|
||||
def test_pair_order_by_number_not_by_file_order(self):
|
||||
l = noisy(30, 0.02, 0.01, 8)
|
||||
doc = make_series(l)
|
||||
a = json.loads(self.eval(doc)[1])["metrics"]["wall_norm"]["vanilla_default"]
|
||||
doc["pairs"].reverse()
|
||||
b = json.loads(self.eval(doc)[1])["metrics"]["wall_norm"]["vanilla_default"]
|
||||
self.assertEqual(a["r1"], b["r1"])
|
||||
self.assertEqual(a["ci_lo"], b["ci_lo"])
|
||||
|
||||
|
||||
class NullSimulation(Cli):
|
||||
def test_rate_is_reproducible_and_below_five_percent(self):
|
||||
args = ("--simulate-null", "--runs", 3000, "--seed", 1)
|
||||
a = json.loads(self.eval(make_series(noisy(30, 0.0, 0.02, 1)), *args)[1])
|
||||
b = json.loads(self.eval(make_series(noisy(30, 0.0, 0.02, 1)), *args)[1])
|
||||
self.assertEqual(a, b)
|
||||
self.assertGreater(a["false_slower_rate"], 0.0)
|
||||
self.assertLessEqual(a["false_slower_rate"], 0.05)
|
||||
self.assertFalse(a["critical_level_replaced"])
|
||||
self.assertEqual(a["look_sizes"], [12, 24])
|
||||
|
||||
def test_ar1_stress_is_used_for_a_positively_correlated_series(self):
|
||||
rng = random.Random(4)
|
||||
x, l = 0.0, []
|
||||
for _ in range(30):
|
||||
x = 0.5 * x + rng.gauss(0, 0.01)
|
||||
l.append(x)
|
||||
d = json.loads(self.eval(make_series(l), "--simulate-null", "--runs", 2000, "--seed", 2)[1])
|
||||
self.assertGreaterEqual(d["false_slower_rate"], d["false_slower_rate_iid"])
|
||||
|
||||
def test_too_loose_look_level_is_replaced_by_the_simulated_level(self):
|
||||
d = json.loads(self.eval(make_series(noisy(30, 0.0, 0.02, 1)), "--simulate-null", "--runs", 2000, "--seed", 1,
|
||||
"--look-alpha", 0.3)[1])
|
||||
self.assertGreater(d["false_slower_rate"], 0.05)
|
||||
self.assertTrue(d["critical_level_replaced"])
|
||||
self.assertLess(d["simulated_alpha_look"], 0.3)
|
||||
self.assertLessEqual(d["false_slower_rate_at_simulated_level"], 0.05)
|
||||
|
||||
def test_bad_runs(self):
|
||||
self.assertEqual(self.eval(make_series([0.0] * 30), "--simulate-null", "--runs", 0)[0], 3)
|
||||
|
||||
|
||||
class RecordsToSeries(unittest.TestCase):
|
||||
"""records_to_series.py on fixtures built with the golden materialize() of STRA-311 (the validity golden file is not edited)."""
|
||||
|
||||
def build(self, tweak=None, n_pairs=6):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
case_input = {"machine": "server", "schedule": "pairs_n6", "pairs": [{"pair": n, "arms": {}} for n in range(1, n_pairs + 1)]}
|
||||
exp = dict((n, {"valid": True, "reasons": [], "event": None, "pair": n}) for n in range(1, n_pairs + 1))
|
||||
mat = G.materialize(case_input, VDOC["templates"], VDOC["schedules"], exp)
|
||||
records = os.path.join(tmp.name, "records")
|
||||
os.makedirs(records)
|
||||
for fname, rec in mat["records"].items():
|
||||
if tweak:
|
||||
tweak(fname, rec)
|
||||
with open(os.path.join(records, fname), "w", encoding="utf-8") as fh:
|
||||
json.dump(rec, fh)
|
||||
sched = os.path.join(tmp.name, "schedule.json")
|
||||
with open(sched, "w", encoding="utf-8") as fh:
|
||||
json.dump(mat["schedule"], fh)
|
||||
ledger = os.path.join(tmp.name, "ledger.jsonl")
|
||||
with open(ledger, "w", encoding="utf-8") as fh:
|
||||
fh.write("".join(json.dumps(line) + "\n" for line in mat["ledger"]))
|
||||
return tmp.name, records, sched, ledger
|
||||
|
||||
def convert(self, records, sched, ledger, *extra):
|
||||
return run(RECORDS_TO_SERIES, "--records", records, "--schedule", sched, "--ledger", ledger, "--machine", "server", *extra)
|
||||
|
||||
def test_series_fields_and_aggregates(self):
|
||||
def tweak(fname, rec):
|
||||
if fname.endswith(".ours.json"):
|
||||
k = int(fname.split("-")[1].split(".")[0])
|
||||
rec["metrics"]["wall_norm_s"] = 350.0 * (1 - 0.01 * k)
|
||||
root, records, sched, ledger = self.build(tweak)
|
||||
rc, out, err = self.convert(records, sched, ledger)
|
||||
self.assertEqual(rc, 0, err)
|
||||
s = json.loads(out)
|
||||
self.assertEqual((s["machine"], s["N"], s["rows_coincide"]), ("server", 6, False))
|
||||
self.assertEqual(len(s["pairs"]), 6)
|
||||
self.assertTrue(all(p["valid"] for p in s["pairs"]), [p["reasons"] for p in s["pairs"]])
|
||||
p1 = s["pairs"][0]
|
||||
self.assertAlmostEqual(p1["arms"]["ours"]["wall_norm"], 350.0 * 0.99)
|
||||
self.assertAlmostEqual(p1["arms"]["ours"]["ttft_sum"], 150.0) # 20 + 25 + 30 + 35 + 40
|
||||
self.assertAlmostEqual(p1["arms"]["ours"]["decode_tps"], 3500 / 50.0) # total tokens / total (wall_s - ttft_s)
|
||||
self.assertEqual(set(p1["arms"]), set(THREE))
|
||||
self.assertIn("ours", p1["position"])
|
||||
self.assertIn(p1["predecessor"]["ours"], (None, "vanilla_default", "vanilla_noskip"))
|
||||
self.assertEqual(len(set(p["ours_build_id"] for p in s["pairs"])), 1)
|
||||
self.assertEqual(s["cache_state"], CACHE)
|
||||
self.assertEqual(len(s["schedule_hash"]), 64)
|
||||
# and the evaluator reads it: 6 valid pairs of N = 6, no looks, a final verdict
|
||||
path = os.path.join(root, "series.json")
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
fh.write(out)
|
||||
rc, out2, err2 = run(SERIES_EVAL, path)
|
||||
self.assertEqual(rc, 0, err2)
|
||||
d = json.loads(out2)
|
||||
self.assertEqual(d["metrics"]["wall_norm"]["vanilla_default"]["n"], 6)
|
||||
self.assertGreater(d["metrics"]["wall_norm"]["vanilla_default"]["mean_l"], 0) # vanilla = 350 s, ours 346.5 .. 329 s
|
||||
self.assertEqual(d["metrics"]["ttft_sum"]["vanilla_default"]["mean_l"], 0.0)
|
||||
|
||||
def test_validity_comes_from_validity_py(self):
|
||||
def tweak(fname, rec):
|
||||
if fname.startswith("pair-0003.vanilla_default"):
|
||||
rec["configuration"]["context_tokens"] = 131072 # WORKLOAD
|
||||
root, records, sched, ledger = self.build(tweak)
|
||||
s = json.loads(self.convert(records, sched, ledger)[1])
|
||||
p3 = [p for p in s["pairs"] if p["pair"] == 3][0]
|
||||
self.assertFalse(p3["valid"])
|
||||
self.assertIn("WORKLOAD", p3["reasons"])
|
||||
self.assertAlmostEqual(s["invalid_rate"], 1 / 6.0)
|
||||
|
||||
def test_n_override_and_rows_coincide_flag(self):
|
||||
root, records, sched, ledger = self.build()
|
||||
s = json.loads(self.convert(records, sched, ledger, "--n", "12", "--rows-coincide")[1])
|
||||
self.assertEqual(s["N"], 12)
|
||||
self.assertTrue(s["rows_coincide"])
|
||||
|
||||
def test_mixed_cache_state_inside_a_pair_is_carried_to_the_evaluator_as_a_mixture(self):
|
||||
def tweak(fname, rec):
|
||||
if fname.startswith("pair-0002.vanilla_noskip"):
|
||||
rec["cache"]["state"] = "COLD"
|
||||
root, records, sched, ledger = self.build(tweak)
|
||||
out = self.convert(records, sched, ledger)[1]
|
||||
path = os.path.join(root, "series.json")
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
fh.write(out)
|
||||
rc, o, e = run(SERIES_EVAL, path)
|
||||
self.assertEqual(rc, 2)
|
||||
self.assertIn("cache_state", o + e)
|
||||
|
||||
def test_manifest_refusal_exit_2_and_malformed_exit_3(self):
|
||||
root, records, sched, ledger = self.build()
|
||||
os.remove(os.path.join(records, "pair-0004.ours.json"))
|
||||
rc, out, err = self.convert(records, sched, ledger)
|
||||
self.assertEqual(rc, 2)
|
||||
self.assertIn("pair-0004.ours", out + err)
|
||||
self.assertEqual(run(RECORDS_TO_SERIES, "--records", os.path.join(root, "nope"), "--schedule", sched, "--ledger", ledger,
|
||||
"--machine", "server")[0], 3)
|
||||
self.assertEqual(run(RECORDS_TO_SERIES, "--machine", "server")[0], 3)
|
||||
|
||||
def test_build_id_string_and_record_metrics_edge_cases(self):
|
||||
sys.path.insert(0, HERE)
|
||||
try:
|
||||
import records_to_series as R
|
||||
finally:
|
||||
sys.path.pop(0)
|
||||
self.assertIsNone(R.build_id_string({}))
|
||||
b = {"commit": "c" * 40, "target_triple": "x86_64-unknown-linux-gnu", "cargo_features": ["b", "a"], "profile_value_sha256": "f" * 64}
|
||||
self.assertEqual(R.build_id_string({"ours_build_id_frozen": b}), "%s|x86_64-unknown-linux-gnu|a+b|%s" % ("c" * 40, "f" * 16))
|
||||
with self.assertRaises(R.Malformed):
|
||||
R.record_metrics({"metrics": {"turns": []}}, "r")
|
||||
with self.assertRaises(R.Malformed):
|
||||
R.record_metrics({"metrics": {"turns": [{"ttft_s": 5.0, "wall_s": 5.0, "output_tokens": 10}], "wall_norm_s": 5.0}}, "r")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user