File size: 7,681 Bytes
72c7148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""``data/eval-v3/general_dev_template_check``: dev rows in the exact evaluation templates.

Round 1 trained and selected on one prompt and was tested on another (FACTBASE: eval/train
template mismatch). This suite takes held-out *dev* rows that the builders drew from the
public *train* splits (``data/master-v3/raw/{general_*,intent_massive,nli}/dev.jsonl``; the
sealed test splits are never touched), re-renders each one in the evaluation template of the
matching sealed protocol (T4 notebook / bench_apps.py wording, criteria descriptions, state
keys), and records whether the builder's own row already used exactly that template
(``meta.template_match`` + ``meta.template_diff``). It is not sealed: training may select on it.

    PYTHONPATH=src python -m macjev.eval.dev_suites [--per-source 60] [--seed 13]
"""
from __future__ import annotations

import argparse
import json
import random
from collections import Counter, defaultdict

from ..paths import EVAL_V3, RAW_V3
from ..schema import make_record, option_names
from .predictions import write_jsonl
from .suites import EMOTIONS, NEWS

SUITE = "general_dev_template_check"
NLI = {"entailment": "the premise implies the hypothesis is true",
       "neutral": "the premise neither implies nor contradicts the hypothesis",
       "contradiction": "the premise implies the hypothesis is false"}
SST = ["very negative", "negative", "neutral", "positive", "very positive"]


def eval_template(row: dict) -> tuple[str, dict, dict] | None:
    """(task, eval state, eval question) for a builder dev row, or None if no sealed protocol matches."""
    src, st, q = row["source"], row["state"], row["question"]
    names = option_names(q)
    if row["category"] == "general_topic" and set(names) == set(NEWS):
        return "ag_news", {"article": st.get("article")}, {"t": "choice", "ins": "What is the topic of `article`?",
                                                            "crit": dict(NEWS)}
    if row["category"] == "general_emotion" and set(names) == set(EMOTIONS):
        return "emotion", {"text": st.get("text")}, {"t": "choice",
                                                     "ins": "Which emotion is most strongly expressed in `text`?",
                                                     "crit": {e: None for e in EMOTIONS}}
    if row["category"] == "general_sentiment" and q["t"] == "score" and len(names) == 5:
        return "sst5", {"text": st.get("text")}, {"t": "score", "ins": "How positive is the sentiment of `text`?",
                                                  "crit": list(SST)}
    if row["category"] == "general_qa" and q["t"] == "noul":
        return "boolq", {"passage": st.get("passage"), "question": st.get("question")}, \
            {"t": "noul", "ins": "Based on `passage`, is the answer to `question` yes?", "crit": None}
    if row["category"] == "intent" and q["t"] == "choice" and "massive" in src:
        scen = "scenario" in src
        ins = "Which domain does `utterance` belong to?" if scen else "What is the user asking for in `utterance`?"
        return ("massive_scenario" if scen else "massive_intent"), {"utterance": st.get("utterance")}, \
            {"t": "choice", "ins": ins, "crit": {k: k.replace("_", " ").replace(".", ": ") for k in names}}
    if row["category"] == "nli" and set(names) == set(NLI):
        return "nli", {"premise": st.get("premise"), "hypothesis": st.get("hypothesis")}, \
            {"t": "choice", "ins": "What is the relationship between `premise` and `hypothesis`?", "crit": dict(NLI)}
    return None


def _diff(row: dict, state: dict, q: dict) -> list[str]:
    d = []
    if not isinstance(row["state"], dict) or set(row["state"]) != set(state):
        d.append("state_keys")
    rq = row["question"]
    if rq["t"] != q["t"]:
        d.append("qtype")
    if rq["ins"] != q["ins"]:
        d.append("ins")
    if q["t"] == "choice" and (list(rq.get("crit") or {}) != list(q["crit"]) and
                               set(rq.get("crit") or {}) == set(q["crit"])):
        d.append("option_order")
    if q["t"] == "choice" and {k: (rq.get("crit") or {}).get(k) for k in q["crit"]} != q["crit"]:
        d.append("crit_descriptions")
    if q["t"] == "score" and rq.get("crit") != q["crit"]:
        d.append("score_levels")
    if q["t"] == "noul" and rq.get("crit"):
        d.append("noul_crit")
    return d


def build(per_source: int = 60, seed: int = 13) -> tuple[list[dict], dict]:
    builders = ["general_topic", "general_emotion", "general_sentiment", "general_qa", "intent_massive", "nli"]
    pools = defaultdict(list)
    skipped = Counter()
    for b in builders:
        path = RAW_V3 / b / "dev.jsonl"
        if not path.exists():
            skipped[f"missing:{b}"] += 1
            continue
        for line in path.open():
            row = json.loads(line)
            t = eval_template(row)
            if t is None or any(v is None for v in t[1].values()):
                skipped[f"no_eval_template:{b}:{row['source']}"] += 1
                continue
            key = (t[0], row["source"], row["lang"] if t[0].startswith("massive") else "all")
            pools[key].append((row, t))
    rng = random.Random(seed)
    out = []
    for key in sorted(pools):
        items = pools[key]
        n = per_source if not key[0].startswith("massive") else max(10, per_source // 6)
        for row, (task, state, q) in rng.sample(items, min(n, len(items))):
            diff = _diff(row, state, q)
            meta = {"suite": SUITE, "task": task, "builder_id": row["id"], "template_match": not diff,
                    "template_diff": diff, "builder_template": (row.get("meta") or {}).get("template")}
            out.append(make_record(id=f"{SUITE}:{row['id']}", group_id=row["group_id"], split="dev",
                                   source=row["source"], category=row["category"], lang=row["lang"],
                                   license=row["license"], state=state, question=q, valid=row["label"]["valid"],
                                   soft=row["label"].get("soft"),
                                   provenance={**row.get("provenance", {}), "via": f"raw/{row['id']}"}, meta=meta))
    report = {"rows": len(out), "by_task": dict(Counter(r["meta"]["task"] for r in out)),
              "template_match": dict(Counter(f"{r['meta']['task']}:{r['meta']['template_match']}" for r in out)),
              "template_diffs": dict(Counter(f"{r['meta']['task']}:{d}" for r in out for d in r["meta"]["template_diff"])),
              "skipped": dict(skipped), "seed": seed, "per_source": per_source}
    return out, report


def write(per_source: int = 60, seed: int = 13) -> dict:
    rows, report = build(per_source, seed)
    d = EVAL_V3 / SUITE
    sha = write_jsonl(d / "rows.jsonl", rows)
    manifest = {"suite": SUITE, "sealed": False, "split": "dev", "rows_sha256": sha,
                "sources": "data/master-v3/raw/{general_topic,general_emotion,general_sentiment,general_qa,"
                           "intent_massive,nli}/dev.jsonl (held out from public train splits by the builders)",
                "licenses": dict(Counter(r["license"] for r in rows)), **report}
    (d / "manifest.json").write_text(json.dumps(manifest, indent=1, ensure_ascii=False) + "\n")
    return manifest


def main(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument("--per-source", type=int, default=60)
    ap.add_argument("--seed", type=int, default=13)
    a = ap.parse_args(argv)
    m = write(a.per_source, a.seed)
    print(json.dumps({k: m[k] for k in ("rows", "by_task", "template_match", "template_diffs", "skipped")}, indent=1))


if __name__ == "__main__":
    main()