File size: 9,418 Bytes
6f2ed01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""Answer-span extraction and full-answer scoring (spec section 7.4).

Five labels, unlike the three-way scheme it replaces:
    correct       an accepted alias is asserted
    incorrect     a different answer is asserted
    ambiguous     several incompatible answers, hedging, or a granularity miss
    abstain       the model declines or says it does not know
    unparseable   nothing answer-shaped survives extraction

Scoring is a pure function of the stored generation, so rules can be revised
and everything re-scored without touching the GPU.
"""
import re
import sys
import os

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from common import normalize

MAX_SPAN_TOKENS = 10
STRICT_SPAN_TOKENS = 6

# Containment only fires for aliases at least this long. Crowd-sourced Wikidata
# alias lists include ISO codes that are ordinary English words -- "can" is an
# alias of Canada, "ja" of Japanese -- and without a floor a generation like
# "It can be Germany" would contain " can " and score as a correct Canada
# answer. Short aliases still count, but only through exact match.
MIN_CONTAINMENT_ALIAS_CHARS = 4
ALIAS_STOPWORDS = {"can", "may", "will", "was", "are", "one", "two", "new",
                   "the", "and", "for", "his", "her", "its", "not", "all"}

_LEADIN = re.compile(
    r"^(?:the\s+answer\s+is|answer\s*:|it\s+is|it\s+was|it's|that\s+would\s+be|"
    r"that\s+is|this\s+is|he\s+is|she\s+is|they\s+are|he\s+was|she\s+was|"
    r"they\s+were)\b[\s:,-]*", re.I)
_NEGATION = re.compile(r"\b(not|no|never|isn't|wasn't|aren't|weren't|doesn't|"
                       r"didn't|don't|cannot|can't)\b", re.I)
_HEDGE = re.compile(r"\b(but|however|although|though|actually|maybe|perhaps|"
                    r"probably|possibly|might|unclear|some\s+sources|depends|"
                    r"either)\b", re.I)
_ABSTAIN = re.compile(
    r"\b(i\s+(?:do\s+not|don't)\s+know|i'm\s+not\s+sure|i\s+am\s+not\s+sure|"
    r"unknown|not\s+sure|no\s+idea|cannot\s+answer|can't\s+answer|"
    r"unable\s+to\s+(?:answer|determine)|insufficient\s+information|"
    r"as\s+an\s+ai)\b", re.I)
_SENT_END = re.compile(r"[.!?\n]")
_LIST_SEP = re.compile(r"\s*(?:,|;|\bor\b|\band\b|/|\|)\s*", re.I)
_YEAR = re.compile(r"\b(1[0-9]{3}|20[0-9]{2})\b")


def _tokens(t):
    return [w for w in re.split(r"[^\w]+", t) if w]


def extract_span(raw):
    """First answer-bearing clause. Returns (span, flags)."""
    flags = set()
    if raw is None:
        return "", {"empty"}
    text = raw.strip()
    if not text:
        return "", {"empty"}
    lines = [l for l in text.split("\n") if l.strip()]
    if not lines:
        return "", {"empty"}
    if len(lines) > 1:
        flags.add("multi_clause")
    first = lines[0].strip()
    m = _SENT_END.search(first)
    if m and first[m.start():].strip(" .!?"):
        flags.add("multi_clause")
    first = first[:m.start()] if m else first

    if _ABSTAIN.search(first):
        flags.add("abstain")
    if _NEGATION.search(first):
        flags.add("negation")
    if _HEDGE.search(first):
        flags.add("hedge")

    span = _LEADIN.sub("", first).strip()
    if len(_tokens(span)) > MAX_SPAN_TOKENS:
        flags.add("truncated")
        span = " ".join(span.split()[:MAX_SPAN_TOKENS])
    if not span:
        flags.add("empty")
    return span, flags


def split_candidates(span):
    parts = [p.strip() for p in _LIST_SEP.split(span) if p.strip()]
    return parts or ([span] if span else [])


def _match_year(span, golds, gran):
    got = set(_YEAR.findall(span))
    want = set()
    for g in golds:
        want.update(_YEAR.findall(str(g)))
    if not got or not want:
        return None
    if len(got) > 1:
        return ("ambiguous", None, "year_multiple")
    y = got.pop()
    if y not in want:
        return ("incorrect", None, "year_mismatch")
    if gran == "date" and not re.search(r"\b\d{1,2}\b", span.replace(y, "")):
        return ("ambiguous", y, "year_granularity_short")
    return ("correct", y, "year_parser")


def score(raw_generation, gold_aliases, answer_type="entity", granularity=None):
    """Label one generation. Returns dict(label, matched_alias, scorer, span, flags)."""
    span, flags = extract_span(raw_generation)
    out = {"span": span, "flags": sorted(flags)}

    if "abstain" in flags:
        return {**out, "label": "abstain", "matched_alias": None, "scorer": "abstain"}
    if "empty" in flags:
        return {**out, "label": "unparseable", "matched_alias": None, "scorer": "empty_span"}
    if "negation" in flags:
        return {**out, "label": "ambiguous", "matched_alias": None, "scorer": "negation"}

    n_span = normalize(span)
    if not n_span:
        return {**out, "label": "unparseable", "matched_alias": None,
                "scorer": "span_normalizes_to_empty"}

    norm_golds = {}
    for a in gold_aliases:
        na = normalize(a)
        if na:
            norm_golds.setdefault(na, a)

    if n_span in norm_golds:
        return {**out, "label": "correct", "matched_alias": norm_golds[n_span],
                "scorer": "exact_alias_after_normalization"}

    if answer_type in ("year", "date"):
        r = _match_year(span, gold_aliases, granularity or answer_type)
        if r:
            lbl, matched, scorer = r
            return {**out, "label": lbl, "matched_alias": matched, "scorer": scorer}

    cands = split_candidates(span)
    if len(cands) > 1:
        hits = [normalize(c) for c in cands if normalize(c) in norm_golds]
        distinct = set(hits)
        if len(distinct) == 1 and len(cands) == len(hits):
            h = distinct.pop()
            return {**out, "label": "correct", "matched_alias": norm_golds[h],
                    "scorer": "alias_list_all_accepted"}
        if hits:
            return {**out, "label": "ambiguous", "matched_alias": norm_golds[hits[0]],
                    "scorer": "conflicting_candidates"}

    if "hedge" not in flags and len(_tokens(n_span)) <= STRICT_SPAN_TOKENS:
        padded = f" {n_span} "
        for na, orig in norm_golds.items():
            if len(na) < MIN_CONTAINMENT_ALIAS_CHARS or na in ALIAS_STOPWORDS:
                continue
            if f" {na} " in padded:
                return {**out, "label": "correct", "matched_alias": orig,
                        "scorer": "alias_substring_short_span"}

    if flags & {"hedge", "truncated", "multi_clause"}:
        for na, orig in norm_golds.items():
            if len(na) < MIN_CONTAINMENT_ALIAS_CHARS or na in ALIAS_STOPWORDS:
                continue
            if f" {na} " in f" {n_span} ":
                return {**out, "label": "ambiguous", "matched_alias": orig,
                        "scorer": "gold_inside_unresolvable_prose"}

    return {**out, "label": "incorrect", "matched_alias": None, "scorer": "no_match"}


def needs_manual_review(result):
    return result["label"] in ("ambiguous", "unparseable") or \
        result["scorer"] in ("alias_substring_short_span", "year_granularity_short")


# --------------------------------------------------------------------- CLI
def main():
    """Label a generations file.

        python runner/scoring_full.py --gen outputs/evaluation/my-model.jsonl

    Pure CPU. The per-query booleans are copied onto every scored row so that
    downstream metric code can filter (`use_for_main_forward`,
    `answer_in_subject_surface`, ...) without joining back to the query bank.
    """
    import json, argparse, collections
    from common import data_path, out_path, read_jsonl

    ap = argparse.ArgumentParser()
    ap.add_argument("--gen", required=True, help="outputs/evaluation/<model>.jsonl")
    ap.add_argument("--queries", default=data_path("evaluation_queries_44416.jsonl"))
    ap.add_argument("--out", default=None, help="default: <gen>.scored.jsonl")
    args = ap.parse_args()

    dest = args.out or args.gen.replace(".jsonl", "") + ".scored.jsonl"
    carry = ("fact_id", "relation", "condition_family", "language", "target_slot",
             "answer_type", "answer_granularity", "answer_in_subject_surface",
             "use_for_main_forward", "use_for_reverse_analysis",
             "use_for_recognition_analysis")
    q = {r["query_id"]: r for r in read_jsonl(args.queries)}

    counts, n, missing = collections.Counter(), 0, 0
    with open(dest, "w") as f:
        for g in read_jsonl(args.gen):
            row = q.get(g["query_id"])
            if row is None:
                missing += 1
                continue
            res = score(g["raw_response"], row["gold_aliases"],
                        answer_type=row["answer_type"],
                        granularity=row.get("answer_granularity"))
            rec = {"query_id": g["query_id"], "model": g.get("model"),
                   **{k: row.get(k) for k in carry},
                   "raw_response": g["raw_response"], **res,
                   "needs_manual_review": needs_manual_review(res)}
            f.write(json.dumps(rec, ensure_ascii=False) + "\n")
            counts[res["label"]] += 1
            n += 1

    if missing:
        print(f"WARNING: {missing} generations had no matching query_id")
    total = max(n, 1)
    print(f"scored {n} -> {dest}")
    for label in ("correct", "incorrect", "ambiguous", "abstain", "unparseable"):
        print(f"  {label:12s} {counts[label]:6d}  {100*counts[label]/total:5.1f}%")


if __name__ == "__main__":
    main()