gerar444 commited on
Commit
e6cdfd6
·
verified ·
1 Parent(s): e95074e

Scaffold: protocol README, official harness, validator, example submission

Browse files
README.md ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-sa-4.0
3
+ pretty_name: "READ-Bench — Leaderboard Submissions"
4
+ tags:
5
+ - leaderboard
6
+ - time-series
7
+ - retrieval
8
+ - anomaly-detection
9
+ - benchmark
10
+ ---
11
+
12
+ # READ-Bench — Leaderboard Submissions
13
+
14
+ This repository collects **community submissions** to the
15
+ [READ-Bench](https://huggingface.co/datasets/c3aiia3c/read-bench) leaderboard for
16
+ historical-instance retrieval in time-series diagnosis
17
+ ([arXiv:2609.32123](https://arxiv.org/abs/2609.32123)).
18
+
19
+ - **Data** lives in [`c3aiia3c/read-bench`](https://huggingface.co/datasets/c3aiia3c/read-bench).
20
+ - **Submissions** (code + results) live here, one folder per method.
21
+ - **The live board** is the
22
+ [READ-Bench Leaderboard Space](https://huggingface.co/spaces/c3aiia3c/read-bench-leaderboard),
23
+ which renders every accepted submission.
24
+
25
+ Submissions are **reproducible by design**: you include runnable code, and the
26
+ official harness (`eval_submission.py`, in this repo) runs *your* method against
27
+ the *hidden* relevance labels to produce the score — so numbers can't be faked
28
+ and anyone can rerun them.
29
+
30
+ ## What a submission contains
31
+
32
+ Add one folder, `submissions/<your-slug>/`, with:
33
+
34
+ | file | required | what |
35
+ |---|---|---|
36
+ | `method.py` | ✅ | exposes `rank(query, corpus) -> list[int]` (see contract below) |
37
+ | `metadata.yaml` | ✅ | method name, family, supervision, authors, links |
38
+ | `requirements.txt` | ✅ | any deps your `method.py` imports |
39
+ | `results.json` | ✅ | produced by the harness (do not hand-edit) |
40
+
41
+ Copy [`example_submission/`](example_submission) as your starting point — it's a
42
+ working Euclidean-distance baseline.
43
+
44
+ ## The method contract
45
+
46
+ ```python
47
+ def rank(query: dict, corpus: list[dict]) -> list[int]:
48
+ """Return corpus INDICES ordered most- to least-relevant to `query`.
49
+
50
+ Each entry has: ts_values ([T][C] floats), channels, label, class_label,
51
+ rca_target, rca_affected, dataset, entry_id, native_split, extras.
52
+
53
+ Rules:
54
+ * NEVER read query["class_label"] — it is the hidden target (and is
55
+ masked out before your function is called).
56
+ * You may read corpus class_labels ONLY if you declare your method
57
+ `supervision: supervised` or `neighbour-labels` in metadata.yaml.
58
+ """
59
+ ```
60
+
61
+ ## How to submit (all on Hugging Face — no GitHub needed)
62
+
63
+ ```bash
64
+ # 1. clone this repo (git-backed, like GitHub)
65
+ git clone https://huggingface.co/datasets/c3aiia3c/read-bench-results
66
+ cd read-bench-results
67
+
68
+ # 2. create your submission from the template
69
+ cp -r example_submission submissions/my-method
70
+ # ... edit submissions/my-method/method.py + metadata.yaml + requirements.txt
71
+
72
+ # 3. validate structure, then score with the official harness
73
+ pip install -r submissions/my-method/requirements.txt
74
+ python validate_submission.py --submission submissions/my-method --run
75
+ # -> writes submissions/my-method/results.json
76
+
77
+ # 4. open a Pull Request on this repo (Community tab) with your folder.
78
+ ```
79
+
80
+ To open the PR: push your branch, or use the **"Community" → "New pull request"**
81
+ button on this repo's page and upload your `submissions/<slug>/` folder. A
82
+ maintainer re-runs the harness to confirm your `results.json`, then merges — and
83
+ the [Leaderboard Space](https://huggingface.co/spaces/c3aiia3c/read-bench-leaderboard)
84
+ picks it up automatically.
85
+
86
+ ## Scoring
87
+
88
+ - **Primary metric:** NDCG@10, macro-averaged over the 12 datasets, at pollution
89
+ levels ρ = 0 / 10 / 20% (fraction of the corpus that is Normal).
90
+ - Also reported: P@{1,3,5,10,20}, HR@{...}, NDCG@{1,3,5,20}, macro-F1.
91
+ - Relevance is binary & multi-target: a corpus item is relevant to a query iff
92
+ they share the same non-normal `class_label`.
93
+ - The split is reconstructed deterministically (seed 42): corpus = train-split
94
+ anomalies + Normals to the pollution fraction; queries = test-split anomalies.
95
+
96
+ See [`eval_submission.py`](eval_submission.py) for the exact, self-contained
97
+ implementation (only `datasets` + `numpy`).
98
+
99
+ ## Citation
100
+
101
+ ```bibtex
102
+ @article{readbench2026,
103
+ title = {READ-Bench: Benchmarking Historical Instance Retrieval for Time-Series Diagnosis},
104
+ author = {Pastrana, Gerardo and Li, Haojun and Mehta, Dhruv and Vyas, Anoushka and
105
+ Khoshfetrat Pakazad, Sina and Ohlsson, Henrik and Paparrizos, John},
106
+ journal = {arXiv preprint arXiv:2609.32123},
107
+ year = {2026}
108
+ }
109
+ ```
eval_submission.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """READ-Bench leaderboard — official evaluation harness (self-contained).
2
+
3
+ This file is the single source of truth for how a submission is scored. It has
4
+ **no dependency on any private package** — only ``datasets`` + ``numpy`` — so a
5
+ submitter can clone the public results repo and reproduce their number exactly.
6
+
7
+ A submission provides a ``method.py`` exposing:
8
+
9
+ def rank(query: dict, corpus: list[dict]) -> list[int]:
10
+ '''Return corpus INDICES ordered most- to least-relevant to `query`.
11
+ You may read ts_values / channels / entry metadata, but NEVER
12
+ query["class_label"] (the hidden target). Corpus class_labels may be
13
+ read only if your method is declared supervised / label-aware.'''
14
+
15
+ The harness loads the public dataset, rebuilds the official corpus/query split
16
+ for each dataset and pollution level, calls ``rank`` per query, and computes
17
+ NDCG@10 (plus P/HR/NDCG@{1,5,20} and macro-F1) with the paper's metric, then
18
+ macro-averages across datasets. Run::
19
+
20
+ python eval_submission.py --submission submissions/my-method --out results.json
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import importlib.util
27
+ import json
28
+ import random
29
+ import sys
30
+ from pathlib import Path
31
+ from typing import Callable, Dict, List, Tuple
32
+
33
+ import numpy as np
34
+
35
+ REPO = "c3aiia3c/read-bench"
36
+ DATASETS = [
37
+ "ctsr", "damadics", "exathlon", "hai", "mit_bih", "petrobras_3w",
38
+ "rats40k", "rcaeval", "road", "telecom_ts", "tennessee_eastman", "voraus",
39
+ ]
40
+ # Official pollution levels: fraction of the corpus that is Normal.
41
+ POLLUTION = {"rho0": 0.0, "rho10": 0.10, "rho20": 0.20}
42
+ TOPK = (1, 3, 5, 10, 20)
43
+ PRIMARY_METRIC = "NDCG@10"
44
+ SEED = 42
45
+ LABEL_NORMAL = "Normal"
46
+
47
+
48
+ # --------------------------------------------------------------------------
49
+ # Metric — vendored verbatim from the paper's implementation so submissions
50
+ # score identically to the published numbers.
51
+ # --------------------------------------------------------------------------
52
+
53
+ def score_retrieval(score_matrix: np.ndarray, corpus_labels: np.ndarray,
54
+ query_labels: np.ndarray, topk: Tuple[int, ...] = TOPK) -> dict:
55
+ """Score a (Q, N) score matrix (higher = better). P/HR/NDCG@K + macro-F1."""
56
+ order = np.argsort(-score_matrix, axis=1, kind="stable")
57
+ ranked = corpus_labels[order]
58
+ n_rel = (corpus_labels == query_labels[:, None]).sum(axis=1)
59
+ return _metrics_from_ranked(ranked, query_labels, n_rel, topk)
60
+
61
+
62
+ def score_from_ranked(ranked: np.ndarray, corpus_labels: np.ndarray,
63
+ query_labels: np.ndarray, topk: Tuple[int, ...] = TOPK) -> dict:
64
+ """Score from a (Q, N) matrix of corpus indices already ranked per query."""
65
+ ranked_labels = corpus_labels[ranked]
66
+ n_rel = (corpus_labels == query_labels[:, None]).sum(axis=1)
67
+ return _metrics_from_ranked(ranked_labels, query_labels, n_rel, topk)
68
+
69
+
70
+ def _metrics_from_ranked(ranked, query_labels, n_rel, topk) -> dict:
71
+ rel = (ranked == query_labels[:, None])
72
+ n_rel = np.maximum(n_rel, 1)
73
+ metrics: Dict[str, float] = {}
74
+ for k in topk:
75
+ rel_k = rel[:, :k]
76
+ metrics[f"P@{k}"] = float(rel_k.mean())
77
+ metrics[f"HR@{k}"] = float(rel_k.any(axis=1).mean())
78
+ discounts = 1.0 / np.log2(np.arange(2, k + 2))
79
+ dcg = (rel_k * discounts).sum(axis=1)
80
+ ideal = np.array([discounts[:min(int(nr), k)].sum() for nr in n_rel])
81
+ metrics[f"NDCG@{k}"] = float(np.where(ideal > 0, dcg / ideal, 0.0).mean())
82
+
83
+ def _majority(top5):
84
+ counts: dict = {}
85
+ order: list = []
86
+ for lbl in top5:
87
+ if lbl not in counts:
88
+ counts[lbl] = 0
89
+ order.append(lbl)
90
+ counts[lbl] += 1
91
+ return max(order, key=lambda l: counts[l])
92
+
93
+ top5 = [_majority(ranked[q, :5].tolist()) for q in range(len(query_labels))]
94
+ classes = np.unique(query_labels)
95
+ f1s = []
96
+ for cls in classes:
97
+ tp = sum(p == cls and t == cls for p, t in zip(top5, query_labels))
98
+ fp = sum(p == cls and t != cls for p, t in zip(top5, query_labels))
99
+ fn = sum(p != cls and t == cls for p, t in zip(top5, query_labels))
100
+ pr = tp / (tp + fp) if tp + fp else 0.0
101
+ rc = tp / (tp + fn) if tp + fn else 0.0
102
+ f1s.append(2 * pr * rc / (pr + rc) if pr + rc else 0.0)
103
+ metrics["macro_F1"] = float(np.mean(f1s)) if f1s else 0.0
104
+ return metrics
105
+
106
+
107
+ # --------------------------------------------------------------------------
108
+ # Official split reconstruction (self-contained; mirrors the paper protocol).
109
+ # Corpus = train-split anomalies (+ Normals to the pollution fraction),
110
+ # query = test-split anomalies. Deterministic given SEED.
111
+ # --------------------------------------------------------------------------
112
+
113
+ def _is_anom(e: dict) -> bool:
114
+ return e.get("label") != LABEL_NORMAL
115
+
116
+
117
+ def _subsample_normals(normals: List[dict], n: int, rng: random.Random) -> List[dict]:
118
+ if n >= len(normals):
119
+ return list(normals)
120
+ return rng.sample(normals, n)
121
+
122
+
123
+ def build_eval_split(rows: List[dict], pollution: float, seed: int = SEED,
124
+ ) -> Tuple[List[dict], List[dict]]:
125
+ """Return ``(corpus, query)`` for one dataset at one pollution level.
126
+
127
+ Corpus = train anomalies + enough train Normals to make ``pollution`` of the
128
+ corpus Normal; query = test anomalies. All deterministic given ``seed``.
129
+ """
130
+ rng = random.Random(seed)
131
+ train = [r for r in rows if r["native_split"] == "train"]
132
+ test = [r for r in rows if r["native_split"] == "test"]
133
+
134
+ corpus_anom = [r for r in train if _is_anom(r)]
135
+ query = [r for r in test if _is_anom(r)]
136
+ if not query: # degenerate datasets: fall back to all test rows
137
+ query = list(test)
138
+
139
+ corpus = list(corpus_anom)
140
+ if pollution > 0 and corpus_anom:
141
+ # n_normal / (n_anom + n_normal) = pollution -> solve for n_normal
142
+ n_norm = round(pollution / (1 - pollution) * len(corpus_anom))
143
+ train_normals = [r for r in train if not _is_anom(r)]
144
+ corpus += _subsample_normals(train_normals, n_norm, rng)
145
+ rng.shuffle(corpus)
146
+ return corpus, query
147
+
148
+
149
+ # --------------------------------------------------------------------------
150
+ # Submission loading + running.
151
+ # --------------------------------------------------------------------------
152
+
153
+ def load_method(submission_dir: Path) -> Callable[[dict, List[dict]], List[int]]:
154
+ """Import ``method.py`` from a submission dir and return its ``rank``."""
155
+ method_path = submission_dir / "method.py"
156
+ if not method_path.exists():
157
+ raise FileNotFoundError(f"no method.py in {submission_dir}")
158
+ spec = importlib.util.spec_from_file_location("submission_method", method_path)
159
+ mod = importlib.util.module_from_spec(spec)
160
+ sys.modules["submission_method"] = mod
161
+ spec.loader.exec_module(mod)
162
+ if not hasattr(mod, "rank"):
163
+ raise AttributeError("method.py must define rank(query, corpus) -> list[int]")
164
+ return mod.rank
165
+
166
+
167
+ def _label_array(entries: List[dict]) -> np.ndarray:
168
+ return np.array([e["class_label"] for e in entries], dtype=object)
169
+
170
+
171
+ def eval_dataset(rank_fn, rows: List[dict], pollution: float) -> dict:
172
+ """Run the method over one dataset at one pollution level -> metrics dict."""
173
+ corpus, query = build_eval_split(rows, pollution)
174
+ corpus_labels = _label_array(corpus)
175
+ query_labels = _label_array(query)
176
+
177
+ # Hide the query's class_label from the method (anti-cheat on the target).
178
+ masked_queries = [{k: v for k, v in q.items() if k != "class_label"} for q in query]
179
+
180
+ ranked = np.zeros((len(query), len(corpus)), dtype=np.int64)
181
+ for i, q in enumerate(masked_queries):
182
+ order = rank_fn(q, corpus)
183
+ order = list(dict.fromkeys(int(j) for j in order)) # dedupe, keep order
184
+ missing = [j for j in range(len(corpus)) if j not in set(order)]
185
+ full = (order + missing)[:len(corpus)]
186
+ ranked[i] = full
187
+ return score_from_ranked(ranked, corpus_labels, query_labels)
188
+
189
+
190
+ def evaluate(submission_dir: Path, datasets: List[str] = None,
191
+ repo: str = REPO, token: str = None) -> dict:
192
+ """Full evaluation of a submission -> results dict (also written as results.json)."""
193
+ from datasets import load_dataset
194
+
195
+ datasets = datasets or DATASETS
196
+ rank_fn = load_method(submission_dir)
197
+
198
+ per_dataset: Dict[str, Dict[str, dict]] = {}
199
+ for name in datasets:
200
+ ds = load_dataset(repo, name, token=token)
201
+ rows = list(ds["train"]) + list(ds["test"])
202
+ per_dataset[name] = {}
203
+ for level, rho in POLLUTION.items():
204
+ per_dataset[name][level] = eval_dataset(rank_fn, rows, rho)
205
+
206
+ # Macro-average across datasets, per pollution level.
207
+ summary: Dict[str, Dict[str, float]] = {}
208
+ all_metrics = next(iter(next(iter(per_dataset.values())).values())).keys()
209
+ for level in POLLUTION:
210
+ summary[level] = {}
211
+ for metric in all_metrics:
212
+ vals = [per_dataset[d][level][metric] for d in datasets]
213
+ summary[level][metric] = float(np.mean(vals))
214
+
215
+ return {
216
+ "primary_metric": PRIMARY_METRIC,
217
+ "headline": {level: summary[level][PRIMARY_METRIC] for level in POLLUTION},
218
+ "summary_macro_avg": summary,
219
+ "per_dataset": per_dataset,
220
+ "datasets": datasets,
221
+ }
222
+
223
+
224
+ def main(argv=None) -> None:
225
+ p = argparse.ArgumentParser(description=__doc__,
226
+ formatter_class=argparse.RawDescriptionHelpFormatter)
227
+ p.add_argument("--submission", required=True, type=Path,
228
+ help="submission dir containing method.py + metadata.yaml")
229
+ p.add_argument("--out", type=Path, default=None,
230
+ help="write results JSON here (default: <submission>/results.json)")
231
+ p.add_argument("--datasets", nargs="*", default=None, help="subset (default: all 12)")
232
+ p.add_argument("--repo", default=REPO)
233
+ p.add_argument("--token", default=None, help="HF token (only needed if repo is private)")
234
+ args = p.parse_args(argv)
235
+
236
+ results = evaluate(args.submission, args.datasets, args.repo, args.token)
237
+ out = args.out or (args.submission / "results.json")
238
+ out.write_text(json.dumps(results, indent=2))
239
+ h = results["headline"]
240
+ print(f"NDCG@10 rho0={h['rho0']:.4f} rho10={h['rho10']:.4f} rho20={h['rho20']:.4f}")
241
+ print(f"wrote {out}")
242
+
243
+
244
+ if __name__ == "__main__":
245
+ main()
example_submission/metadata.yaml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: "ED (channel-independent Euclidean)"
2
+ # Short slug used for the submission folder + leaderboard row.
3
+ slug: "ed-baseline"
4
+ family: "Raw-window distance" # one of: Raw-window distance | Symbolic | FM embedder | Fusion | Reranker | Supervised
5
+ supervision: "label-free" # one of: label-free | neighbour-labels | supervised
6
+ authors: "READ-Bench maintainers"
7
+ affiliation: "C3 AI"
8
+ paper: "" # URL to a paper/preprint, optional
9
+ code: "" # URL to a public code release, optional
10
+ description: >
11
+ Baseline reference: z-normalize each channel, linearly resample every window
12
+ to a common length, and rank corpus items by Euclidean distance. Label-free.
13
+ # Filled in automatically by the harness; leave blank in your PR.
14
+ results_file: "results.json"
example_submission/method.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Example READ-Bench submission: a channel-independent Euclidean (ED) retriever.
2
+
3
+ Copy this folder, rename it, and replace `rank` with your method. The only
4
+ contract is the `rank(query, corpus)` signature below. This baseline needs just
5
+ numpy — real submissions may import torch, an embedder, etc. (declare them in
6
+ `requirements.txt`).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Dict, List
12
+
13
+ import numpy as np
14
+
15
+
16
+ def _flat(entry: Dict) -> np.ndarray:
17
+ """Flatten a window to a 1-D vector; z-normalize per channel for scale.
18
+
19
+ `ts_values` is a nested `[T][C]` list (variable T, C across datasets). We
20
+ z-score each channel then flatten, so Euclidean distance is comparable.
21
+ """
22
+ x = np.asarray(entry["ts_values"], dtype=np.float32) # (T, C)
23
+ if x.ndim == 1:
24
+ x = x[:, None]
25
+ mu = x.mean(axis=0, keepdims=True)
26
+ sd = x.std(axis=0, keepdims=True)
27
+ sd = np.where(sd == 0, 1.0, sd)
28
+ return ((x - mu) / sd).ravel()
29
+
30
+
31
+ def rank(query: Dict, corpus: List[Dict]) -> List[int]:
32
+ """Return corpus indices ordered most- to least-relevant to `query`.
33
+
34
+ Label-free: ignores class_label entirely (never reads the query's, which is
35
+ masked anyway). Distance = Euclidean on resampled, z-normalized windows.
36
+ Windows of different length are compared on a common resampled grid.
37
+ """
38
+ GRID = 128
39
+ q = _resample(_flat(query), GRID)
40
+ dists = []
41
+ for item in corpus:
42
+ c = _resample(_flat(item), GRID)
43
+ dists.append(float(np.linalg.norm(q - c)))
44
+ # smaller distance = more relevant
45
+ return list(np.argsort(dists, kind="stable"))
46
+
47
+
48
+ def _resample(vec: np.ndarray, n: int) -> np.ndarray:
49
+ """Linear-resample a 1-D vector to length `n` so variable-shape windows align."""
50
+ if len(vec) == n:
51
+ return vec
52
+ if len(vec) == 0:
53
+ return np.zeros(n, dtype=np.float32)
54
+ xp = np.linspace(0.0, 1.0, num=len(vec))
55
+ x = np.linspace(0.0, 1.0, num=n)
56
+ return np.interp(x, xp, vec).astype(np.float32)
example_submission/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Example submission depends only on numpy. Declare any extra deps your
2
+ # method.py imports (torch, transformers, a specific embedder SDK, ...).
3
+ numpy>=1.24
4
+ datasets>=2.19
validate_submission.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate a READ-Bench submission before opening a PR.
2
+
3
+ Checks the submission folder is well-formed and (optionally) re-runs the
4
+ official harness to verify the reported numbers. Run::
5
+
6
+ python validate_submission.py --submission submissions/my-method # structure only
7
+ python validate_submission.py --submission submissions/my-method --run # + recompute scores
8
+
9
+ Exits non-zero on any failure, so it doubles as a CI gate.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ REQUIRED_FILES = ["method.py", "metadata.yaml", "requirements.txt"]
20
+ REQUIRED_META = ["name", "slug", "family", "supervision"]
21
+ FAMILIES = {"Raw-window distance", "Symbolic", "FM embedder", "Fusion",
22
+ "Reranker", "Supervised", "Other"}
23
+ SUPERVISION = {"label-free", "neighbour-labels", "supervised"}
24
+
25
+
26
+ def _fail(msg: str) -> None:
27
+ print(f" ✗ {msg}")
28
+
29
+
30
+ def _ok(msg: str) -> None:
31
+ print(f" ✓ {msg}")
32
+
33
+
34
+ def validate(submission: Path, run: bool, token: str = None) -> bool:
35
+ import yaml
36
+
37
+ print(f"Validating {submission}")
38
+ ok = True
39
+
40
+ for f in REQUIRED_FILES:
41
+ if (submission / f).exists():
42
+ _ok(f"{f} present")
43
+ else:
44
+ _fail(f"missing {f}")
45
+ ok = False
46
+
47
+ meta = {}
48
+ if (submission / "metadata.yaml").exists():
49
+ meta = yaml.safe_load((submission / "metadata.yaml").read_text()) or {}
50
+ for key in REQUIRED_META:
51
+ if meta.get(key):
52
+ _ok(f"metadata.{key} = {meta[key]!r}")
53
+ else:
54
+ _fail(f"metadata.{key} missing/empty")
55
+ ok = False
56
+ if meta.get("family") and meta["family"] not in FAMILIES:
57
+ _fail(f"family must be one of {sorted(FAMILIES)}")
58
+ ok = False
59
+ if meta.get("supervision") and meta["supervision"] not in SUPERVISION:
60
+ _fail(f"supervision must be one of {sorted(SUPERVISION)}")
61
+ ok = False
62
+
63
+ # method.py must import and expose rank(query, corpus).
64
+ try:
65
+ from eval_submission import load_method
66
+ load_method(submission)
67
+ _ok("method.py exposes rank(query, corpus)")
68
+ except Exception as exc: # noqa: BLE001
69
+ _fail(f"method.py not loadable: {type(exc).__name__}: {exc}")
70
+ ok = False
71
+
72
+ if run and ok:
73
+ print("Running official harness (this downloads the dataset)…")
74
+ try:
75
+ from eval_submission import evaluate
76
+ results = evaluate(submission, token=token)
77
+ out = submission / "results.json"
78
+ out.write_text(json.dumps(results, indent=2))
79
+ h = results["headline"]
80
+ _ok(f"scored NDCG@10 rho0/10/20 = "
81
+ f"{h['rho0']:.4f}/{h['rho10']:.4f}/{h['rho20']:.4f} -> {out.name}")
82
+ except Exception as exc: # noqa: BLE001
83
+ _fail(f"harness failed: {type(exc).__name__}: {exc}")
84
+ ok = False
85
+
86
+ print("PASS ✅" if ok else "FAIL ❌")
87
+ return ok
88
+
89
+
90
+ def main(argv=None) -> None:
91
+ p = argparse.ArgumentParser(description=__doc__,
92
+ formatter_class=argparse.RawDescriptionHelpFormatter)
93
+ p.add_argument("--submission", required=True, type=Path)
94
+ p.add_argument("--run", action="store_true", help="also recompute scores via the harness")
95
+ p.add_argument("--token", default=None)
96
+ args = p.parse_args(argv)
97
+ sys.exit(0 if validate(args.submission, args.run, args.token) else 1)
98
+
99
+
100
+ if __name__ == "__main__":
101
+ main()