yacht's picture
OpenThai2.0-NLP-Core-Benchmark 1.1: test sets, scorers and system outputs for six Thai tasks.
0e6d825
Raw History Blame Contribute Delete
22.7 kB
"""Thai sentences, clauses, POS, UD dependencies and Penn trees: the frozen benchmark, version 1.0 (working name).
python bench.py check # every file against the sha256 in manifest.json
python bench.py score [--systems A B ...] [--tasks sentences clauses pos dependencies penn] [--json OUT]
python bench.py table # every system: results.json and the results block of README.md
A system is a folder predictions/<name>/ with any of these files (a task is scored when all its files are there):
sentences/<set>.jsonl {"id", "ends"}: character offsets in the given text where each sentence ends
clauses/<set>.jsonl the same for clauses (elementary discourse units)
syntax/<set>.gold.conllu CoNLL-U on the treebank's own words: UPOS and/or HEAD and DEPREL
syntax/<set>.raw.conllu CoNLL-U from each sentence's text alone (the system finds the words), with
"# sent_id" and "# text" as in data/syntax/<set>.conllu
penn/tud.gold.jsonl {"sent_id", "words", "brackets": [[i, j, label], ...]} on the gold words
penn/tud.raw.jsonl the same on the system's own words
`write_segments(name, task, fn)` writes sentences/ or clauses/ from a function text -> list of strings, and
`penn_brackets(tree)` turns a bracketed Penn tree into the words and brackets that are counted.
Comparisons are paired bootstraps with 10,000 resamples and a 95% interval, as in the test openings: documents
within each set for sentences and clauses (seed 112), sentences for POS and dependencies (seed 112) and for Penn
trees (seed 0). A difference is always the system minus the one it is compared with.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import sys
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from scoring.conllu import read_conllu # noqa: E402
from scoring.eval_spans import paired_bootstrap_f1, sentence_counts, sentence_summary # noqa: E402
from scoring.metrics import _nows_spans, corpus_counts, paired_bootstrap, summarize # noqa: E402
DATA, PRED = HERE / "data", HERE / "predictions"
SENT_BASE = ("pud", "opus100", "sukity", "alt")
SENT_SETS = [s + c for c in ("", "-nospace", "-asr") for s in SENT_BASE]
SENT_GROUPS = {"twelve sets": SENT_SETS, "spaced": SENT_SETS[:4], "no space": SENT_SETS[4:8], "ASR": SENT_SETS[8:]}
EDU_SETS = ("tud", "pud", "tdt")
SYN_SETS = ("tud", "pud", "tdt", "tudp")
TASKS = ("sentences", "clauses", "pos", "dependencies", "penn")
N_BOOT = 10000
def load_jsonl(path: Path) -> list[dict]:
return [json.loads(x) for x in open(path, encoding="utf-8")]
def manifest() -> dict:
return json.loads((HERE / "manifest.json").read_text(encoding="utf-8"))
# ------------------------------------------------------------------------------------------------ helpers for users
def write_segments(name: str, task: str, fn) -> None:
"""Run fn(text) -> list of strings (sentences or clauses, in order) on every document of `task` ("sentences" or
"clauses") and write predictions/<name>/<task>/. Whitespace between the pieces is ignored."""
sets = SENT_SETS if task == "sentences" else EDU_SETS
for st in sets:
rows = []
for d in load_jsonl(DATA / task / f"{st}.jsonl"):
text, pos, ends = d["text"], 0, []
for piece in fn(text):
piece = piece.strip()
if not piece:
continue
k = text.find(piece, pos)
if k < 0:
raise ValueError(f"{st} {d['id']}: a piece is not in the text in order: {piece[:40]!r}")
pos = k + len(piece)
ends.append(pos)
rows.append({"id": d["id"], "ends": ends})
f = PRED / name / task / f"{st}.jsonl"
f.parent.mkdir(parents=True, exist_ok=True)
f.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding="utf-8")
def _parse_tree(s: str):
toks = re.findall(r"\(|\)|[^\s()]+", s)
pos = 0
def node():
nonlocal pos
assert toks[pos] == "("
pos += 1
label = toks[pos] if toks[pos] not in "()" else ""
if label:
pos += 1
kids = []
while toks[pos] != ")":
if toks[pos] == "(":
kids.append(node())
else:
kids.append(toks[pos])
pos += 1
pos += 1
return label, kids
return node()
PTB_ESCAPES = {"-LRB-": "(", "-RRB-": ")", "-LSB-": "[", "-RSB-": "]", "-LCB-": "{", "-RCB-": "}"}
def penn_brackets(tree: str) -> tuple[list[str], list[list]]:
"""Words and brackets of a bracketed tree, counted as in the gold file: labels without function tags (NP-SBJ ->
NP) or indices, a unary chain one bracket per label, no preterminals (a node over one word only), no empty
elements (-NONE-) and no *SPC* leaves (a space). Leaves -LRB- and -RRB- are the words ( and )."""
words: list[str] = []
out: set = set()
def walk(n) -> tuple[int, int] | None:
label, kids = n
if label == "-NONE-":
return None
if len(kids) == 1 and isinstance(kids[0], str): # preterminal
if kids[0] == "*SPC*":
return None
words.append(PTB_ESCAPES.get(kids[0], kids[0]))
return len(words) - 1, len(words)
got = [s for s in (walk(k) for k in kids if not isinstance(k, str)) if s]
if not got:
return None
i, j = got[0][0], got[-1][1]
base = re.split(r"[-=]", label)[0] if label and not label.startswith("-") else label
if base:
out.add((i, j, base))
return i, j
root = _parse_tree(tree)
if root[0] == "" and len(root[1]) == 1: # ( (S ...) ) wrapper
root = root[1][0]
walk(root)
return words, [list(b) for b in sorted(out)]
def _chars(words: list[str]) -> list[tuple[int, int]]:
out, k = [], 0
for w in words:
n = sum(not c.isspace() for c in w)
out.append((k, k + n))
k += n
return out
# ------------------------------------------------------------------------------------------------ scoring per task
def _f1(x: np.ndarray) -> np.ndarray:
c, g, s = x[..., 0], x[..., 1], x[..., 2]
p = np.divide(c, s, out=np.zeros_like(c), where=s > 0)
r = np.divide(c, g, out=np.zeros_like(c), where=g > 0)
return np.divide(2 * p * r, p + r, out=np.zeros_like(p), where=(p + r) > 0)
def _interval(diffs: np.ndarray, base: float) -> dict:
lo, hi = np.percentile(diffs, [2.5, 97.5])
p = 2 * float(np.mean(diffs <= 0)) if base > 0 else (2 * float(np.mean(diffs >= 0)) if base < 0 else 1.0)
return _rounded({"diff": 100 * base, "lo": 100 * float(lo), "hi": 100 * float(hi), "p": min(p, 1.0)})
def _rounded(r: dict) -> dict:
"""Two decimals (p four), and `tie` decided before rounding: the 95% interval contains 0."""
out = {k: round(float(v), 2 if k != "p" else 4) for k, v in r.items()}
out["tie"] = bool(r["lo"] <= 0 <= r["hi"])
return out
class Segments:
"""Sentences or clauses: boundary F1 in whitespace-free coordinates (document ends excluded)."""
def __init__(self, task: str):
self.task, self.sets = task, (SENT_SETS if task == "sentences" else EDU_SETS)
self.gold = {st: load_jsonl(DATA / task / f"{st}.jsonl") for st in self.sets}
self._counts: dict = {}
def has(self, name: str) -> bool:
return all((PRED / name / self.task / f"{st}.jsonl").exists() for st in self.sets)
def counts(self, name: str, st: str) -> list:
key = (name, st)
if key not in self._counts:
pred = {d["id"]: d for d in load_jsonl(PRED / name / self.task / f"{st}.jsonl")}
missing = [g["id"] for g in self.gold[st] if g["id"] not in pred]
if missing:
raise ValueError(f"{name}: {len(missing)} documents missing in {self.task}/{st}")
self._counts[key] = [sentence_counts(g["text"], g["ends"], pred[g["id"]]["ends"]) for g in self.gold[st]]
return self._counts[key]
def scores(self, name: str) -> dict:
out = {}
for st in self.sets:
s = sentence_summary(self.counts(name, st))
out[st] = {"precision": round(s["precision"], 2), "recall": round(s["recall"], 2), "f1": round(s["f1"], 2)}
groups = SENT_GROUPS if self.task == "sentences" else {"mean of three": list(self.sets)}
for g, sets in groups.items():
out[g] = round(float(np.mean([sentence_summary(self.counts(name, st))["f1"] for st in sets])), 2)
return out
def compare(self, a: str, b: str) -> dict:
out = {}
if self.task == "sentences": # documents resampled within each set, the group's mean F1 (test opening)
for g, sets in SENT_GROUPS.items():
rng = np.random.default_rng(112)
diffs, base = np.zeros(N_BOOT), 0.0
for st in sets:
xa = np.array([[c.correct, c.gold, c.system] for c in self.counts(a, st)], float)
xb = np.array([[c.correct, c.gold, c.system] for c in self.counts(b, st)], float)
idx = rng.integers(0, len(xa), (N_BOOT, len(xa)))
diffs += (_f1(xa[idx].sum(1)) - _f1(xb[idx].sum(1))) / len(sets)
base += float(_f1(xa.sum(0)) - _f1(xb.sum(0))) / len(sets)
out[g] = _interval(diffs, base)
else:
for st in self.sets:
out[st] = _rounded(paired_bootstrap_f1(self.counts(a, st), self.counts(b, st)))
return out
class Syntax:
"""POS (UPOS) and UD dependencies, at gold words and from raw text (CoNLL 2018 definitions)."""
PRIMARY = {"pos": {"gold": "upos_acc", "raw": "upos_f1"}, "dependencies": {"gold": "las", "raw": "las_f1"}}
SHOWN = {"pos": {"gold": ["upos_acc", "upos_macro_f1_gold_labels"], "raw": ["words_f1", "upos_f1"]},
"dependencies": {"gold": ["uas", "las"], "raw": ["uas_f1", "las_f1"]}}
def __init__(self, task: str):
self.task = task
self.gold = {st: read_conllu(DATA / "syntax" / f"{st}.conllu") for st in SYN_SETS}
self._counts: dict = {}
def files(self, name: str) -> dict:
out = {}
for st in SYN_SETS:
for mode in ("gold", "raw"):
f = PRED / name / "syntax" / f"{st}.{mode}.conllu"
if f.exists():
out[(st, mode)] = f
return out
def has(self, name: str) -> bool:
fs = self.files(name)
if not fs:
return False
sents = read_conllu(next(iter(fs.values())))
words = [w for s in sents for w in s.words]
if self.task == "pos":
return any(w.upos not in ("_", "", None) for w in words)
return any(w.head >= 0 for w in words)
def counts(self, name: str, st: str, mode: str):
key = (name, st, mode)
if key not in self._counts:
self._counts[key] = corpus_counts(self.gold[st], read_conllu(self.files(name)[(st, mode)]), mode == "gold")
return self._counts[key]
def scores(self, name: str) -> dict:
out = {}
for (st, mode) in self.files(name):
s = summarize(self.counts(name, st, mode), mode == "gold")
out.setdefault(st, {})[mode] = {m: round(s[m], 2) for m in self.SHOWN[self.task][mode]}
return out
def compare(self, a: str, b: str) -> dict:
out = {}
both = set(self.files(a)) & set(self.files(b))
for (st, mode) in sorted(both):
m = self.PRIMARY[self.task][mode]
r = paired_bootstrap(self.counts(a, st, mode), self.counts(b, st, mode), mode == "gold", m)
out.setdefault(st, {})[mode] = {"metric": m, **_rounded(r)}
return out
class Penn:
"""Penn bracket F1 on tud-ptb v3 test (third round). At gold words a bracket is a span of words; from raw text it
is the span of characters (whitespace removed) its words cover, so it counts only if it covers exactly the
characters of a gold bracket with the same label."""
def __init__(self):
self.gold = load_jsonl(DATA / "penn/tud.jsonl")
self.ids = [g["sent_id"] for g in self.gold]
gsent = {s.sent_id: s for s in read_conllu(DATA / "syntax/tud.conllu")}
self.gb = {"gold": [{tuple(b) for b in g["brackets"]} for g in self.gold]}
self.gb["raw"] = [self._to_chars(g["brackets"], _nows_spans(gsent[g["sent_id"]])) for g in self.gold]
self._counts: dict = {}
@staticmethod
def _to_chars(brs, spans) -> set:
return {(spans[i][0], spans[j - 1][1], lb) for i, j, lb in brs}
def has(self, name: str) -> bool:
return all((PRED / name / "penn" / f"tud.{m}.jsonl").exists() for m in ("gold", "raw"))
def counts(self, name: str, mode: str):
key = (name, mode)
if key not in self._counts:
got = {r["sent_id"]: r for r in load_jsonl(PRED / name / "penn" / f"tud.{mode}.jsonl")}
cs, missing = [], 0
for sid, g, gw in zip(self.ids, self.gb[mode], self.gold):
r = got.get(sid)
if r is None or r.get("missing"):
missing += 1
if r is None:
br = set()
elif mode == "gold":
if r["words"] != gw["words"]:
raise ValueError(f"{name}: penn/tud.gold.jsonl {sid}: the words are not the gold words")
br = {tuple(b) for b in r["brackets"]}
else:
br = self._to_chars(r["brackets"], _chars(r["words"]))
cs.append((len(br & g), len(br), len(g)))
self._counts[key] = (np.array(cs, float), missing)
return self._counts[key]
@staticmethod
def _prf(c: np.ndarray):
tp, n_p, n_g = c.sum(0)
P, R = tp / max(n_p, 1), tp / max(n_g, 1)
return 100 * P, 100 * R, 100 * 2 * P * R / max(P + R, 1e-9)
def scores(self, name: str) -> dict:
out = {}
for mode in ("gold", "raw"):
c, missing = self.counts(name, mode)
P, R, F = self._prf(c)
out[mode] = {"precision": round(P, 2), "recall": round(R, 2), "f1": round(F, 2), "missing": missing}
return out
def compare(self, a: str, b: str) -> dict:
out = {}
for mode in ("gold", "raw"):
ca, cb = self.counts(a, mode)[0], self.counts(b, mode)[0]
idx = np.random.default_rng(0).integers(0, len(ca), (N_BOOT, len(ca)))
def f(x):
s = x[idx].sum(1)
P, R = s[:, 0] / np.maximum(s[:, 1], 1), s[:, 0] / np.maximum(s[:, 2], 1)
return 200 * P * R / np.maximum(P + R, 1e-9)
d = f(ca) - f(cb)
base = self._prf(ca)[2] - self._prf(cb)[2]
p = 2 * float(np.mean(d <= 0)) if base > 0 else (2 * float(np.mean(d >= 0)) if base < 0 else 1.0)
out[mode] = _rounded({"diff": base, "lo": float(np.percentile(d, 2.5)),
"hi": float(np.percentile(d, 97.5)), "p": min(p, 1.0)})
return out
def scorer(task: str):
return {"sentences": lambda: Segments("sentences"), "clauses": lambda: Segments("clauses"),
"pos": lambda: Syntax("pos"), "dependencies": lambda: Syntax("dependencies"), "penn": Penn}[task]()
# ------------------------------------------------------------------------------------------------ commands
def check() -> bool:
files = manifest()["files"]
bad = [f for f, h in files.items() if not (HERE / f).exists()
or hashlib.sha256((HERE / f).read_bytes()).hexdigest() != h]
print(f"{len(files) - len(bad)} of {len(files)} files match manifest.json" + (": " + ", ".join(bad) if bad else ""))
return not bad
def systems_info() -> dict:
return manifest()["systems"]
def run(systems: list[str] | None, tasks: list[str]) -> dict:
info = systems_info()
names = systems or sorted(p.name for p in PRED.iterdir() if p.is_dir())
ours = [n for n in names if info.get(n, {}).get("kind") in ("ours", None)]
res: dict = {"version": manifest()["version"], "tasks": {}}
for task in tasks:
sc = scorer(task)
have = [n for n in names if sc.has(n)]
t = {"scores": {n: sc.scores(n) for n in have}, "compared": {}}
for a in ours:
if a in have:
t["compared"][a] = {b: sc.compare(a, b) for b in have if b != a}
res["tasks"][task] = t
return res
def _name(n: str) -> str:
return systems_info().get(n, {}).get("name", n + " (submitted)")
def _kind(n: str) -> str:
return systems_info().get(n, {}).get("kind", "ours")
def render(res: dict) -> str:
"""Markdown tables: the rivals and references, sorted by the primary score, ours in bold; then each of our systems
minus the strongest rival of each column, with the 95% interval."""
L = []
def row(n, cells):
name = f"**{_name(n)}**" if _kind(n) == "ours" else _name(n)
return "| " + " | ".join([name] + cells) + " |"
def best_rival(scores, key):
rivals = [(key(v), n) for n, v in scores.items() if _kind(n) in ("rival", "baseline") and key(v) is not None]
return max(rivals)[1] if rivals else None
def d(c):
hi = f"{c['hi']:+.2f}" if c["hi"] or c["tie"] else "-0.00" # an interval that ends just below 0 is no tie
return f"{c['diff']:+.2f} [{c['lo']:+.2f}, {hi}]" + (" tie" if c["tie"] else "")
t = res["tasks"]
if "sentences" in t:
s = t["sentences"]["scores"]
L += ["### Sentences: boundary F1, mean of twelve sets", "",
"| System | Twelve sets | Spaced | No space | ASR |", "|---|---:|---:|---:|---:|"]
for n, v in sorted(s.items(), key=lambda kv: -kv[1]["twelve sets"]):
L.append(row(n, [f"{v[g]:.2f}" for g in SENT_GROUPS]))
for a, cmp in t["sentences"]["compared"].items():
b = best_rival(s, lambda v: v["twelve sets"])
if b:
L += ["", f"{_name(a)} minus {_name(b)}: " + "; ".join(f"{g} {d(cmp[b][g])}" for g in SENT_GROUPS) + "."]
L.append("")
if "clauses" in t:
s = t["clauses"]["scores"]
L += ["### Clauses: boundary F1", "", "| System | TUD | PUD | TDT | Mean |", "|---|---:|---:|---:|---:|"]
for n, v in sorted(s.items(), key=lambda kv: -kv[1]["mean of three"]):
L.append(row(n, [f"{v[st]['f1']:.2f}" for st in EDU_SETS] + [f"{v['mean of three']:.2f}"]))
for a, cmp in t["clauses"]["compared"].items():
for b in cmp:
L += ["", f"{_name(a)} minus {_name(b)}: " + "; ".join(f"{st.upper()} {d(cmp[b][st])}"
for st in EDU_SETS) + "."]
L.append("")
for task, title, cols in (("pos", "POS: UPOS accuracy at gold words, UPOS F1 from raw text", ("upos_acc", "upos_f1")),
("dependencies", "Dependencies: LAS at gold words, LAS F1 from raw text", ("las", "las_f1"))):
if task not in t:
continue
s = t[task]["scores"]
sets = ("tud", "pud", "tdt") if task == "pos" else SYN_SETS
L += [f"### {title}", "", "| System | " + " | ".join(f"{st.upper()} gold / raw" for st in sets) + " |",
"|---|" + "---:|" * len(sets)]
def cell(v, st):
g = v.get(st, {}).get("gold", {}).get(cols[0])
r = v.get(st, {}).get("raw", {}).get(cols[1])
return f"{g:.2f}" if g is not None else "–", f"{r:.2f}" if r is not None else "–"
for n, v in sorted(s.items(), key=lambda kv: -(kv[1].get("tud", {}).get("gold", {}).get(cols[0]) or 0)):
cells = [cell(v, st) for st in sets]
if any(x != "–" for c in cells for x in c): # a system with none of these sets (tudp only) is left out
L.append(row(n, [" / ".join(c) for c in cells]))
for a, cmp in t[task]["compared"].items():
parts = []
for st in sets:
for mode, col in (("gold", cols[0]), ("raw", cols[1])):
b = best_rival({n: v for n, v in s.items() if n in cmp},
lambda v: v.get(st, {}).get(mode, {}).get(col))
if b and st in cmp[b] and mode in cmp[b][st]:
parts.append(f"{st.upper()} {mode} vs {_name(b)} {d(cmp[b][st][mode])}")
if parts:
L += ["", f"{_name(a)} minus the strongest rival of each column: " + "; ".join(parts) + "."]
L.append("")
if "penn" in t:
s = t["penn"]["scores"]
L += ["### Penn trees: bracket F1 on tud-ptb v3 test (362 trees)", "",
"| System | Gold words P / R / F1 | Raw text P / R / F1 |", "|---|---:|---:|"]
for n, v in sorted(s.items(), key=lambda kv: -kv[1]["gold"]["f1"]):
L.append(row(n, [f"{v[m]['precision']:.2f} / {v[m]['recall']:.2f} / {v[m]['f1']:.2f}" for m in ("gold", "raw")]))
for a, cmp in t["penn"]["compared"].items():
for b in cmp:
if _kind(b) == "rival":
L += ["", f"{_name(a)} minus {_name(b)}: gold words {d(cmp[b]['gold'])}; raw text {d(cmp[b]['raw'])}."]
L.append("")
return "\n".join(L)
def main() -> None:
p = argparse.ArgumentParser()
p.add_argument("command", choices=("check", "score", "table"))
p.add_argument("--systems", nargs="*", default=None)
p.add_argument("--tasks", nargs="*", default=list(TASKS), choices=TASKS)
p.add_argument("--json", default=None)
a = p.parse_args()
if a.command == "check":
sys.exit(0 if check() else 1)
if not check():
sys.exit("files differ from manifest.json: the benchmark is not the frozen version")
res = run(a.systems, a.tasks)
if a.json:
Path(a.json).write_text(json.dumps(res, ensure_ascii=False, indent=1), encoding="utf-8")
md = render(res)
print(md)
if a.command == "table":
(HERE / "results.json").write_text(json.dumps(res, ensure_ascii=False, indent=1), encoding="utf-8")
readme = HERE / "README.md"
txt = readme.read_text(encoding="utf-8")
start, end = "<!-- results:start -->", "<!-- results:end -->"
if start in txt and end in txt:
txt = txt[:txt.index(start) + len(start)] + "\n" + md + "\n" + txt[txt.index(end):]
readme.write_text(txt, encoding="utf-8")
if __name__ == "__main__":
main()