File size: 9,220 Bytes
510314e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""§6–§7: diagnosi per domanda (tutte le politiche), con attenzione alle discordanti D/B a 128k.
Uso: python3 analysis/diag.py  -> analysis/diag.json + analysis/diag.md

Convenzione del banco (verificata su tutte le 100 domande, vedi check_convention): il "tool result for round N" è
l'uscita dello strumento che PRECEDE il messaggio utente "Round N: ..." (indice = idx(Round N) − 2). La lettura
alternativa naturale, l'uscita che SEGUE "Round N" (idx(Round N) + 2), dà un "gold alternativo".
"""
import json
import re
import sqlite3
from collections import Counter, defaultdict
from pathlib import Path

import load as LD

OUT = Path(__file__).resolve().parent
rows = LD.load_results()
by = {(r["L"], r["pol"], r["qid"]): r for r in rows}


def ids_of(content):
    try:
        v = json.loads(content)
        if isinstance(v, dict) and "intersection" in v:
            return list(v["intersection"])
    except (ValueError, TypeError):
        pass
    return re.findall(r"\b\d{4}\b", content or "")


def round_user_idx(M, r):
    for n, m in enumerate(M):
        if m["role"] == "user" and isinstance(m["content"], str) and m["content"].startswith("Round %d:" % r):
            return n
    return None


def evidence(s):
    """Indici dei messaggi-prova (convenzione del banco) e alternativi, gold e gold alternativo."""
    M = s["messages"]
    t = s.get("pokemon_name") or s.get("target_name")
    rounds = [s["i_round"], s["j_round"]] if "i_round" in s else [s["round"]]
    ev, alt = [], []
    for r in rounds:
        k = round_user_idx(M, r)
        ev.append(k - 2)
        alt.append(k + 2 if k + 2 < len(M) and M[k + 2]["role"] == "tool" else None)
    if "i_round" in s:
        g = all(t in ids_of(M[i]["content"]) for i in ev)
        ga = all(i is not None and t in ids_of(M[i]["content"]) for i in alt)
    else:
        g = ids_of(M[ev[0]]["content"]).count(t)
        ga = ids_of(M[alt[0]]["content"]).count(t) if alt[0] is not None else None
    assert g == s["answer"], (s["id"], g, s["answer"])
    return {"target": t, "rounds": rounds, "ev": ev, "alt": alt, "gold": s["answer"], "gold_alt": ga,
            "n_msgs": len(M)}


def lcs_run(a, b):
    """Lunghezza della più lunga sequenza contigua comune (a = prova, b = testo)."""
    if not a or not b:
        return 0
    best = 0
    pos = defaultdict(list)
    for j, x in enumerate(b):
        pos[x].append(j)
    prev = {}
    for i, x in enumerate(a):
        cur = {}
        for j in pos.get(x, ()):
            cur[j] = prev.get(j - 1, 0) + 1
            if cur[j] > best:
                best = cur[j]
        prev = cur
    return best


def pred_norm(r):
    p = r["pred"]
    if isinstance(p, bool):
        return p
    if isinstance(p, str) and p.strip().lower() in ("yes", "true", "no", "false"):
        return p.strip().lower() in ("yes", "true")
    try:
        return int(p)
    except (TypeError, ValueError):
        return p


def _arg(rc, k):
    try:
        return json.loads(rc.get("args") or "{}").get(k)
    except ValueError:
        return None


def _kind(rc):
    try:
        a = json.loads(rc.get("args") or "{}")
    except ValueError:
        return "?"
    if "query" in a:
        return "id+query"
    if "offset" in a:
        return "id+offset"
    return "id+" + str(a.get("mode", "intero"))


def d_diag(r, e, sample):
    """Diagnostica D dal giornale e dall'archivio del proxy."""
    d = Path(r["dir"]) / "proxy"
    J = [json.loads(l) for l in open(d / "journal.jsonl", errors="replace") if l.strip()]
    ec = LD.load_engine_calls(r["dir"])
    con = sqlite3.connect("file:%s?mode=ro" % (d / "archive.sqlite"), uri=True)
    segs = con.execute("select seg, cut_idx, notes_msg from segments order by seg").fetchall()
    cut = segs[-1][1] if segs else 0
    notes = segs[-1][2] if segs else ""
    masked = {i for (i,) in con.execute("select idx from masks")}
    rid2idx = {rid: i for rid, i in con.execute("select rid, idx from archive")}
    arch_len = {i: n for i, n in con.execute("select idx, length(content) from archive where role='tool'")}
    inserts = []
    for (msgs,) in con.execute("select msgs from inserts"):
        for m in json.loads(msgs):
            if m.get("role") == "tool":
                inserts.append(m.get("content") or "")
    con.close()
    guards = [x for x in J if x.get("event") == "window_guard"]
    recalls = [x for x in J if x.get("event") == "recall"]
    notes_ev = [x for x in J if x.get("event") == "notes"]
    M = sample["messages"]
    out = {"switches": len(segs), "cut": cut, "rounds": sum(1 for c in ec if c["kind"] == "round"),
           "final_calls": sum(1 for c in ec if c["kind"] == "final"),
           "recall_n": len(recalls), "recall_args": [x.get("args") for x in recalls],
           "close": [(g.get("action"), g.get("reason"), g.get("where")) for g in guards],
           "removed_final": sum(len(g.get("removed_final") or []) for g in guards),
           "removed_search": sum(len(g.get("removed_search") or []) for g in guards),
           "notes_finish": [x.get("finish") for x in notes_ev],
           "final_prompt": max((c["prompt_tokens"] for c in ec if c["kind"] in ("final", "round")), default=0)}
    t = e["target"]
    for key, idxs in (("ev", e["ev"]), ("alt", e["alt"])):
        st = []
        for i in idxs:
            if i is None:
                st.append("n/a")
                continue
            ev_ids = ids_of(M[i]["content"])
            live = i >= cut and i not in masked
            rec = max((lcs_run(ev_ids, ids_of(x)) for x in inserts), default=0)
            res_i = [x for rc in recalls for x in (rc.get("results") or []) if x.get("idx") == i]
            by_id = [rc for rc in recalls if rid2idx.get(_arg(rc, "id")) == i]
            if live:
                st.append("vivo")
            elif rec >= max(1, int(0.9 * len(ev_ids))):
                st.append("letto intero")
            elif by_id or res_i:
                st.append("toccato (%s)" % ", ".join(sorted({_kind(rc) for rc in by_id} |
                                                         ({"risultato"} if res_i else set()))))
            else:
                st.append("assente")
        out[key + "_in_final"] = st
    # il modello ha cercato i round giusti? (recall che toccano gli indici-prova o i loro vicini)
    hit = set()
    for x in recalls:
        for res in x.get("results") or []:
            hit.add(res.get("idx"))
    out["touched_ev"] = [i in hit for i in e["ev"]]
    out["touched_alt"] = [i in hit for i in e["alt"] if i is not None]
    out["target_in_notes"] = t in (notes or "")
    out["reasoning_head"] = (json.loads((Path(r["dir"]) / "result.json").read_text()).get("reasoning") or "")[-600:]
    return out


def b_diag(r, e, sample):
    res = json.loads((Path(r["dir"]) / "result.json").read_text())
    evs = res.get("policy_events") or []
    comps = [x for x in evs if x.get("event") == "compact"]
    fc = [x for x in evs if x.get("event") == "final_context"]
    n_hist = e["n_msgs"] - 1                      # messaggi di storia (indici 1..n_hist)
    raw = (fc[-1]["messages"] - 3) if (fc and comps) else n_hist
    first_raw = n_hist - raw + 1
    summ = comps[-1]["summary"] if comps else ""
    t = e["target"]
    st = []
    for i in e["ev"]:
        if i >= first_raw:
            st.append("vivo")
        else:
            ev_ids = ids_of(sample["messages"][i]["content"])
            run = lcs_run(ev_ids, ids_of(summ))
            st.append("nel riassunto intero" if run >= len(ev_ids) else
                      ("nel riassunto in parte (%d/%d)" % (run, len(ev_ids)) if run else "assente"))
    return {"compactions": len(comps), "first_raw_idx": first_raw, "ev_in_final": st,
            "target_in_summary": t in summ,
            "rounds_in_summary": [("Round %d" % k) in summ or ("round %d" % k) in summ.lower() for k in e["rounds"]],
            "summary_finish": [x.get("finish_reason") for x in comps][-1:] if comps else [],
            "summary_tail": summ[-500:]}


def main():
    diag = {}
    for L in LD.LENGTHS:
        S = {**LD.samples(L, "CF"), **LD.samples(L, "FD")}
        for q in sorted({r["qid"] for r in rows if r["L"] == L}):
            s = S[q]
            e = evidence(s)
            rec = {"L": L, "qid": q, "qt": LD.qtype_short(s["question_type"]), **{k: v for k, v in e.items()}}
            rec["neg"] = (e["gold"] is False) or (e["gold"] == 0)
            rec["conv_distinguishes"] = e["gold"] != e["gold_alt"]
            for pol in LD.POLS:
                r = by[(L, pol, q)]
                p = pred_norm(r)
                rec[pol] = {"ok": int(r["off"] >= 1), "pred": p if not isinstance(p, str) else p[:40],
                            "trunc": r["trunc"], "matches_alt": (p == e["gold_alt"]) and e["gold"] != e["gold_alt"],
                            "neg_answer": p in (False, 0)}
            rec["D_diag"] = d_diag(by[(L, "D", q)], e, s)
            rec["B_diag"] = b_diag(by[(L, "B", q)], e, s)
            diag[f"{L}/{q}"] = rec
    (OUT / "diag.json").write_text(json.dumps(diag, indent=1, ensure_ascii=False, default=str))
    return diag


if __name__ == "__main__":
    d = main()
    print(len(d), "domande")