File size: 10,813 Bytes
870b63c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
"""Scoring for typed extraction.

A prediction for one field is ``{"value": ..., "confidence": c, "p_null": p}``:
``value`` None (an empty list for lists) means "not in the state", ``confidence``
is the predictor's probability that the answer it returned -- value or null --
is correct, and ``p_null`` its probability that the field is absent.

Every field gets an exact score in {0, 1} (lists: exact set match) plus a
partial score (text: token F1; lists: multiset F1). Three things are reported
separately because a single blended number hides them:

* **hallucination rate** -- on fields whose gold is null, the share answered
  with a value anyway. This is the safety number for an extractor.
* **miss rate** -- on fields with a value, the share answered null.
* **accuracy at 90% coverage** -- answer only the 90% most confident fields;
  extraction products tell users to route on confidence, so it has to mean
  something.

numpy only, so the scorer is testable without a model.
"""

from __future__ import annotations

import datetime as dt
import math
import re
import string
from collections import Counter, defaultdict
from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple

import numpy as np

from .schema import (DATE, DATETIME, DURATION, LIST, NUMBER, TEXT, TIME, Case,
                     Field, Gold)

REL_TOL = 1e-3


# ---------------------------------------------------------------- normalisers

_ARTICLES = re.compile(r"\b(a|an|the)\b", re.UNICODE)
_PUNCT = set(string.punctuation)


def norm_text(s: str) -> str:
    """SQuAD's answer normalisation: lower, no punctuation/articles, one space."""
    s = "".join(ch for ch in s.lower() if ch not in _PUNCT)
    return " ".join(_ARTICLES.sub(" ", s).split())


def token_f1(pred: str, gold: str) -> float:
    p, g = norm_text(pred).split(), norm_text(gold).split()
    if not p or not g:
        return float(p == g)
    common = sum((Counter(p) & Counter(g)).values())
    if common == 0:
        return 0.0
    prec, rec = common / len(p), common / len(g)
    return 2 * prec * rec / (prec + rec)


def _num(v: Any) -> Optional[float]:
    if isinstance(v, bool):
        return None
    if isinstance(v, (int, float)):
        return float(v)
    return None


def same_number(p: Any, g: Any, decimals: Optional[int] = None) -> bool:
    a, b = _num(p), _num(g)
    if a is None or b is None:
        return False
    if decimals is not None:
        return round(a, decimals) == round(b, decimals)
    return math.isclose(a, b, rel_tol=REL_TOL, abs_tol=1e-9)


def same_temporal(t: str, p: Any, g: Any) -> bool:
    if not isinstance(p, str) or not isinstance(g, str):
        return False
    try:
        if t == DATE:
            return dt.date.fromisoformat(p) == dt.date.fromisoformat(g)
        if t == TIME:
            return dt.time.fromisoformat(p) == dt.time.fromisoformat(g)
        return dt.datetime.fromisoformat(p) == dt.datetime.fromisoformat(g)
    except ValueError:
        return False


def same_scalar(t: str, p: Any, g: Any, options: Mapping[str, Any]) -> bool:
    if t == TEXT:
        return isinstance(p, str) and norm_text(p) == norm_text(g)
    if t in (NUMBER, DURATION):
        return same_number(p, g, options.get("decimals"))
    if t in (DATE, TIME, DATETIME):
        return same_temporal(t, p, g)
    return False


def _is_null(v: Any) -> bool:
    return v is None or v == []


# ---------------------------------------------------------------- one field

def score_field(f: Field, gold: Gold, value: Any) -> Tuple[float, float]:
    """(exact, partial) for one predicted value against the gold."""
    if gold.null or _is_null(value):
        s = float(gold.null and _is_null(value))
        return s, s
    if f.type == LIST:
        if not isinstance(value, list):
            return 0.0, 0.0
        best = max((_list_f1(f, value, g) for g in gold.accepted() if g), default=0.0)
        return float(best >= 1.0 - 1e-9), best
    exact = any(same_scalar(f.type, value, g, f.options) for g in gold.accepted())
    partial = float(exact)
    if f.type == TEXT and isinstance(value, str):
        partial = max(token_f1(value, g) for g in gold.accepted())
    return float(exact), partial


#: A text list item matches a gold item at this token Jaccard or above -- CUAD's own
#: convention. List gold is often whole clauses (CUAD, citations), and exact clause
#: boundaries are not what extraction is about.
LIST_TEXT_JACCARD = 0.5


def _jaccard(a: str, b: str) -> float:
    x, y = set(norm_text(a).split()), set(norm_text(b).split())
    return len(x & y) / len(x | y) if x | y else 1.0


def _item_match(t: str, p: Any, g: Any, options: Mapping[str, Any]) -> bool:
    if t == TEXT and isinstance(p, str) and isinstance(g, str):
        return norm_text(p) == norm_text(g) or _jaccard(p, g) >= LIST_TEXT_JACCARD
    return same_scalar(t, p, g, options)


def _list_f1(f: Field, pred: Sequence[Any], gold: Sequence[Any]) -> float:
    t = f.item_type
    unmatched = list(gold)
    hit = 0
    for p in pred:
        for i, g in enumerate(unmatched):
            if _item_match(t, p, g, f.options):
                hit += 1
                unmatched.pop(i)
                break
    if hit == 0:
        return 0.0
    prec, rec = hit / len(pred), hit / len(gold)
    return 2 * prec * rec / (prec + rec)


# ---------------------------------------------------------------- aggregate

def score_cases(cases: Sequence[Case], preds: Sequence[Mapping[str, Mapping[str, Any]]]
                ) -> Dict[str, Any]:
    rows: List[Dict[str, Any]] = []
    for case, pred in zip(cases, preds):
        for name, f in case.fields.items():
            g = case.gold[name]
            p = pred.get(name) or {}
            value = p.get("value")
            exact, partial = score_field(f, g, value)
            rows.append({
                "case": case.id, "family": case.family, "type": f.type,
                "gold_null": g.null, "pred_null": _is_null(value), "source": g.source,
                "exact": exact, "partial": partial,
                "confidence": p.get("confidence"), "p_null": p.get("p_null")})
    return summarise(rows)


def summarise(rows: Sequence[Mapping[str, Any]]) -> Dict[str, Any]:
    if not rows:
        return {"fields": 0}
    exact = np.array([r["exact"] for r in rows])
    out: Dict[str, Any] = {"fields": len(rows), "cases": len({r["case"] for r in rows}),
                           "exact": float(exact.mean()),
                           "partial": float(np.mean([r["partial"] for r in rows]))}
    by_type: Dict[str, List[float]] = defaultdict(list)
    for r in rows:
        by_type[r["type"]].append(r["exact"])
    out["by_type"] = {t: {"n": len(v), "exact": float(np.mean(v))} for t, v in sorted(by_type.items())}
    out["macro_exact"] = float(np.mean([v["exact"] for v in out["by_type"].values()]))

    by_family: Dict[str, List[Mapping[str, Any]]] = defaultdict(list)
    for r in rows:
        by_family[r["family"]].append(r)
    out["by_family"] = {k: _family(v) for k, v in sorted(by_family.items())}
    # Families differ ~10x in field count (CUAD asks 41 clauses per contract), so the
    # headline averages families rather than fields.
    out["macro_family_exact"] = float(np.mean([v["exact"] for v in out["by_family"].values()]))
    present = [v["exact_present"] for v in out["by_family"].values() if v.get("exact_present") is not None]
    out["macro_family_exact_present"] = float(np.mean(present)) if present else None

    by_source: Dict[str, List[float]] = defaultdict(list)
    for r in rows:
        if not r["gold_null"]:
            by_source[r["source"]].append(r["exact"])
    out["by_source"] = {k: {"n": len(v), "exact": float(np.mean(v))} for k, v in sorted(by_source.items())}

    out.update(_null_metrics(rows))
    out.update(_confidence_metrics(rows))
    return out


def _family(rows: Sequence[Mapping[str, Any]]) -> Dict[str, Any]:
    d = {"n": len(rows), "exact": float(np.mean([r["exact"] for r in rows])),
         "partial": float(np.mean([r["partial"] for r in rows]))}
    d.update(_null_metrics(rows))
    return d


def _null_metrics(rows: Sequence[Mapping[str, Any]]) -> Dict[str, Any]:
    null = [r for r in rows if r["gold_null"]]
    full = [r for r in rows if not r["gold_null"]]
    out: Dict[str, Any] = {
        "null_share": len(null) / len(rows),
        "hallucination": (float(np.mean([not r["pred_null"] for r in null])) if null else None),
        "miss": (float(np.mean([r["pred_null"] for r in full])) if full else None),
        "exact_present": (float(np.mean([r["exact"] for r in full])) if full else None),
    }
    scored = [r for r in rows if r.get("p_null") is not None]
    if null and full and len(scored) == len(rows):
        out["p_null_auroc"] = auroc([r["p_null"] for r in rows], [r["gold_null"] for r in rows])
    return out


def _confidence_metrics(rows: Sequence[Mapping[str, Any]]) -> Dict[str, Any]:
    conf = [r["confidence"] for r in rows]
    if any(c is None for c in conf):
        return {}
    c = np.clip(np.array(conf, dtype=float), 0.0, 1.0)
    y = np.array([r["exact"] for r in rows], dtype=float)
    order = np.argsort(-c, kind="stable")
    k = max(1, int(round(0.9 * len(rows))))
    return {"ece": ece(c, y), "brier": float(np.mean((c - y) ** 2)),
            "exact_at_90_coverage": float(y[order[:k]].mean()),
            "aurc": aurc(c, y)}


def ece(conf: np.ndarray, correct: np.ndarray, bins: int = 10) -> float:
    edges = np.linspace(0.0, 1.0, bins + 1)
    idx = np.clip(np.digitize(conf, edges[1:-1]), 0, bins - 1)
    total = 0.0
    for b in range(bins):
        m = idx == b
        if m.any():
            total += m.mean() * abs(conf[m].mean() - correct[m].mean())
    return float(total)


def aurc(conf: np.ndarray, correct: np.ndarray) -> float:
    """Area under the risk-coverage curve (lower is better)."""
    order = np.argsort(-conf, kind="stable")
    risk = np.cumsum(1.0 - correct[order]) / np.arange(1, len(order) + 1)
    return float(risk.mean())


def auroc(scores: Sequence[float], labels: Sequence[bool]) -> Optional[float]:
    s = np.asarray(scores, dtype=float)
    y = np.asarray(labels, dtype=bool)
    pos, neg = s[y], s[~y]
    if len(pos) == 0 or len(neg) == 0:
        return None
    ranks = _rankdata(np.concatenate([pos, neg]))
    return float((ranks[:len(pos)].sum() - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg)))


def _rankdata(a: np.ndarray) -> np.ndarray:
    order = np.argsort(a, kind="mergesort")
    ranks = np.empty(len(a), dtype=float)
    sa = a[order]
    i = 0
    while i < len(a):
        j = i
        while j + 1 < len(a) and sa[j + 1] == sa[i]:
            j += 1
        ranks[order[i:j + 1]] = (i + j) / 2 + 1
        i = j + 1
    return ranks