From bfa1f3c304a25b8d9747b38902d5ad67970745a6 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 1 Dec 2026 16:25:17 +0100 Subject: [PATCH] feat(compare): add scoring functions to the Leaderboard One function is active, saved in the profile's leaderboard-weights.json. Counts, the default: every labelled task once. Weight vector: one weight per axis for Overall. Weight matrix: one weight per benchmark and axis, relative within the axis. Every weight is 1 until changed. The page's Scoring dialog edits them, with Normalize and Reset; the command saves the same. Closes #528 --- app/nullius/client.py | 4 +- app/nullius/leaderboard/board.py | 31 ++- app/nullius/leaderboard/cli.py | 52 +++- app/nullius/leaderboard/projection.py | 70 +++-- app/nullius/leaderboard/service.py | 16 +- app/nullius/leaderboard/weighting.py | 142 ++++++++++ app/static/leaderboard/board.js | 110 ++++++-- app/static/leaderboard/leaderboard.css | 8 + app/templates/leaderboard/board.html | 32 ++- app/tests/test_client.py | 3 + app/tests/test_leaderboard_weights.py | 341 ++++++++++++++++++++++++ app/ui_tests/browser/leaderboard.py | 340 ++++++++++++++++++++--- app/ui_tests/test_leaderboard_routes.py | 129 ++++++++- app/web/leaderboard.py | 35 ++- docs/cli/pages.md | 2 +- docs/cli/read-jobs.md | 5 + docs/field-guide.md | 43 ++- docs/releases/next.md | 1 + 18 files changed, 1256 insertions(+), 108 deletions(-) create mode 100644 app/nullius/leaderboard/weighting.py create mode 100644 app/tests/test_leaderboard_weights.py diff --git a/app/nullius/client.py b/app/nullius/client.py index ac11cf993..e6916f9b9 100644 --- a/app/nullius/client.py +++ b/app/nullius/client.py @@ -141,9 +141,9 @@ def compare(self, *job_ids: str, matched: bool = False, workspace: Optional[str] def leaderboard(self, workspace: Optional[str] = None, *, rows=None, every_task: bool = False, hide_axes=(), show_axes=(), hide_versions=(), hide_runs=(), unchecked_labels: Optional[str] = None) -> dict: """The workspace's Leaderboard: each row over its labelled tasks, by axis. ``rows``: the keys of the rows - compared on shared tasks, every row by default; ``every_task``: the view asked, never ranked; the rest + compared on shared tasks, every row by default, none when empty; ``every_task``: the view asked, never ranked; the rest leaves an axis, a ``benchmark@version`` or a run out. ``steps`` and ``calls`` stay uncounted.""" - return self.request("GET", "/leaderboard", workspace=workspace, row=list(rows or ()), tasks="every" if every_task else None, + return self.request("GET", "/leaderboard", workspace=workspace, row=list(rows or ()) or (None if rows is None else [""]), tasks="every" if every_task else None, hide_axis=list(hide_axes), show_axis=list(show_axes), hide_version=list(hide_versions), hide_run=list(hide_runs), unchecked=unchecked_labels) diff --git a/app/nullius/leaderboard/board.py b/app/nullius/leaderboard/board.py index b7dabc2d2..a20c0efbd 100644 --- a/app/nullius/leaderboard/board.py +++ b/app/nullius/leaderboard/board.py @@ -17,7 +17,7 @@ from math import isfinite from nullius.standard.contract import definitions -from . import labels as labelling, projection, weights +from . import labels as labelling, projection, weighting, weights TASKS = ("shared", "every") @@ -61,8 +61,12 @@ def _pass3(estimate, name): def build(jobs, agents, benchmarks, labels, *, rows=None, tasks="shared", hide_axes=(), show_axes=(), hide_versions=(), - hide_runs=(), unchecked="omit", listings=None, workspace_open=True, metric_sources=None): - """Pure board projection. Inputs belong to a single workspace and profile.""" + hide_runs=(), unchecked="omit", listings=None, workspace_open=True, metric_sources=None, function="counts", saved=None, vector=None): + """Pure board projection. Inputs belong to a single workspace and profile. ``function``: the scoring function + (``weighting.FUNCTIONS``), over ``saved``, the matrix, or ``vector``: + Overall, and so the ranks, follow it.""" + if function not in weighting.FUNCTIONS: + raise ValueError(f"function: {' or '.join(weighting.FUNCTIONS)}") if tasks not in TASKS: raise ValueError(f"tasks: {' or '.join(TASKS)}") unknown = [a for a in (*hide_axes, *show_axes) if a not in labelling.AXES] @@ -92,7 +96,9 @@ def build(jobs, agents, benchmarks, labels, *, rows=None, tasks="shared", hide_a kept = lambda j: j.job_id not in hide_runs and "@".join(at(j)) not in hide_versions trials = {} got = projection.project({key: [j for j in runs if kept(j)] for key, runs in grouped.items()}, benchmarks, labels, - cohort=rows, axes=shown, unchecked=unchecked, listings=listings, trials=trials) + cohort=rows, axes=shown, unchecked=unchecked, listings=listings, trials=trials, + weights=(saved or {}) if function == "matrix" else None, + vector=(vector or {}) if function == "vector" else None) names = {(b["key"], definitions.version_identity(b)): (b["label"], definitions.version_label(b)) for b in benchmarks} def name(benchmark, version): @@ -100,6 +106,19 @@ def name(benchmark, version): label, said = names.get((benchmark, version), (benchmark, "")) return " ".join(filter(None, (label, said or version[:7]))) + # the matrix: a cell only where the view's tasks give the benchmark the axis; the vector: a weight per shown axis + saved, vector, held, labels_of = saved or {}, vector or {}, got["held"][tasks], {b["key"]: b["label"] for b in benchmarks} + cells = sorted(({"key": b, "name": labels_of.get(b, b), "cells": {a: {"weight": saved.get(b, {}).get(a, 1)} for a in shown if b in held[a]}} + for b in {b for own in held.values() for b in own}), key=lambda b: (b["name"], b["key"])) + shown_by = {family: [a for a in names if a in shown] for family, names in labelling.FAMILIES.items()} + matrix = {"name": weighting.FUNCTIONS[function], "note": weighting.NOTES[function], + "axes": shown, "benchmarks": cells, "vector": {a: vector.get(a, 1) for a in shown}, + # weights that sum to 0 have no share to give: the matrix's axis, the vector's Overall, is not + # scored, and Normalize leaves it + "zero": [a for a in shown if held[a] and not any(b["cells"][a]["weight"] for b in cells if a in b["cells"])] if function == "matrix" + else [f"{family.capitalize()} overall" for family, names in shown_by.items() if any(held[a] for a in names) and not any(vector.get(a, 1) for a in names if held[a])] if function == "vector" else [], + "unused": [{"benchmark": b, "name": labels_of.get(b, b), "axis": a, "weight": own[a]} + for b, own in sorted(saved.items()) for a in shown if a in own and b not in held[a]]} out, aside = [], {} for key, runs in grouped.items(): identity, projected = identities[key], got["rows"][key] @@ -133,8 +152,8 @@ def name(benchmark, version): recorded = sorted({(at(j), j.job_id, key, j.dataset) for key, runs in grouped.items() for j in runs if all(at(j))}) counted = {id for r in out for id in r["runs"]} return {"rows": out, "tasks": tasks, "unchecked": got["unchecked"], "cohort": got["cohort"], - "axes": shown, "hidden": [a for a in labelling.AXES if a not in shown], - **{family: [a for a in axes if a in shown] for family, axes in labelling.FAMILIES.items()}, + "axes": shown, "hidden": [a for a in labelling.AXES if a not in shown], "function": function, "weights": matrix, + **shown_by, "n": got["n"], "n_overall": {family: compared["overall"][family]["n"] if compared else 0 for family in labelling.FAMILIES}, "warnings": got["warnings"] + [f"{name(*version)}: {len(ids)} {'run' if len(ids) == 1 else 'runs'} set aside. Hide a run to count another." for version, ids in sorted(aside.items())], diff --git a/app/nullius/leaderboard/cli.py b/app/nullius/leaderboard/cli.py index c092049d9..eaf48d0e1 100644 --- a/app/nullius/leaderboard/cli.py +++ b/app/nullius/leaderboard/cli.py @@ -7,7 +7,7 @@ import sys from nullius.runs import parse -from . import labels as labelling, service, weights +from . import labels as labelling, service, weighting, weights def options(parser): @@ -21,6 +21,25 @@ def options(parser): parser.add_argument("--unchecked-labels", dest="unchecked", choices=labelling.UNCHECKED, help=f"task labels not checked at a run's benchmark version; default: LEADERBOARD_UNCHECKED_LABELS, else omit") +def weight(text): + """``BENCHMARK:AXIS=NUMBER`` as (benchmark, axis, weight); no number is 1 again.""" + cell, _, value = text.rpartition("=") + benchmark, _, axis = cell.rpartition(":") + try: + return benchmark, axis, float(value) if value else None + except ValueError: + raise argparse.ArgumentTypeError(f"{text}: BENCHMARK:AXIS=NUMBER") from None + + +def axis_weight(text): + """``AXIS=NUMBER`` as (axis, weight); no number is 1 again.""" + axis, _, value = text.rpartition("=") + try: + return axis, float(value) if value else None + except ValueError: + raise argparse.ArgumentTypeError(f"{text}: AXIS=NUMBER") from None + + def chosen(args) -> dict: return {name: getattr(args, name) for name in (*service.QUERY.values(), "tasks", "unchecked")} @@ -67,13 +86,24 @@ def main(argv=None): epilog="Exit 0: read; 2: usage, an unknown row or axis; 3: missing root. Rows are compared on the tasks they all evaluated; --json holds both views.") parser.add_argument("roots", nargs="*", help="result roots in one workspace; omit for catalogue rows without recorded-run measurements") options(parser) - parser.add_argument("--json", action="store_true", help="full precision: rows and their keys, both views, N, ranks, coverage, pass^k, runs, warnings and observed metric counts") + parser.add_argument("--function", choices=tuple(weighting.FUNCTIONS), help="the scoring function, saved in the profile, counts at first. counts: each task once; " + "vector: Overall weighs each axis; matrix: an axis weighs each benchmark, and Overall is the average of the axes") + parser.add_argument("--weight", dest="cells", action="append", default=[], type=weight, metavar="BENCHMARK:AXIS=NUMBER", + help="save one weight of the matrix, relative within its axis; no number is 1 again") + parser.add_argument("--axis-weight", dest="axis_weights", action="append", default=[], type=axis_weight, metavar="AXIS=NUMBER", + help="save one weight of the vector, relative within its family; no number is 1 again") + parser.add_argument("--normalize-weights", action="store_true", help="rewrite the function's weights so each axis of the matrix, or each family of the vector, sums to 1; one that sums to 0 is left") + parser.add_argument("--reset-weights", action="store_true", help="every weight of the function back to 1") + parser.add_argument("--json", action="store_true", help="full precision: rows and their keys, both views, N, ranks, coverage, pass^k, runs, weights, warnings and observed metric counts") args = parser.parse_args(argv) if any(not os.path.isdir(root) for root in args.roots): print("A result root does not exist or is not a directory.", file=sys.stderr) return 3 try: - result = service.document(service.qualified(parse.load_all(args.roots)), workspace_open=bool(args.roots), deferred=True, **chosen(args)) + jobs = service.qualified(parse.load_all(args.roots)) + read = lambda deferred=False: service.document(jobs, workspace_open=bool(args.roots), deferred=deferred, **chosen(args)) + service.weigh(read, function=args.function, cells=args.cells, axes=args.axis_weights, normalize=args.normalize_weights, reset=args.reset_weights) + result = read(deferred=True) except ValueError as error: print(error, file=sys.stderr) return 2 @@ -84,6 +114,22 @@ def main(argv=None): print(line) shared = result["tasks"] == "shared" print(("Shared tasks" if shared else "Every task (not comparable)") + f" · unchecked labels: {result['unchecked']}") + matrix = result["weights"] + print(" · ".join(filter(None, (f"Function: {matrix['name']}", matrix["note"])))) + if result["function"] == "vector": + for family in labelling.FAMILIES: + if result[family]: + print(f" {family.capitalize()}: " + " · ".join(f"{axis} {matrix['vector'][axis]:g}" for axis in result[family])) + if result["function"] == "matrix": + for axis in result["axes"]: + column = [f"{b['name']} {b['cells'][axis]['weight']:g}" for b in matrix["benchmarks"] if axis in b["cells"]] + if column: + print(f" {axis}: {' · '.join(column)}") + unused = " · ".join(f"{u['name']} {u['axis']} {u['weight']:g}" for u in matrix["unused"]) + if unused: + print(f" Not applied: {unused}. No compared task of the benchmark has the label.") + if matrix["zero"]: + print(f" Not scored: {', '.join(matrix['zero'])}. The weights sum to 0.") for row in result["rows"]: overall = row[result["tasks"]]["overall"]["capabilities"]["resolved"] if row[result["tasks"]] else None print(f"{row['rank']['capabilities'] or ''}\t{row['name']}\t{row['company']}\t{row['version_label']}\t{weights.percent(overall)}") diff --git a/app/nullius/leaderboard/projection.py b/app/nullius/leaderboard/projection.py index 356972499..26c6b4428 100644 --- a/app/nullius/leaderboard/projection.py +++ b/app/nullius/leaderboard/projection.py @@ -123,6 +123,7 @@ def _tasks(jobs, whole, axes_of) -> tuple[dict, list, list]: def _rates(tasks): + """Both rates over the tasks, each counted once.""" n = len(tasks) return {"n": n, "resolved": sum(t.resolved for t in tasks) / n if n else None, "mean_score": sum(t.score for t in tasks) / n if n else None} @@ -141,33 +142,66 @@ def _pass_k(tasks): "benchmarks": [dict(benchmark=b, version=v, pass_k=attempts.for_tasks(ts)) for (b, v), ts in by.items()]} -def _cell(tasks): +def _cell(tasks, saved=None): """One cell over evaluated tasks: both rates, and each benchmark version apart, with the runs its tasks come - from. Two versions of one benchmark are two data points: the cell then has no rate of its own.""" + from. Two versions of one benchmark are two data points: the cell then has no rate of its own. ``saved``, a + weight per benchmark, weights the cell's own rates alone: each benchmark's rate counts by its weight over + their total, 1 with none saved; None counts each task once. + A benchmark weighted 0 counts for nothing, its versions neither; all at 0, the cell has no rate.""" by = {} for t in tasks: by.setdefault(t.id[:2], []).append(t) - apart = len({b for b, _ in by}) < len(by) - return dict(_rates(tasks), **({"resolved": None, "mean_score": None} if apart else {}), - benchmarks=[dict(benchmark=b, version=v, runs=sorted({t.job_id for t in ts}), **_rates(ts)) for (b, v), ts in by.items()]) - - -def _view(tasks, shown): + parts = {at: _rates(ts) for at, ts in by.items()} + own = _rates(tasks) + counted = {at: 1 for at in by} + if saved is not None: + top = max((saved.get(b, 1) for b, _ in by), default=0) # largest first: no total overflows + counted = {at: saved.get(at[0], 1) / top for at in by if saved.get(at[0], 1)} if top else {} + own.update({rate: _mean([(parts[at][rate], w) for at, w in counted.items()]) for rate in ("resolved", "mean_score")}) + if len({b for b, _ in counted}) < len(counted): + own.update(resolved=None, mean_score=None) + return dict(own, benchmarks=[dict(benchmark=b, version=v, runs=sorted({t.job_id for t in ts}), **parts[b, v]) for (b, v), ts in by.items()]) + + +def _mean(pairs): + """(value, weight) pairs as one value, a pair with no value left out; None when nothing weighs.""" + pairs = [(v, w) for v, w in pairs if v is not None] + top = max((w for _, w in pairs), default=0) + total = sum(w / top for _, w in pairs) if top else 0 + return sum(v * (w / top) for v, w in pairs) / total if total else None + + +def _view(tasks, shown, weights=None, vector=None): evaluated = [t for t in tasks if t.resolved is not None] - return {"axes": {a: _cell([t for t in evaluated if a in t.axes]) for a in shown}, - "overall": {family: _cell([t for t in evaluated if t.axes & (set(names) & set(shown))]) - for family, names in labelling.FAMILIES.items()}, + column = lambda a: None if weights is None else {b: own[a] for b, own in weights.items() if a in own} + axes = {a: _cell([t for t in evaluated if a in t.axes], column(a)) for a in shown} + overall = {family: _cell([t for t in evaluated if t.axes & (set(names) & set(shown))]) for family, names in labelling.FAMILIES.items()} + for family, rate in ((f, r) for f in overall for r in ("resolved", "mean_score") if weights is not None or vector is not None): + # a function with weights: the family's shown axes, each by the vector's weight or once + overall[family][rate] = _mean([(axes[a][rate], (vector or {}).get(a, 1)) for a in labelling.FAMILIES[family] if a in axes]) + return {"axes": axes, "overall": overall, "pass_k": _pass_k(tasks), "evidence": {"pass_k": {a: _pass_k([t for t in tasks if a in t.axes]) for a in shown}}} def project(rows: Mapping[str, Sequence], benchmarks: Sequence[dict], labels: Mapping[str, labelling.Labels], *, cohort: Sequence[str] | None = None, axes: Sequence[str] = labelling.AXES, unchecked: str = "omit", - listings: Mapping[tuple, Sequence[str]] | None = None, trials: dict | None = None) -> dict: + listings: Mapping[tuple, Sequence[str]] | None = None, trials: dict | None = None, + weights: Mapping[str, Mapping[str, float]] | None = None, + vector: Mapping[str, float] | None = None) -> dict: """``rows``: each row's runs by its key. ``benchmarks``: every version, resolved. ``labels``: ``labels.load``'s. ``cohort``: the rows compared on shared tasks; None is every row with an evaluated task of a shown axis, and an unknown key is refused. ``axes``: those shown; another leaves Overall. ``listings``: the unit ids of (benchmark, version, dataset), for coverage. ``trials``, when given, takes each row's attempts that ran of the - evaluated tasks a shown axis of each family holds, by view: what its time and cost are read from.""" + evaluated tasks a shown axis of each family holds, by view: what its time and cost are read from. + ``weights``: the matrix, a number per benchmark and axis (``weighting``), None for each task counted once. On + an axis, a row's value in a view is then its benchmarks' rates over that view's tasks, each by its weight over + their total (``_cell``), so equal weights are equal shares whatever each benchmark's count of tasks. A benchmark + with no weight counts by 1. Overall is then the mean of its family's shown axes' + values, each axis once, one with no value left out. ``vector``: a number per axis, None for no vector; an axis's + value stays the tasks', and Overall is its family's shown axes' values, each by its weight, 1 with none, over + their total. pass^k and coverage count each task once. + ``held``, per view, is the benchmarks that give each axis a task: of the shared ones, of every row's evaluated + tasks under ``every``.""" if unchecked not in labelling.UNCHECKED: raise ValueError(f"unchecked labels: {' or '.join(labelling.UNCHECKED)}") unknown = [k for k in cohort or () if k not in rows] @@ -193,6 +227,10 @@ def axes_of(tid): cohort = (list(dict.fromkeys(cohort)) if cohort is not None else [k for k in rows if any(per_row[k][0][tid].axes & set(axes) for tid in evaluated[k])]) shared = set.intersection(*(evaluated[k] for k in cohort)) if cohort else set() + def holders(tids): + return {a: sorted({tid[0] for tid in tids if a in axes_of(tid)}) for a in axes} + + held = {"shared": holders(shared), "every": holders(set().union(*evaluated.values()))} seen = sorted({(j.identity["benchmark"], j.identity["benchmark_version"]) for _, runs, _ in per_row.values() for j in runs}) warnings = [] for benchmark, version in seen: @@ -244,13 +282,13 @@ def total(runs, axis): out = {} for key, (tasks, runs, said) in per_row.items(): out[key] = {"runs": [j.job_id for j in runs], "warnings": said, "evaluated": len(evaluated[key]), - "every": _view(list(tasks.values()), axes), - "shared": _view([t for tid, t in tasks.items() if tid in shared], axes) if key in cohort else None, + "every": _view(list(tasks.values()), axes, weights, vector), + "shared": _view([t for tid, t in tasks.items() if tid in shared], axes, weights, vector) if key in cohort else None, "coverage": {a: {"evaluated": sum(a in tasks[tid].axes for tid in evaluated[key]), "labelled": total(runs, a)} for a in axes}} if trials is not None: ran = lambda view: {family: [t for task in view if task.resolved is not None and task.axes & set(names) & set(axes) for t in attempts.ran(task.trials)] for family, names in labelling.FAMILIES.items()} trials[key] = {"every": ran(tasks.values()), "shared": ran([t for tid, t in tasks.items() if tid in shared])} - return {"unchecked": unchecked, "axes": list(axes), "cohort": cohort, "warnings": warnings, "rows": out, + return {"unchecked": unchecked, "axes": list(axes), "cohort": cohort, "warnings": warnings, "rows": out, "held": held, "n": {a: sum(a in axes_of(tid) for tid in shared) for a in axes}} diff --git a/app/nullius/leaderboard/service.py b/app/nullius/leaderboard/service.py index 29f873e40..3b98b43ba 100644 --- a/app/nullius/leaderboard/service.py +++ b/app/nullius/leaderboard/service.py @@ -12,7 +12,7 @@ from nullius import paths from nullius.standard.contract import definitions from nullius.standard.runner import units -from . import board, labels as labelling, metrics +from . import board, labels as labelling, metrics, weighting # a query string's names for ``board.build``'s lists, each repeated QUERY = {"row": "rows", "hide_axis": "hide_axes", "show_axis": "show_axes", "hide_version": "hide_versions", "hide_run": "hide_runs"} @@ -63,12 +63,22 @@ def listings(benchmarks, jobs) -> dict: return out +def weigh(read, *, function=None, cells=(), axes=(), normalize=False, reset=False, shown=None) -> None: + """One change of the saved weights, the page's and the command's, as ``weighting.change`` takes it; Normalize + is over the axes and benchmarks of the board ``read`` gives. ``read`` refuses a selection it does not know + before anything is saved.""" + if function is not None or cells or axes or reset or normalize: + matrix = read()["weights"] + weighting.change(function=function, cells=cells, axes=axes, reset=reset, normalize=matrix if normalize else None, shown=shown) + + def document(jobs, *, workspace="", workspace_open=False, deferred=False, unchecked=None, **chosen): """The Leaderboard's document under ``board.build``'s input contract; ``unchecked`` None is the setting's.""" agents, benchmarks = catalogue() - sources = {} + sources, saved = {}, weighting.load() result = board.build(jobs, agents, benchmarks, labelling.load(benchmarks), listings=listings(benchmarks, jobs), workspace_open=workspace_open, - metric_sources=sources, unchecked=unchecked or unchecked_default(), **chosen) + metric_sources=sources, unchecked=unchecked or unchecked_default(), function=saved["function"], saved=saved["weights"], vector=saved["vector"], **chosen) + result["warnings"] += [f"{weighting.FILE}: {p}. To reset it: {weighting.RESET}" for p in saved["problems"]] # what a late answer is checked against: everything asked and everything read, before the deferred counts result["context"] = hashlib.sha256(json.dumps([workspace, result], sort_keys=True, default=str).encode()).hexdigest() # v0.3.0 saved its weights here: nothing reads the file, converts it or removes it diff --git a/app/nullius/leaderboard/weighting.py b/app/nullius/leaderboard/weighting.py new file mode 100644 index 000000000..1a738d35b --- /dev/null +++ b/app/nullius/leaderboard/weighting.py @@ -0,0 +1,142 @@ +"""The Leaderboard's scoring function and its weights, in the profile's ``leaderboard-weights.json``. + +``{"schema": 1, "function": "counts", "weights": {benchmark: {axis: number}}, "vector": {axis: number}}``. One function is active (``FUNCTIONS``); the numbers of the other two stay saved. + +- ``counts``: every labelled task once. +- ``vector``: one weight per axis, 1 unless saved. An axis's value is as ``counts`` gives it; Overall is its + family's shown axes' values, each by its weight over their total. +- ``matrix``: one weight per benchmark and axis, relative within the axis: a benchmark's share of an axis is its + weight over the total of the benchmarks there, whatever its count of tasks. A cell with none saved weighs 1. + Overall is the plain mean of its family's shown axes' values. + +A weight gives no task an axis: one for a benchmark with no labelled task on the axis is said, never applied. An +entry that does not read is left out alone and said; a file that does not read is ``counts``. Either way the file +is kept as it is until Reset or a correction. A file with ``on`` and no ``function`` reads as ``matrix`` or +``counts``. The page, the command and the API read this one file; a change is made under a lock beside it. +""" +from __future__ import annotations + +import json +from math import isfinite +from pathlib import Path + +from nullius import ondisk, paths +from . import labels as labelling + +FILE = "leaderboard-weights.json" +SCHEMA = 1 +# each function's name, and what the board says of Overall under it +FUNCTIONS = {"counts": "Counts", "vector": "Weight vector", "matrix": "Weight matrix"} +NOTES = {"counts": "", "vector": "Overall: the weighted average of the axes", "matrix": "Overall: the average of the weighted axes"} +RESET = "nullius leaderboard --reset-weights" +_NONE = {"function": "counts", "weights": {}, "vector": {}} +UNWRITABLE = "Normalize: a weight is too small or too large to rewrite. Nothing is changed." + + +def path() -> Path: + return Path(paths.config_dir()) / FILE + + +def number(value) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) and isfinite(value) and value >= 0 + + +def load() -> dict: + """``{function, weights, vector, problems}``: no file is ``counts`` with nothing saved.""" + try: + document = json.loads(path().read_text(encoding="utf-8")) + except FileNotFoundError: + return dict(_NONE, weights={}, vector={}, problems=[]) + except (OSError, ValueError, RecursionError) as error: + return dict(_NONE, weights={}, vector={}, problems=[str(error)]) + if not isinstance(document, dict) or document.get("schema") != SCHEMA or not isinstance(document.get("on", False), bool) \ + or not isinstance(document.get("function", "counts"), str) or document.get("function", "counts") not in FUNCTIONS \ + or set(document) - {"schema", "on", "function", "weights", "vector"} \ + or not all(isinstance(document.get(part, {}), dict) for part in ("weights", "vector")): + return dict(_NONE, weights={}, vector={}, problems=[ + f"{{schema: {SCHEMA}, function: {' or '.join(FUNCTIONS)}, weights: {{benchmark: {{axis: number}}}}, vector: {{axis: number}}}} and nothing else"]) + weights, problems = {}, [] + for benchmark, cells in document.get("weights", {}).items(): + for axis, value in cells.items() if isinstance(cells, dict) else [("", None)]: + if axis in labelling.AXES and number(value): + weights.setdefault(benchmark, {})[axis] = value + else: + problems.append(f"weights.{benchmark}{'.' + axis if axis else ''}: an axis and a number, 0 or more") + vector = {axis: value for axis, value in document.get("vector", {}).items() if axis in labelling.AXES and number(value)} + problems += [f"vector.{axis}: an axis and a number, 0 or more" for axis in document.get("vector", {}) if axis not in vector] + return {"function": document.get("function") or ("matrix" if document.get("on") else "counts"), + "weights": weights, "vector": vector, "problems": problems} + + +def _sum_to_1(column): + """What rewrites a column to sum to 1, largest first so no total overflows; None for a column of zeros. + A weight above 0 that would be written 0 is refused.""" + top = max(column, default=0) + total = sum(value / top for value in column) if top else 0 + + def by(value): + if value and not value / top / total: + raise ValueError(UNWRITABLE) + return value / top / total + return by if total else None + + +def change(*, function=None, cells=(), axes=(), reset=False, normalize=None, shown=None) -> None: + """Save what is asked and nothing else, one writer at a time. ``function``: the one now active. ``cells``: + (benchmark, axis, weight) of the matrix and ``axes``: (axis, weight) of the vector, None for 1 again. ``reset`` + and ``normalize`` are the active function's: every weight back to 1; the board's ``weights`` + (``board.build``), each of its matrix columns or each family of the vector rewritten to sum to 1 over what is + saved by then, every share kept; a benchmark the board does not have and with no weight saved stays at 1. + ``shown``: the function the asker saw, refused when another is active by then. ``counts`` has no weight to reset. + A file with a problem is changed by Reset alone, which then clears both.""" + for benchmark, axis, value in (*cells, *(("vector", axis, value) for axis, value in axes)): + if axis not in labelling.AXES: + raise ValueError(f"unknown axis {axis}") + if not benchmark or not isinstance(benchmark, str) or (value is not None and not number(value)): + raise ValueError("a weight: a benchmark, an axis and a number, 0 or more") + if function is not None and function not in FUNCTIONS: + raise ValueError(f"function: {' or '.join(FUNCTIONS)}") + path().parent.mkdir(parents=True, exist_ok=True) + with ondisk.locked(path().with_name(FILE + ".lock")): + saved = load() + if saved["problems"] and not reset: + raise ValueError(f"{FILE} does not read. Correct it, or reset it: {RESET}") + if shown is not None and not saved["problems"] and shown != saved["function"]: + raise ValueError(f"The function is now {FUNCTIONS[saved['function']]}. Nothing is changed.") + function = function or saved["function"] + if reset and function == "counts" and not saved["problems"]: + raise ValueError(f"{FUNCTIONS[function]} has no weights to reset. Nothing is changed.") + weights, vector = saved["weights"], saved["vector"] + if reset and (saved["problems"] or function != "vector"): + weights = {} + if reset and (saved["problems"] or function != "matrix"): + vector = {} + for benchmark, axis, value in cells: + weights.setdefault(benchmark, {})[axis] = value + weights = {b: kept for b, own in weights.items() if (kept := {a: w for a, w in own.items() if w is not None})} + for axis, value in axes: + vector[axis] = value + vector = {a: w for a, w in vector.items() if w is not None} + if normalize and function == "matrix": + for axis in normalize["axes"]: + # the whole axis by one divisor, the saved weights of benchmarks not on this board too, and the + # board's cells with none saved written: every share stays what it was. A column of zeros is left + held = [b["key"] for b in normalize["benchmarks"] if axis in b["cells"]] + by = _sum_to_1([weights.get(b, {}).get(axis, 1) for b in held]) + if by: + for b in held: + weights.setdefault(b, {}).setdefault(axis, 1) + for own in weights.values(): + if axis in own: + own[axis] = by(own[axis]) + if normalize and function == "vector": + for names in labelling.FAMILIES.values(): + by = _sum_to_1([vector.get(a, 1) for a in names if a in normalize["axes"]]) + if by: # every axis of the family is written, the hidden ones too: every share kept + vector.update({a: by(vector.get(a, 1)) for a in names}) + if not all(number(w) for own in weights.values() for w in own.values()) or not all(number(w) for w in vector.values()): + raise ValueError(UNWRITABLE) + document = {"schema": SCHEMA, "function": function, "weights": weights} + if vector: + document["vector"] = vector + ondisk.write_whole(path(), json.dumps(document, indent=2, allow_nan=False) + "\n") diff --git a/app/static/leaderboard/board.js b/app/static/leaderboard/board.js index 9b7271ba4..1cc0092c0 100644 --- a/app/static/leaderboard/board.js +++ b/app/static/leaderboard/board.js @@ -33,8 +33,8 @@ /* the charts, the card and the pickers show who is on the board: an agent filtered out of the table leaves them too */ let onTable = null; const shown = r => !onTable || onTable.has(r.key); - /* the average is the server's own mean, taken over the agents on the board */ - const fieldAverage = axis => { const v=data.rows.filter(shown).map(r=>value(r,axis)).filter(x=>x!=null); return v.length?v.reduce((a,b)=>a+b,0)/v.length:null; }; + /* the average is the server's own mean, taken over the cohort: a search or a filter leaves it as it is */ + const fieldAverage = axis => { const v=data.rows.map(r=>value(r,axis)).filter(x=>x!=null); return v.length?v.reduce((a,b)=>a+b,0)/v.length:null; }; const scored = () => data.rows.filter(r => overall(r) != null && shown(r)); /* a name says only as much as tells two rows apart: the version when an agent has several, the model when a version has several */ /* what tells a row from the others of its agent and version: the parts of its setup that differ among them */ @@ -209,26 +209,13 @@ th.replaceChildren(th.dataset.label, element('span', `${n} shared`, {class:'lb-n muted small'})); }); } - /* the rank is the server's, over the cohort the address names: a search or filter that asks reads the board again for - the rows that pass, and a redraw that does not ask never renumbers */ + /* the rank is the server's, over the cohort the address names (Scoring's Agents): a search or a filter only shows + and hides rows, and never renumbers */ table.addEventListener('table:drawn',e=>{ const keys=new Set(e.detail.rows.map(tr=>tr.dataset.key)); - if(asked){asked=false;cohort(keys);} const moved=!onTable||keys.size!==onTable.size||[...keys].some(k=>!onTable.has(k));onTable=keys; if(moved)follow(); }); - /* the agents a filter or a search leaves are the cohort: the board is read again for them, compared on the tasks they - share, and the address says who. Only the reader's own change of the search or a filter asks: a cohort the address - came with stays until then, and so does the one asked when its scores, drawn, move a row past a filter. */ - let asked=false; - function cohort(keys) { - /* every evaluated row is the default, no row at all is an empty `row=`: never the default's N */ - const all=data.rows.filter(r=>r.evaluated).map(r=>r.key), on=all.filter(k=>keys.has(k)), want=on.length===all.length?[]:on.length?on:['']; - const q=address(); - if(JSON.stringify([...want].sort())===JSON.stringify(q.getAll('row').sort()))return; - q.delete('row');want.forEach(k=>q.append('row',k));history.replaceState(null,'','?'+q); - fetchBoard().then(got=>{if(got)apply(got);}).catch(()=>{}); - } function follow() { const first=scored().sort((a,b)=>(rankOf(a)??1e9)-(rankOf(b)??1e9))[0]||data.rows.find(shown); if(row(versus)&&!shown(row(versus))){versus='average';document.querySelectorAll('[data-vs-select]').forEach(v=>setSelect(v,versus));} @@ -264,7 +251,6 @@ settle(); } const tools=document.getElementById(`${table.id}-tools`); - Object.entries({input:'[data-search]',change:'[data-filter-menu]',click:'[data-clear],[data-all],[data-none]'}).forEach(([type,asks])=>tools?.addEventListener(type,e=>{if(e.target.closest(asks))asked=true;},true)); function applyFamily() { document.querySelectorAll('[data-family]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.family===family))); table.querySelectorAll('[data-col]').forEach(cell=> { if(data.axes.includes(cell.dataset.col)) cell.hidden=!data[family].includes(cell.dataset.col); }); @@ -274,6 +260,8 @@ function menus() { const showing=new Set(shownHeads().map(th=>th.dataset.col)); tools?.querySelectorAll('input[data-sort-col]').forEach(box=>{if(box.value)box.closest('label').hidden=!showing.has(box.value);}); + /* Columns lists the shown family's axes, never the other's */ + tools?.querySelectorAll('[data-tools="columns"] input[data-col]').forEach(box=>{if(data.axes.includes(box.dataset.col))box.closest('label').hidden=!data[family].includes(box.dataset.col);}); const sorted=table.tHead.querySelector('th[data-sorted]')?.dataset.col; if(sorted&&!showing.has(sorted))unsort(); } @@ -555,18 +543,31 @@ /* the table's score columns and every chart show one measure, and each chart's title says which */ const measureName=()=>measure==='resolved'?'Resolved':'Mean score'; const showMeasure=()=>{press('lb-measure','data-measure',measure);document.querySelectorAll('[data-measure-name]').forEach(e=>{e.textContent=measureName();});}; + /* Scoring asks for a board with itself open: said after the address, and gone from it once read */ + const scoringAsked=location.hash==='#scoring'; /* the measure, the family and the unchecked-labels mode are in the address, like the rest of the view */ const addressed=()=>{const q=address();if(measure==='resolved')q.delete('measure');else q.set('measure',measure);if(family==='capabilities')q.delete('family');else q.set('family',family);history.replaceState(null,'','?'+q);}; showMeasure();addressed(); document.querySelectorAll('[data-measure]').forEach(b=>b.onclick=()=>{measure=b.dataset.measure;showMeasure();addressed();updateTable();draw();}); /* the view, the unchecked labels and the selection are the address: a change opens the board it names */ - document.querySelectorAll('[data-set]').forEach(b=>b.onclick=()=>{location.assign('?'+address({[b.dataset.set]:b.value}));}); - tools?.addEventListener('change',e=>{ + /* a weight being saved is saved first: a board is opened only once every save asked was answered, those asked + meanwhile too, and not after one that failed: Scoring stays open to try again, the box unticked as it was */ + let saving=Promise.resolve(), last=0, failed=0, saved=null; + const go=async(q,undo)=>{const before=failed;let asked;do{asked=saving;await asked;}while(asked!==saving);if(failed===before)location.assign('?'+q+'#scoring');else undo?.();}; + document.querySelectorAll('[data-set]').forEach(b=>b.onclick=()=>go(address({[b.dataset.set]:b.value}))); + const scoring=document.getElementById('lb-scoring'); + /* Agents names each row as the charts do: as much as tells it from the others */ + scoring.querySelectorAll('[data-choose="row"]').forEach(b=>{const r=row(b.value);if(r&&b.nextSibling)b.nextSibling.textContent=' '+label(r);}); + scoring.addEventListener('change',e=>{ if(!e.target.matches('[data-choose]'))return; - const q=address(), boxes=[...tools.querySelectorAll('[data-choose]')]; - /* an axis hidden unless asked is named when ticked; anything else when not */ - new Set(boxes.map(b=>b.dataset.choose)).forEach(name=>{q.delete(name);boxes.filter(b=>b.dataset.choose===name&&b.checked===(name==='show_axis')).forEach(b=>q.append(name,b.value));}); - location.assign('?'+q); + /* only the group changed is rewritten: the agents counted stay unnamed until Agents itself is changed. + An axis hidden unless asked is named when ticked; anything else when not; the agents counted are named when + not all of them, an empty `row=` when none */ + const q=address(), name=e.target.dataset.choose, boxes=[...scoring.querySelectorAll('[data-choose]')].filter(b=>b.dataset.choose===name), on=boxes.filter(b=>b.checked); + q.delete(name); + if(name==='row'){if(on.lengthb.value):['']).forEach(k=>q.append('row',k));} + else boxes.filter(b=>b.checked===(name==='show_axis')).forEach(b=>q.append(name,b.value)); + go(q,()=>{e.target.checked=!e.target.checked;}); }); document.querySelectorAll('[data-metric]').forEach(b=>b.onclick=()=>{metric=b.dataset.metric;press('lb-metric','data-metric',metric);drawScatter();}); /* the measures answer for the board they were asked about; when it changed meanwhile (a run that wrote a trial), the @@ -579,7 +580,66 @@ async function fetchBoard(){const turn=++generation;const response=await nulliusFetch(`/api/leaderboard?${address()}`);if(!response.ok)return null;const next=await response.json();return turn===generation?{next,turn}:null;} /* each family has its own Overall and ranks: the shown family's ranking orders the rows */ function useFamily(){data.rows.sort((a,b)=>(rankOf(a)??1e9)-(rankOf(b)??1e9)||!a.evaluated-!b.evaluated||a.name.localeCompare(b.name)||a.key.localeCompare(b.key));} - function apply({next,turn}){if(turn!==generation)return;data=next;useFamily();if(!row(selected))selected=data.selected;updateTable();draw();deferred(turn).catch(()=>{});} + function apply({next,turn},restore){if(turn!==generation)return;data=next;useFamily();if(!row(selected))selected=data.selected;updateTable();draw();weights(restore);deferred(turn).catch(()=>{});} + /* Scoring, a dialog: the view and the unchecked labels open the board they name with it still open; the function + and its weights are saved one change at a time, in the order asked. Only the last one asked draws its board, + and only for the address it was asked under; one that failed draws what the server holds, the saves before it + included, or the last board answered when the server cannot be read; an emptied cell is 1 again */ + const weightsBox=document.getElementById('lb-weights'); + document.getElementById('lb-scoring-open').onclick=()=>scoring.showModal(); + document.getElementById('lb-scoring-close').onclick=()=>scoring.close(); + /* the selection's menus, as a toolbar's; Escape in an open one closes the menu alone */ + scoring.querySelectorAll('[data-dropdown]').forEach(b=>NulliusTable.menu(b,b.parentNode.querySelector('.menu'))); + scoring.addEventListener('keydown',e=>{if(e.key==='Escape'&&scoring.querySelector('.menu:not([hidden])'))e.preventDefault();}); + scoring.addEventListener('click',e=>{ // the backdrop, not the dialog's own padding + const r=scoring.getBoundingClientRect(); + if(e.target===scoring&&(e.clientXr.right||e.clientYr.bottom))scoring.close(); + }); + if(scoringAsked)scoring.showModal(); + function weigh(body){ + const turn=++last; + saving=saving.then(async()=>{ + const at=String(address());let response=null; + try{response=await nulliusFetch(`/leaderboard/weights?${at}`,{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':scoring.dataset.csrf},body:JSON.stringify(body)});}catch(_){} + const next=await response?.json().catch(()=>null), ok=response?.ok&&next; + if(!ok){failed++;window.nulliusNotify?.(next?.error||'Weights not saved.',{error:true,key:'weights'});} + if(ok)saved={next,at}; + if(turn!==last)return; + if(ok&&at===String(address()))apply({next,turn:++generation}); + else{const got=await fetchBoard().catch(()=>null);if(got)apply(got,!ok);else if(!ok){if(saved?.at===String(address()))apply({next:saved.next,turn:++generation},true);else weights(true);}} + }); + } + function weights(restore){ + /* a cell being typed in keeps its text through another's answer, unless its own save failed */ + const w=data.weights, fn=data.function, at=document.activeElement?.dataset?.cell, typed=at&&!restore?document.activeElement.value:'', grid=weightsBox.querySelector('table'), note=name=>weightsBox.querySelector(`[data-note="${name}"]`); + document.querySelectorAll('[data-function]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.function===fn))); + const says=document.getElementById('lb-weights-on');says.hidden=!w.note;says.textContent=w.note;weightsBox.hidden=fn==='counts'; + /* what is no number is said by the field and saves nothing: the saved weight stays */ + const cell=(name,id,weight,body)=>{const td=element('td'),input=element('input',null,{type:'number',min:'0',step:'any','aria-label':name,'data-cell':id});input.value=Number(weight.toPrecision(3)); + input.onchange=()=>{if(!input.validity.valid){input.reportValidity();return;}weigh(body(input.value.trim()===''?null:Number(input.value)));};td.append(input);return td;}; + const head=element('tr'),thead=element('thead'),body=element('tbody'); + if(fn==='vector'){ + /* one row, an axis a cell, each family under its name */ + const groups=element('tr'),tr=element('tr'); + [['capabilities','Capabilities'],['domains','Domains']].forEach(([family,title])=>{if(!data[family].length)return;groups.append(element('th',title,{colspan:String(data[family].length)})); + data[family].forEach(a=>{head.append(element('th',a));tr.append(cell(a,a,w.vector[a],weight=>({axis:{axis:a,weight}})));});}); + thead.append(groups,head);body.append(tr); + }else{ + const axes=w.axes.filter(a=>w.benchmarks.some(b=>b.cells[a])); + head.append(element('th','Benchmark'));axes.forEach(a=>head.append(element('th',a)));thead.append(head); + w.benchmarks.forEach(b=>{const tr=element('tr');tr.append(element('td',b.name)); + axes.forEach(a=>tr.append(b.cells[a]?cell(`${b.name} ${a}`,`${b.key} ${a}`,b.cells[a].weight,weight=>({cell:{benchmark:b.key,axis:a,weight}})):element('td')));body.append(tr);}); + } + grid.replaceChildren(thead,body); + const unused=fn==='matrix'?w.unused:[]; + note('unused').hidden=!unused.length;note('unused').textContent=`Not applied: ${unused.map(u=>`${u.name} ${u.axis} ${Number(u.weight.toPrecision(3))}`).join(' · ')}. No compared task of the benchmark has the label.`; + note('zero').hidden=!w.zero.length;note('zero').textContent=`Not scored: ${w.zero.join(', ')}. The weights sum to 0.`; + const again=at&&[...grid.querySelectorAll('input')].find(i=>i.dataset.cell===at); + if(again){again.focus();if(typed)again.value=typed;} + } + document.querySelectorAll('[data-function]').forEach(b=>b.onclick=()=>weigh({function:b.dataset.function})); + scoring.querySelectorAll('[data-weights-do]').forEach(b=>b.onclick=()=>weigh({[b.dataset.weightsDo]:data.function})); + weights(); tools?.addEventListener('change',e=>{ const box=e.target;if(!box.matches('input[data-col]')||passing)return; if(!box.checked){e.stopPropagation();shrink(box);} diff --git a/app/static/leaderboard/leaderboard.css b/app/static/leaderboard/leaderboard.css index 168ecc82a..711cfa5f4 100644 --- a/app/static/leaderboard/leaderboard.css +++ b/app/static/leaderboard/leaderboard.css @@ -205,3 +205,11 @@ tr:hover .lb-medal .lb-disc { animation: lb-glow .9s ease-in-out .25s; } @media (prefers-reduced-motion: reduce) { .lb-medal, .lb-medal *, .lb-point, .lb-bar i, .lb-table, .lb-table th, .lb-table td, .lb-track > *, .lb-dot .lb-logo { animation: none !important; transition: none !important; } } +/* Scoring: wide enough for the weights' matrix; each toggle on its label's line; the weights' two actions under their + matrix, each cell a number as wide as five figures */ +dialog.std-how.lb-scoring { width: min(1440px, calc(100vw - 32px)); } +.lb-scoring-row { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; justify-content: space-between; margin-top: 16px; } +.lb-scoring-row > h3 { margin: 0; } +#lb-weights { margin: 12px 0 0; } +.lb-weights-do { display: flex; flex-wrap: wrap; gap: 8px; justify-content: flex-end; margin-top: 8px; } +#lb-weights input { width: 5.5rem; padding: 4px 8px; border: 1px solid var(--border); border-radius: 8px; background: var(--bg); color: var(--text); } diff --git a/app/templates/leaderboard/board.html b/app/templates/leaderboard/board.html index 67c2e6649..23d318f43 100644 --- a/app/templates/leaderboard/board.html +++ b/app/templates/leaderboard/board.html @@ -2,7 +2,7 @@ {% from '_page.html' import page_head %} {% import '_tables.html' as tables %} {% block title %}Leaderboard · Nullius{% endblock %} -{% block head %}{% endblock %} +{% block head %}{# the dialog's frame #}{% endblock %} {% macro picks() %}vs{% endmacro %} {#- One of the selection's menus: a box ticked counts. `name` is the query argument its unticked boxes are sent under; `shown`, for the axes hidden unless asked, the one its ticked boxes are. #} @@ -13,24 +13,24 @@ {% endif %}{% endmacro %} {% macro selection() %} {%- set axes = [] %}{% for family, title in [('capabilities', 'Capabilities'), ('domains', 'Domains')] %}{% for a in families[family] %}{% set _ = axes.append(dict(id=a, name=a, group=title, hidden=a in board.hidden, asked=a in unless_asked)) %}{% endfor %}{% endfor %} +{%- set agents = [] %}{% for r in board.rows if r.evaluated %}{% set _ = agents.append(dict(id=r.key, name=r.name, group='', hidden=r.key not in board.cohort)) %}{% endfor %} {%- set names = {} %}{% for r in board.rows %}{% set _ = names.update({r.key: r.name}) %}{% endfor %} {%- set versions = [] %}{% for v in board.versions %}{% set _ = versions.append(dict(v, group='')) %}{% endfor %} {%- set runs = [] %}{% for r in board.runs %}{% set _ = runs.append(dict(id=r.id, name=names[r.row] ~ ' · ' ~ r.id ~ (' · ' ~ r.dataset if r.dataset else ''), group=r.benchmark, hidden=r.hidden)) %}{% endfor %} -{{ choose('Axes', 'hide_axis', axes, 'show_axis') }}{{ choose('Benchmark versions', 'hide_version', versions) }}{{ choose('Runs', 'hide_run', runs) }} +{{ choose('Agents', 'row', agents) }}{{ choose('Axes', 'hide_axis', axes, 'show_axis') }}{{ choose('Benchmark versions', 'hide_version', versions) }}{{ choose('Runs', 'hide_run', runs) }} {%- endmacro %} {% block body %} -{{ page_head('Leaderboard', id='lb-title') }} +{% set actions %}{% endset %} +{{ page_head('Leaderboard', id='lb-title', actions=actions) }} {% for warning in board.warnings %}

{{ warning }}

{% endfor %} {% if board.empty %}

{{ board.empty }}

{% endif %}
-
{% for value, text in [('shared', 'Shared tasks'), ('every', 'Every task (not comparable)')] %}{% endfor %}
-
-
{% for value, text in [('omit', 'Checked labels only'), ('include', 'With unchecked labels')] %}{% endfor %}
+ {{ board.weights.note }}
{% set cols = [dict(key='rank', label='#', type='num', fixed=true, sticky=true), dict(key='agent', label='Agent', fixed=true, sticky=true), dict(key='overall', label='Overall', type='num', fixed=true), dict(key='mean', label='Mean score', type='num'), dict(key='pass3', label='pass^3', type='num')] %} -{% for name in board.axes %}{% set _ = cols.append(dict(key=name, label=name, type='num', menu=false)) %}{% endfor %} +{% for name in board.axes %}{% set _ = cols.append(dict(key=name, label=name, type='num')) %}{% endfor %} {% for key, label in [('steps','Steps'),('time','Time'),('calls','Tool calls'),('cost','Cost')] %}{% set _ = cols.append(dict(key=key, label=label, type='num')) %}{% endfor %} {# Company and Status are filters, never columns: Columns and Sort by leave them out #} {% set sortable = cols|map(attribute='key')|list %} @@ -38,7 +38,7 @@ {% set _ = cols.append(dict(key='status', label='Status', table=false, menu=false)) %} {% set filters = dict(agent=[],company=[],status=[('ranked','Ranked'),('not-ranked','Not ranked'),('no-run','No run')]) %} {% for r in board.rows %}{% if (r.agent,r.name) not in filters.agent %}{% set _=filters.agent.append((r.agent,r.name)) %}{% endif %}{% if r.company and (r.company,r.company) not in filters.company %}{% set _=filters.company.append((r.company,r.company)) %}{% endif %}{% endfor %} -{{ tables.controls('leaderboard-table', cols, search='Search by agent or company', columns=true, choices=filters, sort=sortable, views=selection) }} +{{ tables.controls('leaderboard-table', cols, search='Search by agent or company', columns=true, choices=filters, sort=sortable) }}
{{ tables.heads(cols|rejectattr('table','sameas',false)|list) }}{% for r in board.rows %} @@ -57,6 +57,22 @@

Resolved by domain and capability

{{ picks() }}

By domain

By capability

Resolved profiles

{{ picks() }}

By domain

By capability

+ +

Scoring

+ {%- set picks = selection() %}{% if picks|trim %} +

Selection

{{ picks }}
{% endif %} +

Tasks

+
{% for value, text in [('shared', 'Shared'), ('every', 'Every task')] %}{% endfor %}
+

Measure

+
+

Unchecked labels

+
{% for value, text in [('omit', 'Omit'), ('include', 'Include')] %}{% endfor %}
+

Function

+
{% for value, text in functions.items() %}{% endfor %}
+
+ +
+ {% endblock %} diff --git a/app/tests/test_client.py b/app/tests/test_client.py index 7796c1051..ead6bf525 100644 --- a/app/tests/test_client.py +++ b/app/tests/test_client.py @@ -94,6 +94,7 @@ def test_every_call_carries_the_token_and_asks_its_route(self): (lambda: self.nx.compare("a", "b"), "GET", "/compare", "job=a&job=b", None), (lambda: self.nx.leaderboard(), "GET", "/leaderboard", "", None), (lambda: self.nx.leaderboard("nightly"), "GET", "/leaderboard", "workspace=nightly", None), + (lambda: self.nx.leaderboard(rows=[]), "GET", "/leaderboard", "row=", None), # no row, not every row (lambda: self.nx.leaderboard(rows=["k1", "k2"], every_task=True, hide_axes=["Safety"], show_axes=["Coding"], hide_versions=["gaia@v1"], hide_runs=["old"], unchecked_labels="include"), "GET", "/leaderboard", "row=k1&row=k2&tasks=every&hide_axis=Safety&show_axis=Coding&hide_version=gaia%40v1&hide_run=old&unchecked=include", None), @@ -359,6 +360,8 @@ def test_a_tool_is_one_call_of_the_client(self): # the same cohort and selection as the page and the command, applied by the server before it scores self.call("get_leaderboard", {"rows": ["k1"], "every_task": True, "hide_runs": ["old"], "unchecked_labels": "include"}) self.assertEqual(self.last()["query"], "row=k1&tasks=every&hide_run=old&unchecked=include") + self.call("get_leaderboard", {"rows": []}) + self.assertEqual(self.last()["query"], "row=") def test_an_argument_a_tool_does_not_take_is_refused_and_nothing_is_asked(self): self.answer("GET", "/leaderboard", {"rows": []}) diff --git a/app/tests/test_leaderboard_weights.py b/app/tests/test_leaderboard_weights.py new file mode 100644 index 000000000..e0c8a09f4 --- /dev/null +++ b/app/tests/test_leaderboard_weights.py @@ -0,0 +1,341 @@ +"""The scoring functions: Counts is each task once whatever is saved; the weight vector moves Overall and the ranks +and no axis value; the weight matrix gives each benchmark its weight's share of an axis, equal at first, and Overall +is then the mean of the shown axes. A change saves one cell, each function keeps its numbers, Normalize keeps every +share, and a weight gives no task an axis.""" +import json +import os +import tempfile +import threading +import unittest +from unittest.mock import patch + +from tests.test_comparison import job, trial +from nullius.leaderboard import board, labels, weighting + +KEYS = ("one", "two", "three", "four") +AGENTS = [{"key": key, "label": key.capitalize(), "_version": "1", "_default": "1"} for key in ("codex", "goose")] +BENCHMARKS = [{"key": key, "label": key.capitalize(), "_version": "v1", "datasets": [{"id": "d"}]} for key in KEYS] +# every task is Memory; those of ``one`` are Safety too, and no other benchmark's +LABELS = {key: labels.check({"schema": 1, "labels": [{"axes": ["Memory", "Safety"] if key == "one" else ["Memory"]}]}, [b]) + for key, b in zip(KEYS, BENCHMARKS)} + + +def run(agent, benchmark, outcomes): + own = {"benchmark": benchmark, "benchmark_version": "v1"} + got = job([trial(f"{benchmark}/{i}", o, trial_name=f"{agent}-{benchmark}-{i}", unit=str(i), **own) for i, o in enumerate(outcomes.split())], + dataset="d", job_id=f"{agent}-{benchmark}") + got.identity = dict(own, agent=agent, model="m") + return got + + +# codex resolves 1/4, 2/2, 0/1 and 1/1; goose ran one more task of ``four``, so its own tasks are not the shared ones +JOBS = [run("codex", "one", "resolved agent_error agent_error agent_error"), run("codex", "two", "resolved resolved"), + run("codex", "three", "agent_error"), run("codex", "four", "resolved"), + run("goose", "one", "resolved resolved agent_error agent_error"), run("goose", "two", "agent_error resolved"), + run("goose", "three", "resolved"), run("goose", "four", "agent_error resolved")] + + +def build(saved=None, function="matrix", **asked): + got = board.build(JOBS, AGENTS, BENCHMARKS, LABELS, saved=saved, function=function, **asked) + return got, {r["agent"]: r for r in got["rows"]} + + +def memory(saved, view="shared"): + return build(saved)[1]["codex"][view]["axes"]["Memory"]["resolved"] + + +def column(*values, axis="Memory"): + return {key: {axis: value} for key, value in zip(KEYS, values)} + + +def values(rows, rate="resolved"): + """Every axis value of every row, in both views.""" + return {(agent, view, axis): cell[rate] for agent, row in rows.items() for view in board.TASKS if row[view] for axis, cell in row[view]["axes"].items()} + + +def overall(rows, agent="codex", view="shared", family="capabilities"): + return rows[agent][view]["overall"][family]["resolved"] + + +class Weights(unittest.TestCase): + def setUp(self): + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + patcher = patch.dict(os.environ, NULLIUS_HOME=folder.name) + patcher.start() + self.addCleanup(patcher.stop) + + def test_counts_matrix_and_vector_on_one_board(self): + # codex shares 8 Memory tasks, 4 resolved: 1/4, 2/2, 0/1 and 1/1; the 4 of ``one`` are Safety's too + (plain, counts), (_, matrix), (_, vector) = build(function="counts"), build(), build(function="vector") + self.assertEqual((plain["function"], plain["weights"]["note"]), ("counts", "")) + axes = lambda rows: (rows["codex"]["shared"]["axes"]["Memory"]["resolved"], rows["codex"]["shared"]["axes"]["Safety"]["resolved"]) + # counts: each task once, Overall over the 8 tasks. vector: the same axes, Overall their mean. + # matrix: Memory is the mean of its four benchmarks' rates, Overall the mean of the two axes + self.assertEqual((axes(counts), overall(counts)), ((.5, .25), .5)) + self.assertEqual((axes(vector), overall(vector)), ((.5, .25), .375)) + self.assertEqual((axes(matrix), overall(matrix)), ((.5625, .25), .40625)) + self.assertAlmostEqual(overall(build(function="vector", vector={"Memory": 3})[1]), (3 * .5 + .25) / 4) + for rows in (matrix, vector): + self.assertEqual((rows["codex"]["shared"]["overall"]["capabilities"]["n"], overall(rows, family="domains")), (8, None)) + # an axis with no value is left out of the mean: Safety's only benchmark weighted 0 + self.assertEqual(overall(build({"one": {"Safety": 0}})[1]), .5625) + # what is saved for the other functions changes nothing under counts + saved = {"saved": {"one": {"Memory": 0}}, "vector": {"Memory": 0}} + self.assertEqual(build(function="counts", **saved)[0]["rows"], plain["rows"]) + self.assertEqual(build(function="counts", **saved)[0]["rows"], board.build(JOBS, AGENTS, BENCHMARKS, LABELS)["rows"]) + self.assertRaises(ValueError, build, function="other") + + def test_the_vector_changes_ranks_and_no_axis_value(self): + # codex is ahead on Memory, goose on Safety + jobs = [run("codex", "one", "resolved agent_error agent_error agent_error"), run("codex", "two", "resolved resolved resolved resolved"), + run("goose", "one", "resolved resolved resolved agent_error"), run("goose", "two", "resolved resolved agent_error agent_error")] + def read(**asked): + got = board.build(jobs, AGENTS, BENCHMARKS, LABELS, **asked) + rows = {r["agent"]: r for r in got["rows"]} + return values(rows), {agent: (r["rank"]["capabilities"], overall(rows, agent)) for agent, r in rows.items()} + counts, ones = read(), read(function="vector") + self.assertEqual(ones[1], {"codex": (2, (5 / 8 + 1 / 4) / 2), "goose": (1, (5 / 8 + 3 / 4) / 2)}) + memory, safety = read(function="vector", vector={"Safety": 0}), read(function="vector", vector={"Memory": 0, "Safety": 2}) + self.assertEqual(memory[1], {"codex": (1, 5 / 8), "goose": (1, 5 / 8)}) + self.assertEqual(safety[1], {"codex": (2, 1 / 4), "goose": (1, 3 / 4)}) + self.assertEqual(read(function="vector", vector={"Memory": 9, "Safety": 1})[1]["codex"][0], 2) + for got in (ones, memory, safety, read(function="vector", vector={"Memory": 1e308, "Safety": 1e308})): + self.assertEqual(got[0], counts[0]) + # every weight at 0: no Overall, no rank, and the board names it + got = board.build(jobs, AGENTS, BENCHMARKS, LABELS, function="vector", vector={"Memory": 0, "Safety": 0}) + self.assertEqual((got["weights"]["zero"], {r["rank"]["capabilities"] for r in got["rows"]}), (["Capabilities overall"], {None})) + + def test_the_matrix_ranks_by_the_mean_of_the_weighted_axes(self): + # two benchmarks, Memory alone shown: codex 3 of 4 and 0 of 2, goose 1 of 4 and 1 of 2 + jobs = [run("codex", "one", "resolved resolved resolved agent_error"), run("codex", "two", "agent_error agent_error"), + run("goose", "one", "resolved agent_error agent_error agent_error"), run("goose", "two", "resolved agent_error")] + def ranks(**asked): + rows = board.build(jobs, AGENTS, BENCHMARKS, LABELS, hide_axes=("Safety",), **asked)["rows"] + return [(r["agent"], r["rank"]["capabilities"], r["shared"]["overall"]["capabilities"]["resolved"]) for r in rows] + self.assertEqual(ranks(), [("codex", 1, .5), ("goose", 2, 2 / 6)]) + self.assertEqual(ranks(function="matrix"), [("codex", 1, .375), ("goose", 1, .375)]) # each benchmark a half + self.assertEqual(ranks(saved={"one": {"Memory": 0}}, function="matrix"), [("goose", 1, .5), ("codex", 2, 0)]) + self.assertEqual(ranks(saved={"one": {"Memory": 0}}), [("codex", 1, .5), ("goose", 2, 2 / 6)]) # saved, under counts + + def test_a_weight_is_relative_within_its_axis(self): + self.assertEqual(memory(column(.4, .25, .25, .4)), memory(column(1.6, 1, 1, 1.6))) + # each benchmark's rate by its weight over the column's total: 1/4, 2/2, 0/1 and 1/1 + self.assertAlmostEqual(memory(column(.4, .25, .25, .4)), (.4 * .25 + .25 * 1 + .25 * 0 + .4 * 1) / 1.3) + self.assertAlmostEqual(memory(column(3)), (3 * .25 + 1 + 0 + 1) / 6) # none saved weighs 1 + # a column of zeros has no rate + self.assertEqual((memory(column(0, 0, 0, 9)), memory(column(0, 0, 0, 0))), (1, None)) + + def test_every_weight_at_1_is_an_equal_share_for_each_benchmark_in_both_views_for_every_row(self): + # codex resolves 9 of 9 of ``two`` and 0 of 1 of ``three``; goose 1 of 1 and 0 of 1, both shared + jobs = [run("codex", "two", " ".join(["resolved"] * 9)), run("codex", "three", "agent_error"), + run("goose", "two", "resolved"), run("goose", "three", "agent_error")] + def rates(saved=None, **asked): + got = board.build(jobs, AGENTS, BENCHMARKS, LABELS, saved=saved, **asked) + return got, {(r["agent"], view): r[view]["axes"]["Memory"]["resolved"] for r in got["rows"] for view in board.TASKS} + halves = dict.fromkeys(((agent, view) for agent in ("codex", "goose") for view in board.TASKS), .5) + for tasks in board.TASKS: + # nothing saved, or the 1 each cell shows saved as it is: the same for either row, in either view + got, shown = rates(function="matrix", tasks=tasks) + self.assertEqual(shown, halves, tasks) + self.assertEqual({c["weight"] for b in got["weights"]["benchmarks"] for c in b["cells"].values()}, {1}) + self.assertEqual(rates({"two": {"Memory": 1}, "three": {"Memory": 1}}, function="matrix", tasks=tasks)[1], halves, tasks) + # counts stays each task once, a row's own in the every-task view + self.assertEqual(rates(tasks=tasks)[1], {**halves, ("codex", "every"): .9}, tasks) + # a benchmark only codex ran is in the every-task matrix, and its weight counts there + got = board.build(jobs + [run("codex", "four", "agent_error")], AGENTS, BENCHMARKS, LABELS, saved={"four": {"Memory": 8}}, function="matrix", tasks="every") + self.assertEqual((got["weights"]["unused"], [b["key"] for b in got["weights"]["benchmarks"]]), ([], ["four", "three", "two"])) + self.assertEqual(next(r for r in got["rows"] if r["agent"] == "codex")["every"]["axes"]["Memory"]["resolved"], .1) + + def test_no_shared_task_gives_the_shared_view_no_cell_and_every_task_keeps_them(self): + jobs = [run("codex", "two", "resolved"), run("goose", "three", "resolved")] + cells = lambda **asked: [b["key"] for b in board.build(jobs, AGENTS, BENCHMARKS, LABELS, function="matrix", **asked)["weights"]["benchmarks"]] + self.assertEqual((cells(), cells(rows=[]), cells(tasks="every"), cells(rows=[], tasks="every")), ([], [], ["three", "two"], ["three", "two"])) + + def test_editing_one_cell_leaves_every_other_cell_and_the_other_function_unchanged(self): + weighting.change(function="matrix", cells=[("one", "Memory", .4), ("two", "Memory", .25)]) + weighting.change(cells=[("three", "Memory", 3)], axes=[("Safety", 2)]) + saved = weighting.load() + self.assertEqual((saved["function"], saved["weights"], saved["vector"]), + ("matrix", {"one": {"Memory": .4}, "two": {"Memory": .25}, "three": {"Memory": 3}}, {"Safety": 2})) + # no number is 1 again; what is no weight is refused, and nothing is saved + weighting.change(cells=[("three", "Memory", None)], axes=[("Safety", None)]) + kept = {"one": {"Memory": .4}, "two": {"Memory": .25}} + self.assertEqual((weighting.load()["weights"], weighting.load()["vector"]), (kept, {})) + self.assertEqual(build(kept)[0]["weights"]["benchmarks"][2]["cells"], {"Memory": {"weight": 1}}) + for cell in (("one", "Speed", 1), ("one", "Memory", -1), ("one", "Memory", float("nan")), ("one", "Memory", True), ("", "Memory", 1)): + self.assertRaises(ValueError, weighting.change, cells=[cell]) + if cell[0]: + self.assertRaises(ValueError, weighting.change, axes=[cell[1:]]) + self.assertRaises(ValueError, weighting.change, function="other") + self.assertEqual((weighting.load()["weights"], weighting.load()["vector"]), (kept, {})) + + def test_each_function_keeps_its_numbers_and_reset_is_the_active_ones(self): + weighting.change(function="matrix", cells=[("one", "Memory", 3)]) + weighting.change(function="vector", axes=[("Safety", 2)]) + both = {"weights": {"one": {"Memory": 3}}, "vector": {"Safety": 2}} + for function in ("counts", "matrix", "vector"): + weighting.change(function=function) + saved = weighting.load() + self.assertEqual((saved["function"], {part: saved[part] for part in both}), (function, both)) + weighting.change(reset=True) # the vector's + self.assertEqual({part: weighting.load()[part] for part in both}, dict(both, vector={})) + weighting.change(function="matrix", axes=[("Safety", 2)], reset=True) + self.assertEqual({part: weighting.load()[part] for part in both}, {"weights": {}, "vector": {"Safety": 2}}) + # a file this branch wrote before the functions: on is the matrix, off counts + for on, function in ((True, "matrix"), (False, "counts")): + weighting.path().write_text(json.dumps({"schema": 1, "on": on, "weights": {"one": {"Memory": 2}}})) + saved = weighting.load() + self.assertEqual((saved["function"], saved["weights"], saved["problems"]), (function, {"one": {"Memory": 2}}, [])) + + def test_reset_and_normalize_are_refused_under_another_function_than_the_one_shown_and_reset_under_counts(self): + weighting.change(function="matrix", cells=[("one", "Memory", 7)], axes=[("Memory", 3)]) + weighting.change(function="vector") + kept = weighting.path().read_text() + for asked in ({"reset": True}, {"normalize": build({"one": {"Memory": 7}})[0]["weights"]}): + with self.assertRaisesRegex(ValueError, "now Weight vector"): + weighting.change(shown="matrix", **asked) + with self.assertRaisesRegex(ValueError, "Counts has no weights to reset"): + weighting.change(function="counts", reset=True) + self.assertEqual(weighting.path().read_text(), kept) + weighting.change(shown="vector", reset=True) + self.assertEqual((weighting.load()["weights"], weighting.load()["vector"]), ({"one": {"Memory": 7}}, {})) + + def test_normalize_makes_each_column_sum_to_1_and_changes_no_value_on_any_board(self): + # goose's run of ``four`` hidden: ``four`` leaves the shared tasks, with a saved weight; ``three`` has none saved + weighting.change(function="matrix", cells=[("one", "Memory", 3), ("two", "Memory", 1), ("four", "Memory", 2)]) + def read(**asked): + saved = weighting.load() + return build(saved["weights"], **asked) + hidden = {"hide_runs": ("goose-four",)} + before = [values(read(**asked)[1]) for asked in (hidden, {}, {"tasks": "every"})] + weighting.change(normalize=read(**hidden)[0]["weights"]) + saved = weighting.load() + # one, two and three are on the board: 3 + 1 + 1, ``three`` now saved; Safety's one cell is 1 already + self.assertAlmostEqual(sum(b["cells"]["Memory"]["weight"] for b in read(**hidden)[0]["weights"]["benchmarks"]), 1) + self.assertAlmostEqual(saved["weights"]["three"]["Memory"], .2) + self.assertAlmostEqual(saved["weights"]["one"]["Memory"], .6) + self.assertAlmostEqual(saved["weights"]["four"]["Memory"], .4) + for was, asked in zip(before, (hidden, {}, {"tasks": "every"})): + now = values(read(**asked)[1]) + for at in was: + self.assertAlmostEqual(now[at], was[at], msg=at) + # emptied after Normalize, a cell is 1 + weighting.change(cells=[("one", "Memory", None)]) + self.assertEqual(read()[0]["weights"]["benchmarks"][1]["cells"]["Memory"], {"weight": 1}) + # a column of zeros cannot sum to 1: left as it is, and named + weighting.change(cells=[(key, "Memory", 0) for key in KEYS]) + zeros = json.loads(weighting.path().read_text())["weights"] + matrix = read()[0]["weights"] + weighting.change(normalize=matrix) + self.assertEqual((matrix["zero"], json.loads(weighting.path().read_text())["weights"]), (["Memory"], zeros)) + + def test_a_benchmark_that_comes_after_normalize_starts_at_1_and_emptying_its_cell_changes_nothing(self): + weighting.change(function="matrix") + two = board.build([j for j in JOBS if j.job_id.endswith(("-one", "-two"))], AGENTS, BENCHMARKS, LABELS, function="matrix") + weighting.change(normalize=two["weights"]) + self.assertEqual(weighting.load()["weights"], {"one": {"Memory": .5, "Safety": 1}, "two": {"Memory": .5}}) + weights = lambda: {b["key"]: b["cells"]["Memory"]["weight"] for b in build(weighting.load()["weights"])[0]["weights"]["benchmarks"]} + self.assertEqual(weights(), {"four": 1, "one": .5, "three": 1, "two": .5}) + was = memory(weighting.load()["weights"]) + weighting.change(cells=[("three", "Memory", None)]) + self.assertEqual((weights()["three"], memory(weighting.load()["weights"])), (1, was)) + + def test_normalize_makes_each_family_of_the_vector_sum_to_1_and_changes_no_overall(self): + weighting.change(function="vector", axes=[("Memory", 3)]) + def read(**asked): + return build(function="vector", vector=weighting.load()["vector"], **asked) + before = [overall(read(**asked)[1]) for asked in ({}, {"hide_axes": ("Safety",)})] + got = read()[0] + weighting.change(normalize=got["weights"]) + vector = weighting.load()["vector"] + self.assertAlmostEqual(sum(vector[a] for a in got["capabilities"]), 1) + self.assertAlmostEqual(vector["Memory"] / vector["Safety"], 3) + self.assertEqual(sorted(vector), sorted(labels.AXES)) # the hidden axes too: no share moves when one is shown + self.assertEqual(weighting.load()["weights"], {}) + for was, asked in zip(before, ({}, {"hide_axes": ("Safety",)})): + self.assertAlmostEqual(overall(read(**asked)[1]), was) + + def test_normalize_that_cannot_write_its_numbers_keeps_the_file_and_says_so(self): + # a weight above 0 is never written 0: its benchmark would leave the axis + weighting.change(function="matrix", cells=[(key, "Memory", value) for key, value in zip(KEYS, (1e308, 1e-310, 1e-310, 0))]) + kept = weighting.path().read_text() + with self.assertRaisesRegex(ValueError, "too small or too large"): + weighting.change(normalize=build(weighting.load()["weights"])[0]["weights"]) + self.assertEqual(weighting.path().read_text(), kept) + weighting.change(cells=[("one", "Safety", 2)]) # and the next change is still taken + self.assertEqual(weighting.load()["problems"], []) + + def test_a_weight_with_no_labelled_task_on_its_axis_is_said_and_not_applied(self): + got, rows = build({"two": {"Safety": 5}, "gone": {"Memory": 2}}) + self.assertEqual(got["weights"]["unused"], [{"benchmark": "gone", "name": "gone", "axis": "Memory", "weight": 2}, + {"benchmark": "two", "name": "Two", "axis": "Safety", "weight": 5}]) + self.assertEqual(got["rows"], build({})[0]["rows"]) + self.assertNotIn("Safety", next(b for b in got["weights"]["benchmarks"] if b["key"] == "two")["cells"]) + + def test_weights_change_no_label_and_give_no_task_an_axis(self): + plain, unweighted = build(function="counts") + got, rows = build({"two": {"Safety": 5, "Memory": 7}, "one": {"Memory": 0}}) + self.assertEqual((got["n"], got["n_overall"], got["axes"]), (plain["n"], plain["n_overall"], plain["axes"])) + for agent in ("codex", "goose"): + self.assertEqual(rows[agent]["coverage"], unweighted[agent]["coverage"]) + for view in board.TASKS: + for axis in got["axes"]: + cell, was = rows[agent][view]["axes"][axis], unweighted[agent][view]["axes"][axis] + self.assertEqual((cell["n"], cell["benchmarks"]), (was["n"], was["benchmarks"]), (agent, view, axis)) + + def test_a_file_that_does_not_read_is_counts_and_an_entry_that_does_not_is_left_out_alone(self): + nothing = {"function": "counts", "weights": {}, "vector": {}, "problems": []} + self.assertEqual(weighting.load(), nothing) + os.makedirs(weighting.path().parent, exist_ok=True) + # v0.3.0's scoring.json is another file with another shape: its entries assign axes, and none is read as a weight + weighting.path().write_text(json.dumps({"schema_version": 2, "axes": {"Memory": [{"benchmark": "one", "weight": 1}]}})) + self.assertEqual((weighting.load()["function"], weighting.load()["weights"], len(weighting.load()["problems"])), ("counts", {}, 1)) + weighting.path().write_text(json.dumps({"schema": 1, "function": "vector", "weights": {"one": {"Memory": 2, "Speed": 1, "Safety": "3"}, "two": 4}, + "vector": {"Memory": 2, "Speed": 1, "Safety": -1}})) + got = weighting.load() + self.assertEqual((got["function"], got["weights"], got["vector"], len(got["problems"])), ("vector", {"one": {"Memory": 2}}, {"Memory": 2}, 5)) + + # a file with a problem is kept as it is, whatever is asked, until Reset, which names its command and clears both + damaged = weighting.path().read_text() + for asked in ({"function": "counts"}, {"cells": [("two", "Memory", 1)]}, {"axes": [("Memory", 1)]}, {"normalize": build({})[0]["weights"]}): + with self.assertRaisesRegex(ValueError, "nullius leaderboard --reset-weights"): + weighting.change(**asked) + self.assertEqual(weighting.path().read_text(), damaged) + weighting.change(reset=True) + self.assertEqual(weighting.load(), dict(nothing, function="vector")) + # a function that is no name is a file that does not read, and Reset recovers it + weighting.path().write_text('{"schema": 1, "function": []}') + self.assertEqual((weighting.load()["function"], len(weighting.load()["problems"])), ("counts", 1)) + weighting.change(reset=True) + self.assertEqual(weighting.load(), nothing) + + def test_changes_made_together_are_all_saved(self): + writers = [threading.Thread(target=weighting.change, kwargs={"cells": [(f"b{i}", "Memory", i)]}) for i in range(16)] + for w in writers: + w.start() + for w in writers: + w.join() + self.assertEqual(weighting.load()["weights"], {f"b{i}": {"Memory": i} for i in range(16)}) + + def test_a_benchmark_weighted_0_keeps_its_versions_out_and_huge_weights_give_a_rate(self): + # ``one`` at two versions would leave Memory with no rate: weighted 0, it counts for nothing, and stays in evidence + other = run("codex", "one", "agent_error") + other.identity["benchmark_version"] = "v2" + other.trials = [trial("one/9", "agent_error", trial_name="codex-one-v2", unit="9", benchmark="one", benchmark_version="v2")] + other.job_id = "codex-one-v2" + labelled = dict(LABELS, one=labels.check({"schema": 1, "labels": [{"axes": ["Memory"]}]}, [BENCHMARKS[0], dict(BENCHMARKS[0], _version="v2")])) + def cell(saved): + rows = board.build(JOBS + [other], AGENTS, BENCHMARKS + [dict(BENCHMARKS[0], _version="v2")], labelled, saved=saved, function="matrix", tasks="every")["rows"] + return next(r for r in rows if r["agent"] == "codex")["every"]["axes"]["Memory"] + self.assertEqual((cell({})["resolved"], len(cell({})["benchmarks"])), (None, 5)) + got = cell({"one": {"Memory": 0}, "two": {"Memory": 1}, "three": {"Memory": 0}, "four": {"Memory": 0}}) + self.assertEqual((got["resolved"], len(got["benchmarks"])), (1, 5)) + self.assertEqual(memory(column(1e308, 1e308, 0, 0)), memory(column(1, 1, 0, 0))) + weighting.change(function="matrix", cells=[("one", "Memory", 1e308), ("two", "Memory", 1e308), ("three", "Memory", 0), ("four", "Memory", 0)]) + weighting.change(normalize=build(weighting.load()["weights"])[0]["weights"]) + self.assertEqual(weighting.load()["weights"], {"one": {"Memory": .5, "Safety": 1}, "two": {"Memory": .5}, "three": {"Memory": 0}, "four": {"Memory": 0}}) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/ui_tests/browser/leaderboard.py b/app/ui_tests/browser/leaderboard.py index ab61a4311..6a97e17a8 100644 --- a/app/ui_tests/browser/leaderboard.py +++ b/app/ui_tests/browser/leaderboard.py @@ -16,7 +16,7 @@ from playwright.sync_api import sync_playwright, expect from ui_tests.test_routes import web from tests.test_comparison import job, trial -from nullius.leaderboard import labels, service +from nullius.leaderboard import labels, service, weighting from nullius.standard.contract import definitions @@ -107,32 +107,52 @@ def choose(self, selector, index): button.click() self.page.locator(f'.ui-select-menu [data-index="{index}"]').click() - def test_a_cohort_a_filter_asked_stays_while_its_scores_are_drawn(self): - self.jobs[:] = [self.run_of("codex", 2, 2), self.run_of("goose", 1, 2, first=2)] # no task shared: nobody is ranked + def test_a_search_or_a_filter_reads_nothing_and_keeps_the_ranks_and_n(self): self.open("/leaderboard") - self.page.locator('[data-tools-btn="filter"]').click() - self.page.locator('[data-filter-menu="status"] [data-value="ranked"]').uncheck() # Not ranked, No run + goose = self.page.locator('tbody tr', has_text="Goose") + retrieval = self.page.locator('th[data-col="Retrieval"]') + expect(retrieval).to_contain_text("2 shared") del self.asked[:] - self.page.locator('#leaderboard-table-tools [data-search]').fill("Codex") - # alone, Codex is ranked, so the filter leaves it out: the cohort asked stays, and is asked once - expect(self.page.locator('[data-empty="leaderboard-table"]')).to_be_visible() - self.page.wait_for_timeout(1000) - self.assertEqual((self.asked.count("/api/leaderboard"), self.page.url.count("row=")), (1, 1)) + self.page.locator('#leaderboard-table-tools [data-search]').fill("Goose") + expect(self.page.locator('tbody tr:visible')).to_have_count(1) + self.page.locator('[data-tools-btn="filter"]').click() + self.page.locator('[data-filter-menu="status"] [data-value="no-run"]').uncheck() + self.page.locator('#leaderboard-table-tools [data-clear]').click() + self.page.wait_for_load_state("networkidle") + expect(goose.locator('[data-col="rank"]')).to_have_text("2") + expect(goose.locator('[data-col="overall"]')).to_contain_text("50.0%") + expect(retrieval).to_contain_text("2 shared") + self.assertEqual((self.asked.count("/api/leaderboard"), self.page.url.count("row=")), (0, 0)) self.assertFalse(self.errors) - def test_clear_filters_asks_for_every_row_again(self): + def test_the_agents_counted_are_scorings_and_in_the_address(self): + self.jobs[:] = [self.run_of("codex", 2, 2), self.run_of("goose", 3, 3)] # alone, Goose has 3 tasks self.open("/leaderboard") - goose = self.page.locator('tbody tr', has_text="Goose").locator('[data-col="overall"]') - expect(goose).to_contain_text("50.0%") - self.page.locator('#leaderboard-table-tools [data-search]').fill("Codex") - expect(self.page).to_have_url(re.compile("row=")) - self.page.locator('[data-set="unchecked"][value="include"]').click() - expect(self.page).to_have_url(re.compile("unchecked=include.*row=|row=.*unchecked=include")) + goose = self.page.locator('tbody tr', has_text="Goose") + retrieval = self.page.locator('th[data-col="Retrieval"]') + expect(retrieval).to_contain_text("2 shared") + key = goose.get_attribute("data-key") + agents = self.page.locator('#lb-scoring').get_by_role("button", name="Agents", exact=True) + self.page.locator('#lb-scoring-open').click() + agents.click() + self.page.locator(f'[data-choose="row"]:not([value="{key}"])').uncheck() + expect(self.page).to_have_url(re.compile(f"row={re.escape(key)}")) self.page.wait_for_load_state("networkidle") - self.page.locator('[data-tools-btn="filter"]').click() - self.page.locator('#leaderboard-table-tools [data-clear]').click() - expect(self.page).not_to_have_url(re.compile("row=")) - expect(goose).to_contain_text("50.0%") + expect(retrieval).to_contain_text("3 shared") + expect(goose.locator('[data-col="rank"]')).to_have_text("1") + # none counted is an empty `row=`, never every row + agents.click() + self.page.locator(f'[data-choose="row"][value="{key}"]').uncheck() + expect(self.page).to_have_url(re.compile(r"row=(&|$)")) + self.page.wait_for_load_state("networkidle") + expect(retrieval).to_contain_text("0 shared") + # all of them again: no row named + for box in (f'[data-choose="row"][value="{key}"]', f'[data-choose="row"]:not([value="{key}"])'): + agents.click() + self.page.locator(box).click() + self.page.wait_for_load_state("networkidle") + self.assertNotIn("row=", self.page.url) + expect(retrieval).to_contain_text("2 shared") self.assertFalse(self.errors) def test_a_restored_search_keeps_the_rank_the_address_scored(self): @@ -146,16 +166,8 @@ def test_a_restored_search_keeps_the_rank_the_address_scored(self): self.assertEqual((self.asked.count("/api/leaderboard"), self.page.url.count("row=")), (0, 0)) self.assertFalse(self.errors) - def test_no_run_alone_is_an_empty_cohort_and_no_match_hides_the_chosen_agent(self): + def test_no_match_hides_the_chosen_agent(self): self.open("/leaderboard") - self.page.locator('[data-tools-btn="filter"]').click() - for status in ("ranked", "not-ranked"): - self.page.locator(f'[data-filter-menu="status"] [data-value="{status}"]').uncheck() - expect(self.page).to_have_url(re.compile(r"row=(&|$)")) - expect(self.page.locator('th[data-col="Retrieval"]')).to_contain_text("0 shared") - # scored on no task, every row is Not ranked: ticking it again asks for every row - self.page.locator('[data-filter-menu="status"] [data-value="not-ranked"]').check() - expect(self.page).not_to_have_url(re.compile("row=")) card = self.page.locator('#lb-card') expect(card).to_be_visible() self.page.locator('#leaderboard-table-tools [data-search]').fill("nobody") @@ -169,10 +181,13 @@ def test_no_run_alone_is_an_empty_cohort_and_no_match_hides_the_chosen_agent(sel def test_the_family_shown_stays_through_a_change_of_the_selection(self): self.open("/leaderboard") self.page.locator('[data-family="domains"]').click() - self.page.get_by_role("button", name="Axes").click() + self.page.locator('#lb-scoring-open').click() + self.page.locator('#lb-scoring').get_by_role("button", name="Axes").click() self.page.locator('[data-choose="hide_axis"][value="Travel"]').uncheck() expect(self.page).to_have_url(re.compile("hide_axis=Travel")) self.page.wait_for_load_state("networkidle") + expect(self.page.locator('#lb-scoring')).to_be_visible() # Scoring stays open on the board it asked for + self.page.keyboard.press("Escape") expect(self.page.locator('[data-family="domains"]')).to_have_attribute("aria-pressed", "true") expect(self.page.locator('th[data-col="Shopping"]')).to_be_visible() self.assertFalse(self.errors) @@ -248,6 +263,21 @@ def test_a_family_switch_drops_a_sort_that_leaves_and_menus_list_the_shown_colum # the columns the table shows, and columns only: a domain with no shared task keeps its column self.assertEqual(listed, ['Default', '#', 'Agent', 'Overall', 'Mean score', 'pass^3', 'Travel', 'Dining', 'Shopping', 'Money', 'Health', 'Home', 'Work', 'Steps', 'Time', 'Tool calls', 'Cost']) + # Columns lists the shown family's axes and never the other's + columns = lambda: {t.strip() for t in self.page.locator('[data-tools="columns"] label:visible').all_inner_texts()} + capabilities, domains = ({a for a in labels.FAMILIES[family] if a not in labels.HIDDEN} for family in ("capabilities", "domains")) + self.page.keyboard.press("Escape") + self.page.locator('[data-tools-btn="columns"]').click() + self.assertEqual((columns() & capabilities, columns() & domains), (set(), domains)) + self.page.keyboard.press("Escape") + self.page.locator('[data-family="capabilities"]').click() + expect(self.page.locator('th[data-col="Retrieval"]')).to_be_visible() + self.page.locator('[data-tools-btn="columns"]').click() + self.assertEqual((columns() & capabilities, columns() & domains), (capabilities, set())) + self.page.keyboard.press("Escape") + self.page.locator('[data-family="domains"]').click() + expect(self.page.locator('th[data-col="Travel"]')).to_be_visible() + self.page.locator('[data-tools-btn="sort"]').click() # Default is the shown family's ranking, whatever the page first came in self.page.locator('[data-tools="sort"] input[value="agent"]').check() self.page.locator('[data-tools="sort"] input[data-sort-dir][value="desc"]').check() @@ -267,9 +297,13 @@ def test_an_empty_axis_says_0_shared_and_every_task_is_never_ranked(self): self.assertEqual([t.strip() for t in self.page.locator('tbody tr:visible [data-col="rank"]').all_inner_texts()][:2], ["1", "2"]) expect(self.page.locator('#lb-card')).to_contain_text('Best against the field') # every task: each row over its own tasks, so no N in a head, no rank, no medal and nothing against the field + self.page.locator('#lb-scoring-open').click() self.page.locator('[data-set="tasks"][value="every"]').click() self.page.wait_for_load_state("networkidle") self.assertIn("tasks=every", self.page.url) + expect(self.page.locator('#lb-scoring')).to_be_visible() # Scoring stays open on the board it asked for + self.assertNotIn("#", self.page.url) + self.page.locator('#lb-scoring-close').click() expect(self.page.locator('th[data-col="Retrieval"]')).to_have_text('Retrieval') self.assertEqual({t.strip() for t in self.page.locator('tbody tr:visible [data-col="rank"]').all_inner_texts()}, {""}) expect(self.page.locator('tbody tr:visible').first.locator('td[data-col="Retrieval"]')).to_contain_text('2 tasks') @@ -280,9 +314,15 @@ def test_an_empty_axis_says_0_shared_and_every_task_is_never_ranked(self): def test_the_selection_and_the_unchecked_mode_are_in_the_address(self): self.open('/leaderboard') self.assertIn("unchecked=omit", self.page.url) # the default, written without a second request - self.page.locator('[data-measure="mean_score"]').click() + expect(self.page.locator('#leaderboard-table-tools [data-dropdown]')).to_have_count(0) # the selection is Scoring's + self.page.locator('#lb-scoring-open').click() + self.page.locator('#lb-scoring [data-measure="mean_score"]').click() self.assertIn("measure=mean_score", self.page.url) - self.page.locator('#leaderboard-table-tools').get_by_role("button", name="Axes", exact=True).click() + axes = self.page.locator('#lb-scoring').get_by_role("button", name="Axes", exact=True) + axes.click() + self.page.keyboard.press("Escape") # closes the menu, not Scoring + expect(self.page.locator('#lb-scoring')).to_be_visible() + axes.click() self.page.locator('[data-choose="hide_axis"][value="Retrieval"]').uncheck() self.page.wait_for_load_state("networkidle") self.assertIn("hide_axis=Retrieval", self.page.url) @@ -298,6 +338,240 @@ def test_the_selection_and_the_unchecked_mode_are_in_the_address(self): expect(self.page.locator('[data-set="unchecked"][value="include"]')).to_have_attribute("aria-pressed", "true") self.assertFalse(self.errors) + def test_columns_hide_an_axis_from_view_and_scoring_leaves_it_out(self): + self.open('/leaderboard') + overall = lambda: self.page.locator('tbody tr td[data-col="overall"]').all_inner_texts() + shown, gaia = overall(), ("Retrieval", "Communication") # GAIA's two axes + # Columns only hides from view: Overall, the ranks and the address stay + self.page.locator('[data-tools-btn="columns"]').click() + for axis in gaia: + self.page.locator(f'[data-tools="columns"] input[data-col="{axis}"]').uncheck() + expect(self.page.locator(f'th[data-col="{axis}"]')).to_be_hidden() + self.page.keyboard.press("Escape") + self.page.wait_for_load_state("networkidle") + self.assertNotIn("_axis", self.page.url) + self.assertEqual(overall(), shown) + # Scoring's Axes decides what counts: left out there, an axis leaves Overall + self.page.locator('#lb-scoring-open').click() + for axis in gaia: + self.page.locator('#lb-scoring').get_by_role("button", name="Axes", exact=True).click() + self.page.locator(f'[data-choose="hide_axis"][value="{axis}"]').uncheck() + expect(self.page).to_have_url(re.compile(f"hide_axis={axis}")) + self.page.wait_for_load_state("networkidle") + self.assertNotEqual(overall(), shown) + self.assertFalse(self.errors) + + def test_scoring_saves_weights_in_the_order_asked_and_keeps_what_did_not_save(self): + self.open('/leaderboard') + scoring = self.page.locator('#lb-scoring') + self.page.locator('#lb-scoring-open').click() + scoring.locator('h2').click() # a click inside keeps it open + expect(scoring).to_be_visible() + self.page.mouse.click(5, 5) # one on the backdrop closes it + expect(scoring).to_be_hidden() + self.page.locator('#lb-scoring-open').click() + matrix, counts, vector = (self.page.locator(f'[data-function="{name}"]') for name in ("matrix", "counts", "vector")) + posts, held = [], [] + def hold(route): + # the first change is saved at once and answered late: its answer must not be the one drawn + posts.append(route.request.post_data) + held.append(route) if len(posts) == 1 else self.answer(route) + self.page.route("**/leaderboard/weights*", hold) + matrix.click() + counts.click() + self.page.wait_for_timeout(300) + self.answer(held[0]) + expect(counts).to_have_attribute("aria-pressed", "true") + self.page.wait_for_load_state("networkidle") + self.assertEqual((posts, weighting.load()["function"]), (['{"function":"matrix"}', '{"function":"counts"}'], "counts")) + expect(matrix).to_have_attribute("aria-pressed", "false") + expect(self.page.locator('#lb-weights-on')).to_be_hidden() + expect(self.page.locator('#lb-weights')).to_be_hidden() # no weight under Counts + self.page.unroute("**/leaderboard/weights*") + # the vector: one row, a cell an axis, each 1 at first; Overall says how it is read + vector.click() + expect(self.page.locator('#lb-weights-on')).to_have_text("Overall: the weighted average of the axes") + expect(self.page.locator('#lb-weights tbody tr')).to_have_count(1) + axis = self.page.locator('#lb-weights input[data-cell="Retrieval"]') + expect(axis).to_have_value("1") + axis.fill("2") + axis.press("Enter") + self.page.wait_for_load_state("networkidle") + self.assertEqual((weighting.load()["vector"], weighting.load()["weights"]), ({"Retrieval": 2}, {})) + matrix.click() + expect(self.page.locator('#lb-weights')).to_be_visible() + expect(self.page.locator('#lb-weights-on')).to_have_text("Overall: the average of the weighted axes") + self.page.wait_for_load_state("networkidle") + cell = self.page.get_by_label("GAIA Retrieval") + expect(cell).to_have_value("1") + cell.fill("1.2") + cell.press("Enter") + expect(self.page.locator('.toast')).to_have_count(0) + self.page.wait_for_load_state("networkidle") + self.assertEqual((weighting.load()["weights"], weighting.load()["vector"]), ({"gaia": {"Retrieval": 1.2}}, {"Retrieval": 2})) + # what is no number saves nothing, and the field says so + cell.press("Control+a") + cell.press_sequentially("1e") + cell.press("Tab") + self.page.wait_for_load_state("networkidle") + self.assertEqual(weighting.load()["weights"], {"gaia": {"Retrieval": 1.2}}) + self.assertTrue(self.page.get_by_label("GAIA Retrieval").evaluate("e=>e.validity.badInput")) + # a save the connection drops is said, and the saved weight is back + self.page.route("**/leaderboard/weights*", lambda route: route.abort()) + cell = self.page.get_by_label("GAIA Retrieval") + cell.focus() + cell.press("Control+a") + cell.press_sequentially("4") + cell.press("Enter") + expect(self.page.locator('.toast.bad')).to_have_text(re.compile("Weights not saved.")) + expect(self.page.get_by_label("GAIA Retrieval")).to_have_value("1.2") + self.assertEqual(weighting.load()["weights"], {"gaia": {"Retrieval": 1.2}}) + self.page.unroute("**/leaderboard/weights*") + # emptied, a cell is 1 again + cell = self.page.get_by_label("GAIA Retrieval") + cell.fill("") + cell.press("Enter") + expect(self.page.get_by_label("GAIA Retrieval")).to_have_value("1") + self.page.wait_for_load_state("networkidle") + self.assertEqual(weighting.load()["weights"], {}) + self.assertFalse(self.errors) + + def test_a_board_is_opened_only_once_every_weight_asked_is_saved(self): + weighting.change(function="matrix") + self.open('/leaderboard') + self.page.locator('#lb-scoring-open').click() + held = [] + self.page.route("**/leaderboard/weights*", lambda route: held.append(route) if not held else self.answer(route)) + first = self.page.get_by_label("GAIA Retrieval") + first.fill("2") + first.press("Enter") + self.page.get_by_label("GAIA Communication").fill("3") + self.page.locator('[data-set="tasks"][value="every"]').click() # commits the cell, then asks for another board + self.page.wait_for_timeout(300) + self.assertNotIn("tasks=every", self.page.url) + self.answer(held[0]) + expect(self.page).to_have_url(re.compile("tasks=every")) + self.page.wait_for_load_state("networkidle") + self.assertEqual(weighting.load()["weights"], {"gaia": {"Retrieval": 2, "Communication": 3}}) + expect(self.page.get_by_label("GAIA Communication")).to_have_value("3") + # a save that failed opens no board: Scoring stays, to try again + self.page.unroute("**/leaderboard/weights*") + self.page.route("**/leaderboard/weights*", lambda route: route.abort()) + self.page.get_by_label("GAIA Communication").fill("5") + self.page.locator('[data-set="tasks"][value="shared"]').click() + expect(self.page.locator('.toast.bad')).to_have_text(re.compile("Weights not saved.")) + self.page.wait_for_timeout(300) + self.assertIn("tasks=every", self.page.url) + expect(self.page.locator('#lb-scoring')).to_be_visible() + expect(self.page.get_by_label("GAIA Communication")).to_have_value("3") + self.assertFalse(self.errors) + + def test_a_save_that_fails_after_one_that_did_not_shows_what_is_saved(self): + weighting.change(function="matrix") + self.open('/leaderboard') + self.page.locator('#lb-scoring-open').click() + held = [] + self.page.route("**/leaderboard/weights*", lambda route: held.append(route) if not held else route.abort()) + first = self.page.get_by_label("GAIA Retrieval") + first.fill("0") + first.press("Enter") + second = self.page.get_by_label("GAIA Communication") + second.fill("3") + second.press("Enter") + self.answer(held[0]) + expect(self.page.locator('.toast.bad')).to_have_text(re.compile("Weights not saved.")) + expect(self.page.get_by_label("GAIA Retrieval")).to_have_value("0") + expect(self.page.get_by_label("GAIA Communication")).to_have_value("1") + self.assertEqual(weighting.load()["weights"], {"gaia": {"Retrieval": 0}}) + self.assertFalse(self.errors) + + def test_a_board_waits_for_the_weights_asked_while_it_waited_and_a_failed_save_gives_the_box_back(self): + weighting.change(function="vector") + self.open('/leaderboard') + self.page.locator('#lb-scoring-open').click() + held = [] + self.page.route("**/leaderboard/weights*", lambda route: held.append(route)) + cell = lambda axis: self.page.locator(f'#lb-weights input[data-cell="{axis}"]') + cell("Retrieval").fill("2") + cell("Retrieval").press("Enter") + self.page.locator('[data-set="tasks"][value="every"]').click() + cell("Communication").fill("3") + cell("Communication").press("Enter") # asked after the board was + self.answer(held[0]) + expect(cell("Retrieval")).to_have_value("2") + self.page.wait_for_timeout(300) + self.assertEqual((len(held), "tasks=every" in self.page.url), (2, False)) + self.answer(held[1]) + expect(self.page).to_have_url(re.compile("tasks=every")) + self.page.wait_for_load_state("networkidle") + self.assertEqual(weighting.load()["vector"], {"Retrieval": 2, "Communication": 3}) + # a save that fails opens no board, and the box unticked for it is ticked as the address has it + del held[:] + cell("Retrieval").fill("5") + cell("Retrieval").press("Enter") + self.page.locator('#lb-scoring').get_by_role("button", name="Axes", exact=True).click() + box = self.page.locator('[data-choose="hide_axis"][value="Retrieval"]') + box.uncheck() + held[0].abort() + expect(self.page.locator('.toast.bad')).to_have_text(re.compile("Weights not saved.")) + expect(box).to_be_checked() + self.assertNotIn("hide_axis", self.page.url) + self.assertFalse(self.errors) + + def test_a_save_that_fails_with_the_server_gone_shows_the_last_board_answered(self): + weighting.change(function="vector") + self.open('/leaderboard') + self.page.locator('#lb-scoring-open').click() + held = [] + self.page.route("**/leaderboard/weights*", lambda route: held.append(route) if not held else route.abort()) + cell = lambda axis: self.page.locator(f'#lb-weights input[data-cell="{axis}"]') + cell("Retrieval").fill("0") + cell("Retrieval").press("Enter") + cell("Communication").fill("3") + cell("Communication").press("Enter") + self.page.route("**/api/leaderboard*", lambda route: route.abort()) + self.answer(held[0]) + expect(self.page.locator('.toast.bad')).to_have_text(re.compile("Weights not saved.")) + expect(cell("Retrieval")).to_have_value("0") + expect(cell("Communication")).to_have_value("1") + self.assertEqual(weighting.load()["vector"], {"Retrieval": 0}) + self.assertFalse(self.errors) + + def test_a_change_of_one_selection_leaves_the_agents_counted_as_the_address_has_them(self): + # Codex ran GAIA alone, Retrieval; Goose τ³-bench alone, Shopping: no task is shared + own = {"benchmark": "tau3-bench", "benchmark_version": definitions.version_identity(definitions.get("benchmark", "tau3-bench"))} + bank = job([trial("tau3-bench/x", "resolved", unit="x", trial_name="bank-x", **own)], dataset="banking_knowledge", agent="goose", job_id="bank") + bank.identity = dict(own, agent="goose", agent_version=definitions.get("agent", "goose")["_version"]) + self.jobs[:] = [self.run_of("codex", 1, 1), bank] + self.stack.enter_context(patch.object(labels, "load", lambda benchmarks: { + key: labels.check({"schema": 1, "labels": [{"axes": [axis]}] if axis else []}, [b for b in benchmarks if b["key"] == key]) + for key in {b["key"] for b in benchmarks} for axis in [{"gaia": "Retrieval", "tau3-bench": "Shopping"}.get(key)]})) + self.open('/leaderboard') + retrieval = self.page.locator('th[data-col="Retrieval"]') + expect(retrieval).to_contain_text("0 shared") + scoring = self.page.locator('#lb-scoring') + def tick(menu, box, on): + if not scoring.is_visible(): + self.page.locator('#lb-scoring-open').click() + scoring.get_by_role("button", name=menu, exact=True).click() + self.page.locator(box).set_checked(on) + self.page.wait_for_load_state("networkidle") + tick("Axes", '[data-choose="hide_axis"][value="Shopping"]', False) + expect(self.page).to_have_url(re.compile("hide_axis=Shopping")) + expect(retrieval).to_contain_text("1 shared") # Goose has no task of a shown axis left + tick("Axes", '[data-choose="hide_axis"][value="Shopping"]', True) + self.assertNotIn("row=", self.page.url) # nobody was named, nobody is + expect(retrieval).to_contain_text("0 shared") + # and one left out stays out when its only run is hidden, then shown again + goose = self.page.locator('tbody tr', has_text="Goose").get_attribute("data-key") + tick("Agents", f'[data-choose="row"][value="{goose}"]', False) + self.assertEqual((self.page.url.count("row="), f"row={goose}" in self.page.url), (1, False)) + tick("Runs", '[data-choose="hide_run"][value="bank"]', False) + tick("Runs", '[data-choose="hide_run"][value="bank"]', True) + self.assertEqual((self.page.url.count("row="), f"row={goose}" in self.page.url, "hide_run" in self.page.url), (1, False, False)) + expect(retrieval).to_contain_text("1 shared") + self.assertFalse(self.errors) + def test_pickers_name_twins_apart_and_measures_round_as_they_read(self): runs = [] for name, agent, model, backend, passed, seconds, cost in (("a", "codex", "gpt-a", "", 2, 119.6, .004), ("b", "codex", "gpt-b", "", 1, 40, 1), diff --git a/app/ui_tests/test_leaderboard_routes.py b/app/ui_tests/test_leaderboard_routes.py index 08fc329f1..6f0214ec5 100644 --- a/app/ui_tests/test_leaderboard_routes.py +++ b/app/ui_tests/test_leaderboard_routes.py @@ -1,5 +1,5 @@ """Leaderboard pages, the command beside them, what is left of saved Scoring weights and deferred response isolation.""" -from contextlib import ExitStack, redirect_stdout +from contextlib import ExitStack, redirect_stderr, redirect_stdout import io import json import os @@ -165,6 +165,133 @@ def test_the_command_gives_each_axis_its_pass3_and_each_family_its_means_per_att (" Capabilities cost per attempt: 1.0 (3 observed)", " Domains cost per attempt: 5.5 (6 observed)")) self.assertIn("time or cost per attempt", self.client.get("/leaderboard").get_data(as_text=True)) + def weigh(self, body, **query): + """One change of the weights as the page saves it.""" + self.client.get("/leaderboard").close() + with self.client.session_transaction() as session: + token = session["csrf"] + return self.client.post("/leaderboard/weights", json=body, query_string=query, headers={"X-CSRF-Token": token}) + + def test_page_and_command_agree_on_the_function_and_every_number_under_it(self): + self.run_of("codex", "one", {"a": "resolved", "b": "agent_error", "c": "resolved"}) + self.run_of("codex", "bank", {"x": "agent_error"}, "tau3-bench", "banking_knowledge") + self.assertEqual(self.client.post("/leaderboard/weights", json={"function": "matrix"}).status_code, 403) + self.assertEqual(self.weigh({"cell": {"benchmark": "gaia", "axis": "Speed", "weight": 1}}).status_code, 400) + self.assertEqual(self.weigh({"function": "other"}).status_code, 400) + board = lambda **query: self.client.get("/api/leaderboard", query_string=query).get_json() + self.assertEqual(board()["function"], "counts") + # every cell is 1 at first; three of four Retrieval tasks are GAIA's: 2 of 3 resolved there, 0 of 1 at the bank + self.assertEqual(self.weigh({"function": "matrix"}).get_json()["weights"]["benchmarks"][0]["cells"]["Retrieval"], {"weight": 1}) + self.assertEqual(self.weigh({"cell": {"benchmark": "gaia", "axis": "Retrieval", "weight": .25}}).status_code, 200) + self.assertEqual(self.weigh({"axis": {"axis": "Retrieval", "weight": 3}}).status_code, 200) + retrieval = {"counts": 1 / 2, "vector": 1 / 2, "matrix": (.25 * 2 / 3) / 1.25} + for function in ("counts", "vector", "matrix"): + # one function set by the command, the others by the page + self.text("--function", function) if function == "vector" else self.weigh({"function": function}) + for query, words in (({}, []), ({"tasks": "every"}, ["--every-task"]), ({"hide_axis": "Money"}, ["--hide-axis", "Money"])): + page, command = board(**query), json.loads(self.text("--json", *words)) + self.assertEqual((command["function"], command["rows"], command["weights"]), (function, page["rows"], page["weights"]), (function, query)) + row = next(r for r in page["rows"] if r["has_runs"]) + self.assertAlmostEqual(row[page["tasks"]]["axes"]["Retrieval"]["resolved"], retrieval[function], msg=(function, query)) + # the command saves what the page does: Normalize, a weight of the matrix and of the vector, Reset and the function + self.text("--normalize-weights") + cells = lambda: {b["key"]: b["cells"]["Retrieval"]["weight"] for b in board()["weights"]["benchmarks"]} + self.assertEqual(cells(), {"gaia": .2, "tau3-bench": .8}) + self.assertEqual(self.weigh({"normalize": "matrix"}).status_code, 200) + self.assertEqual(cells(), {"gaia": .2, "tau3-bench": .8}) + self.text("--weight", "tau3-bench:Retrieval=2") + self.assertEqual(cells(), {"gaia": .2, "tau3-bench": 2}) + self.assertEqual(self.weigh({"reset": "matrix"}).get_json()["function"], "matrix") + self.assertEqual((cells(), board()["weights"]["vector"]["Retrieval"]), ({"gaia": 1, "tau3-bench": 1}, 3)) # the matrix's, not the vector's + self.text("--function", "vector", "--axis-weight", "Retrieval=2", "--axis-weight", "Memory=") + self.assertEqual((board()["function"], board()["weights"]["vector"]["Retrieval"], board()["weights"]["vector"]["Memory"]), ("vector", 2, 1)) + self.assertEqual(self.weigh({"axis": {"axis": "Retrieval"}}).get_json()["weights"]["vector"]["Retrieval"], 1) + self.text("--function", "counts") + self.assertEqual(board()["function"], "counts") + + def test_a_refused_change_of_the_weights_saves_nothing(self): + self.run_of("codex", "one", {"a": "resolved"}) + self.weigh({"function": "matrix"}) + self.weigh({"cell": {"benchmark": "gaia", "axis": "Retrieval", "weight": 3}}) + saved = lambda: self.client.get("/api/leaderboard").get_json()["weights"]["benchmarks"][0]["cells"]["Retrieval"]["weight"] + # a board the address or the command does not name: refused before Reset, or anything, is saved + self.assertEqual(self.weigh({"reset": "matrix"}, row="stale").status_code, 400) + with patch.object(parse, "load_all", return_value=self.jobs): + self.assertEqual(cli.main(["leaderboard", self.folder, "--row", "unknown-row", "--reset-weights"]), 2) + self.assertEqual(saved(), 3) + # what is not one change, spelled as the route says: never read as a cell with no weight + for body in ({"cell": {"benchmark": "gaia", "axis": "Retrieval", "weights": 5}}, {"cell": {"benchmark": "gaia"}}, {"cell": []}, {"function": True}, + {"axis": {"weight": 2}}, {"axis": {"axis": "Retrieval", "weights": 2}}, {"on": True}, + {"reset": False}, {"reset": True}, {"normalize": "other"}, {"reset": True, "function": "matrix"}, {"other": 1}, {}, [], 5): + self.assertEqual(self.weigh(body).status_code, 400, body) + self.assertEqual(saved(), 3) + # Reset and Normalize of a function no longer active, and Reset under Counts: refused, naming the function + self.text("--function", "vector") + for body in ({"reset": "matrix"}, {"normalize": "matrix"}): + answer = self.weigh(body) + self.assertEqual((answer.status_code, answer.get_json()["error"]), (400, "The function is now Weight vector. Nothing is changed."), body) + with patch.object(parse, "load_all", return_value=self.jobs), redirect_stderr(io.StringIO()) as said: + self.assertEqual(cli.main(["leaderboard", self.folder, "--function", "counts", "--reset-weights"]), 2) + self.assertEqual((said.getvalue(), saved()), ("Counts has no weights to reset. Nothing is changed.\n", 3)) + # every weight of an axis at 0: the command names the axis it cannot score + self.weigh({"function": "matrix"}) + self.weigh({"cell": {"benchmark": "gaia", "axis": "Retrieval", "weight": 0}}) + self.assertIn(" Not scored: Retrieval. The weights sum to 0.\n", self.text()) + + def test_a_weights_file_that_does_not_read_names_the_command_that_resets_it(self): + self.run_of("codex", "one", {"a": "resolved"}) + path = Path(paths.config_dir()) / "leaderboard-weights.json" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('{"schema": 7}') + html = self.client.get("/leaderboard").get_data(as_text=True) + self.assertIn("To reset it: nullius leaderboard --reset-weights

", html) + self.assertIn('id="lb-weights" hidden', html) # counts, and no weight shown + answer = self.weigh({"function": "matrix"}) + self.assertEqual((answer.status_code, "nullius leaderboard --reset-weights" in answer.get_json()["error"]), (400, True)) + self.assertEqual(path.read_text(), '{"schema": 7}') + self.assertIn("Function: Counts\n", self.text("--reset-weights")) + self.assertNotIn("reset", self.client.get("/leaderboard").get_data(as_text=True).split("")] + for control in ('data-set="tasks"', 'data-set="unchecked"', 'data-function="counts"', 'data-function="vector"', 'data-function="matrix"', + 'data-weights-do="normalize"', 'data-weights-do="reset"', 'id="lb-weights"'): + self.assertEqual((control in dialog, control in html.replace(dialog, "")), (True, False), control) + self.assertIn(">Counts", dialog) + self.assertIn(">Weight vector", dialog) + self.assertIn(">Weight matrix", dialog) + says = '{}' + notes = {"vector": "Overall: the weighted average of the axes", "matrix": "Overall: the average of the weighted axes"} + self.assertIn(pressed.format("counts"), html) + self.assertIn('id="lb-weights-on" hidden', html) + self.assertIn("Function: Counts\n", self.text()) + self.weigh({"cell": {"benchmark": "gaia", "axis": "Retrieval", "weight": 3}}) + self.weigh({"cell": {"benchmark": "gaia", "axis": "Money", "weight": 2}}) + self.weigh({"axis": {"axis": "Retrieval", "weight": 4}}) + for function, note in notes.items(): + self.weigh({"function": function}) + html = self.client.get("/leaderboard").get_data(as_text=True) + self.assertIn(pressed.format(function), html) + self.assertIn(says.format(note), html) + self.assertEqual(html.count('aria-pressed="true"', html.index('aria-label="Function"'), html.index('id="lb-weights"')), 1) + text = self.text("--function", "vector") + self.assertIn("Function: Weight vector · Overall: the weighted average of the axes\n", text) + self.assertIn(" Capabilities: ", text) + self.assertIn("Retrieval 4 · ", text) + self.assertNotIn("GAIA 3", text) + text = self.text("--function", "matrix") + self.assertIn("Function: Weight matrix · Overall: the average of the weighted axes\n", text) + self.assertIn(" Retrieval: GAIA 3 · τ³-bench 1\n", text) + self.assertIn(" Not applied: GAIA Money 2. No compared task of the benchmark has the label.\n", text) + document = json.loads(self.text("--json")) + self.assertEqual((document["function"], document["weights"]["name"], document["weights"]["unused"]), + ("matrix", "Weight matrix", [{"benchmark": "gaia", "name": "GAIA", "axis": "Money", "weight": 2}])) + def test_saved_scoring_weights_are_said_and_the_file_is_never_touched(self): self.run_of("codex", "one", {"a": "resolved"}) self.assertEqual(self.client.get("/api/leaderboard").get_json()["notice"], "") diff --git a/app/web/leaderboard.py b/app/web/leaderboard.py index 8447a540d..5afecf40c 100644 --- a/app/web/leaderboard.py +++ b/app/web/leaderboard.py @@ -2,7 +2,7 @@ from __future__ import annotations from flask import abort, jsonify, render_template, request -from nullius.leaderboard import labels, service +from nullius.leaderboard import labels, service, weighting from .core import app from . import shared @@ -19,7 +19,38 @@ def _document(deferred=False): @app.get("/leaderboard") def leaderboard(): - return render_template("leaderboard/board.html", board=_document(), families=labels.FAMILIES, unless_asked=labels.HIDDEN) + return render_template("leaderboard/board.html", board=_document(), families=labels.FAMILIES, unless_asked=labels.HIDDEN, functions=weighting.FUNCTIONS) + + +def _change(body) -> dict: + """The one change a body asks, as ``service.weigh`` takes it; anything else is refused before a weight is read.""" + if isinstance(body, dict) and len(body) == 1: + (key, value), = body.items() + if key == "function" and isinstance(value, str): + return {"function": value} + if key in ("normalize", "reset") and isinstance(value, str) and value in weighting.FUNCTIONS: + return {key: True, "shown": value} + if key == "cell" and isinstance(value, dict) and {"benchmark", "axis"} <= set(value) <= {"benchmark", "axis", "weight"}: + return {"cells": [(value["benchmark"], value["axis"], value.get("weight"))]} + if key == "axis" and isinstance(value, dict) and {"axis"} <= set(value) <= {"axis", "weight"}: + return {"axes": [(value["axis"], value.get("weight"))]} + abort(400, "One of {function}, {cell: {benchmark, axis, weight}}, {axis: {axis, weight}}, {normalize: FUNCTION}, {reset: FUNCTION}.") + + +@app.post("/leaderboard/weights") +def leaderboard_weights(): + """One change of the saved weights, then the board the address names: ``{function}``, ``{cell: {benchmark, axis, + weight}}`` of the matrix or ``{axis: {axis, weight}}`` of the vector (no weight: 1), ``{normalize: FUNCTION}`` or + ``{reset: FUNCTION}``, the function the page showed: refused when another is active.""" + shared._require_csrf() + if not shared._local_client(): + abort(403, description="Weights are saved from a browser on the application host only.") + change = _change(request.get_json(silent=True)) + try: + service.weigh(_document, **change) + except ValueError as error: + return jsonify(error=str(error)), 400 + return jsonify(_document()) @app.get("/api/leaderboard") diff --git a/docs/cli/pages.md b/docs/cli/pages.md index 8379ce187..2c6ca3c60 100644 --- a/docs/cli/pages.md +++ b/docs/cli/pages.md @@ -11,7 +11,7 @@ Each page's command, or why there is none. | `/trial//` | `nullius runs show [--json]` | | A trial's Conversation, by call | `nullius runs show --calls` | | `/import`, `/use-path` | `nullius import -o [--json]`; `--list` | -| `/leaderboard?row=&tasks=&hide_axis=&show_axis=&hide_version=&hide_run=&unchecked=`; `&measure=mean_score` and `&family=domains` show the other of the two numbers and of the two families the command prints | `nullius leaderboard ... [--row KEY]... [--every-task] [--hide-axis AXIS] [--show-axis AXIS] [--hide-version BENCHMARK@VERSION] [--hide-run ID] [--unchecked-labels omit\|include] [--json]`; `nullius remote leaderboard` against a served Nullius | +| `/leaderboard?row=&tasks=&hide_axis=&show_axis=&hide_version=&hide_run=&unchecked=`; `&measure=mean_score` and `&family=domains` show the other of the two numbers and of the two families the command prints | `nullius leaderboard ... [--row KEY]... [--every-task] [--hide-axis AXIS] [--show-axis AXIS] [--hide-version BENCHMARK@VERSION] [--hide-run ID] [--unchecked-labels omit\|include] [--json]`; its *Scoring* dialog holds `row` (*Agents*), `hide_axis`, `show_axis`, `hide_version`, `hide_run`, `tasks`, `measure` and `unchecked`, and *Function*, a weight of the matrix or of the vector, *Normalize* and *Reset*: `--function counts\|vector\|matrix`, `--weight BENCHMARK:AXIS=NUMBER`, `--axis-weight AXIS=NUMBER`, `--normalize-weights`, `--reset-weights`; `nullius remote leaderboard` against a served Nullius | | `/compare` | `nullius compare ... [--matched] [--exclude KIND]... [--json]` | | `/workspaces/open/` | `nullius serve ...`, `WORKSPACE=` | | `/workspaces` | `nullius workspace list [--home DIR] [--json]` | diff --git a/docs/cli/read-jobs.md b/docs/cli/read-jobs.md index 6d16183e6..5a51156db 100644 --- a/docs/cli/read-jobs.md +++ b/docs/cli/read-jobs.md @@ -89,7 +89,12 @@ the document was read; an invalid root exits 3, invalid arguments or an unknown | `--hide-axis AXIS`, `--show-axis AXIS` | Leave an axis out of the columns and Overall; show one hidden by default | | `--hide-version BENCHMARK@VERSION`, `--hide-run ID` | Leave a benchmark version or a run out | | `--unchecked-labels omit\|include` | Count labels not checked at a run's version; the `LEADERBOARD_UNCHECKED_LABELS` setting by default | +| `--function counts\|vector\|matrix` | The scoring function, saved in the profile; `counts` at first. `vector`: Overall weighs each axis. `matrix`: an axis weighs each benchmark, and Overall is the average of the axes | +| `--weight BENCHMARK:AXIS=NUMBER` | Save one weight of the matrix, repeatable; no number is 1 again | +| `--axis-weight AXIS=NUMBER` | Save one weight of the vector, repeatable; no number is 1 again | +| `--normalize-weights`, `--reset-weights` | Of the active function: rewrite its weights to sum to 1, per axis of the matrix or per family of the vector, those that sum to 0 left and named; put every weight back to 1 | +The text names the function and lists its weights; JSON carries them under `function` and `weights`. The page takes the same options in its address and gives the same numbers: see the [Leaderboard](../field-guide.md#leaderboard). JSON carries, per row, its key, identity, runs, rank and both views (`shared`, `every`): each axis's count diff --git a/docs/field-guide.md b/docs/field-guide.md index 028818b0a..e91728d07 100644 --- a/docs/field-guide.md +++ b/docs/field-guide.md @@ -305,16 +305,43 @@ benchmark versions it was checked at; at another version it counts only with unchecked labels included. A benchmark without labels scores nothing. Each axis is defined under [Leaderboard axes](#leaderboard-axes). +**Function.** The scoring function, in the page's *Scoring* dialog and +`--function` on the command. One is active; the other two keep their saved +weights. Every weight is 1 until changed, and an emptied one is 1 again. + +- **Counts**, the default: every labelled task counts once. Overall is the share + resolved of the tasks of its family's shown axes. +- **Weight vector**: one weight per axis. Axis values are as Counts gives them. + Overall is the average of its family's shown axes, each by its weight over + their total, so all at 1 is their plain average. +- **Weight matrix**: one weight per benchmark and axis. A benchmark's share of an + axis is its weight over the total of the axis's weights, whatever its count of + tasks, so all at 1 gives each benchmark an equal share, which is not Counts. + Overall is the plain average of its family's shown axes. A weight exists only + where the view's tasks give the benchmark the axis; another is said and not + applied. + +Under either weighted function the ranks follow Overall, and an axis with no +value is left out of it. *Normalize* rewrites the active function's weights to +sum to 1, per axis of the matrix or per family of the vector, and changes no +score; weights that sum to 0 are not scored, are named, and are left as they +are. A benchmark first run after *Normalize* starts at 1. *Reset* puts the +active function's weights back to 1; Counts has none to reset. +The page, the command and the API read `leaderboard-weights.json` in the user +config directory. A file that does not read is Counts and kept until a +correction or `nullius leaderboard --reset-weights`. A v0.3.0 `scoring.json` is +not read. + **Runs.** Per row, the most recent finished run of each benchmark version and dataset counts. Every other run is set aside, with one warning per benchmark version: hide a run to count another. A run must record its benchmark version. Two versions of a benchmark are never pooled. **Rows compared.** With nothing asked, the rows are those with an evaluated task -on a shown axis. Filters and the search on the page, `--row` on the command and -`row` on the API choose them, before anything is scored; an empty `row=` chooses -none. Clear filters resets the filters, not the search. An unknown row is -refused. +on a shown axis. *Agents* in the page's *Scoring* dialog, `--row` on the command +and `row` on the API choose them, before anything is scored; an empty `row=` +chooses none. An unknown row is refused. The table's search, filters and +Columns only show and hide: they change no score, N or rank. | View | Reads | Ranked | | --- | --- | --- | @@ -327,8 +354,8 @@ refused. - **Resolved** is the share of tasks fully resolved. **Mean score** is the mean task score; a graded task below full score is not resolved. Each chart says which it shows. Infrastructure failures are excluded. -- **Overall** covers the tasks of the shown axes of one family, each task once. - Hiding an axis changes it. Every row with shared tasks is ranked by Overall +- **Overall** covers the tasks of the shown axes of one family, each task once; + under a weighted function, it is an average of those axes. Hiding an axis changes it. Every row with shared tasks is ranked by Overall Resolved; ties share a rank. - **pass^3** needs three recorded attempts per task. It is given over all the tasks, or for each benchmark version that recorded them, with its count of @@ -337,8 +364,8 @@ refused. the runs those tasks come from (a run whose name two folders hold is named by its folder, without a link), coverage (evaluated over labelled tasks, "?" when the dataset was never listed) and pass^3. -- **Selection.** Axes, benchmark versions and runs can be hidden. The page's - address carries the selection, the rows, the view, the family and measure +- **Selection.** Axes, benchmark versions and runs can be left out, in the + *Scoring* dialog. The page's address carries the selection, the rows, the view, the family and measure shown and the unchecked-labels mode. Time and cost are means per attempt over the observed trials of the tasks diff --git a/docs/releases/next.md b/docs/releases/next.md index f4cd99093..b9ec89390 100644 --- a/docs/releases/next.md +++ b/docs/releases/next.md @@ -1,3 +1,4 @@ **Next release** - **Leaderboard.** Scores come from task labels (`labels.json`), compared on the tasks rows share. Saved Scoring weights stop counting: `scoring.json` is no longer read and is kept where it is. The Scoring view is gone; `task_parts` in a benchmark definition no longer has an effect: `nullius standard check` warns, the definition still loads. `/api/leaderboard/comparison` is gone: choose versions with `hide_version` on `/api/leaderboard`. +- **Leaderboard scoring function.** The view, the unchecked labels and the function are in the page's *Scoring* dialog: *Counts*, the default, *Weight vector*, one weight per axis for Overall, or *Weight matrix*, one weight per benchmark and axis. `--function counts|vector|matrix` on the command. Every weight starts at 1: the matrix then gives each benchmark an equal share of an axis. Under a weighted function Overall is an average of the axes and the ranks follow it.