File size: 11,193 Bytes
ff736b7
 
 
f45b781
ff736b7
 
 
 
 
 
 
f45b781
 
 
ff736b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f45b781
 
 
 
ff736b7
 
 
f45b781
 
 
 
 
 
ff736b7
 
 
 
 
 
 
 
 
 
 
 
f45b781
 
 
 
 
 
 
 
 
 
ff736b7
 
 
 
 
 
 
 
 
 
 
 
 
f45b781
 
 
 
 
 
ff736b7
 
 
f45b781
 
 
 
 
 
 
 
ff736b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f45b781
 
 
 
ff736b7
 
 
 
 
 
 
 
 
 
 
f45b781
ff736b7
f45b781
 
 
ff736b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f45b781
 
ff736b7
f45b781
 
 
ff736b7
 
 
 
f45b781
ff736b7
f45b781
 
ff736b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f45b781
 
 
 
 
 
 
 
 
 
ff736b7
 
 
 
 
 
 
 
 
 
 
 
 
 
f45b781
 
 
ff736b7
 
 
f45b781
ff736b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
#!/usr/bin/env python3
"""Unblind a finished run and write the final evaluation report.

  python3 report.py --run runs/myrun [--config models.json]

Reads results.jsonl, votes.jsonl and (only now) blinding.json, then writes
runs/<run>/report.md with:
  - overall winner and vote counts (wins / both_good / both_bad)
  - per-topic (tag) win rates -> each model's strengths and weaknesses
  - per-difficulty and per-cohort breakdown
  - token usage and cost per model (needs prices in models.json)
  - latency, tool-call and escalation stats, empty replies, failures
Model labels/prices come from runs/<run>/run_config.json (written by
run_eval.py, no keys) unless --config is given.
"""
from __future__ import annotations

import argparse
import json
import os
from collections import defaultdict

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)


def pct(n, d):
    return f"{(100.0 * n / d):.0f}%" if d else "—"


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--run", required=True)
    ap.add_argument("--config", default="",
                    help="models.json (default: <run>/run_config.json)")
    ap.add_argument("--allow-partial", action="store_true",
                    help="unblind even though some cases have no verdict")
    args = ap.parse_args()
    run = args.run

    cfg_path = args.config or os.path.join(run, "run_config.json")
    if not os.path.exists(cfg_path):
        cfg_path = os.path.join(ROOT, "models.json")
    if not os.path.exists(cfg_path):
        raise SystemExit("no model config found: pass --config models.json")
    cfg = json.load(open(cfg_path))

    def lines(p):
        if not os.path.exists(p):
            return []
        out = []
        for l in open(p):
            try:
                out.append(json.loads(l))
            except json.JSONDecodeError:
                pass
        return out

    meta_path = os.path.join(run, "run_meta.json")
    if os.path.exists(meta_path):
        import hashlib
        want = json.load(open(meta_path)).get("dataset_sha256_16")
        have = hashlib.sha256(open(os.path.join(
            ROOT, "dataset", "cases.jsonl"), "rb").read()).hexdigest()[:16]
        if want and want != have:
            print("WARNING: dataset/cases.jsonl changed since this run was "
                  "made; conversations shown may differ from what the models "
                  "saw")
    results = lines(os.path.join(run, "results.jsonl"))
    votes = {v["case_id"]: v for v in lines(os.path.join(run, "votes.jsonl"))}
    blind = json.load(open(os.path.join(run, "blinding.json")))["A"]

    cases = {}
    for l in open(os.path.join(ROOT, "dataset", "cases.jsonl")):
        c = json.loads(l)
        cases[c["id"]] = c

    recs = {}
    for r in results:
        if r.get("status") == "completed":
            recs[(r["case_id"], r["variant"])] = r
    completed = sorted({cid for cid, v in recs if v == "A"
                        and (cid, "B") in recs and cid in cases})
    unknown = sorted({cid for cid, _ in recs if cid not in cases})
    if unknown:
        print(f"WARNING: {len(unknown)} result ids are not in the dataset "
              f"(e.g. {unknown[0]}); ignored")
    judged = [c for c in completed if c in votes]
    unjudged = [c for c in completed if c not in votes]

    not_run = [c for c in cases if c not in completed]
    if (unjudged or not_run) and not args.allow_partial:
        raise SystemExit(
            f"run is not finished: {len(not_run)} of {len(cases)} cases not "
            f"run yet, {len(unjudged)} run but not judged. The report "
            "unblinds the run, so it waits until every case is run and "
            "judged (or pass --allow-partial).")

    name = {"base": cfg.get("base", {}).get("label", "base"),
            "candidate": cfg.get("candidate", {}).get("label", "candidate")}
    price = {s: (cfg.get(s, {}) or {}).get("price_per_1m") or {}
             for s in ("base", "candidate")}

    # ---- votes ----
    wins = defaultdict(int)
    both = defaultdict(int)
    tag_wins = defaultdict(lambda: defaultdict(int))
    tag_decided = defaultdict(int)
    diff_stats = defaultdict(lambda: defaultdict(int))
    for cid in judged:
        v = votes[cid]["verdict"]
        a_owner = blind[cid]
        b_owner = "candidate" if a_owner == "base" else "base"
        if v == "a_better":
            wins[a_owner] += 1
        elif v == "b_better":
            wins[b_owner] += 1
        else:
            both[v] += 1
        for tag in cases[cid]["tags"]:
            if v in ("both_good", "both_bad"):
                tag_decided[tag] += 0
            else:
                tag_decided[tag] += 1
                winner = a_owner if v == "a_better" else b_owner
                tag_wins[tag][winner] += 1
        winner = (a_owner if v == "a_better" else
                  b_owner if v == "b_better" else v)
        diff_stats[f"difficulty {cases[cid]['difficulty']}"][winner] += 1
        diff_stats[f"cohort {cases[cid]['cohort']}"][winner] += 1

    # ---- usage / cost / latency / tools ----
    stats = {}
    for side in ("base", "candidate"):
        rs = [recs[(cid, "A")] for cid in completed if blind.get(cid) == side]
        rs += [recs[(cid, "B")] for cid in completed
               if blind.get(cid) != side and (cid, "B") in recs]
        usage = defaultdict(int)
        lat = []
        ntools = 0
        nesc = 0
        nempty = 0
        for r in rs:
            for fl in r.get("reply_flags") or []:
                if "empty_reply" in fl or "no_final_reply" in fl:
                    nempty += 1
            for k, val in (r.get("usage") or {}).items():
                usage[k] += val
            lat.append(r.get("latency_ms") or 0)
            for tc in r.get("tool_calls") or []:
                ntools += 1
                if tc.get("tool") == "escalate_to_vendor":
                    nesc += 1
        lat.sort()
        p50 = lat[len(lat) // 2] if lat else 0
        p95 = lat[int(len(lat) * 0.95)] if lat else 0
        cost = None
        if price[side].get("input") is not None:
            cost = (usage["input"] / 1e6) * float(price[side]["input"]) + \
                   (usage["output"] / 1e6) * float(price[side]["output"])
        stats[side] = {"n": len(rs), "usage": dict(usage), "p50": p50,
                       "p95": p95, "tools": ntools, "esc": nesc, "cost": cost,
                       "empty": nempty}

    # a case that failed once and later completed is not a failure
    failed = [r for r in results if r.get("status") == "failed"
              and r["case_id"] not in completed]

    # ---- report ----
    o = []
    a = o.append
    a(f"# گزارش ارزیابی کور — {os.path.basename(os.path.normpath(run))}")
    a("")
    a(f"- پرونده‌ها: {len(completed)} از {len(cases)} اجرا شده "
      f"(قضاوت‌شده: {len(judged)}"
      + (f"، بدون قضاوت: {len(unjudged)}" if unjudged else "") + ")")
    a(f"- مدل پایه: **{name['base']}** | مدل کاندید: **{name['candidate']}**")
    a("")
    a("## نتیجه کلی")
    a("")
    a("| مدل | برد | both_good | both_bad | نرخ برد (بدون مساوی‌ها) |")
    a("|---|---|---|---|---|")
    decided = wins["base"] + wins["candidate"]
    for s in ("base", "candidate"):
        a(f"| {name[s]} | {wins[s]} | {both['both_good']} "
          f"| {both['both_bad']} | {pct(wins[s], decided)} |")
    winner = max(("base", "candidate"), key=lambda s: wins[s])
    if decided and wins[winner] > wins["candidate" if winner == "base" else "base"]:
        margin = wins[winner] - wins["candidate" if winner == "base" else "base"]
        a("")
        a(f"**برنده: {name[winner]}** با {wins[winner]} برد در برابر "
          f"{decided - wins[winner]} برد حریف (اختلاف {margin}).")
    elif decided:
        a("")
        a("**نتیجه: مساوی** — تعداد بردها برابر است.")
    a("")

    a("## نقاط قوت و ضعف هر مدل (بر اساس برچسب موضوعی)")
    a("")
    for s in ("base", "candidate"):
        other = "candidate" if s == "base" else "base"
        strengths, weak = [], []
        for tag, w in sorted(tag_wins.items()):
            n = tag_decided[tag]
            if n < 3:
                continue
            wr = w[s] / n
            if wr >= 0.6:
                strengths.append(f"{tag} ({w[s]}/{n})")
            elif wr <= 0.4:
                weak.append(f"{tag} ({w[s]}/{n})")
        a(f"**{name[s]}**")
        a(f"- قوی در: {', '.join(strengths) if strengths else '—'}")
        a(f"- ضعیف در: {', '.join(weak) if weak else '—'}")
        a("")

    a("## جزئیات موضوعی (بردها در هر برچسب)")
    a("")
    a("| موضوع | پرونده‌های قضاوت‌شده | برد base | برد candidate |")
    a("|---|---|---|---|")
    for tag, w in sorted(tag_wins.items(), key=lambda kv: -tag_decided[kv[0]]):
        a(f"| {tag} | {tag_decided[tag]} | {w['base']} | {w['candidate']} |")
    a("")

    a("## به تفکیک سختی و دسته")
    a("")
    a(f"| گروه | برد {name['base']} | برد {name['candidate']} | both_good | both_bad |")
    a("|---|---|---|---|---|")
    for g in sorted(diff_stats):
        d = diff_stats[g]
        a(f"| {g} | {d['base']} | {d['candidate']} | {d['both_good']} "
          f"| {d['both_bad']} |")
    a("")

    a("## هزینه و مصرف")
    a("")
    a("| مدل | توکن ورودی | توکن خروجی | کش‌شده | هزینه (دلار) |")
    a("|---|---|---|---|---|")
    for s in ("base", "candidate"):
        u = stats[s]["usage"]
        c = f"${stats[s]['cost']:.4f}" if stats[s]["cost"] is not None \
            else "قیمت وارد نشده"
        a(f"| {name[s]} | {u.get('input', 0):,} | {u.get('output', 0):,} "
          f"| {u.get('cached', 0):,} | {c} |")
    a("")

    a("## سرعت و ابزارها")
    a("")
    a("| مدل | تأخیر میانه (ثانیه) | تأخیر ۹۵٪ | فراخوانی ابزار "
      "| ارجاع به غرفه‌دار | پاسخ خالی |")
    a("|---|---|---|---|---|---|")
    for s in ("base", "candidate"):
        st = stats[s]
        a(f"| {name[s]} | {st['p50'] / 1000:.1f} | {st['p95'] / 1000:.1f} "
          f"| {st['tools']} | {st['esc']} | {st['empty']} |")
    a("")
    if failed:
        a(f"## خطاها")
        a("")
        for r in failed[:20]:
            a(f"- {r['case_id']}: {str(r.get('error'))[:160]}")
        a("")
    if unjudged:
        a("## بدون قضاوت")
        a("")
        a(", ".join(unjudged))
        a("")

    a("## دلایل قضاوت (خلاصه هر پرونده)")
    a("")
    for cid in judged:
        a(f"- **{cid}** [{votes[cid]['verdict']}]: {votes[cid]['reason']}")

    out = os.path.join(run, "report.md")
    open(out, "w").write("\n".join(o) + "\n")
    print(f"report written: {out}")
    if unjudged:
        print(f"WARNING: {len(unjudged)} completed cases have no verdict")
    return 0


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