File size: 8,740 Bytes
b78ff28
 
49442cb
 
 
 
 
 
 
 
 
 
b78ff28
580f4e5
 
 
 
 
b78ff28
 
49442cb
 
 
 
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
 
 
 
 
 
 
49442cb
 
b78ff28
49442cb
 
 
 
b78ff28
 
 
 
 
49442cb
 
b78ff28
 
 
 
49442cb
 
b78ff28
 
 
 
49442cb
 
 
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580f4e5
 
 
 
b78ff28
 
 
580f4e5
b78ff28
 
580f4e5
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b78ff28
49442cb
 
 
b78ff28
 
 
49442cb
 
b78ff28
 
 
 
 
 
 
 
 
49442cb
 
 
 
b78ff28
 
 
 
 
49442cb
 
 
b78ff28
 
 
 
 
 
49442cb
 
 
 
 
b78ff28
 
 
49442cb
b78ff28
 
 
49442cb
b78ff28
 
49442cb
580f4e5
 
 
 
 
 
 
 
49442cb
b78ff28
580f4e5
 
 
 
b78ff28
 
49442cb
 
580f4e5
 
49442cb
580f4e5
b78ff28
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
"""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