alanclayrichard's picture
score bindingdb on only exact == measurements, accept partial submissions (single or few function only) with unsubmitted set to chance)
580f4e5
Raw History Blame Contribute Delete
8.74 kB
"""Aggregating eleven benchmarks into one leaderboard.
The per-benchmark numbers do not share a chance level — random predictions
score a Spearman of 0, an AUROC of 0.5 and an Fmax near 0 — so an unweighted mean
of the raw values would mix improvement over chance with the chance level itself.
``normalise`` maps each metric so that chance is 0 and perfect is 1, and their
mean is the **PLUG Score**: the average improvement over random chance.
Nothing is clipped, so a below-chance AUROC counts against a submission. A
Spearman correlation is the exception, normalised on its magnitude: its sign is
a convention of which way a label was written, and a model scoring -0.99 is as
predictive as one scoring 0.99 once reversed.
The mean is always over every benchmark. One a submission left out (or could not
be scored on) counts as chance, 0, so a bundle covering a single benchmark cannot
top the overall board on that benchmark alone; it is ranked on that benchmark's
own tab, where only the entries that covered it appear.
The PLUG Score is deterministic: it depends only on a submission's own
predictions, so a number stays the same as other entries arrive and is safe to
quote in a paper. It is recomputed from the stored per-benchmark metrics every
time the board is built, so a change to the normalisation needs no migration.
``mean_rank`` is reported next to it as the relative view, and that one does
move as the field fills in.
"""
import numpy as np
import pandas as pd
from .benchmarks import BENCHMARKS, BenchmarkSpec, MetricSpec
# Column prefix separator for the flattened per-benchmark metric columns in a
# leaderboard row: "megascale__spearman_mean". Double underscore because several
# benchmark names and metric keys contain single underscores.
SEP = "__"
# Public leaderboard columns that are not per-benchmark metrics, in display order.
IDENTITY_COLUMNS = (
"rank",
"track",
"username",
"submitted_at",
"plug_score",
"mean_rank",
"benchmarks_scored",
"model_report_link",
"used_proprietary_data",
"open_source_code",
)
def normalise(value: float, metric: MetricSpec) -> float:
"""Map a metric value so that chance is 0 and a perfect score is 1.
``(value - chance) / (1 - chance)``: a Spearman of 0, an AUROC of 0.5 and an
Fmax of 0 all land on 0. Values below chance stay negative rather than being
clipped, except for a sign-free metric (Spearman), which is normalised on
its magnitude.
Parameters
----------
value : float
The raw metric value.
metric : MetricSpec
The metric, for its ``chance`` level and whether it is ``sign_free``.
Returns
-------
float
The normalised value, in ``[-1, 1]`` for AUROC and ``[0, 1]`` for the
rest, or NaN if ``value`` is not finite.
"""
if not np.isfinite(value):
return float("nan")
if metric.sign_free:
value = abs(value)
return float((value - metric.chance) / (1.0 - metric.chance))
def plug_score(
scores: dict[str, dict[str, float]], specs: tuple[BenchmarkSpec, ...] = BENCHMARKS
) -> float:
"""Compute the headline number: mean normalised primary metric across benchmarks.
Parameters
----------
scores : dict[str, dict[str, float]]
Per-benchmark metric values, as returned by ``scoring.score_bundle``.
specs : tuple[BenchmarkSpec, ...]
The benchmarks the challenge runs.
Returns
-------
float
Mean over **every** benchmark in ``specs`` of the normalised primary
metric, where 0 is chance and 1 is perfect. A benchmark that is absent,
or whose metric is not finite, counts as 0 (chance), so a partial
bundle is not rewarded for what it skipped.
"""
values = [
normalise(scores.get(spec.name, {}).get(f"{spec.primary.key}_mean", np.nan), spec.primary)
for spec in specs
]
return float(np.mean([v if np.isfinite(v) else 0.0 for v in values]))
def flatten(scores: dict[str, dict[str, float]]) -> dict[str, float]:
"""Flatten nested per-benchmark scores into leaderboard columns.
Parameters
----------
scores : dict[str, dict[str, float]]
Per-benchmark metric values.
Returns
-------
dict[str, float]
``{"megascale__spearman_mean": ..., "megascale__n": ..., ...}``.
"""
return {
f"{benchmark}{SEP}{key}": value
for benchmark, benchmark_scores in scores.items()
for key, value in benchmark_scores.items()
}
def column(benchmark: str, metric: MetricSpec, statistic: str = "mean") -> str:
"""Name of the flattened leaderboard column for one benchmark's metric.
Parameters
----------
benchmark : str
Benchmark name.
metric : MetricSpec
The metric.
statistic : str
``"mean"`` or ``"std"``.
Returns
-------
str
e.g. ``"megascale__spearman_mean"``.
"""
return f"{benchmark}{SEP}{metric.key}_{statistic}"
def score_column(benchmark: str) -> str:
"""Name of the leaderboard column holding a benchmark's normalised primary metric.
Parameters
----------
benchmark : str
Benchmark name.
Returns
-------
str
e.g. ``"megascale__score"``.
"""
return f"{benchmark}{SEP}score"
def build_leaderboard(
entries: list[dict],
specs: tuple[BenchmarkSpec, ...] = BENCHMARKS,
track: str | None = None,
) -> pd.DataFrame:
"""Rank leaderboard entries and add the per-benchmark and overall rank columns.
Only a participant's **latest** submission per track is ranked: earlier ones
are dropped so the board shows one row per entrant, which is what makes
``mean_rank`` meaningful.
Parameters
----------
entries : list[dict]
One dict per submission — identity fields plus the flattened metric
columns from ``flatten``.
specs : tuple[BenchmarkSpec, ...]
The benchmarks the challenge runs, in display order.
track : str | None
Keep only this track's entries. An entry stored before tracks existed
has no ``track`` and counts as ``supervised``. ``None`` keeps every
entry, which only makes sense when they all share a track.
Returns
-------
pd.DataFrame
One row per entrant, sorted best-first by ``plug_score``, with a 1-based
``rank``, a normalised ``<benchmark>__score`` and ``<benchmark>__rank``
per benchmark, and ``mean_rank``. Returns an empty frame with the
expected columns when no entry is left.
"""
if not entries:
return pd.DataFrame(columns=list(IDENTITY_COLUMNS))
df = pd.DataFrame(entries)
df["track"] = df["track"].fillna("supervised") if "track" in df.columns else "supervised"
if track is not None:
df = df[df["track"] == track]
if df.empty:
return pd.DataFrame(columns=list(IDENTITY_COLUMNS))
df["submitted_at"] = pd.to_datetime(df["submitted_at"], utc=True, errors="coerce")
df = (
df.sort_values("submitted_at")
.drop_duplicates(subset=["username", "track"], keep="last")
.reset_index(drop=True)
)
rank_columns, normalised_columns = [], []
for spec in specs:
metric_column = column(spec.name, spec.primary)
normalised = score_column(spec.name)
df[normalised] = (
[
normalise(value, spec.primary)
for value in pd.to_numeric(df[metric_column], errors="coerce")
]
if metric_column in df.columns
else np.nan
)
normalised_columns.append(normalised)
rank_column = f"{spec.name}{SEP}rank"
# An entrant with no score here ranks last, behind everyone who has one.
df[rank_column] = (
df[normalised].rank(ascending=False, method="min").fillna(len(df))
)
rank_columns.append(rank_column)
# Recomputed rather than read back, so a stored score from an older
# normalisation can never disagree with the per-benchmark columns beside it.
# A benchmark with no score counts as chance (0) — see the module docstring.
df["plug_score"] = df[normalised_columns].fillna(0.0).mean(axis=1)
df["mean_rank"] = df[rank_columns].mean(axis=1)
primary_columns = [
column(spec.name, spec.primary)
for spec in specs
if column(spec.name, spec.primary) in df.columns
]
df["benchmarks_scored"] = df[primary_columns].notna().sum(axis=1)
df = df.sort_values(
["plug_score", "mean_rank"], ascending=[False, True], na_position="last"
).reset_index(drop=True)
df.insert(0, "rank", np.arange(1, len(df) + 1))
return df