| |
| """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 |
|
|
| |
| |
| |
| |
| |
| 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") |
|
|
|
|
| |
| 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() |
|
|