File size: 7,224 Bytes
fd280c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
"""Check the joint Rack Lab release, with explicit missing and failing gates."""
import argparse
import json
import math
from pathlib import Path
import re

from local_graphs import digest

SPEC_PATH = Path(__file__).with_name("spec.json")
SPEC = json.loads(SPEC_PATH.read_text(encoding="utf-8"))
HEX = re.compile(r"[a-f0-9]{64}")


def read(path):
    return json.loads(path.read_text(encoding="utf-8"))


def number(value):
    return type(value) in (int, float) and math.isfinite(value)


def meets(row, key, bound, *, minimum=True):
    value = row.get(key)
    return number(value) and (value >= bound if minimum else 0 <= value <= bound)


def positive(row, key):
    return number(row.get(key)) and row[key] > 0


def roles_for(model):
    shared = {"candidate_onnx", "candidate_ir", "judge", "holdout", "selection",
              "controls", "contract", "independence"}
    return shared | ({"catalog", "tokenizer"} if model == "bankshot" else {"audio"})


def artifacts_match(frozen, directory, model):
    files = frozen.get("files", {})
    roles = frozen.get("roles", {})
    required = roles_for(model)
    if not required <= roles.keys() or not files:
        return False
    for role in required:
        paths = roles[role]
        if not paths or any(path not in files for path in paths):
            return False
    root = directory.resolve()
    for name, expected in files.items():
        path = (root / name).resolve()
        if root not in path.parents or not path.is_file():
            return False
        if not isinstance(expected, str) or not HEX.fullmatch(expected) or digest(path) != expected:
            return False
    return True


def bankshot(row, domain):
    bar = SPEC["models"]["bankshot"]
    return {
        "sample_and_source_counts": all(meets(row, key, bar[limit]) for key, limit in (
            ("answerable", "answerable_min"), ("real_answerable", "real_answerable_min"),
            ("negative", "negative_min"))),
        "hit10": meets(row, "hit10", bar["hit10_min"]),
        "negative_cases": meets(row, "negative_correct", bar["negative_correct_min"]),
        "mrr_vs_native": positive(row, "mrr_gain_native_lower95"),
        "mrr_vs_cpu": positive(row, "mrr_gain_cpu_lower95"),
        "full_query_latency": meets(row, "p95_ms", bar["p95_ms_max"], minimum=False),
        **({"vehicle_subset": positive(row, "exact_vehicle_cases")
            and meets(row, "vehicle_hit10_gain_vs_cpu", 0)
            and meets(row, "vehicle_hit1_gain_vs_cpu", 0)} if domain == "dealership" else {}),
    }


def breakshot(row, primary):
    bar = SPEC["models"]["breakshot"]
    improvements = {
        "event_recall": "event_recall_gain_lower95",
        "mixed_wakes": "mixed_wake_reduction_lower95",
    }
    key = improvements.get(primary)
    controls = [row.get("vs_" + control, {}) for control in ("v7", "silero")]
    return {
        "sample_and_source_counts": meets(row, "expected_events", bar["events_min"])
            and meets(row, "quiet_hours", bar["quiet_hours_min"]),
        "event_recall": meets(row, "event_recall", bar["event_recall_min"]),
        "duration_recall": meets(row, "duration_recall", bar["duration_recall_min"]),
        "quiet_wakes": meets(row, "quiet_wakes_upper95_per_hour", bar["quiet_wakes_upper95_per_hour_max"], minimum=False),
        "mixed_stream_nonregression": all(meets(c, "event_recall_gain", 0)
            and meets(c, "mixed_wake_reduction", 0) for c in controls),
        "mixed_stream_improvement": bool(key) and all(positive(c, key) for c in controls),
        "block_latency": meets(row, "block_p95_ms", bar["block_p95_ms_max"], minimum=False),
        "onset_latency": meets(row, "onset_p95_ms", bar["onset_p95_ms_max"], minimum=False),
    }


def check_model(name, root):
    freeze_file = root / "freeze.json"
    result_file = root / "results.json"
    if not freeze_file.is_file() or not result_file.is_file():
        return {"ready": False, "missing": [p.name for p in (freeze_file, result_file) if not p.is_file()]}

    frozen, result = read(freeze_file), read(result_file)
    shared = {
        "frozen_inputs": frozen.get("launch_spec_sha256") == digest(SPEC_PATH)
            and result.get("freeze_sha256") == digest(freeze_file) and frozen.get("model") == name
            and artifacts_match(frozen, root, name),
        "physical_ncs1": result.get("device", {}).get("boot_usb_id") == "03E7:2150"
            and result.get("placement") == "all_learned_stages_on_ncs1",
        "fixed_contract": all(
            type(r.get("total")) is int and r["total"] > 0
            and type(r.get("passed")) is int and r["passed"] == r["total"]
            for r in (result.get("contracts", {}).get(lane, {}).get(domain, {})
                      for lane in ("ncs1", "cpu") for domain in SPEC["verticals"])),
        "paired_timings": meets(result, "paired_timing_passes", SPEC["paired_timing_passes_min"]),
        "soak": meets(result.get("soak", {}), "seconds", SPEC["soak_seconds_min"])
            and result.get("soak", {}).get("failed_requests") == 0,
        "disconnect_and_recovery": result.get("disconnect_recovery_passed") is True,
    }
    if name == "breakshot":
        bar = SPEC["models"][name]
        parity = result.get("rolling_parity", {})
        structure = frozen.get("state_design")
        shared["rolling_parity"] = (
            meets(parity, "agreement", bar["rolling_agreement_min"])
            and meets(parity, "posterior_p95", bar["posterior_p95_max"], minimum=False)
            and (structure == "stateless_overlap" or (structure == "carried"
                 and meets(parity, "max_abs_state", bar["carried_state_max"], minimum=False))))
    domain_rows = {}
    for domain in SPEC["verticals"]:
        row = result.get("verticals", {}).get(domain, {})
        if name == "bankshot":
            domain_rows[domain] = bankshot(row, domain)
        else:
            primary = frozen.get("primary_improvement", {}).get(domain)
            domain_rows[domain] = breakshot(row, primary)
    ready = all(shared.values()) and all(all(values.values()) for values in domain_rows.values())
    distribution = {key: result.get("distribution", {}).get(key) is True
                    for key in ("license_review", "github_evidence", "private_clean_replay")}
    return {"ready": ready and all(distribution.values()), "shared": shared,
            "verticals": domain_rows, "distribution": distribution}


def launch_status(directory):
    models = {name: check_model(name, directory / name) for name in SPEC["models"]}
    return {"spec": SPEC["version"], "ready": all(m["ready"] for m in models.values()), "models": models}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("evidence", type=Path, help="Directory containing bankshot/ and breakshot/ evidence")
    args = parser.parse_args()
    result = launch_status(args.evidence)
    print(json.dumps(result, indent=2))
    return 0 if result["ready"] else 1


if __name__ == "__main__":
    raise SystemExit(main())