BankShot-Search / runtime /metrics.py
chadstthomas's picture
Stage BankShot Search v0.1.0 research preview
fd280c7 verified
Raw History Blame Contribute Delete
8.03 kB
"""Derive launch metrics from matched, per-case evidence on the frozen cohorts."""
import argparse
from collections import defaultdict
import json
from pathlib import Path
import numpy as np
from acceptance import SPEC, read
def exact_rows(rows):
indexed = {row["id"]: row for row in rows}
if len(indexed) != len(rows) or not indexed:
raise ValueError("Each split needs at least one row and unique case IDs")
return indexed
def paired_lower(groups, numerators, denominators):
"""Two-sided 95% lower endpoint, resampling whole source groups."""
totals = defaultdict(lambda: np.zeros(2))
for key, value, volume in zip(groups, numerators, denominators):
totals[key] += (value, volume)
units = np.asarray([totals[key] for key in sorted(totals)])
if len(units) < 2:
raise ValueError("Paired intervals require at least two independent source groups")
rng = np.random.default_rng(20261122)
ratios = []
for _ in range(20):
draws = rng.integers(0, len(units), size=(1_000, len(units)))
sums = units[draws].sum(axis=1)
ratios.extend(sums[sums[:, 1] > 0, 0] / sums[sums[:, 1] > 0, 1])
if not ratios:
raise ValueError("Comparison has no scored evidence")
return float(np.percentile(ratios, 2.5))
def quiet_upper95(count, hours):
from scipy.stats import chi2
if type(count) != int or count < 0 or hours <= 0:
raise ValueError("Quiet evidence needs a valid event count and positive duration")
return float(chi2.ppf(0.95, 2 * (count + 1)) / (2 * hours))
def bank(rows, lanes):
by_id = exact_rows(rows)
expected = set(by_id)
for name in ("candidate", "incumbent", "cpu"):
if set(lanes[name]) != expected:
raise ValueError("Every lane must cover exactly the frozen case IDs")
out = {}
for domain in SPEC["verticals"]:
eligible = [row for row in rows if row["domain"] == domain]
positive = [row for row in eligible if row["label"] == "answerable"]
negative = [row for row in eligible if row["label"] in ("no_match", "ambiguous")]
if len(positive) + len(negative) != len(eligible) or not positive or not negative:
raise ValueError("Each vertical needs both answerable and labeled negative cases")
groups = [r["group"] for r in positive]
reciprocal = {}
top = {}
for name in ("candidate", "incumbent", "cpu"):
rank = []
for r in positive:
lane = lanes[name][r["id"]]
ids = lane["top10"]
if len(set(ids)) != len(ids) or len(ids) > 10:
raise ValueError("Rankings must contain at most ten distinct source IDs")
rank.append(next((i for i, ident in enumerate(ids, 1) if ident in r["targets"]), 0)
if lane["status"] == "found" else 0)
top[name] = np.asarray(rank)
reciprocal[name] = np.asarray([1 / r if r else 0.0 for r in rank])
result = top["candidate"]
row = {
"answerable": len(positive),
"real_answerable": sum(r["source_kind"] == "real" for r in positive),
"negative": len(negative),
"hit10": float(np.mean(result > 0)),
"hit1": float(np.mean(result == 1)),
"negative_correct": sum(
lanes["candidate"][r["id"]]["status"] == r["label"] for r in negative
) / len(negative),
"p95_ms": float(np.percentile([lanes["candidate"][r["id"]]["ms"] for r in eligible], 95)),
"mrr_gain_native_lower95": paired_lower(groups, reciprocal["candidate"] - reciprocal["incumbent"],
np.ones(len(groups))),
"mrr_gain_cpu_lower95": paired_lower(groups, reciprocal["candidate"] - reciprocal["cpu"],
np.ones(len(groups))),
}
if domain == "dealership":
exact = np.asarray([bool(r.get("vehicle")) for r in positive])
row["exact_vehicle_cases"] = int(exact.sum())
if exact.any():
row["vehicle_hit10_gain_vs_cpu"] = float(np.mean(result[exact] > 0) - np.mean(top["cpu"][exact] > 0))
row["vehicle_hit1_gain_vs_cpu"] = float(np.mean(result[exact] == 1) - np.mean(top["cpu"][exact] == 1))
out[domain] = row
return out
def vad(rows, lanes):
source = exact_rows(rows)
for name in ("candidate", "v7", "silero"):
if set(lanes[name]) != set(source):
raise ValueError("Speech lanes must cover the same frozen recording IDs")
out = {}
for domain in SPEC["verticals"]:
scope = [r for r in rows if r["domain"] == domain]
mixed = [r["id"] for r in scope if r["kind"] == "mixed"]
quiet = [r["id"] for r in scope if r["kind"] == "verified_quiet"]
if set(mixed) & set(quiet) or len(mixed) + len(quiet) != len(scope) or not mixed or not quiet:
raise ValueError("Each vertical needs both mixed and verified quiet recordings")
candidate = lanes["candidate"]
field = lambda ids, lane, key: np.asarray([lanes[lane][r][key] for r in ids])
expected = field(mixed, "candidate", "expected_events")
truth = field(mixed, "candidate", "truth")
samples = field(mixed, "candidate", "samples")
mixed_hours = (samples - truth) / (16_000 * 3600)
quiet_hours = sum(candidate[r]["samples"] for r in quiet) / (16_000 * 3600)
if not expected.sum() or not truth.sum() or not mixed_hours.sum() or any(candidate[r]["truth"] for r in quiet):
raise ValueError("Check speech-positive and quiet segmentation")
miss = field(mixed, "candidate", "missed_events")
wakes = field(mixed, "candidate", "false_wakes")
onsets = [v for recording in mixed for v in candidate[recording]["onset_ms"]]
blocks = [v for recording in mixed + quiet for v in candidate[recording]["block_ms"]]
if not onsets or not blocks:
raise ValueError("Collect actual onset and block timings before evaluation")
result = {
"expected_events": int(expected.sum()),
"quiet_hours": quiet_hours,
"event_recall": float(1 - miss.sum() / expected.sum()),
"duration_recall": float(field(mixed, "candidate", "covered").sum() / truth.sum()),
"quiet_wakes_upper95_per_hour": quiet_upper95(sum(candidate[r]["false_wakes"] for r in quiet), quiet_hours),
"block_p95_ms": float(np.percentile(blocks, 95)),
"onset_p95_ms": float(np.percentile(onsets, 95)),
}
groups = [source[r]["group"] for r in mixed]
for name in ("v7", "silero"):
for key, values in (("expected_events", expected), ("truth", truth), ("samples", samples)):
if not np.array_equal(field(mixed, name, key), values):
raise ValueError("Control truth differs from the candidate input")
gain = field(mixed, name, "missed_events") - miss
reduction = field(mixed, name, "false_wakes") - wakes
result["vs_" + name] = {
"event_recall_gain": float(gain.sum() / expected.sum()),
"event_recall_gain_lower95": paired_lower(groups, gain, expected),
"mixed_wake_reduction": float(reduction.sum() / mixed_hours.sum()),
"mixed_wake_reduction_lower95": paired_lower(groups, reduction, mixed_hours),
}
out[domain] = result
return out
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("model", choices=("bankshot", "breakshot"))
parser.add_argument("input", type=Path)
args = parser.parse_args()
data = read(args.input)
calculate = bank if args.model == "bankshot" else vad
print(json.dumps(calculate(data["cases"], data["lanes"]), indent=2, allow_nan=False))
if __name__ == "__main__":
main()