Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions app/nullius/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
31 changes: 25 additions & 6 deletions app/nullius/leaderboard/board.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -92,14 +96,29 @@ 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):
# a reader names a version by its release or short commit, never the whole pin
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]
Expand Down Expand Up @@ -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())],
Expand Down
52 changes: 49 additions & 3 deletions app/nullius/leaderboard/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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")}

Expand Down Expand Up @@ -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
Expand All @@ -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)}")
Expand Down
70 changes: 54 additions & 16 deletions app/nullius/leaderboard/projection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand All @@ -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]
Expand All @@ -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:
Expand Down Expand Up @@ -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}}
Loading
Loading