"""Score a system on this benchmark in one call. Which task this folder holds is in release.json. from benchmark import evaluate evaluate(fn, raw=raw_fn, name="my-system") python benchmark.py --module my_package:fn [--raw-module my_package:raw_fn] --name my-system python benchmark.py --predictions DIR --name my-system # DIR in the layout of predictions// The functions, by task (give fn, raw or both; sentences and clauses take fn only): sentences fn(text) -> the sentences of the text, in order (whitespace between them does not matter) clauses fn(text) -> the clause units of the text (one sentence), in order pos fn(words) -> one UPOS tag per word; raw(text) -> [(word, UPOS), ...] in text order dependencies fn(words) -> one (head, deprel) per word, heads 1-based, 0 = root; raw(text) -> [(word, head, deprel), ...] penn fn(words) -> a bracketed Penn tree over these words, "(S (NP (N w1)) ...)", the words ( and ) as -LRB- and -RRB-, None for no tree; raw(text) -> a bracketed tree over the parser's own words fn sees the treebank's words, raw only the text. The outputs go to outputs/NAME/ in the layout of predictions/, the scores are printed next to the published systems and saved in results-NAME.json. `python add_system.py NAME --from outputs/NAME` then adds the system to the published table. The first run builds the test files that may not be shared (build_testsets.py), once. """ from __future__ import annotations import argparse import contextlib import importlib import json import sys import time from pathlib import Path import numpy as np HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) import bench # noqa: E402 (the scorer of benchmark 1.0, unchanged) import build_testsets # noqa: E402 from scoring.conllu import Sentence, Word, format_sentence, read_conllu, words_from_spans # noqa: E402 from scoring.eval_spans import sentence_summary # noqa: E402 from scoring.metrics import summarize # noqa: E402 RELEASE = json.loads((HERE / "release.json").read_text(encoding="utf-8")) TASK = RELEASE["task"] FOLDER = {"sentences": "sentences", "clauses": "clauses", "pos": "syntax", "dependencies": "syntax", "penn": "penn"}[TASK] SYN = {"pos": ("upos_acc", "upos_f1"), "dependencies": ("las", "las_f1")} # the card's metric at gold words, raw text EXPECTED = HERE / "results" / "expected.json" # systems not run on ALT are scored on the other nine sentence sets, in groups of three (they are not in the # twelve-set ranking) SENT9 = [st for st in bench.SENT_SETS if not st.startswith("alt")] GROUPS9 = {"nine sets": SENT9, "spaced (3 sets)": SENT9[:3], "no space (3 sets)": SENT9[3:6], "ASR (3 sets)": SENT9[6:]} # marks of table cells (manifest.json: systems[NAME]["marks"] = {symbol: [set or mode, ...]}); a cell marked ‡, § or # † is never the bold best value of its column (‖ is no contamination: trained on the train split of that release) LEGEND = {"‡": "trained on this test set, as its model card, corpus name or training script says", "§": "likely trained on PUD: its card names no treebank, and its PUD score is far above its TDT score", "†": "no word segmenter: from raw text, its words are subword pieces", "‖": "trained on the training split of TUD as released with its paper, so the TUDP column holds the " "annotation it learnt"} NOT_BEST = ("‡", "§", "†") def manifest() -> dict: return json.loads((HERE / "manifest.json").read_text(encoding="utf-8")) def expected() -> dict: return json.loads(EXPECTED.read_text(encoding="utf-8")) @contextlib.contextmanager def system_root(folder: Path): """Let the unchanged scorer read a system folder outside predictions/: it reads PRED///.""" old = bench.PRED bench.PRED = folder.resolve().parent try: yield folder.resolve().name finally: bench.PRED = old def scorer(): return bench.scorer(TASK) def sentence_sets(name: str) -> list[str]: return [st for st in bench.SENT_SETS if (bench.PRED / name / "sentences" / f"{st}.jsonl").exists()] def has(sc, name: str) -> bool: if TASK == "penn": return any((bench.PRED / name / "penn" / f"tud.{m}.jsonl").exists() for m in ("gold", "raw")) if TASK == "sentences": return set(SENT9) <= set(sentence_sets(name)) return sc.has(name) def scores_of(folder: Path, sc=None) -> dict: """The scores of one system folder, as results.json of benchmark 1.0 stores them (two decimals). Sentences without the ALT sets: the nine other sets and the means of their groups of three, by the same rules.""" sc = sc or scorer() with system_root(folder) as name: if not has(sc, name): raise SystemExit(f"{folder}: no {TASK} outputs (see the formats in bench.py)") if TASK == "sentences": have = sentence_sets(name) if len(have) == len(bench.SENT_SETS): return sc.scores(name) if set(have) != set(SENT9): raise SystemExit(f"{folder}: the three ALT sets come all together or not at all") out = {} for st in SENT9: s = sentence_summary(sc.counts(name, st)) out[st] = {"precision": round(s["precision"], 2), "recall": round(s["recall"], 2), "f1": round(s["f1"], 2)} for g, sets in GROUPS9.items(): out[g] = round(float(np.mean([sentence_summary(sc.counts(name, st))["f1"] for st in sets])), 2) return out if TASK != "penn": return sc.scores(name) out = {} # bench.Penn.scores needs both modes; one is enough here for mode in ("gold", "raw"): if (bench.PRED / name / "penn" / f"tud.{mode}.jsonl").exists(): c, missing = sc.counts(name, mode) P, R, F = sc._prf(c) out[mode] = {"precision": round(P, 2), "recall": round(R, 2), "f1": round(F, 2), "missing": missing} return out def exact_of(folder: Path, sc=None) -> dict: """The numbers of the card, unrounded, so that one decimal is rounded once (from the stored outputs).""" sc = sc or scorer() with system_root(folder) as name: if TASK == "sentences": f1 = {st: sentence_summary(sc.counts(name, st))["f1"] for st in sentence_sets(name)} return {g: float(np.mean([f1[st] for st in sets])) for groups in (bench.SENT_GROUPS, GROUPS9) for g, sets in groups.items() if all(st in f1 for st in sets)} if TASK == "clauses": f1 = {st: sentence_summary(sc.counts(name, st))["f1"] for st in bench.EDU_SETS} return {**f1, "mean of three": float(np.mean([f1[st] for st in bench.EDU_SETS]))} if TASK == "penn": return {m: sc._prf(sc.counts(name, m)[0])[2] for m in ("gold", "raw") if (bench.PRED / name / "penn" / f"tud.{m}.jsonl").exists()} return {f"{st}/{mode}": summarize(sc.counts(name, st, mode), mode == "gold")[SYN[TASK][mode == "raw"]] for (st, mode) in sc.files(name)} def compare(sc, a: str, b: str) -> dict: """a minus b, the paired bootstrap of bench.py (10,000 resamples, its seeds). Sentences: on the twelve sets when both systems have them, else in the same way on the nine sets without ALT (groups of three).""" if TASK != "sentences" or len(sentence_sets(a)) == len(sentence_sets(b)) == len(bench.SENT_SETS): return sc.compare(a, b) out = {} for g, sets in GROUPS9.items(): # as bench.Segments.compare: documents resampled within each set rng = np.random.default_rng(112) diffs, base = np.zeros(bench.N_BOOT), 0.0 for st in sets: xa = np.array([[c.correct, c.gold, c.system] for c in sc.counts(a, st)], float) xb = np.array([[c.correct, c.gold, c.system] for c in sc.counts(b, st)], float) idx = rng.integers(0, len(xa), (bench.N_BOOT, len(xa))) diffs += (bench._f1(xa[idx].sum(1)) - bench._f1(xb[idx].sum(1))) / len(sets) base += float(bench._f1(xa.sum(0)) - bench._f1(xb.sum(0))) / len(sets) out[g] = bench._interval(diffs, base) return out # ------------------------------------------------------------------------------------------------ the card's table def _marks(info: dict, sets=(), mode: str | None = None) -> str: """The marks of one cell: a mark applies to the cells of the sets or the mode (gold, raw) it names.""" return "".join(sym for sym, targets in info.get("marks", {}).items() if any(t == mode or t in sets for t in targets)) def _render(head: list[str], rows: list, state: dict) -> list[str]: """rows: (label, cells, counts); a cell is a list of parts (value or None, marks). The best shown value of each part of each column is bold; parts marked ‡, § or †, and the rows of reference systems (counts False), left out. state["bold"] records whether any value is bold.""" shown = lambda v: float(f"{v:.1f}") # noqa: E731 eligible = lambda m, ok: ok and not any(s in m for s in NOT_BEST) # noqa: E731 best: dict = {} for _, cells, ok in rows: for j, parts in enumerate(cells): for k, (v, m) in enumerate(parts): if v is not None and eligible(m, ok): best[(j, k)] = max(best.get((j, k), float("-inf")), shown(v)) lines = ["| " + " | ".join(head) + " |", "|---|" + "---:|" * (len(head) - 1)] for label, cells, ok in rows: out = [] for j, parts in enumerate(cells): texts = [] for k, (v, m) in enumerate(parts): if v is None: texts.append("–") continue t = f"{v:.1f}" if eligible(m, ok) and shown(v) == best[(j, k)]: t, state["bold"] = f"**{t}**", True texts.append(t + m) out.append("–" if set(texts) == {"–"} else " / ".join(texts)) lines.append("| " + " | ".join([label] + out) + " |") return lines def card_table() -> str: """The results of README.md: every system of manifest.json with stored outputs, sorted by the first column, ours in bold, one decimal from the unrounded scores, the best value of each column in bold, then the legend.""" systems = manifest()["systems"] names = [n for n in systems if (HERE / "predictions" / n).is_dir()] sc = scorer() exact = {n: exact_of(HERE / "predictions" / n, sc) for n in names} used: set = set() def label(n): s = systems[n].get("card", systems[n]["name"]) return f"**{s}**" if systems[n].get("kind") == "ours" else s def cell(n, value, **where): m = _marks(systems[n], **where) if value is not None else "" used.update(m) return value, m def ok(n): # a reference row is never the bold best value return systems[n].get("kind") != "reference" lines: list[str] = [] state = {"bold": False} if TASK == "sentences": twelve = [n for n in names if "twelve sets" in exact[n]] nine = [n for n in names if n not in twelve] def table(ns, groups, head): first = next(iter(groups)) rows = [(label(n), [[cell(n, exact[n].get(g), sets=sets)] for g, sets in groups.items()], ok(n)) for n in sorted(ns, key=lambda n: -exact[n][first])] return _render(head, rows, state) lines += table(twelve, bench.SENT_GROUPS, ["System", "All 12", "Spaced", "No space", "ASR"]) if nine: ours = [n for n in twelve if systems[n].get("kind") == "ours"] lines += ["", "Systems that were not run on ALT, on the other three sets (PUD, OPUS-100, sukity): boundary F1 " "(%), the mean of the three sets in each condition" + (", our row on the same sets" if ours else "") + ":", ""] lines += table(nine + ours, GROUPS9, ["System", "All 9", "Spaced", "No space", "ASR"]) elif TASK == "clauses": sets = bench.EDU_SETS rows = [(label(n), [[cell(n, exact[n][st], sets=(st,))] for st in sets] + [[cell(n, exact[n]["mean of three"], sets=sets)]], ok(n)) for n in sorted(names, key=lambda n: -exact[n]["mean of three"])] lines += _render(["System"] + [st.upper() for st in sets] + ["Mean"], rows, state) elif TASK == "penn": rows = [(label(n), [[cell(n, exact[n].get(m), mode=m)] for m in ("gold", "raw")], ok(n)) for n in sorted(names, key=lambda n: (-exact[n].get("gold", -1), -exact[n].get("raw", -1)))] lines += _render(["System", "Gold words", "Raw text"], rows, state) else: rows, keys = [], {} for n in names: if "row_of" in systems[n]: # shown in the row of the run it belongs to continue r = systems[n].get("raw_from", n) # the run whose raw-text columns this row shows er = exact.get(r, {}) cells = [[cell(n, exact[n].get(f"{st}/gold"), sets=(st,), mode="gold"), cell(r if r in systems else n, er.get(f"{st}/raw"), sets=(st,), mode="raw")] for st in bench.SYN_SETS] rows.append((label(n), cells, ok(n))) keys[label(n)] = (-exact[n].get("tud/gold", -1), -er.get("tud/raw", -1)) lines += _render(["System"] + [st.upper() for st in bench.SYN_SETS], sorted(rows, key=lambda r: keys[r[0]]), state) joined = [systems[n].get("card", systems[n]["name"]) for n in names # the "-text" runs; any other if "row_of" not in systems[n] and systems[n].get("raw_from") == f"{n}-text"] # join: in the card if joined: owners = {j.split("/")[0] for j in joined} who = f"Each {owners.pop()} row" if len(owners) == 1 and "/" in joined[0] else "Each of the rows " + ", ".join(joined) lines += ["", f"{who} joins two runs of the model: the gold-word columns come from the run given the words, " "the raw-text columns from the run given the text (`-text` in `predictions/`)."] notes = [] legend = "; ".join(f"{s} {LEGEND[s]}" for s in LEGEND if s in used) if legend: notes.append(legend + ".") if state["bold"]: out_of_bold = [s for s in NOT_BEST if s in used] left = ([f"cells marked {'‡, § or †' if len(out_of_bold) == 3 else ' or '.join(out_of_bold)}"] if out_of_bold else []) left += ["reference rows"] if not all(ok(n) for n in names) else [] notes.append("Bold: the best value of each column" + (", " + " and ".join(left) + " left out" if left else "") + ".") if notes: lines += ["", " ".join(notes)] return "\n".join(lines) START, END = "", "" def card_with_table(card: str) -> str: if START not in card or END not in card: raise SystemExit(f"README.md has no {START} ... {END} block") return card[:card.index(START) + len(START)] + "\n" + card_table() + "\n" + card[card.index(END):] # ------------------------------------------------------------------------------------------------ writing outputs def _locate(text: str, forms: list[str], where: str) -> list[tuple[int, int]]: spans, pos = [], 0 for f in forms: i = text.find(f, pos) if not f or i < 0 or text[pos:i].strip(): raise ValueError(f"{where}: the word {f!r} is not the next part of the text: {text!r}") spans.append((i, i + len(f))) pos = i + len(f) if text[pos:].strip(): raise ValueError(f"{where}: the words do not cover the end of the text: {text!r}") return spans def _write(path: Path, blob: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(blob.encode("utf-8")) def write_outputs(folder: Path, fn=None, raw=None) -> None: """Run the functions on every test input and write the files the scorer reads, in folder/.""" if TASK in ("sentences", "clauses"): if fn is None: raise ValueError(f"{TASK}: give fn(text) -> list of {TASK}") with system_root(folder) as name: bench.write_segments(name, TASK, fn) return if TASK == "penn": gold = bench.load_jsonl(bench.DATA / "penn/tud.jsonl") for mode, f in (("gold", fn), ("raw", raw)): if f is None: continue rows = [] for g in gold: tree = f(list(g["words"])) if mode == "gold" else f(g["text"]) if tree is None: # no tree: counted with no brackets, as in benchmark 1.0 rows.append({"sent_id": g["sent_id"], "words": g["words"] if mode == "gold" else [], "brackets": [], "missing": True}) continue words, brackets = bench.penn_brackets(tree) if mode == "gold" and words != g["words"]: raise ValueError(f"penn {g['sent_id']}: the leaves of the tree are not the given words") if mode == "raw" and "".join("".join(words).split()) != "".join(g["text"].split()): raise ValueError(f"penn {g['sent_id']}: the leaves of the tree are not the characters of the text") rows.append({"sent_id": g["sent_id"], "words": words, "brackets": brackets}) _write(folder / "penn" / f"tud.{mode}.jsonl", "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows)) return for st in bench.SYN_SETS: gold = read_conllu(bench.DATA / "syntax" / f"{st}.conllu") for mode, f in (("gold", fn), ("raw", raw)): if f is None: continue sents = [] for g in gold: where = f"{st} sentence {len(sents) + 1}" if mode == "gold": out = list(f([w.form for w in g.words])) if len(out) != len(g.words): raise ValueError(f"{where}: {len(out)} outputs for {len(g.words)} words") words = [Word(form=w.form, misc=w.misc) for w in g.words] else: items = [tuple(x) for x in f(g.text)] words = words_from_spans(g.text, _locate(g.text, [x[0] for x in items], where)) out = [x[1:] for x in items] for w, o in zip(words, out): if TASK == "pos": w.upos = o if isinstance(o, str) else o[0] else: head, deprel = o if not 0 <= int(head) <= len(words): raise ValueError(f"{where}: head {head} is not a word of the sentence") w.head, w.deprel = int(head), str(deprel) sents.append(Sentence(words, list(g.comments))) # sent_id and text as in the gold file _write(folder / "syntax" / f"{st}.{mode}.conllu", "".join(format_sentence(s) for s in sents)) # ------------------------------------------------------------------------------------------------ evaluate def summary(scores: dict) -> dict: """The headline numbers of one system (stored precision: two decimals).""" if TASK == "sentences": groups = bench.SENT_GROUPS if "twelve sets" in scores else GROUPS9 return {g: scores[g] for g in groups} if TASK == "clauses": return {**{st: scores[st]["f1"] for st in bench.EDU_SETS}, "mean of three": scores["mean of three"]} if TASK == "penn": return {f"{m} F1": scores[m]["f1"] for m in ("gold", "raw") if m in scores} return {f"{st} {mode} {metric}": scores[st][mode][metric] for st in bench.SYN_SETS for mode, metric in zip(("gold", "raw"), SYN[TASK]) if mode in scores.get(st, {})} def _board(mine: dict, name: str, published: dict, systems: dict) -> None: cols = list(mine) print(" " + " ".join(f"{c:>18s}" for c in cols) + " system") rows = sorted(published.items(), key=lambda kv: -(kv[1].get(cols[0]) or 0)) + [(f"> {name}", mine)] for n, v in rows: cells = [f"{v[c]:18.2f}" if v.get(c) is not None else f"{'–':>18s}" for c in cols] print(" " + " ".join(cells) + " " + systems.get(n, {}).get("name", n)) def evaluate(fn=None, raw=None, name: str = "my-system", predictions: str | Path | None = None, save: bool = True) -> dict: """Score fn and/or raw (see the module docstring), or the files of a predictions folder.""" if predictions is None and fn is None and raw is None: raise ValueError("give fn, raw, or a predictions folder") build_testsets.prepare() t0 = time.time() if predictions is not None: folder = Path(predictions) else: folder = HERE / "outputs" / name write_outputs(folder, fn, raw) scores = scores_of(folder) print(f"{TASK}, benchmark {RELEASE['version']}: {name} ({time.time() - t0:.0f} s)\n") mine, systems = summary(scores), manifest()["systems"] published = {n: summary(v) for n, v in expected()["scores"].items()} _board(mine, name, {n: v for n, v in published.items() if set(v) & set(mine)}, systems) others = {n: v for n, v in published.items() if not set(v) & set(mine)} if TASK == "sentences" and others and "twelve sets" in scores: # the systems not run on ALT: the nine sets print("\n on the nine sets without ALT:") _board({g: round(x, 2) for g, x in exact_of(folder).items() if g in GROUPS9}, name, others, systems) result = {"task": TASK, "version": RELEASE["version"], "system": name, "date": time.strftime("%Y-%m-%d"), "outputs": str(folder), "scores": scores} if save: path = Path(f"results-{name}.json") path.write_text(json.dumps(result, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") print(f"\nSaved {path}" + ("" if predictions else f"; the outputs are in {folder}")) return result def _load(spec: str | None): if not spec: return None mod, _, fn = spec.partition(":") return getattr(importlib.import_module(mod), fn) def main() -> None: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--module", help="MODULE:FUNCTION, fn of the task (see above)") ap.add_argument("--raw-module", help="MODULE:FUNCTION, raw of the task (see above)") ap.add_argument("--predictions", help="a system folder in the layout of predictions//") ap.add_argument("--name", default="my-system") a = ap.parse_args() if not (a.module or a.raw_module or a.predictions): ap.error("give --module, --raw-module or --predictions") if a.module or a.raw_module: sys.path.insert(1, str(Path.cwd())) # the user's package, from the current folder evaluate(_load(a.module), _load(a.raw_module), name=a.name, predictions=a.predictions) if __name__ == "__main__": main()