File size: 9,558 Bytes
90264a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Deterministic QA of publish/ (variants + generated): formats, keys, excerpts, variant/parent consistency,
duplicates, leakage into val/test and the benchmark; writes stats.json and QA_REPORT.md.

    python qa.py            # report only
    python qa.py --drop     # also remove records with hard errors (format, leakage, duplicates) from publish/
"""
import argparse
import glob
import json
import re
from collections import Counter, defaultdict

from common import PUBLISH, RUNS, load_originals, norm_pl, read_jsonl, shingles, write_jsonl
from tasks import SYNTH, parse, rubric_error, tf_truth
from wiki import canon

REPO_SRV = "/scratch/WarsawModelTrainersHackathon-main"
HARD = {"format", "key", "excerpt", "leak_eval", "dup_exact", "parent_mismatch"}


def body(r):
    """Task content without header, instructions and source texts (for duplicate detection)."""
    p = parse(r)
    if r["task_type"] == "true_false":
        return " ".join(t for _, t in p["statements"])
    if r["task_type"] == "closed_choice":
        return " ".join(p["pre"][-1:] + [t for _, t in p["options"]])
    if r["task_type"] == "essay":
        return (p["thesis"] or "") + " " + " ".join(p["elements"])
    return " ".join(p["pre"])


def check(r, parents):
    f = []
    q, t, p = r.get("question", ""), r.get("task_type"), r.get("max_points")
    if not all(r.get(k) not in (None, "") for k in ("id", "epoch", "requirement", "task_type", "max_points",
                                                     "question", "rubric", "key_answer")):
        f.append(("format", "missing field"))
    if not re.match(rf"^Zadanie \d+\. \(0[–-]{p}\)$", q.split("\n")[0]):
        f.append(("format", "header"))
    if SYNTH in q:
        f.append(("format", "synthetic source label left"))
    if t == "closed_choice":
        if len(re.findall(r"(?m)^[A-D]\. ", q)) != 4 or r["key_answer"] not in list("ABCD"):
            f.append(("key", "mcq options/key"))
    elif t == "true_false":
        if len(re.findall(r"(?m)^[1-3]\. ", q)) != 3 or not re.fullmatch(r"1\. [PF], 2\. [PF], 3\. [PF]", r["key_answer"]):
            f.append(("key", "tf statements/key"))
    elif t == "essay":
        gk = r.get("grading_key") or {}
        if p != 15 or len(gk.get("elementy", [])) != 3 or "B. SPÓJNOŚĆ" not in r["rubric"]:
            f.append(("format", "essay key/rubric"))
    elif t and t.startswith("open"):
        if rubric_error(r["rubric"], p):
            f.append(("format", "open rubric"))
    for s in r.get("source_excerpt") or []:
        if canon(s["text"]) not in canon(q):
            f.append(("excerpt", "excerpt not in question"))
        if not (100 <= len(s["text"]) <= 700):
            f.append(("excerpt", f"excerpt length {len(s['text'])}"))
        if f"Fragment artykułu „{s['title']}”" not in q:
            f.append(("excerpt", "label"))
    if r.get("parent_id"):
        par = parents.get(r["parent_id"])
        if not par:
            f.append(("parent_mismatch", "parent missing"))
        elif t == "closed_choice":
            pp, vp = parse(par), parse(r)
            po, vo = dict(pp["options"]), dict(vp["options"])
            if sorted(canon(x) for x in po.values()) != sorted(canon(x) for x in vo.values()) or \
                    canon(po.get(par["key_answer"][:1], "")) != canon(vo.get(r["key_answer"], "?")):
                f.append(("parent_mismatch", "mcq options/correct option differ from parent"))
        elif t == "true_false":
            if sorted(tf_truth(par["key_answer"]).values()) != sorted(tf_truth(r["key_answer"]).values()):
                f.append(("parent_mismatch", "tf truth values differ from parent"))
    return f


def grams(s, n=5):
    t = norm_pl(s).split()
    return {" ".join(t[i:i + n]) for i in range(max(0, len(t) - n + 1))}


def main(a):
    parents = {r["id"]: r for r in load_originals()}
    recs = []
    for fam in ("variants", "generated"):
        for fn in sorted(glob.glob(str(PUBLISH / fam / "*" / "*.jsonl"))):
            for r in read_jsonl(fn):
                recs.append((fam, fn, r))
    flags = defaultdict(list)
    for fam, fn, r in recs:
        for k in check(r, parents):
            flags[r["id"]].append(k)
    # leakage into val/test/benchmark (80-char shingles, >= 2 shared)
    ev = set()
    for s in ("val", "test"):
        for x in read_jsonl(f"{REPO_SRV}/output/sft-v2.1/{s}.jsonl"):
            ev |= shingles(x["messages"][0]["content"])
    for fn in glob.glob(f"{REPO_SRV}/benchmark/exams_claude_extracted/*.json"):
        try:
            d = json.load(open(fn, encoding="utf-8"))
        except Exception:
            continue
        for qq in (d.get("questions") or []) if isinstance(d, dict) else []:
            ev |= shingles(qq if isinstance(qq, str) else json.dumps(qq, ensure_ascii=False))
    for fam, fn, r in recs:
        if len(shingles(r["question"]) & ev) >= 2:
            flags[r["id"]].append(("leak_eval", "shares >=2 shingles with val/test/benchmark"))
    # duplicates: exact (normalised body prefix) and near (word 5-gram Jaccard >= 0.8), variant-parent pairs excluded
    seen = {}
    for pid, par in parents.items():
        seen.setdefault(norm_pl(body(par))[:200], pid)
    for fam, fn, r in recs:
        k = norm_pl(body(r))[:200]
        if k in seen and seen[k] != r.get("parent_id"):
            flags[r["id"]].append(("dup_exact", f"same text as {seen[k]}"))
        else:
            seen.setdefault(k, r["id"])
    index, G = defaultdict(set), {}
    for fam, fn, r in recs:
        g = grams(body(r))
        G[r["id"]] = g
        for x in list(g)[:40]:
            index[x].add(r["id"])
    near = 0
    for fam, fn, r in recs:
        cand = Counter(o for x in list(G[r["id"]])[:40] for o in index[x] if o != r["id"])
        for o, c in cand.items():
            if c >= 3 and o < r["id"]:
                a_, b_ = G[r["id"]], G[o]
                if a_ and len(a_ & b_) / len(a_ | b_) >= 0.8:
                    flags[r["id"]].append(("dup_near", f"~{o}"))
                    near += 1
                    break
    # stats
    st = {"families": {}, "kinds_total": Counter(), "by_epoch_type": Counter(), "verify": Counter(),
          "paraphrase": Counter(), "grounding": Counter(), "with_source": Counter()}
    kind_of = lambda t: "essay" if t == "essay" else "closed" if t in ("closed_choice", "true_false") else "open"
    for fam, fn, r in recs:
        st["families"][fam] = st["families"].get(fam, 0) + 1
        st["kinds_total"][kind_of(r["task_type"])] += 1
        st["by_epoch_type"][f"{fam}|{r['epoch']}|{r['task_type']}"] += 1
        st["verify"][f"{fam}|{r['verify']['status']}|{r['verify']['method']}"] += 1
        if fam == "variants":
            st["paraphrase"][r["paraphrase"]["kind"]] += 1
        else:
            st["grounding"][r.get("grounding")] += 1
        st["with_source"][f"{fam}|{bool(r.get('source_excerpt'))}"] += 1
    fl = Counter(k for v in flags.values() for k, _ in v)
    hard_ids = {i for i, v in flags.items() if any(k in HARD for k, _ in v)}
    wc = [x for fn in glob.glob(str(PUBLISH / "wiki_check" / "*.jsonl")) for x in read_jsonl(fn)]
    st["wiki_check"] = Counter(f"{x['status']}|{'evidence' if x['evidence_verified'] else 'no_evidence'}" for x in wc)
    st["flags"] = fl
    st["hard_flagged"] = len(hard_ids)
    st = json.loads(json.dumps(st))
    if a.drop and hard_ids:
        for fn in sorted({fn for fam, fn, r in recs}):
            rows = read_jsonl(fn)
            keep = [r for r in rows if r["id"] not in hard_ids]
            if len(keep) != len(rows):
                write_jsonl(fn, keep)
        st["dropped"] = len(hard_ids)
    kt = Counter(st["kinds_total"])
    if a.drop:
        for fam, fn, r in recs:
            if r["id"] in hard_ids:
                kt[kind_of(r["task_type"])] -= 1
    st["kinds_total_published"] = dict(kt)
    (PUBLISH / "stats.json").write_text(json.dumps(st, ensure_ascii=False, indent=1), encoding="utf-8")
    write_jsonl(RUNS / "qa_flags.jsonl", [{"id": i, "flags": [f"{k}: {m}" for k, m in v]} for i, v in flags.items()])
    lines = ["# QA report (generated by scripts/qa.py)", "",
             f"Records checked: {len(recs)} ({st['families']}).", "",
             "## Totals per kind (variants + generated)", "", "| kind | records | published |", "|---|---|---|"]
    for k in ("closed", "open", "essay"):
        lines.append(f"| {k} | {st['kinds_total'].get(k, 0)} | {kt.get(k, 0)} |")
    lines += ["", "## Flags", "", "| flag | count | hard (dropped with --drop) |", "|---|---|---|"]
    for k, v in fl.most_common():
        lines.append(f"| {k} | {v} | {'yes' if k in HARD else 'no'} |")
    lines += ["", f"Hard-flagged records: {len(hard_ids)}" + (" (dropped)" if a.drop else ""), "",
              "## Verification", "", "| family / status / method | count |", "|---|---|"]
    for k, v in sorted(st["verify"].items()):
        lines.append(f"| {k} | {v} |")
    lines += ["", "## Fact-check of the originals (wiki_check)", "", "| status | count |", "|---|---|"]
    for k, v in sorted(st["wiki_check"].items()):
        lines.append(f"| {k} | {v} |")
    (PUBLISH / "QA_REPORT.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
    print(json.dumps({"records": len(recs), "flags": fl, "hard": len(hard_ids), "kinds": st["kinds_total"],
                      "published": dict(kt)}, ensure_ascii=False))


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--drop", action="store_true")
    main(ap.parse_args())