read-bench-results / eval_submission.py
gerar444's picture
Scaffold: protocol README, official harness, validator, example submission
e6cdfd6 verified
Raw History Blame Contribute Delete
10.4 kB
"""READ-Bench leaderboard — official evaluation harness (self-contained).
This file is the single source of truth for how a submission is scored. It has
**no dependency on any private package** — only ``datasets`` + ``numpy`` — so a
submitter can clone the public results repo and reproduce their number exactly.
A submission provides a ``method.py`` exposing:
def rank(query: dict, corpus: list[dict]) -> list[int]:
'''Return corpus INDICES ordered most- to least-relevant to `query`.
You may read ts_values / channels / entry metadata, but NEVER
query["class_label"] (the hidden target). Corpus class_labels may be
read only if your method is declared supervised / label-aware.'''
The harness loads the public dataset, rebuilds the official corpus/query split
for each dataset and pollution level, calls ``rank`` per query, and computes
NDCG@10 (plus P/HR/NDCG@{1,5,20} and macro-F1) with the paper's metric, then
macro-averages across datasets. Run::
python eval_submission.py --submission submissions/my-method --out results.json
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import random
import sys
from pathlib import Path
from typing import Callable, Dict, List, Tuple
import numpy as np
REPO = "c3aiia3c/read-bench"
DATASETS = [
"ctsr", "damadics", "exathlon", "hai", "mit_bih", "petrobras_3w",
"rats40k", "rcaeval", "road", "telecom_ts", "tennessee_eastman", "voraus",
]
# Official pollution levels: fraction of the corpus that is Normal.
POLLUTION = {"rho0": 0.0, "rho10": 0.10, "rho20": 0.20}
TOPK = (1, 3, 5, 10, 20)
PRIMARY_METRIC = "NDCG@10"
SEED = 42
LABEL_NORMAL = "Normal"
# --------------------------------------------------------------------------
# Metric — vendored verbatim from the paper's implementation so submissions
# score identically to the published numbers.
# --------------------------------------------------------------------------
def score_retrieval(score_matrix: np.ndarray, corpus_labels: np.ndarray,
query_labels: np.ndarray, topk: Tuple[int, ...] = TOPK) -> dict:
"""Score a (Q, N) score matrix (higher = better). P/HR/NDCG@K + macro-F1."""
order = np.argsort(-score_matrix, axis=1, kind="stable")
ranked = corpus_labels[order]
n_rel = (corpus_labels == query_labels[:, None]).sum(axis=1)
return _metrics_from_ranked(ranked, query_labels, n_rel, topk)
def score_from_ranked(ranked: np.ndarray, corpus_labels: np.ndarray,
query_labels: np.ndarray, topk: Tuple[int, ...] = TOPK) -> dict:
"""Score from a (Q, N) matrix of corpus indices already ranked per query."""
ranked_labels = corpus_labels[ranked]
n_rel = (corpus_labels == query_labels[:, None]).sum(axis=1)
return _metrics_from_ranked(ranked_labels, query_labels, n_rel, topk)
def _metrics_from_ranked(ranked, query_labels, n_rel, topk) -> dict:
rel = (ranked == query_labels[:, None])
n_rel = np.maximum(n_rel, 1)
metrics: Dict[str, float] = {}
for k in topk:
rel_k = rel[:, :k]
metrics[f"P@{k}"] = float(rel_k.mean())
metrics[f"HR@{k}"] = float(rel_k.any(axis=1).mean())
discounts = 1.0 / np.log2(np.arange(2, k + 2))
dcg = (rel_k * discounts).sum(axis=1)
ideal = np.array([discounts[:min(int(nr), k)].sum() for nr in n_rel])
metrics[f"NDCG@{k}"] = float(np.where(ideal > 0, dcg / ideal, 0.0).mean())
def _majority(top5):
counts: dict = {}
order: list = []
for lbl in top5:
if lbl not in counts:
counts[lbl] = 0
order.append(lbl)
counts[lbl] += 1
return max(order, key=lambda l: counts[l])
top5 = [_majority(ranked[q, :5].tolist()) for q in range(len(query_labels))]
classes = np.unique(query_labels)
f1s = []
for cls in classes:
tp = sum(p == cls and t == cls for p, t in zip(top5, query_labels))
fp = sum(p == cls and t != cls for p, t in zip(top5, query_labels))
fn = sum(p != cls and t == cls for p, t in zip(top5, query_labels))
pr = tp / (tp + fp) if tp + fp else 0.0
rc = tp / (tp + fn) if tp + fn else 0.0
f1s.append(2 * pr * rc / (pr + rc) if pr + rc else 0.0)
metrics["macro_F1"] = float(np.mean(f1s)) if f1s else 0.0
return metrics
# --------------------------------------------------------------------------
# Official split reconstruction (self-contained; mirrors the paper protocol).
# Corpus = train-split anomalies (+ Normals to the pollution fraction),
# query = test-split anomalies. Deterministic given SEED.
# --------------------------------------------------------------------------
def _is_anom(e: dict) -> bool:
return e.get("label") != LABEL_NORMAL
def _subsample_normals(normals: List[dict], n: int, rng: random.Random) -> List[dict]:
if n >= len(normals):
return list(normals)
return rng.sample(normals, n)
def build_eval_split(rows: List[dict], pollution: float, seed: int = SEED,
) -> Tuple[List[dict], List[dict]]:
"""Return ``(corpus, query)`` for one dataset at one pollution level.
Corpus = train anomalies + enough train Normals to make ``pollution`` of the
corpus Normal; query = test anomalies. All deterministic given ``seed``.
"""
rng = random.Random(seed)
train = [r for r in rows if r["native_split"] == "train"]
test = [r for r in rows if r["native_split"] == "test"]
corpus_anom = [r for r in train if _is_anom(r)]
query = [r for r in test if _is_anom(r)]
if not query: # degenerate datasets: fall back to all test rows
query = list(test)
corpus = list(corpus_anom)
if pollution > 0 and corpus_anom:
# n_normal / (n_anom + n_normal) = pollution -> solve for n_normal
n_norm = round(pollution / (1 - pollution) * len(corpus_anom))
train_normals = [r for r in train if not _is_anom(r)]
corpus += _subsample_normals(train_normals, n_norm, rng)
rng.shuffle(corpus)
return corpus, query
# --------------------------------------------------------------------------
# Submission loading + running.
# --------------------------------------------------------------------------
def load_method(submission_dir: Path) -> Callable[[dict, List[dict]], List[int]]:
"""Import ``method.py`` from a submission dir and return its ``rank``."""
method_path = submission_dir / "method.py"
if not method_path.exists():
raise FileNotFoundError(f"no method.py in {submission_dir}")
spec = importlib.util.spec_from_file_location("submission_method", method_path)
mod = importlib.util.module_from_spec(spec)
sys.modules["submission_method"] = mod
spec.loader.exec_module(mod)
if not hasattr(mod, "rank"):
raise AttributeError("method.py must define rank(query, corpus) -> list[int]")
return mod.rank
def _label_array(entries: List[dict]) -> np.ndarray:
return np.array([e["class_label"] for e in entries], dtype=object)
def eval_dataset(rank_fn, rows: List[dict], pollution: float) -> dict:
"""Run the method over one dataset at one pollution level -> metrics dict."""
corpus, query = build_eval_split(rows, pollution)
corpus_labels = _label_array(corpus)
query_labels = _label_array(query)
# Hide the query's class_label from the method (anti-cheat on the target).
masked_queries = [{k: v for k, v in q.items() if k != "class_label"} for q in query]
ranked = np.zeros((len(query), len(corpus)), dtype=np.int64)
for i, q in enumerate(masked_queries):
order = rank_fn(q, corpus)
order = list(dict.fromkeys(int(j) for j in order)) # dedupe, keep order
missing = [j for j in range(len(corpus)) if j not in set(order)]
full = (order + missing)[:len(corpus)]
ranked[i] = full
return score_from_ranked(ranked, corpus_labels, query_labels)
def evaluate(submission_dir: Path, datasets: List[str] = None,
repo: str = REPO, token: str = None) -> dict:
"""Full evaluation of a submission -> results dict (also written as results.json)."""
from datasets import load_dataset
datasets = datasets or DATASETS
rank_fn = load_method(submission_dir)
per_dataset: Dict[str, Dict[str, dict]] = {}
for name in datasets:
ds = load_dataset(repo, name, token=token)
rows = list(ds["train"]) + list(ds["test"])
per_dataset[name] = {}
for level, rho in POLLUTION.items():
per_dataset[name][level] = eval_dataset(rank_fn, rows, rho)
# Macro-average across datasets, per pollution level.
summary: Dict[str, Dict[str, float]] = {}
all_metrics = next(iter(next(iter(per_dataset.values())).values())).keys()
for level in POLLUTION:
summary[level] = {}
for metric in all_metrics:
vals = [per_dataset[d][level][metric] for d in datasets]
summary[level][metric] = float(np.mean(vals))
return {
"primary_metric": PRIMARY_METRIC,
"headline": {level: summary[level][PRIMARY_METRIC] for level in POLLUTION},
"summary_macro_avg": summary,
"per_dataset": per_dataset,
"datasets": datasets,
}
def main(argv=None) -> None:
p = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--submission", required=True, type=Path,
help="submission dir containing method.py + metadata.yaml")
p.add_argument("--out", type=Path, default=None,
help="write results JSON here (default: <submission>/results.json)")
p.add_argument("--datasets", nargs="*", default=None, help="subset (default: all 12)")
p.add_argument("--repo", default=REPO)
p.add_argument("--token", default=None, help="HF token (only needed if repo is private)")
args = p.parse_args(argv)
results = evaluate(args.submission, args.datasets, args.repo, args.token)
out = args.out or (args.submission / "results.json")
out.write_text(json.dumps(results, indent=2))
h = results["headline"]
print(f"NDCG@10 rho0={h['rho0']:.4f} rho10={h['rho10']:.4f} rho20={h['rho20']:.4f}")
print(f"wrote {out}")
if __name__ == "__main__":
main()