Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(examples): look up official numbers in the benchmark example (#912)
Shai Shmuel027153ade739
diff --git a/examples/README.md b/examples/README.mdindex dbe75ead1..655f33378 100644--- a/examples/README.md+++ b/examples/README.md@@ -39,7 +39,7 @@ to a separately maintained repository (clone and run there).| [Answer several triage questions about one record, each with a probability](./typed-decisions) | Asking CVE descriptions typed pick-one and yes-or-no questions against NVD analyst gold, with a fast, a smart and an LLM lane, and the questions no model passed reported rather than shown | `extract`, `chat/completions` | Self-hosted SIE with GLiFormer, GLiClass, Laya, GLiNER2, GLiNER2.5-Decide and Qwen3 4B; `fetch.py` pulls the recorded run, `score.py` reproduces the figures with no key | Runnable recorded example || [Screen harmful prompts before your model sees them](./guardrails) | Scoring SIE's Qwen3Guard 4B and GLiGuard against three LLM judges and OpenAI Moderation on 4,768 human-labelled ToxicChat and Aegis 2.0 prompts, with a paired bootstrap and the pre-registered bars | `chat/completions`, `extract` | SIE Cloud with GLiGuard, an SIE server for Qwen3Guard; `fetch.py` pulls the recorded run and both sets, `score.py` reproduces every figure with no key | Runnable recorded example || [Expand a query into matchable terms](./sparse) | Comparing SPLADE, which adds terms the text never used, with bge-m3 sparse, which does not | `encode` | SIE Cloud with SPLADE++ and bge-m3; `fetch.py` pulls the recorded vectors, `score.py` reproduces the figures with no key | Runnable recorded example |-| [Repeat the published benchmarks or test a new model](./evaluations/published-benchmarks) | Repeating the method behind the twelve published Cloud benchmark records, six quality and six fixed-rate performance, for SPLADE++ and bge-m3 sparse on NFCorpus, GTE-ModernColBERT and bge-m3 multivector on SciFact, Qwen3 Reranker 0.6B and 4B on AskUbuntuDupQuestions, from one client process, and reading the delta against every published metric; measuring a model you are adding the same way, against an official number you supply | `encode`, `score` | SIE Cloud with an SIE API key for a run, which spends credits, or your own `sie-server`, with no key by default; `score.py` recomputes quality metrics from a run's predictions and the pinned qrels, and performance metrics from its requests file, with no key | Runnable |+| [Repeat the published benchmarks or test a new model](./evaluations/published-benchmarks) | Repeating the method behind the twelve published Cloud benchmark records, six quality and six fixed-rate performance, for SPLADE++ and bge-m3 sparse on NFCorpus, GTE-ModernColBERT and bge-m3 multivector on SciFact, Qwen3 Reranker 0.6B and 4B on AskUbuntuDupQuestions, from one client process, and reading the delta against every published metric; measuring a model you are adding the same way, against an official number looked up in the public results repository or one you supply | `encode`, `score` | SIE Cloud with an SIE API key for a run, which spends credits, or your own `sie-server`, with no key by default; `score.py` recomputes quality metrics from a run's predictions and the pinned qrels, and performance metrics from its requests file, with no key | Runnable || [Mask personal data before it reaches a log, a prompt or a vendor](./redact) | Composing two PII models and scoring coverage recall on 660 documents against Presidio, OpenAI Privacy Filter and two LLM prompts, with the price of each | `extract` | SIE Cloud with GLiNER PII and NuNER Zero; `fetch.py` pulls the recorded run, `score.py` reproduces the figures with no key | Runnable recorded example || [Read a full app screenshot into typed fields](./screenshot-fields) | Reproducing all 26 original field checks from one complete Kanboard task screenshot and a strict schema | `chat/completions` | SIE endpoint with Gemma 4 31B; pinned evidence and offline scoring need no API key | Runnable recorded example || [Read the numbers off a dashboard that has no API](./screenshot-mining) | Reading twelve Superset, Argo CD, Airflow, Kubernetes, GitLab and Jaeger screens into schema-valid JSON | `generate` | SIE Cloud with Qwen3.8 27B; `fetch.py` pulls the recorded run and the screenshots, `score.py` reproduces 328 of 335 with no key | Runnable recorded example |diff --git a/examples/evaluations/published-benchmarks/README.md b/examples/evaluations/published-benchmarks/README.mdindex dbd00b249..a21e9d3b7 100644--- a/examples/evaluations/published-benchmarks/README.md+++ b/examples/evaluations/published-benchmarks/README.md@@ -3,8 +3,9 @@This example does two things from one client process on your machine. Itrepeats the method behind the benchmark numbers published on the SIE website,six quality records and six fixed-rate performance records. And it measures a-model you are adding the same way, against an official number you supply,-before you open a pull request: see [Test a new model](#test-a-new-model).+model you are adding the same way, against an official number it looks up in+the public results repository or one you supply, before you open a pull+request: see [Test a new model](#test-a-new-model).Each `references/<id>.json` is a projection of one published benchmark record:the model and profile, the task key, the pinned dataset revision, the request@@ -64,10 +65,10 @@ and request timeout come from the file. The only flags accepted beside it are`--endpoint` (default `https://api.superlinked.com`) and `--task` with thesmoke key. Without a reference, `--model <id[:profile]>` and `--task` arerequired; `--output sparse|dense|multivector` and `--items-per-request` are-required for the encode tasks and refused for `mteb/AskUbuntuDupQuestions`,-which scores each query against its 20 task-native candidates. `--baseline`,-`--baseline-source` and `--instruction` belong to a run without a reference:-see [Test a new model](#test-a-new-model).+required for the encode tasks and refused for the score tasks, which score each+query against its task-native candidates. `--baseline`, `--baseline-source` and+`--instruction` belong to a run without a reference: see+[Test a new model](#test-a-new-model).When a result is not valid, the command prints each reason to stderr.@@ -84,7 +85,7 @@ in `validity.reasons`:run. It is rebuilt from the plan, so credentials in a URL never reach theresult.- `results/<id>-<utc>.predictions.json`: the ranked list per query, the top- 1000 documents with their scores, or the reranker's 20 candidates per query.+ 1000 documents with their scores, or the reranker's candidates per query.Every metric is recomputed from this file.### Recompute offline@@ -108,8 +109,9 @@ place.These are not flags. They are the method behind the published numbers, andthe example applies them to every run:-- the whole `test` split of the pinned dataset revision; queries with no- relevance judgement are dropped, as MTEB does;+- the whole evaluation split of the pinned dataset revision, `test` unless+ [Task keys](#task-keys) names another; queries with no relevance judgement+ are dropped, as MTEB does;- one readiness request on the first batch, not recorded, waits up to 300 sfor the model to load; a failure writes `valid: false` with the reason andexits 1;@@ -120,7 +122,8 @@ the example applies them to every run:unless `--instruction` gives one, which goes with queries only;- sparse vectors are scored by the raw dot product, dense vectors by cosineover L2-normalised vectors, multivector outputs by MaxSim over L2-normalised- token rows, and the reranker's own scores rank its candidates. A `muvera`+ token rows, and the reranker's own scores rank its candidates, sent in+ requests of at most 100 items for one query and merged. A `muvera`profile is refused with `--output dense` on a quality run, because thepublished method scores those vectors by the similarity the profile declares,usually the raw dot product, and this example scores dense only by cosine;@@ -164,10 +167,11 @@ gets a verdict.### The verdictAfter the metrics, a quality run prints one `verdict:` line. It compares one-metric with a baseline: the record's `main_score` for a `--reference` run, or-the number you supply with `--baseline`. With a margin of 0.98, the low bound-is the baseline × 0.98 and the high bound is the baseline ÷ 0.98. The first-row that matches decides:+metric with a baseline: the record's `main_score` for a `--reference` run,+the number you supply with `--baseline`, or the official number the tool looks+up when you pass neither. With a margin of 0.98, the low bound is the baseline+× 0.98 and the high bound is the baseline ÷ 0.98. The first row that matches+decides:| Case | Verdict | Reason || --- | --- | --- |@@ -194,10 +198,11 @@ The verdict is a report. The exit status does not follow it: the command exitsit writes reaches the website or a published record, and it is no floor, targetor gate.-The result stores `baseline`, null when there is none, with `kind` (`published`-or `supplied`), `metric`, `value` and `source`, and `verdict` with `verdict`,-`reason`, `metric`, `current`, `baseline`, `delta_pct`, `threshold_low`,-`threshold_high` and `margin`.+The result stores `baseline`, null when there is none, with `kind` (`published`,+`supplied` or `official`), `metric`, `value` and `source`, and `verdict` with+`verdict`, `reason`, `metric`, `current`, `baseline`, `delta_pct`,+`threshold_low`, `threshold_high` and `margin`. An `official` baseline also has+`model_revision`, `dataset_revision` and `mteb_version`.## Performance@@ -234,7 +239,7 @@ the record's published level, `--duration` to 60 and `--warmup` to 30,`--endpoint` is accepted as for quality, and any value that differs from thereference adds a `comparable_reasons` entry. Without a reference, `--model`,`--task` and `--rate` are required, `--output` and `--items-per-request` are-required for the encode tasks and refused for the score task, and the timeout+required for the encode tasks and refused for the score tasks, and the timeoutand cap are 30 s and 64 for encode, 300 s and 128 for score. `--output` takes`sparse`, `dense` or `multivector`. No other flags exist.@@ -258,11 +263,12 @@ and cap are 30 s and 64 for encode, 300 s and 128 for score. `--output` takesread and written on the request's row;- selection by the task key: `filter=nonempty` drops rows whose text is emptyafter stripping whitespace; `role=corpus` takes the documents, otherwise- the queries with relevance judgments in the test split; the remaining rows are ordered by source id compared as strings- and `limit=N` keeps the first N; for AskUbuntu, `limit=64` keeps the first+ the queries with relevance judgments in the task's split; the remaining rows+ are ordered by source id compared as strings and `limit=N` keeps the first N; for AskUbuntu, `limit=64` keeps the first64 queries in that order and `candidates-k=20` each query's 20 task-native- candidates in source order; the chosen ids go to `dataset.selected_ids` in- that order;+ candidates in source order; one request sends at most 100 candidates, so a+ key without `candidates-k` sends the first 100 and `candidates-k` above 100+ exits 2; the chosen ids go to `dataset.selected_ids` in that order;- rows cycle: encode request `s` takes documents `s × n` to `s × n + n − 1`of the selection, modulo its size, with `n` the items per request (1 inevery record); score request `s` takes query `s` modulo the selection@@ -408,12 +414,26 @@ official number.[Run it against your own server](#run-it-against-your-own-server) apply: nokey unless the server runs in token mode, and the first request loads themodel.-3. **Find the official number** on the model card, in the paper or on a- leaderboard. It must be for the same benchmark and the same metric: the same- dataset and split, and the same metric at the same cut. A number for another- dataset, or `ndcg_at_100` where you compare `ndcg_at_10`, is not a baseline.- This example ships no official numbers.-4. **Run it** from this directory:+3. **Run it** from this directory. The tool first looks the official number up+ in the public results repository,+ [embeddings-benchmark/results](https://github.com/embeddings-benchmark/results),+ and prints an `official:` line before any inference request:++ ```sh+ uv run python run.py quality \+ --model your-org/your-model \+ --task mteb/NFCorpus \+ --output dense \+ --items-per-request 32 \+ --endpoint http://localhost:8080+ ```++4. **If it finds none**, the `official:` line says why and the run reads+ `MEASUREMENT`. Find the number on the model card, in the paper or on a+ leaderboard and pass it. It must be for the same benchmark and the same+ metric: the same dataset and split, and the same metric at the same cut. A+ number for another dataset, or `ndcg_at_100` where you compare `ndcg_at_10`,+ is not a baseline. This example ships no official numbers.```shuv run python run.py quality \@@ -436,10 +456,50 @@ official number.### The baseline-`--baseline <metric>=<value>` and `--baseline-source <text>` go together. The-metric is one a quality run writes: `main_score`, `accuracy`, or-`<family>_at_<k>` with family `ndcg`, `map`, `recall`, `precision` or `mrr` and-k one of 1, 3, 5, 10, 20, 100, 1000; a bare family name is refused. The value is+A run with neither `--reference` nor `--baseline` looks the number up. The+lookup sends the model id and the task name to GitHub, with no key or token, so+do not use it for a model id you want to keep private: pass `--baseline`+instead. It asks for the current commit of the repository's `main`, the model's+revision directories, and `<TaskName>.json` in each. It reads the task's main+metric from the one `default` entry of the task's split. When several directories+have the file, it prefers the revision the endpoint serves, then the highest+`mteb_version`.++It prints one line first, so you know before you spend anything:++```text+official: <metric> <value> from <link to the file>+official: none, <reason>; the run reads MEASUREMENT unless you pass --baseline+```++A `note:` line follows when the file's model revision differs from the one the+endpoint serves, or its `dataset_revision` differs from the pinned one. These+are notes only and the run still compares, because mismatched revisions usually+give the same score.++The lookup is skipped, with the reason on that line, for a key with `limit`, for+a two-stage key, for a profile other than the default, and for an output other+than `dense` on a model with more than one of dense, sparse and multivector, or+on a model whose outputs the endpoint does not report, because the number in the+repository is for the dense output. A key with `limit` stays `MEASUREMENT` even+with `--baseline`, so its line leaves that part out.++A network error, a rate limit or a bad response never blocks the run: it goes on+as `MEASUREMENT`. Older result files of the reranking tasks name their number+`map` and not `map_at_1000`, and the lookup finds nothing in them. Read the file+and pass `--baseline` if it is the number you want to compare with.++A run with no `--baseline` records `official_lookup` with `status` (`found`,+`not_found`, `failed` or `skipped`) and `detail`, and a found number is stored as+the `baseline`. `score.py` recomputes the verdict from that stored value and+looks nothing up. `run.command` gains no `--baseline`, so repeating it looks the+number up again.++`--baseline <metric>=<value>` and `--baseline-source <text>` go together and win+over the lookup, which then does not run. The metric is one a quality run+writes: `main_score`, `accuracy`, or `<family>_at_<k>` with family `ndcg`, `map`,+`recall`, `precision` or `mrr` and k one of 1, 3, 5, 10, 20, 100, 1000; a bare+family name is refused. The value isa ratio, finite, above 0 and at most 1, so a leaderboard that prints percentneeds dividing by 100. A bad form exits 2 before any request, and both flags arerefused beside `--reference`, which brings its own baseline.@@ -461,9 +521,9 @@ does not expose a query template. Read `query_template` in the model's config:prepended to every query, which pollutes the query.`--instruction` is sent with queries only, never with documents, and is recorded-in `payload.parameters`. It is refused beside `--reference` and on the score-task. `run.py performance` has no such flag, because its encode requests set-`is_query` to false.+in `payload.parameters`. It is refused beside `--reference`, on the score tasks+and on a two-stage key. `run.py performance` has no such flag, because its encode+requests set `is_query` to false.### The limited-run rule@@ -479,27 +539,89 @@ every document.Each key is pinned to the dataset revision mteb 2.7.5 names; the revisions arein `score.py`. All of them load anonymously from Hugging Face.-| Task key | Dataset | Operation | `main_score` |-| --- | --- | --- | --- |-| `mteb/SciFact` | `mteb/scifact` | encode | `ndcg_at_10` |-| `mteb/NFCorpus` | `mteb/nfcorpus` | encode | `ndcg_at_10` |-| `mteb/AskUbuntuDupQuestions` | `mteb/AskUbuntuDupQuestions` | score | `map_at_1000` |-| `mteb/FiQA2018` | `mteb/fiqa` | encode | `ndcg_at_10` |-| `mteb/SCIDOCS` | `mteb/scidocs` | encode | `ndcg_at_10` |-| `mteb/CQADupstackPhysicsRetrieval` | `mteb/cqadupstack-physics` | encode | `ndcg_at_10` |-| `mteb/CosQA` | `CoIR-Retrieval/cosqa` | encode | `ndcg_at_10` |-| `mteb/StackOverflowQA` | `CoIR-Retrieval/stackoverflow-qa` | encode | `ndcg_at_10` |-| `mteb/LegalBenchConsumerContractsQA` | `mteb/legalbench_consumer_contracts_qa` | encode | `ndcg_at_10` |+| Task key | Dataset | Split | Operation | `main_score` |+| --- | --- | --- | --- | --- |+| `mteb/SciFact` | `mteb/scifact` | `test` | encode | `ndcg_at_10` |+| `mteb/NFCorpus` | `mteb/nfcorpus` | `test` | encode | `ndcg_at_10` |+| `mteb/AskUbuntuDupQuestions` | `mteb/AskUbuntuDupQuestions` | `test` | score | `map_at_1000` |+| `mteb/FiQA2018` | `mteb/fiqa` | `test` | encode | `ndcg_at_10` |+| `mteb/SCIDOCS` | `mteb/scidocs` | `test` | encode | `ndcg_at_10` |+| `mteb/CQADupstackPhysicsRetrieval` | `mteb/cqadupstack-physics` | `test` | encode | `ndcg_at_10` |+| `mteb/CosQA` | `CoIR-Retrieval/cosqa` | `test` | encode | `ndcg_at_10` |+| `mteb/StackOverflowQA` | `CoIR-Retrieval/stackoverflow-qa` | `test` | encode | `ndcg_at_10` |+| `mteb/LegalBenchConsumerContractsQA` | `mteb/legalbench_consumer_contracts_qa` | `test` | encode | `ndcg_at_10` |+| `mteb/MMarcoReranking` | `mteb/MMarcoReranking` | `dev` | score | `map_at_1000` |+| `mteb/T2Reranking` | `mteb/T2Reranking` | `dev` | score | `map_at_1000` |+| `mteb/CMedQAv1-reranking` | `mteb/CMedQAv1-reranking` | `test` | score | `map_at_1000` |+| `mteb/CMedQAv2-reranking` | `mteb/CMedQAv2-reranking` | `test` | score | `map_at_1000` |+| `mteb/NanoFiQA2018Retrieval` | `zeta-alpha-ai/NanoFiQA2018` | `train` | encode | `ndcg_at_10` |++`mteb/CMedQAv1Reranking` and `mteb/CMedQAv2Reranking` are accepted as other+spellings of the two CMedQA keys; the result keeps the key you typed in+`task_key` and names the dataset in `dataset.name`.`mteb/FiQA2018` sets mteb's `ignore_identical_ids`: a document whose id equalsthe query's id is removed from that query's ranking after the top-1000 cut andbefore scoring, as mteb does. The predictions file keeps it, and `score.py`applies the same rule.-`run.py quality` takes a name alone or with `limit`; any other parameter exits 2-before any request. `run.py performance` takes the same names with the-parameters its selection rule reads, for example-`mteb/FiQA2018?split=test&role=corpus&limit=256&filter=nonempty`.+`run.py quality` takes a name alone or with `limit`, and an encode task also+takes a [two-stage key](#two-stage-keys); any other parameter exits 2 before any+request. `run.py performance` takes the same names with the parameters its+selection rule reads, for example+`mteb/FiQA2018?split=test&role=corpus&limit=256&filter=nonempty`; any other+parameter exits 2 before any request.++### Two-stage keys++A two-stage key scores a reranker over a retriever's top candidates:++```sh+uv run python run.py quality \+ --model your-org/your-reranker \+ --task "mteb/NFCorpus?candidates_model=Alibaba-NLP/gte-multilingual-base&candidates_k=50" \+ --endpoint http://localhost:8080+```++`candidates_model`, a plain `<org>/<name>` id, and `candidates_k`, a positive+integer, go together on an encode task, optionally with `limit`. A bad form exits+2 before any request. The method is fixed, so `--output`, `--items-per-request`+and `--instruction` are refused:++- one readiness request for each model;+- the whole corpus goes to the encoder in batches of 64 documents with+ `is_query=False`, then the queries with `is_query=True`, as dense vectors with+ no instruction;+- cosine over L2-normalised vectors picks the top k documents per query, ties+ broken by corpus order;+- the reranker scores each query's k documents, in requests of at most 100 items,+ and its scores rank them. Only those k documents are in the predictions.++The result names the encoder and k in `payload.parameters`, and+`execution_revisions` holds the revisions of both models. There is no official+number for such a pair, so the verdict is `MEASUREMENT` unless you pass+`--baseline`. `score.py` recomputes the metrics from the predictions file as for+any other key.++## Check a number on the website++A row on a model page maps to the flags below. Start every command with+`uv run python run.py quality` and add `--endpoint` for your own server. Without+a baseline the run compares with the official number when there is one. To+compare with the number in the row, add `--baseline <metric>=<value in the row>+--baseline-source "<link to the page>"`. A profile row and a two-stage row have+no official number, so they need it to get a verdict.++| Row on a model page | Flags |+| --- | --- |+| A plain row | `--model <model> --task mteb/NFCorpus --output dense --items-per-request 32` |+| A profile row | `--model <model>:<profile> --task mteb/NFCorpus --output <the profile's output> --items-per-request 32` |+| A reranker row | `--model <reranker> --task mteb/T2Reranking` |+| A row that says "reranking the top 50 from \<model\>" | `--model <reranker> --task "mteb/NFCorpus?candidates_model=<model>&candidates_k=50"` |+| Image retrieval, and non-MTEB tasks such as extraction, classification, OCR, detection, speech and generation | This example does not run these |++Some rows on the model pages are measured on our own GPUs, and a row may differ+from your run for that reason. Read the `verdict:` line with that in mind.## Validation@@ -633,8 +755,7 @@ The tests use a fake client, in-memory datasets and the committedrecords, and no floor, target or gate;- no `mteb` dependency, no nAUC or cv_recall metrics, and no match of thescorer's implementation digest;-- no multi-process client, load ladder, Poisson arrivals, clock calibration- or candidate generation;+- no multi-process client, load ladder, Poisson arrivals or clock calibration;- no cost, price or accounting fields;- no recorded-evidence download: the inputs are the six reference files andthe pinned public datasets;diff --git a/examples/evaluations/published-benchmarks/official.py b/examples/evaluations/published-benchmarks/official.pynew file mode 100644index 000000000..d4e4b01e7--- /dev/null+++ b/examples/evaluations/published-benchmarks/official.py@@ -0,0 +1,221 @@+"""Look up a model's official number in the public MTEB results repository, with the standard library only."""++import json+import math+import re+import urllib.error+import urllib.request+from collections.abc import Callable, Mapping+from dataclasses import dataclass+from typing import Any+from urllib.parse import urlsplit++RESULTS_REPOSITORY = "embeddings-benchmark/results"+COMMIT_URL = f"https://api.github.com/repos/{RESULTS_REPOSITORY}/commits/main"+CONTENTS_URL = f"https://api.github.com/repos/{RESULTS_REPOSITORY}/contents/results"+RAW_URL = f"https://raw.githubusercontent.com/{RESULTS_REPOSITORY}"+BLOB_URL = f"https://github.com/{RESULTS_REPOSITORY}/blob"+SHA_MEDIA_TYPE = "application/vnd.github.sha"+JSON_MEDIA_TYPE = "application/vnd.github+json"+USER_AGENT = "published-benchmarks-example"+TIMEOUT_S = 30.0+MAX_BYTES = 5 * 1024 * 1024+MAX_TEXT = 100+RATE_LIMIT_CODES = frozenset({403, 429})+MODEL_ID = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$")+DIRECTORY_NAME = re.compile(r"^[A-Za-z0-9._-]+$")+COMMIT_ID = re.compile(r"^[0-9a-f]{40}$")+VERSION_PREFIX = re.compile(r"\d+(?:\.\d+)*")+FOUND = "found"+NOT_FOUND = "not_found"+FAILED = "failed"+SKIPPED = "skipped"++Fetch = Callable[[str, str | None], bytes]+++class NotFound(Exception):+ pass+++class LookupFailed(Exception):+ pass+++class Miss(Exception):+ pass+++@dataclass(frozen=True)+class Lookup:+ status: str+ detail: str+ baseline: dict[str, Any] | None = None+++def checked_baseline_value(value: float) -> float:+ if not math.isfinite(value) or value <= 0 or value > 1:+ raise ValueError("a baseline value must be finite, above 0 and at most 1")+ return value+++def plain_text(value: Any) -> str | None:+ if isinstance(value, str) and len(value) <= MAX_TEXT and value.isascii() and value.isprintable():+ return value+ return None+++def http_fetch(url: str, accept: str | None = None) -> bytes:+ headers = {"User-Agent": USER_AGENT}+ if accept is not None:+ headers["Accept"] = accept+ try:+ with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=TIMEOUT_S) as response:+ body = response.read(MAX_BYTES + 1)+ except urllib.error.HTTPError as exc:+ if exc.code == 404:+ raise NotFound(url) from None+ hint = ", probably GitHub's rate limit" if exc.code in RATE_LIMIT_CODES else ""+ raise LookupFailed(f"HTTP {exc.code} from {urlsplit(url).hostname}{hint}") from None+ except OSError as exc:+ raise LookupFailed(f"could not reach {urlsplit(url).hostname} ({type(exc).__name__})") from None+ if len(body) > MAX_BYTES:+ raise LookupFailed(f"a response from {urlsplit(url).hostname} is larger than {MAX_BYTES} bytes")+ return body+++def describe(baseline: Mapping[str, Any]) -> str:+ return f"{baseline['metric']} {baseline['value']} from {baseline['source']}"+++def _json(body: bytes, label: str) -> Any:+ try:+ return json.loads(body)+ except (ValueError, RecursionError):+ raise LookupFailed(f"{label} is not JSON") from None+++def _main_commit(fetch: Fetch) -> str:+ try:+ body = fetch(COMMIT_URL, SHA_MEDIA_TYPE)+ except NotFound:+ raise Miss(f"{RESULTS_REPOSITORY} has no main branch") from None+ text = body.decode("ascii", "replace").strip()+ if COMMIT_ID.fullmatch(text):+ return text+ payload = _json(body, "the main commit")+ sha = payload.get("sha") if isinstance(payload, dict) else None+ if not isinstance(sha, str) or not COMMIT_ID.fullmatch(sha):+ raise LookupFailed("the main commit has no commit id")+ return sha+++def _revision_directories(fetch: Fetch, model: str, folder: str, sha: str) -> list[str]:+ try:+ body = fetch(f"{CONTENTS_URL}/{folder}?ref={sha}", JSON_MEDIA_TYPE)+ except NotFound:+ raise Miss(f"{model} is not in {RESULTS_REPOSITORY}") from None+ entries = _json(body, "the model's directory listing")+ if not isinstance(entries, list) or not all(isinstance(entry, dict) for entry in entries):+ raise LookupFailed("the model's directory listing is not a list of entries")+ names = [entry.get("name") for entry in entries if entry.get("type") == "dir"]+ return sorted(+ name for name in names if isinstance(name, str) and DIRECTORY_NAME.fullmatch(name) and name not in {".", ".."}+ )+++def _main_value(payload: Any, label: str, split: str, metric: str) -> float:+ scores = payload.get("scores") if isinstance(payload, dict) else None+ if isinstance(scores, dict) and split not in scores:+ raise Miss(f"{label} has no {split} scores")+ rows = scores.get(split) if isinstance(scores, dict) else None+ if not isinstance(rows, list):+ raise LookupFailed(f"{label} has no list of {split} scores")+ defaults = [row for row in rows if isinstance(row, dict) and row.get("hf_subset") == "default"]+ if len(defaults) != 1:+ raise LookupFailed(f"{label} has {len(defaults)} {split} entries for the default subset, not one")+ if metric not in defaults[0]:+ raise Miss(f"{label} has no {metric}")+ value = defaults[0][metric]+ if isinstance(value, bool) or not isinstance(value, int | float):+ raise LookupFailed(f"{label} has no number for {metric}")+ try:+ return checked_baseline_value(float(value))+ except (ValueError, OverflowError):+ raise LookupFailed(f"{label} has a {metric} that is not above 0 and at most 1") from None+++def _version_key(version: str | None) -> tuple[int, ...]:+ match = VERSION_PREFIX.match(version or "")+ return tuple(int(part) for part in match.group().split(".")) if match else ()+++def _preferred(found: list[dict[str, Any]], served_revision: str | None) -> dict[str, Any]:+ for result in found:+ if result["model_revision"] == served_revision:+ return result+ return max(found, key=lambda result: _version_key(result["mteb_version"]))+++def _find_result(+ model: str, task_name: str, split: str, metric: str, served_revision: str | None, fetch: Fetch+) -> dict:+ folder = model.replace("/", "__")+ file_name = f"{task_name.removeprefix('mteb/')}.json"+ sha = _main_commit(fetch)+ found: list[dict[str, Any]] = []+ problems: list[str] = []+ misses: list[str] = []+ for directory in _revision_directories(fetch, model, folder, sha):+ try:+ body = fetch(f"{RAW_URL}/{sha}/results/{folder}/{directory}/{file_name}", None)+ except NotFound:+ continue+ label = f"{directory}/{file_name}"+ try:+ payload = _json(body, label)+ value = _main_value(payload, label, split, metric)+ except LookupFailed as exc:+ problems.append(str(exc))+ continue+ except Miss as exc:+ misses.append(str(exc))+ continue+ found.append(+ {+ "kind": "official",+ "metric": metric,+ "value": value,+ "source": f"{BLOB_URL}/{sha}/results/{folder}/{directory}/{file_name}",+ "model_revision": directory,+ "dataset_revision": plain_text(payload.get("dataset_revision")),+ "mteb_version": plain_text(payload.get("mteb_version")),+ }+ )+ if found:+ return _preferred(found, served_revision)+ if problems:+ raise LookupFailed(problems[0])+ raise Miss(misses[0] if misses else f"{model} has no {file_name} in {RESULTS_REPOSITORY}")+++def lookup_official(+ model: str,+ task_name: str,+ split: str,+ metric: str,+ served_revision: str | None = None,+ fetch: Fetch = http_fetch,+) -> Lookup:+ """Find the number; every failure is an answer, never an exception, because a lookup must not block a run."""+ if not MODEL_ID.fullmatch(model):+ return Lookup(NOT_FOUND, f"{model!r} is not an <org>/<name> model id")+ try:+ baseline = _find_result(model, task_name, split, metric, served_revision, fetch)+ except Miss as exc:+ return Lookup(NOT_FOUND, str(exc))+ except LookupFailed as exc:+ return Lookup(FAILED, str(exc))+ except Exception as exc: # noqa: BLE001+ return Lookup(FAILED, f"the lookup failed ({type(exc).__name__})")+ return Lookup(FOUND, describe(baseline), baseline)diff --git a/examples/evaluations/published-benchmarks/pyproject.toml b/examples/evaluations/published-benchmarks/pyproject.tomlindex 6428627b2..6d1923d77 100644--- a/examples/evaluations/published-benchmarks/pyproject.toml+++ b/examples/evaluations/published-benchmarks/pyproject.toml@@ -1,7 +1,7 @@[project]name = "superlinked-sie-published-benchmarks-example"version = "0.1.0"-description = "Repeat the method behind the published SIE benchmark numbers from one client process"+description = "Repeat the method behind the published SIE benchmark numbers, or test a new model the same way, from one client process"requires-python = ">=3.12,<3.13"dependencies = ["sie-sdk>=0.10.1,<0.11",diff --git a/examples/evaluations/published-benchmarks/run.py b/examples/evaluations/published-benchmarks/run.pyindex a7fcb13a6..bcb299059 100644--- a/examples/evaluations/published-benchmarks/run.py+++ b/examples/evaluations/published-benchmarks/run.py@@ -13,7 +13,7 @@ import threadingimport timefrom collections.abc import Callable, Mapping, Sequencefrom concurrent.futures import ThreadPoolExecutor, wait-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom datetime import UTC, datetimefrom fractions import Fractionfrom pathlib import Path@@ -26,9 +26,20 @@ import sie_sdkfrom scipy.sparse import csr_matrixfrom sie_sdk import SIEClient+from official import (+ MODEL_ID,+ SKIPPED,+ Fetch,+ Lookup,+ checked_baseline_value,+ http_fetch,+ lookup_official,+ plain_text,+)from score import (BASELINE_METRICS,HF_DATASETS,+ MAIN_SCORE,NS_PER_MS,NS_PER_S,PERFORMANCE_MODE,@@ -38,6 +49,7 @@ from score import (Rows,compare,compute_verdict,+ eval_split,format_rows,format_verdict,load_corpus,@@ -62,7 +74,19 @@ DOCUMENT_CHUNK = 500QUERY_TOKEN_ROWS = 256COSINE_NORM_FLOOR = 1e-12RESULTS_DIR = Path("results")-SCORE_TASKS = frozenset({"mteb/AskUbuntuDupQuestions"})+SCORE_TASKS = frozenset(+ {+ "mteb/AskUbuntuDupQuestions",+ "mteb/MMarcoReranking",+ "mteb/T2Reranking",+ "mteb/CMedQAv1-reranking",+ "mteb/CMedQAv2-reranking",+ }+)+SCORE_ITEMS_PER_REQUEST = 100+CANDIDATE_ENCODE_ITEMS_PER_REQUEST = 64+QUALITY_PARAMETERS = frozenset({"limit", "candidates_model", "candidates_k"})+PERFORMANCE_PARAMETERS = frozenset({"limit", "candidates-k", "split", "filter", "role"})ENCODE_OUTPUTS = ("sparse", "dense", "multivector")MUVERA_PROFILE = "muvera"REFERENCE_KIND = "published-benchmark-reference"@@ -108,6 +132,8 @@ class QualityPlan:comparable_reasons: list[str]baseline: dict[str, Any] | None = Noneinstruction: str | None = None+ candidates_model: str | None = None+ candidates_k: int | None = None@propertydef route(self) -> str:@@ -177,6 +203,7 @@ class CallLog:failure_count: int = 0sdk_retries: int = 0execution_revisions: list[str] = field(default_factory=list)+ encoder_revisions: list[str] = field(default_factory=list)failure: str | None = Nonereadiness_failure: str | None = None@@ -193,6 +220,10 @@ class CallLog:self.sdk_retries += int(client.last_retry_count)self.failure = f"{type(exc).__name__}: {exc}"+ @property+ def revision_changed(self) -> bool:+ return len(self.execution_revisions) > 1 or len(self.encoder_revisions) > 1+def _add_shared_arguments(command: argparse.ArgumentParser) -> None:command.add_argument("--reference", type=Path, help="A references/<id>.json file")@@ -206,7 +237,9 @@ def _add_shared_arguments(command: argparse.ArgumentParser) -> None:def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(description=__doc__)commands = parser.add_subparsers(dest="command", required=True)- quality = commands.add_parser("quality", help="Measure quality against a published record or a supplied baseline")+ quality = commands.add_parser(+ "quality", help="Measure quality against a published record, an official number or a supplied baseline"+ )_add_shared_arguments(quality)quality.add_argument("--baseline", help="The number to compare with, <metric>=<value>, for example ndcg_at_10=0.32")quality.add_argument("--baseline-source", help="Where the baseline comes from: model card, paper or leaderboard")@@ -227,12 +260,12 @@ def plan_quality(args: argparse.Namespace) -> QualityPlan:def _endpoint_key(url: str) -> tuple[str, str | None, int, str]:- parts = urlsplit(url)- scheme = parts.scheme.lower()try:+ parts = urlsplit(url)port = parts.portexcept ValueError:raise ValueError("endpoint must be an http(s) URL") from None+ scheme = parts.scheme.lower()if port is None:port = 443 if scheme == "https" else 80elif port == 0:@@ -273,7 +306,7 @@ def _resolve_api_key(parser: argparse.ArgumentParser, endpoint: str) -> str:key, scope = _key_scope()if key and not api_key:print(- f"note: SIE_API_KEY is scoped to {scope} and was not sent to {endpoint}; "+ f"note: SIE_API_KEY is scoped to {_scope_text(scope)} and was not sent to {endpoint}; ""set SIE_BASE_URL to the endpoint to send it",file=sys.stderr,)@@ -285,6 +318,14 @@ def _without_credentials(url: str) -> str:return urlunsplit((parts.scheme, parts.netloc.rpartition("@")[2], parts.path, "", ""))+def _scope_text(scope: str) -> str:+ try:+ normalize_endpoint(scope)+ except ValueError:+ return "an SIE_BASE_URL that is not an http(s) URL"+ return _without_credentials(scope)++def _endpoint_reasons(endpoint: str) -> list[str]:if _endpoint_key(endpoint) == _endpoint_key(DEFAULT_ENDPOINT):return []@@ -301,11 +342,19 @@ def _check_positive_integer(params: Mapping[str, str], name: str) -> None:raise ValueError(f"{name} must be a positive integer")-def _check_performance_params(params: Mapping[str, str], operation: str) -> None:+def _check_performance_params(task_name: str, params: Mapping[str, str], operation: str) -> None:+ unknown = sorted(set(params) - PERFORMANCE_PARAMETERS)+ if unknown:+ raise ValueError(+ f"a performance task key takes {', '.join(sorted(PERFORMANCE_PARAMETERS))}, got {', '.join(unknown)}"+ )_check_limit(params)_check_positive_integer(params, "candidates-k")- if params.get("split", "test") != "test":- raise ValueError("only split=test is available")+ if int(params.get("candidates-k", 1)) > SCORE_ITEMS_PER_REQUEST:+ raise ValueError(f"candidates-k must be at most {SCORE_ITEMS_PER_REQUEST}; a performance request is one call")+ split = eval_split(task_name)+ if params.get("split", split) != split:+ raise ValueError(f"only split={split} is available")if params.get("filter", "nonempty") != "nonempty":raise ValueError("filter must be nonempty")role = params.get("role", "queries")@@ -355,12 +404,6 @@ def _check_output_flags(args: argparse.Namespace, operation: str) -> None:raise ValueError("--items-per-request must be a positive integer")-def _checked_baseline_value(value: float) -> float:- if not math.isfinite(value) or value <= 0 or value > 1:- raise ValueError("a baseline value must be finite, above 0 and at most 1")- return value--def _supplied_baseline(args: argparse.Namespace) -> dict[str, Any] | None:if args.baseline is None and args.baseline_source is None:return None@@ -378,7 +421,7 @@ def _supplied_baseline(args: argparse.Namespace) -> dict[str, Any] | None:return {"kind": "supplied","metric": metric,- "value": _checked_baseline_value(parsed),+ "value": checked_baseline_value(parsed),"source": args.baseline_source,}@@ -389,7 +432,7 @@ def _published_baseline(reference: Mapping[str, Any]) -> dict[str, Any]:return {"kind": "published","metric": PRIMARY_METRIC,- "value": _checked_baseline_value(float(row["value"])),+ "value": checked_baseline_value(float(row["value"])),"source": reference["reference_id"],}raise ValueError(f"the reference has no {PRIMARY_METRIC} metric")@@ -407,6 +450,20 @@ def _checked_instruction(args: argparse.Namespace, operation: str) -> str | Nonereturn args.instruction+def _checked_two_stage(task_name: str, params: Mapping[str, str]) -> tuple[str | None, int | None]:+ model, k = params.get("candidates_model"), params.get("candidates_k")+ if model is None and k is None:+ return None, None+ if model is None or k is None:+ raise ValueError("candidates_model and candidates_k go together")+ if task_name in SCORE_TASKS:+ raise ValueError(f"candidates_model and candidates_k are for the encode tasks; {task_name} is a score task")+ if not MODEL_ID.fullmatch(model):+ raise ValueError("candidates_model must be a plain <org>/<name> model id, with no profile")+ _check_positive_integer(params, "candidates_k")+ return model, int(k)++def _override(value: float | None, fixed: float, label: str, reasons: list[str]) -> float:if value is None or value == fixed:return fixed@@ -462,12 +519,16 @@ def _plan_from_flags(args: argparse.Namespace) -> QualityPlan:if args.model is None or args.task is None:raise ValueError("--model and --task are required without --reference")task_name, params = parse_task_key(args.task)- other_params = sorted(set(params) - {"limit"})+ other_params = sorted(set(params) - QUALITY_PARAMETERS)if other_params:- raise ValueError(f"a quality task key takes only limit, got {', '.join(other_params)}")+ raise ValueError(+ f"a quality task key takes only limit, got {', '.join(other_params)}; "+ "a two-stage key adds candidates_model and candidates_k"+ )_check_limit(params)+ candidates_model, candidates_k = _checked_two_stage(task_name, params)model, _, profile = args.model.partition(":")- operation = "score" if task_name in SCORE_TASKS else "encode"+ operation = "score" if task_name in SCORE_TASKS or candidates_model is not None else "encode"_check_output_flags(args, operation)if args.output == "dense" and profile.casefold() == MUVERA_PROFILE:raise ValueError(@@ -498,6 +559,8 @@ def _plan_from_flags(args: argparse.Namespace) -> QualityPlan:comparable_reasons=reasons,baseline=baseline,instruction=instruction,+ candidates_model=candidates_model,+ candidates_k=candidates_k,)@@ -518,7 +581,7 @@ def _performance_plan_from_reference(args: argparse.Namespace, reference: Mappinraise ValueError(f"--task must equal the reference task_key {task_key!r}")task_name, params = parse_task_key(task_key)operation = reference["operation"]- _check_performance_params(params, operation)+ _check_performance_params(task_name, params, operation)level, timing = reference["schedule"]["levels"][0], reference["timing"]reasons: list[str] = []rate = _override(args.rate, float(level["rate"]), "rate", reasons)@@ -565,7 +628,7 @@ def _performance_plan_from_flags(args: argparse.Namespace) -> PerformancePlan:task_name, params = parse_task_key(args.task)model, _, profile = args.model.partition(":")operation = "score" if task_name in SCORE_TASKS else "encode"- _check_performance_params(params, operation)+ _check_performance_params(task_name, params, operation)_check_output_flags(args, operation)duration_s = DEFAULT_DURATION_S if args.duration is None else args.durationwarmup_s = DEFAULT_WARMUP_S if args.warmup is None else args.warmup@@ -611,7 +674,7 @@ def load_quality_data(plan: QualityPlan, loaders: Loaders | None = None) -> Qualqrels = loaders.qrels(plan.task_name, plan.revision)queries = select_queries(loaders.queries(plan.task_name, plan.revision), qrels, plan.task_params)top_ranked = None- if plan.operation == "score":+ if plan.operation == "score" and plan.candidates_model is None:candidates = loaders.top_ranked(plan.task_name, plan.revision)top_ranked = {query_id: list(candidates[query_id]) for query_id in queries}return QualityData(@@ -646,7 +709,7 @@ def load_performance_data(plan: PerformancePlan, loaders: Loaders | None = None)corpus = loaders.corpus(plan.task_name, plan.revision)top_ranked = loaders.top_ranked(plan.task_name, plan.revision)selected = select_ids(queries, params)- k = int(params["candidates-k"]) if "candidates-k" in params else None+ k = int(params.get("candidates-k", SCORE_ITEMS_PER_REQUEST))requests: list[ScoreRequest] = [({"text": queries[query_id]},@@ -801,11 +864,29 @@ def warmup(client: Any, plan: PerformancePlan, data: PerformanceData) -> None:performance_call(client, plan, payload, wait_for_capacity=False, provision_timeout_s=plan.request_timeout_s)+def encoder_plan(plan: QualityPlan) -> QualityPlan:+ return replace(+ plan,+ model=plan.candidates_model,+ profile="default",+ operation="encode",+ output_contract="dense",+ items_per_request=CANDIDATE_ENCODE_ITEMS_PER_REQUEST,+ )++def quality_readiness_request(client: Any, plan: QualityPlan, data: QualityData) -> None:+ if plan.candidates_model is not None:+ _encode_readiness_request(client, encoder_plan(plan), data)if plan.operation == "score":query_id, text = next(iter(data.queries.items()))+ if plan.candidates_model is not None:+ candidates = list(data.corpus)[: plan.candidates_k]+ else:+ candidates = (data.top_ranked or {})[query_id]items = [- {"id": doc_id, "text": document_text(data.corpus[doc_id])} for doc_id in (data.top_ranked or {})[query_id]+ {"id": doc_id, "text": document_text(data.corpus[doc_id])}+ for doc_id in candidates[:SCORE_ITEMS_PER_REQUEST]]client.score(plan.route,@@ -816,6 +897,10 @@ def quality_readiness_request(client: Any, plan: QualityPlan, data: QualityData)max_oom_retries=0,)return+ _encode_readiness_request(client, plan, data)+++def _encode_readiness_request(client: Any, plan: QualityPlan, data: QualityData) -> None:document_ids = list(data.corpus)[: plan.items_per_request]client.encode(plan.route,@@ -958,7 +1043,9 @@ def top_k_predictions(return predictions-def encode_predictions(client: Any, plan: QualityPlan, data: QualityData, log: CallLog) -> PredictionMap:+def encode_predictions(+ client: Any, plan: QualityPlan, data: QualityData, log: CallLog, *, k: int = TOP_K+) -> PredictionMap:document_ids = list(data.corpus)document_texts = [document_text(data.corpus[doc_id]) for doc_id in document_ids]documents = encode_texts(client, plan, document_ids, document_texts, log, is_query=False)@@ -967,36 +1054,56 @@ def encode_predictions(client: Any, plan: QualityPlan, data: QualityData, log: Cif plan.output_contract == "sparse":scores = sparse_scores(queries, documents)elif plan.output_contract == "dense":- scores = dense_scores([q["dense"] for q in queries], [d["dense"] for d in documents])+ query_vectors, document_vectors = [q["dense"] for q in queries], [d["dense"] for d in documents]+ for role, vectors in (("document", document_vectors), ("query", query_vectors)):+ if not any(np.any(vector) for vector in vectors):+ raise ValueError(f"every returned dense {role} vector is all zeros")+ scores = dense_scores(query_vectors, document_vectors)else:scores = maxsim_scores([q["multivector"] for q in queries], [d["multivector"] for d in documents])- return top_k_predictions(scores, query_ids, document_ids)+ return top_k_predictions(scores, query_ids, document_ids, k)+++def candidate_batches(candidates: Sequence[str]) -> list[Sequence[str]]:+ return [+ candidates[start : start + SCORE_ITEMS_PER_REQUEST]+ for start in range(0, len(candidates), SCORE_ITEMS_PER_REQUEST)+ ]def rerank_predictions(client: Any, plan: QualityPlan, data: QualityData, log: CallLog) -> PredictionMap:top_ranked = data.top_ranked or {}predictions: PredictionMap = {}for query_id, text in data.queries.items():- candidates = top_ranked[query_id]- items = [{"id": doc_id, "text": document_text(data.corpus[doc_id])} for doc_id in candidates]- result = _call(- log,- client,- client.score,- plan.route,- {"text": text},- items,- wait_for_capacity=False,- provision_timeout_s=plan.request_timeout_s,- max_oom_retries=0,- )- scored = {entry["item_id"]: float(entry["score"]) for entry in result["scores"]}- if set(scored) != set(candidates):- raise ValueError(f"score returned item ids that differ from the candidates of query {query_id}")+ scored: dict[str, float] = {}+ for candidates in candidate_batches(top_ranked[query_id]):+ items = [{"id": doc_id, "text": document_text(data.corpus[doc_id])} for doc_id in candidates]+ result = _call(+ log,+ client,+ client.score,+ plan.route,+ {"text": text},+ items,+ wait_for_capacity=False,+ provision_timeout_s=plan.request_timeout_s,+ max_oom_retries=0,+ )+ batch = {entry["item_id"]: float(entry["score"]) for entry in result["scores"]}+ if set(batch) != set(candidates):+ raise ValueError(f"score returned item ids that differ from the candidates of query {query_id}")+ scored.update(batch)predictions[query_id] = scoredreturn predictions+def two_stage_predictions(client: Any, plan: QualityPlan, data: QualityData, log: CallLog) -> PredictionMap:+ retrieved = encode_predictions(client, encoder_plan(plan), data, log, k=plan.candidates_k or TOP_K)+ log.encoder_revisions, log.execution_revisions = log.execution_revisions, []+ top_ranked = {query_id: list(documents) for query_id, documents in retrieved.items()}+ return rerank_predictions(client, plan, replace(data, top_ranked=top_ranked), log)++def client_description() -> str:return f"single process, {platform.platform()}, python {platform.python_version()}, sie-sdk {sie_sdk.__version__}"@@ -1027,7 +1134,7 @@ def quality_command_line(plan: QualityPlan) -> str:flags += ["--task", plan.task_key]else:flags = _common_flags(plan)- if plan.baseline is not None:+ if plan.baseline is not None and plan.baseline["kind"] == "supplied":metric, value, source = plan.baseline["metric"], plan.baseline["value"], plan.baseline["source"]flags += ["--baseline", f"{metric}={value!r}", f"--baseline-source={source}"]if plan.instruction is not None:@@ -1052,6 +1159,24 @@ def comparison_basis(reference_id: str | None, comparable: bool, reasons: Sequenreturn "same method, different parameters: " + "; ".join(reasons)+def _largest_score_request(plan: QualityPlan, data: QualityData) -> int:+ if plan.candidates_k is not None:+ largest = min(plan.candidates_k, len(data.corpus))+ else:+ largest = max((len(candidates) for candidates in (data.top_ranked or {}).values()), default=0)+ return min(largest, SCORE_ITEMS_PER_REQUEST)+++def _payload_parameters(plan: QualityPlan) -> list[dict[str, Any]]:+ parameters: list[dict[str, Any]] = []+ if plan.instruction is not None:+ parameters.append({"name": "instruction", "value": plan.instruction})+ if plan.candidates_model is not None:+ parameters.append({"name": "candidates_model", "value": plan.candidates_model})+ parameters.append({"name": "candidates_k", "value": plan.candidates_k})+ return parameters++def build_record(plan: QualityPlan,data: QualityData,@@ -1060,9 +1185,10 @@ def build_record(finished: datetime,predictions_path: Path | None,rows: list[dict[str, Any]],+ official_lookup: Mapping[str, str] | None = None,) -> dict[str, Any]:reasons = list(plan.comparable_reasons)- if len(log.execution_revisions) > 1:+ if log.revision_changed:reasons.append("execution revision changed")comparable = not reasonsvalidity_reasons: list[str] = []@@ -1072,8 +1198,7 @@ def build_record(validity_reasons.append(f"sdk retries {log.sdk_retries}")if log.failure is not None:validity_reasons.append(f"request failed: {log.failure}")- candidate_counts = [len(candidates) for candidates in (data.top_ranked or {}).values()]- return {+ record = {"kind": RESULT_KIND,"schema_version": 1,"reference_id": plan.reference_id,@@ -1084,19 +1209,19 @@ def build_record("profile": plan.profile,"operation": plan.operation,"model_version": plan.model_version,- "execution_revisions": list(log.execution_revisions),+ "execution_revisions": list(dict.fromkeys([*log.encoder_revisions, *log.execution_revisions])),"ingress": {"url": plan.endpoint},"task_key": plan.task_key,"dataset": {"name": plan.task_name,"revision": plan.revision,- "subset": "test",+ "subset": eval_split(plan.task_name),"parameters": [{"name": name, "value": value} for name, value in plan.task_params.items()],},"payload": {- "items_per_request": plan.items_per_request or max(candidate_counts, default=0),+ "items_per_request": plan.items_per_request or _largest_score_request(plan, data),"output_contract": plan.output_contract,- "parameters": [{"name": "instruction", "value": plan.instruction}] if plan.instruction is not None else [],+ "parameters": _payload_parameters(plan),},"client": {"description": client_description(), "worker_count": 1, "processes_per_worker": 1},"scorer": {"id": SCORER_ID, "version": scorer_version(), "reference_scorer_matched": False},@@ -1118,6 +1243,9 @@ def build_record({row["name"]: row["value"] for row in rows}, plan.baseline, limited="limit" in plan.task_params),}+ if official_lookup is not None:+ record["official_lookup"] = dict(official_lookup)+ return recorddef performance_validity(plan: PerformancePlan, dispatcher: Dispatcher, metrics: Mapping[str, float]) -> dict[str, Any]:@@ -1176,7 +1304,7 @@ def build_performance_record("dataset": {"name": plan.task_name,"revision": plan.revision,- "subset": "test",+ "subset": eval_split(plan.task_name),"parameters": [{"name": name, "value": value} for name, value in plan.task_params.items()],"selected_ids": list(data.selected_ids),},@@ -1224,6 +1352,7 @@ def run_quality(*,results_dir: Path = RESULTS_DIR,now: Callable[[], datetime] | None = None,+ official_lookup: Mapping[str, str] | None = None,) -> tuple[dict[str, Any], Path]:clock = now or (lambda: datetime.now(UTC))started = clock()@@ -1235,7 +1364,9 @@ def run_quality(except Exception as exc: # noqa: BLE001log.readiness_failure = f"{type(exc).__name__}: {exc}"if log.readiness_failure is None:- if plan.operation == "score":+ if plan.candidates_model is not None:+ predictions = two_stage_predictions(client, plan, data, log)+ elif plan.operation == "score":predictions = rerank_predictions(client, plan, data, log)else:predictions = encode_predictions(client, plan, data, log)@@ -1253,7 +1384,7 @@ def run_quality(predictions_path = results_dir / f"{stem}.predictions.json"write_json(predictions_path, predictions, compact=True)rows = metric_rows(task_metrics(predictions, data.qrels, plan.task_name))- record = build_record(plan, data, log, started, finished, predictions_path, rows)+ record = build_record(plan, data, log, started, finished, predictions_path, rows, official_lookup)write_json(result_path, record)return record, result_path@@ -1292,6 +1423,82 @@ def run_performance(return record, result_path+def _plan_skip_reason(plan: QualityPlan) -> str | None:+ if "limit" in plan.task_params:+ return "a task key with limit is not compared with a full-dataset number"+ if plan.candidates_model is not None:+ return "the results repository has no number for a retriever and reranker pair"+ if plan.profile != "default":+ return "the results repository has no number for a profile"+ return None+++def _served_model(client: Any, model: str) -> tuple[set[str] | None, str | None]:+ try:+ info = client.get_model(model)+ outputs, revision = info.get("outputs"), info.get("revision")+ known = set(ENCODE_OUTPUTS).intersection(outputs) if isinstance(outputs, list) and outputs else None+ except Exception: # noqa: BLE001+ return None, None+ return known, plain_text(revision)+++def _output_skip_reason(plan: QualityPlan, outputs: set[str] | None) -> str | None:+ if plan.operation != "encode" or plan.output_contract == "dense":+ return None+ if outputs is None:+ return f"the endpoint did not say what the model outputs, and an official number is for dense, not {plan.output_contract}"+ if len(outputs) > 1:+ return f"the model has several outputs and the official number is for dense, not {plan.output_contract}"+ return None+++def _official_lookup(plan: QualityPlan, client: Any, fetch: Fetch) -> tuple[Lookup, str | None]:+ reason = _plan_skip_reason(plan)+ if reason is not None:+ return Lookup(SKIPPED, reason), None+ outputs, served_revision = _served_model(client, plan.model)+ reason = _output_skip_reason(plan, outputs)+ if reason is not None:+ return Lookup(SKIPPED, reason), served_revision+ lookup = lookup_official(+ plan.model, plan.task_name, eval_split(plan.task_name), MAIN_SCORE[plan.task_name], served_revision, fetch+ )+ return lookup, served_revision+++def _official_notes(plan: QualityPlan, baseline: Mapping[str, Any], served_revision: str | None) -> list[str]:+ notes = []+ if served_revision is not None and baseline["model_revision"] != served_revision:+ notes.append(+ f"the official number is for model revision {baseline['model_revision']}, the endpoint serves {served_revision}"+ )+ if baseline["dataset_revision"] is not None and baseline["dataset_revision"] != plan.revision:+ notes.append(+ f"the official number is for dataset revision {baseline['dataset_revision']}, this run uses {plan.revision}"+ )+ return notes+++def official_baseline(plan: QualityPlan, client: Any, fetch: Fetch) -> tuple[QualityPlan, dict[str, str] | None]:+ """Look the official number up for a run with no baseline; say what happened before anything is spent."""+ if plan.reference_id is not None or plan.baseline is not None:+ return plan, None+ lookup, served_revision = _official_lookup(plan, client, fetch)+ if lookup.baseline is None:+ reading = "the run reads MEASUREMENT"+ if "limit" not in plan.task_params:+ reading += " unless you pass --baseline"+ print(f"official: none, {lookup.detail}; {reading}", flush=True)+ return plan, {"status": lookup.status, "detail": lookup.detail}+ notes = _official_notes(plan, lookup.baseline, served_revision)+ print(f"official: {lookup.detail}", flush=True)+ for note in notes:+ print(f"note: {note}", flush=True)+ detail = "; ".join([lookup.detail, *notes])+ return replace(plan, baseline=lookup.baseline), {"status": lookup.status, "detail": detail}++def report_invalid(record: Mapping[str, Any]) -> None:if not record["validity"]["valid"]:for reason in record["validity"]["reasons"]:@@ -1308,7 +1515,8 @@ def quality_command(parser: argparse.ArgumentParser, args: argparse.Namespace) -api_key = _resolve_api_key(parser, plan.endpoint)data = load_quality_data(plan)with SIEClient(plan.endpoint, api_key=api_key, timeout_s=plan.request_timeout_s) as client:- record, result_path = run_quality(plan, data, client)+ plan, official_lookup = official_baseline(plan, client, http_fetch)+ record, result_path = run_quality(plan, data, client, official_lookup=official_lookup)print(result_path)for line in format_rows(record["metrics"], record["comparison"]):print(line)diff --git a/examples/evaluations/published-benchmarks/score.py b/examples/evaluations/published-benchmarks/score.pyindex 9bdb0715c..5d951956c 100644--- a/examples/evaluations/published-benchmarks/score.py+++ b/examples/evaluations/published-benchmarks/score.py@@ -27,6 +27,15 @@ HF_DATASETS = {"mteb/legalbench_consumer_contracts_qa","b23590301ec94e8087e2850b21d43d4956b1cca9",),+ "mteb/MMarcoReranking": ("mteb/MMarcoReranking", "91c0f9d5cbd4cdc7ecd7039c5c2e57740cb62b00"),+ "mteb/T2Reranking": ("mteb/T2Reranking", "a34fe6bc0dff185af1228e49a0f6fb1de1565627"),+ "mteb/CMedQAv1-reranking": ("mteb/CMedQAv1-reranking", "f77f0345c9b6ac0a2447a3a71483d5b27393cb35"),+ "mteb/CMedQAv2-reranking": ("mteb/CMedQAv2-reranking", "01399b6956a4c6bf9edc5b6b90e176aeeb399686"),+ "mteb/NanoFiQA2018Retrieval": ("zeta-alpha-ai/NanoFiQA2018", "4163ba032953d5044a7a6244261413f609c14342"),+}+TASK_ALIASES = {+ "mteb/CMedQAv1Reranking": "mteb/CMedQAv1-reranking",+ "mteb/CMedQAv2Reranking": "mteb/CMedQAv2-reranking",}MAIN_SCORE = {"mteb/SciFact": "ndcg_at_10",@@ -38,6 +47,11 @@ MAIN_SCORE = {"mteb/CosQA": "ndcg_at_10","mteb/StackOverflowQA": "ndcg_at_10","mteb/LegalBenchConsumerContractsQA": "ndcg_at_10",+ "mteb/MMarcoReranking": "map_at_1000",+ "mteb/T2Reranking": "map_at_1000",+ "mteb/CMedQAv1-reranking": "map_at_1000",+ "mteb/CMedQAv2-reranking": "map_at_1000",+ "mteb/NanoFiQA2018Retrieval": "ndcg_at_10",}ROLE_SPLITS = {"mteb/SciFact": {"corpus": "corpus", "queries": "queries"},@@ -49,7 +63,20 @@ ROLE_SPLITS = {"mteb/CosQA": {"corpus": "corpus", "queries": "queries"},"mteb/StackOverflowQA": {"corpus": "corpus", "queries": "queries"},"mteb/LegalBenchConsumerContractsQA": {"corpus": "corpus", "queries": "queries"},+ "mteb/MMarcoReranking": {"corpus": "dev", "queries": "dev"},+ "mteb/T2Reranking": {"corpus": "dev", "queries": "dev"},+ "mteb/CMedQAv1-reranking": {"corpus": "test", "queries": "test"},+ "mteb/CMedQAv2-reranking": {"corpus": "test", "queries": "test"},+ "mteb/NanoFiQA2018Retrieval": {"corpus": "train", "queries": "train"},+}+EVAL_SPLITS = {+ "mteb/MMarcoReranking": "dev",+ "mteb/T2Reranking": "dev",+ "mteb/NanoFiQA2018Retrieval": "train",}+DEFAULT_EVAL_SPLIT = "test"+QRELS_CONFIGS = {"mteb/NanoFiQA2018Retrieval": "qrels"}+DEFAULT_QRELS_CONFIG = "default"IGNORE_IDENTICAL_IDS = frozenset({"mteb/FiQA2018"})METRIC_UNIT = "ratio"AGGREGATION = "task_native"@@ -94,9 +121,18 @@ Rows = list[dict[str, Any]]def parse_task_key(task_key: str) -> tuple[str, dict[str, str]]:task_name, _, query = task_key.partition("?")+ task_name = TASK_ALIASES.get(task_name, task_name)if task_name not in HF_DATASETS:raise ValueError(f"unknown task {task_name!r}; known tasks: {', '.join(HF_DATASETS)}")- return task_name, dict(parse_qsl(query, keep_blank_values=True))+ pairs = parse_qsl(query, keep_blank_values=True)+ params = dict(pairs)+ if len(params) != len(pairs):+ raise ValueError(f"the task key {task_key!r} repeats a parameter")+ return task_name, params+++def eval_split(task_name: str) -> str:+ return EVAL_SPLITS.get(task_name, DEFAULT_EVAL_SPLIT)def scorer_version() -> str:@@ -124,16 +160,18 @@ def load_queries(task_name: str, revision: str) -> dict[str, str]:return {str(query_id): text for query_id, text in zip(rows["_id"], rows["text"], strict=True)}-def load_qrels(task_name: str, revision: str, split: str = "test") -> Qrels:- rows = _rows(task_name, "default", split, revision)+def load_qrels(task_name: str, revision: str, split: str | None = None) -> Qrels:+ config = QRELS_CONFIGS.get(task_name, DEFAULT_QRELS_CONFIG)+ rows = _rows(task_name, config, split or eval_split(task_name), revision)+ grades = rows["score"] if "score" in rows.column_names else [1] * len(rows)qrels: Qrels = {}- for query_id, doc_id, grade in zip(rows["query-id"], rows["corpus-id"], rows["score"], strict=True):+ for query_id, doc_id, grade in zip(rows["query-id"], rows["corpus-id"], grades, strict=True):qrels.setdefault(str(query_id), {})[str(doc_id)] = int(grade)return qrels-def load_top_ranked(task_name: str, revision: str, split: str = "test") -> dict[str, list[str]]:- rows = _rows(task_name, "top_ranked", split, revision)+def load_top_ranked(task_name: str, revision: str, split: str | None = None) -> dict[str, list[str]]:+ rows = _rows(task_name, "top_ranked", split or eval_split(task_name), revision)return {str(query_id): [str(doc_id) for doc_id in doc_ids]for query_id, doc_ids in zip(rows["query-id"], rows["corpus-ids"], strict=True)diff --git a/examples/evaluations/published-benchmarks/tests/test_official.py b/examples/evaluations/published-benchmarks/tests/test_official.pynew file mode 100644index 000000000..a9318fc13--- /dev/null+++ b/examples/evaluations/published-benchmarks/tests/test_official.py@@ -0,0 +1,660 @@+import contextlib+import io+import json+import shlex+import tempfile+import unittest+import urllib.error+from pathlib import Path+from typing import ClassVar+from unittest.mock import patch++from test_quality import FakeClient, clock, parse, reference_file, tiny_loaders+from test_verdict import DENSE_FLAGS, DenseClient, judged_qrels++import official+import run+import score+from official import COMMIT_URL, CONTENTS_URL, RAW_URL, LookupFailed, NotFound, http_fetch, lookup_official+from run import load_quality_data, official_baseline, plan_quality, run_quality+from score import recompute_verdict++MODEL = "example/dense"+FOLDER = "example__dense"+SHA = "a" * 40+PINNED = score.HF_DATASETS["mteb/SciFact"][1]+LOCAL = "http://localhost:8080"+SPARSE_FLAGS = ("--model", MODEL, "--task", "mteb/SciFact", "--output", "sparse", "--items-per-request", "2")+NO_LOOKUP = AssertionError("nothing may be looked up")+++def result_file(value=0.31411, *, split="test", metric="ndcg_at_10", dataset_revision=PINNED, version="1.36.32"):+ return {+ "dataset_revision": dataset_revision,+ "task_name": "SciFact",+ "mteb_version": version,+ "scores": {split: [{"hf_subset": "default", metric: value, "main_score": value, "languages": ["eng-Latn"]}]},+ }+++class FakeGitHub:+ def __init__(self, files=None, *, directories=None, commit=None, listing=None):+ self.files = {"rev-a": result_file()} if files is None else files+ self.directories = list(self.files) if directories is None else directories+ self.commit = SHA.encode() if commit is None else commit+ self.listing = listing+ self.urls = []+ self.accepts = []++ def _route(self, url):+ if url == COMMIT_URL:+ return self.commit+ if url == f"{CONTENTS_URL}/{FOLDER}?ref={SHA}":+ if self.listing is not None:+ return self.listing+ return json.dumps([{"name": name, "type": "dir"} for name in self.directories]).encode()+ prefix = f"{RAW_URL}/{SHA}/results/{FOLDER}/"+ directory, _, file_name = url.removeprefix(prefix).partition("/")+ if url.startswith(prefix) and directory in self.files and file_name.endswith(".json"):+ body = self.files[directory]+ return body if isinstance(body, bytes) else json.dumps(body).encode()+ raise NotFound(url)++ def __call__(self, url, accept=None):+ self.urls.append(url)+ self.accepts.append(accept)+ return self._route(url)+++class Failing(FakeGitHub):+ def __init__(self, url_part, error, **kwargs):+ super().__init__(**kwargs)+ self.url_part, self.error = url_part, error++ def _route(self, url):+ if self.url_part in url:+ raise self.error+ return super()._route(url)+++def lookup(fetch, *, model=MODEL, task="mteb/SciFact", split="test", metric="ndcg_at_10", served=None):+ return lookup_official(model, task, split, metric, served, fetch)+++class LookupFoundTest(unittest.TestCase):+ def test_the_baseline_names_the_exact_file_at_the_resolved_commit(self):+ fetch = FakeGitHub()+ found = lookup(fetch)+ self.assertEqual(found.status, "found")+ source = f"https://github.com/embeddings-benchmark/results/blob/{SHA}/results/{FOLDER}/rev-a/SciFact.json"+ self.assertEqual(+ found.baseline,+ {+ "kind": "official",+ "metric": "ndcg_at_10",+ "value": 0.31411,+ "source": source,+ "model_revision": "rev-a",+ "dataset_revision": PINNED,+ "mteb_version": "1.36.32",+ },+ )+ self.assertEqual(found.detail, f"ndcg_at_10 0.31411 from {source}")+ self.assertEqual(+ fetch.urls,+ [+ "https://api.github.com/repos/embeddings-benchmark/results/commits/main",+ f"https://api.github.com/repos/embeddings-benchmark/results/contents/results/{FOLDER}?ref={SHA}",+ f"https://raw.githubusercontent.com/embeddings-benchmark/results/{SHA}/results/{FOLDER}/rev-a/SciFact.json",+ ],+ )+ self.assertEqual(fetch.accepts, ["application/vnd.github.sha", "application/vnd.github+json", None])++ def test_the_commit_can_also_come_as_json(self):+ self.assertEqual(lookup(FakeGitHub(commit=json.dumps({"sha": SHA}).encode())).status, "found")++ def test_the_split_and_metric_of_the_task_are_read(self):+ fetch = FakeGitHub({"rev-a": result_file(0.5, split="dev", metric="map_at_1000")})+ found = lookup(fetch, task="mteb/T2Reranking", split="dev", metric="map_at_1000")+ self.assertEqual((found.status, found.baseline["value"]), ("found", 0.5))+ self.assertTrue(fetch.urls[-1].endswith("/rev-a/T2Reranking.json"))++ def test_a_value_of_one_and_an_integer_one_are_accepted(self):+ for value in (1.0, 1):+ with self.subTest(value=value):+ self.assertEqual(lookup(FakeGitHub({"rev-a": result_file(value)})).baseline["value"], 1.0)++ def test_another_subset_beside_the_default_one_is_left_alone(self):+ body = result_file()+ body["scores"]["test"].append({"hf_subset": "other", "ndcg_at_10": 0.9})+ self.assertEqual(lookup(FakeGitHub({"rev-a": body})).baseline["value"], 0.31411)++ def test_missing_or_odd_revision_fields_are_recorded_as_null(self):+ body = result_file()+ del body["dataset_revision"]+ body["mteb_version"] = "line\nbreak"+ found = lookup(FakeGitHub({"rev-a": body}))+ self.assertIsNone(found.baseline["dataset_revision"])+ self.assertIsNone(found.baseline["mteb_version"])+++class LookupNotFoundTest(unittest.TestCase):+ def assert_not_found(self, result, text):+ self.assertEqual(result.status, "not_found")+ self.assertIn(text, result.detail)+ self.assertIsNone(result.baseline)++ def test_a_404_at_each_step(self):+ self.assert_not_found(lookup(Failing("/commits/main", NotFound("x"))), "no main branch")+ self.assert_not_found(lookup(Failing("/contents/", NotFound("x"))), f"{MODEL} is not in")+ self.assert_not_found(lookup(FakeGitHub({}, directories=["rev-a", "rev-b"])), "no SciFact.json")++ def test_a_file_with_no_such_split_or_metric_has_no_number(self):+ self.assert_not_found(lookup(FakeGitHub({"rev-a": result_file(split="train")})), "has no test scores")+ older = {"scores": {"dev": [{"hf_subset": "default", "map": 0.66, "main_score": 0.66}]}}+ fetch = FakeGitHub({"rev-a": older})+ self.assert_not_found(+ lookup(fetch, task="mteb/T2Reranking", split="dev", metric="map_at_1000"),+ "rev-a/T2Reranking.json has no map_at_1000",+ )++ def test_a_newer_file_is_used_beside_one_with_no_number(self):+ older = {"scores": {"dev": [{"hf_subset": "default", "map": 0.66, "main_score": 0.66}]}}+ fetch = FakeGitHub({"rev-a": older, "rev-b": result_file(0.65, split="dev", metric="map_at_1000")})+ found = lookup(fetch, task="mteb/T2Reranking", split="dev", metric="map_at_1000", served="rev-a")+ self.assertEqual((found.status, found.baseline["model_revision"]), ("found", "rev-b"))++ def test_a_listing_with_no_directories(self):+ self.assert_not_found(lookup(FakeGitHub(listing=b'[{"name": "README.md", "type": "file"}]')), "no SciFact.json")++ def test_a_model_id_that_is_not_plain_builds_no_url(self):+ for model in ("noslash", "a/b/c", "a/b?x=1", "a b/c", "a/b\n", "", "org/na%2Fme", "../x/y"):+ with self.subTest(model=model):+ fetch = FakeGitHub()+ self.assert_not_found(lookup(fetch, model=model), "not an <org>/<name> model id")+ self.assertEqual(fetch.urls, [])++ def test_directory_names_that_are_not_plain_are_never_fetched(self):+ names = ["../../secrets", "a/b", "a b", ".", "..", "x?y", ""]+ listing = json.dumps([{"name": name, "type": "dir"} for name in names] + [{"name": 7, "type": "dir"}]).encode()+ fetch = FakeGitHub(listing=listing)+ self.assert_not_found(lookup(fetch), "no SciFact.json")+ self.assertEqual(len(fetch.urls), 2)+++class LookupFailedTest(unittest.TestCase):+ def assert_failed(self, result, text=""):+ self.assertEqual(result.status, "failed")+ self.assertIn(text, result.detail)+ self.assertIsNone(result.baseline)++ def test_a_rate_limit_or_network_error_at_each_step(self):+ for part in ("/commits/main", "/contents/", "/SciFact.json"):+ for error in (LookupFailed("HTTP 403 from api.github.com"), TimeoutError("slow"), RuntimeError("x")):+ with self.subTest(part=part, error=error):+ self.assert_failed(lookup(Failing(part, error)))++ def test_a_failure_on_one_directory_fails_the_lookup(self):+ fetch = Failing("/rev-b/", LookupFailed("HTTP 500"), files={"rev-a": result_file(), "rev-b": result_file()})+ self.assert_failed(lookup(fetch), "HTTP 500")++ def test_a_commit_that_is_no_commit_id(self):+ for commit in (b"<html>", b'{"sha": "main"}', b'{"sha": 7}', b"[]", b"A" * 40, b"../" * 14):+ with self.subTest(commit=commit):+ fetch = FakeGitHub(commit=commit)+ self.assert_failed(lookup(fetch))+ self.assertEqual(len(fetch.urls), 1)++ def test_a_listing_of_the_wrong_type(self):+ for listing in (b"not json", b'{"message": "x"}', b"[1, 2]", b"null"):+ with self.subTest(listing=listing):+ self.assert_failed(lookup(FakeGitHub(listing=listing)), "listing")++ def test_a_result_file_that_cannot_be_used(self):+ cases = {+ "not JSON": b"<html>",+ "deeply nested JSON": b"[" * 100000,+ "not an object": [],+ "no scores": {"task_name": "SciFact"},+ "scores of the wrong type": {"scores": []},+ "split of the wrong type": {"scores": {"test": {"hf_subset": "default"}}},+ "entries of the wrong type": {"scores": {"test": [1, "x", None]}},+ "no default subset": {"scores": {"test": [{"hf_subset": "a", "ndcg_at_10": 0.3}]}},+ "several subsets, none default": {+ "scores": {"test": [{"hf_subset": "a", "ndcg_at_10": 0.3}, {"hf_subset": "b", "ndcg_at_10": 0.3}]}+ },+ "two default subsets": {+ "scores": {+ "test": [{"hf_subset": "default", "ndcg_at_10": 0.3}, {"hf_subset": "default", "ndcg_at_10": 0.4}]+ }+ },+ "metric as text": result_file("0.3"),+ "metric as a boolean": result_file(True),+ "metric null": result_file(None),+ "metric zero": result_file(0.0),+ "metric negative": result_file(-0.1),+ "metric in percent": result_file(31.4),+ "metric not finite": b'{"scores": {"test": [{"hf_subset": "default", "ndcg_at_10": NaN}]}}',+ "metric infinite": b'{"scores": {"test": [{"hf_subset": "default", "ndcg_at_10": Infinity}]}}',+ "metric too large for a float": result_file(10**400),+ }+ for name, body in cases.items():+ with self.subTest(name):+ self.assert_failed(lookup(FakeGitHub({"rev-a": body})), "rev-a/SciFact.json")++ def test_a_bad_file_does_not_hide_a_good_one(self):+ found = lookup(FakeGitHub({"rev-a": b"<html>", "rev-b": result_file(0.4)}))+ self.assertEqual((found.status, found.baseline["model_revision"]), ("found", "rev-b"))++ def test_a_bad_file_is_reported_ahead_of_a_file_with_no_number(self):+ self.assert_failed(lookup(FakeGitHub({"rev-a": result_file(split="train"), "rev-b": b"<html>"})), "not JSON")+++class LookupPreferenceTest(unittest.TestCase):+ FILES: ClassVar[dict] = {+ "rev-a": result_file(0.1, version="1.9.0"),+ "rev-b": result_file(0.2, version="1.36.32"),+ "rev-c": result_file(0.3, version="1.36.32"),+ "rev-d": result_file(0.4, version=None),+ }++ def test_the_served_revision_wins(self):+ self.assertEqual(lookup(FakeGitHub(self.FILES), served="rev-a").baseline["model_revision"], "rev-a")++ def test_otherwise_the_highest_mteb_version_numerically_and_ties_by_sorted_name(self):+ for served in (None, "rev-z"):+ with self.subTest(served=served):+ self.assertEqual(lookup(FakeGitHub(self.FILES), served=served).baseline["model_revision"], "rev-b")++ def test_a_listing_order_changes_nothing(self):+ fetch = FakeGitHub(self.FILES, directories=["rev-d", "rev-c", "rev-b", "rev-a"])+ self.assertEqual(lookup(fetch).baseline["model_revision"], "rev-b")++ def test_a_file_with_no_version_is_the_last_choice(self):+ found = lookup(FakeGitHub({"rev-a": result_file(version=None), "rev-b": result_file(version="0.1")}))+ self.assertEqual(found.baseline["model_revision"], "rev-b")+++class HttpFetchTest(unittest.TestCase):+ def test_a_plain_request_with_no_credential(self):+ environ = {"GITHUB_TOKEN": "t0ken", "GH_TOKEN": "t0ken", "HF_TOKEN": "t0ken", "SIE_API_KEY": "t0ken"}+ with (+ patch.dict("os.environ", environ),+ patch("official.urllib.request.urlopen", return_value=io.BytesIO(b"body")) as urlopen,+ ):+ self.assertEqual(http_fetch(COMMIT_URL, "application/vnd.github.sha"), b"body")+ request = urlopen.call_args.args[0]+ self.assertEqual(request.full_url, COMMIT_URL)+ headers = dict(request.header_items())+ self.assertEqual(set(headers), {"User-agent", "Accept"})+ self.assertNotIn("@", headers["User-agent"])+ self.assertNotIn("t0ken", json.dumps(headers))+ self.assertEqual(urlopen.call_args.kwargs, {"timeout": 30.0})++ def test_without_an_accept_only_the_user_agent_is_sent(self):+ with patch("official.urllib.request.urlopen", return_value=io.BytesIO(b"body")) as urlopen:+ http_fetch(f"{RAW_URL}/x")+ self.assertEqual(set(dict(urlopen.call_args.args[0].header_items())), {"User-agent"})++ def test_the_bytes_read_are_capped(self):+ with patch("official.urllib.request.urlopen", return_value=io.BytesIO(b"x" * official.MAX_BYTES)):+ self.assertEqual(len(http_fetch(COMMIT_URL)), official.MAX_BYTES)+ with (+ patch("official.urllib.request.urlopen", return_value=io.BytesIO(b"x" * (official.MAX_BYTES + 1))),+ self.assertRaises(LookupFailed),+ ):+ http_fetch(COMMIT_URL)++ def http_error(self, code):+ return urllib.error.HTTPError(COMMIT_URL, code, "x", None, None)++ def test_a_404_is_not_found(self):+ with patch("official.urllib.request.urlopen", side_effect=self.http_error(404)), self.assertRaises(NotFound):+ http_fetch(COMMIT_URL)++ def test_a_rate_limit_is_named_and_short(self):+ for code in (403, 429):+ with (+ self.subTest(code=code),+ patch("official.urllib.request.urlopen", side_effect=self.http_error(code)),+ self.assertRaisesRegex(LookupFailed, f"^HTTP {code} from api.github.com, probably .*rate limit$"),+ ):+ http_fetch(COMMIT_URL)++ def test_a_network_error_is_a_failure(self):+ for error in (urllib.error.URLError("no route"), TimeoutError("slow"), ConnectionResetError("reset")):+ with (+ self.subTest(error=error),+ patch("official.urllib.request.urlopen", side_effect=error),+ self.assertRaisesRegex(LookupFailed, "could not reach api.github.com"),+ ):+ http_fetch(COMMIT_URL)+++class InfoClient(DenseClient):+ def __init__(self, *, outputs=("dense",), revision="rev-a", info_error=None, **kwargs):+ super().__init__(**kwargs)+ self.info = {"outputs": list(outputs) if outputs is not None else None, "revision": revision}+ self.info_error = info_error+ self.info_calls = []++ def get_model(self, model):+ self.info_calls.append(model)+ if self.info_error is not None:+ raise self.info_error+ return self.info+++class TemporaryCase(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.directory = Path(self.temporary.name)++ def resolve(self, client, fetch, *flags):+ stdout = io.StringIO()+ with contextlib.redirect_stdout(stdout):+ plan, record = official_baseline(plan_quality(parse(*flags)), client, fetch)+ return plan, record, stdout.getvalue().splitlines()++ def run_official(self, client, fetch, *flags):+ plan, lookup_record, _ = self.resolve(client, fetch, *flags)+ return run_quality(+ plan,+ load_quality_data(plan, tiny_loaders()),+ client,+ results_dir=self.directory / "results",+ now=clock,+ official_lookup=lookup_record,+ )+++class OfficialBaselineTest(TemporaryCase):+ def test_a_found_number_becomes_the_baseline_and_no_inference_request_is_made(self):+ client, fetch = InfoClient(), FakeGitHub()+ plan, record, lines = self.resolve(client, fetch, *DENSE_FLAGS)+ self.assertEqual(plan.baseline["kind"], "official")+ self.assertEqual(plan.baseline["value"], 0.31411)+ self.assertEqual(record["status"], "found")+ self.assertEqual(lines, [f"official: ndcg_at_10 0.31411 from {plan.baseline['source']}"])+ self.assertEqual(record["detail"], lines[0].removeprefix("official: "))+ self.assertEqual(client.calls, [])+ self.assertEqual(client.info_calls, [MODEL])++ def test_a_miss_and_a_failure_keep_the_plan_and_say_so(self):+ for fetch, status, text in (+ (Failing("/contents/", NotFound("x")), "not_found", f"{MODEL} is not in"),+ (Failing("/commits/main", LookupFailed("HTTP 403 from api.github.com")), "failed", "HTTP 403"),+ (FakeGitHub({"rev-a": b"<html>"}), "failed", "not JSON"),+ ):+ with self.subTest(status=status):+ plan, record, lines = self.resolve(InfoClient(), fetch, *DENSE_FLAGS)+ self.assertIsNone(plan.baseline)+ self.assertEqual(record["status"], status)+ self.assertIn(text, record["detail"])+ self.assertEqual(+ lines,+ [f"official: none, {record['detail']}; the run reads MEASUREMENT unless you pass --baseline"],+ )++ def test_notes_when_the_revisions_differ(self):+ fetch = FakeGitHub({"rev-a": result_file(dataset_revision="other-dataset")})+ _, record, lines = self.resolve(InfoClient(revision="rev-served"), fetch, *DENSE_FLAGS)+ self.assertTrue(lines[0].startswith("official: ndcg_at_10 0.31411"))+ self.assertEqual(+ lines[1:],+ [+ "note: the official number is for model revision rev-a, the endpoint serves rev-served",+ f"note: the official number is for dataset revision other-dataset, this run uses {PINNED}",+ ],+ )+ self.assertEqual(record["status"], "found")+ self.assertIn("the endpoint serves rev-served", record["detail"])++ def test_no_note_when_they_agree_or_are_unknown(self):+ for client, body in (+ (InfoClient(), result_file()),+ (InfoClient(revision=None), result_file()),+ (InfoClient(info_error=RuntimeError("down")), result_file()),+ (InfoClient(), result_file(dataset_revision=None)),+ ):+ with self.subTest(info=client.info, error=client.info_error):+ _, _, lines = self.resolve(client, FakeGitHub({"rev-a": body}), *DENSE_FLAGS)+ self.assertEqual(len(lines), 1)++ def test_the_served_revision_picks_the_file(self):+ files = {"rev-a": result_file(0.1, version="1.0"), "rev-b": result_file(0.2, version="2.0")}+ plan, _, _ = self.resolve(InfoClient(revision="rev-a"), FakeGitHub(files), *DENSE_FLAGS)+ self.assertEqual(plan.baseline["value"], 0.1)++ def assert_skipped(self, client, flags, text):+ fetch = FakeGitHub()+ plan, record, lines = self.resolve(client, fetch, *flags)+ self.assertIsNone(plan.baseline)+ self.assertEqual(record["status"], "skipped")+ self.assertIn(text, record["detail"])+ self.assertEqual(fetch.urls, [])+ self.assertEqual(len(lines), 1)+ self.assertEqual(+ lines, [f"official: none, {record['detail']}; the run reads MEASUREMENT unless you pass --baseline"]+ )++ def test_a_limit_key_is_skipped_and_the_line_does_not_promise_a_baseline_helps(self):+ client = InfoClient()+ fetch = FakeGitHub()+ plan, record, lines = self.resolve(+ client,+ fetch,+ "--model",+ MODEL,+ "--task",+ "mteb/SciFact?limit=2",+ "--output",+ "dense",+ "--items-per-request",+ "2",+ )+ self.assertIsNone(plan.baseline)+ self.assertEqual(record["status"], "skipped")+ self.assertIn("limit", record["detail"])+ self.assertEqual(lines, [f"official: none, {record['detail']}; the run reads MEASUREMENT"])+ self.assertEqual((fetch.urls, client.info_calls), ([], []))++ def test_a_two_stage_key_is_skipped(self):+ client = InfoClient()+ key = "mteb/SciFact?candidates_model=org/encoder&candidates_k=2"+ self.assert_skipped(client, ("--model", "org/reranker", "--task", key), "retriever and reranker")+ self.assertEqual(client.info_calls, [])++ def test_a_profile_other_than_default_is_skipped(self):+ client = InfoClient()+ flags = ("--model", f"{MODEL}:sparse", *SPARSE_FLAGS[2:])+ self.assert_skipped(client, flags, "profile")+ self.assertEqual(client.info_calls, [])++ def test_a_non_dense_output_on_a_model_with_several_outputs_is_skipped(self):+ for flags, output in (+ (SPARSE_FLAGS, "sparse"),+ (SPARSE_FLAGS[:5] + ("multivector",) + SPARSE_FLAGS[6:], "multivector"),+ ):+ with self.subTest(output=output):+ client = InfoClient(outputs=("dense", "sparse", "multivector"))+ self.assert_skipped(+ client, flags, f"several outputs and the official number is for dense, not {output}"+ )++ def test_a_non_dense_output_is_skipped_when_the_outputs_are_unknown(self):+ for client in (+ InfoClient(info_error=RuntimeError("down")),+ InfoClient(outputs=None),+ InfoClient(outputs=()),+ ):+ with self.subTest(info=client.info, error=client.info_error):+ self.assert_skipped(client, SPARSE_FLAGS, "did not say what the model outputs")++ def test_a_model_with_one_output_is_looked_up_on_that_output(self):+ for outputs in (("sparse",), ("sparse", "score")):+ with self.subTest(outputs=outputs):+ plan, record, _ = self.resolve(InfoClient(outputs=outputs), FakeGitHub(), *SPARSE_FLAGS)+ self.assertEqual((plan.baseline["kind"], record["status"]), ("official", "found"))++ def test_a_dense_output_is_looked_up_whatever_the_model_exposes(self):+ for client in (+ InfoClient(outputs=("dense", "sparse", "multivector")),+ InfoClient(info_error=RuntimeError("down")),+ ):+ with self.subTest(info=client.info, error=client.info_error):+ plan, _, _ = self.resolve(client, FakeGitHub(), *DENSE_FLAGS)+ self.assertEqual(plan.baseline["kind"], "official")++ def test_a_score_task_is_looked_up_with_its_split_and_metric(self):+ fetch = FakeGitHub({"rev-a": result_file(0.6, split="dev", metric="map_at_1000")})+ plan, _, _ = self.resolve(+ InfoClient(outputs=("score",), info_error=RuntimeError("down")),+ fetch,+ "--model",+ MODEL,+ "--task",+ "mteb/T2Reranking",+ )+ self.assertEqual((plan.baseline["metric"], plan.baseline["value"]), ("map_at_1000", 0.6))++ def test_an_alias_looks_up_the_canonical_file(self):+ fetch = FakeGitHub()+ self.resolve(InfoClient(), fetch, "--model", MODEL, "--task", "mteb/CMedQAv1Reranking")+ self.assertTrue(fetch.urls[-1].endswith("/rev-a/CMedQAv1-reranking.json"))++ def test_a_supplied_baseline_wins_and_nothing_is_looked_up(self):+ client, fetch = InfoClient(), FakeGitHub()+ plan, record, lines = self.resolve(+ client, fetch, *DENSE_FLAGS, "--baseline", "ndcg_at_10=0.3", "--baseline-source", "a paper"+ )+ self.assertEqual(plan.baseline["kind"], "supplied")+ self.assertIsNone(record)+ self.assertEqual((lines, fetch.urls, client.info_calls), ([], [], []))++ def test_a_reference_run_looks_nothing_up(self):+ client, fetch = InfoClient(), FakeGitHub()+ plan, record, lines = self.resolve(client, fetch, "--reference", str(reference_file(self.directory)))+ self.assertEqual(plan.baseline["kind"], "published")+ self.assertIsNone(record)+ self.assertEqual((lines, fetch.urls, client.info_calls), ([], [], []))+++class OfficialRecordTest(TemporaryCase):+ def test_the_result_records_the_lookup_and_compares_with_the_number(self):+ record, _ = self.run_official(InfoClient(), FakeGitHub(), *DENSE_FLAGS)+ self.assertEqual(record["schema_version"], 1)+ self.assertEqual(record["official_lookup"]["status"], "found")+ self.assertEqual(record["baseline"]["kind"], "official")+ self.assertEqual(record["verdict"]["baseline"], 0.31411)+ self.assertEqual(record["verdict"]["metric"], "ndcg_at_10")+ self.assertIn(record["verdict"]["reason"], {"above_margin", "below_margin", "within_margin"})++ def test_a_miss_records_the_status_and_reads_measurement(self):+ record, _ = self.run_official(InfoClient(), Failing("/contents/", NotFound("x")), *DENSE_FLAGS)+ self.assertEqual(record["official_lookup"]["status"], "not_found")+ self.assertIsNone(record["baseline"])+ self.assertEqual((record["verdict"]["verdict"], record["verdict"]["reason"]), ("MEASUREMENT", "no_baseline"))++ def test_the_field_is_absent_beside_a_baseline_or_a_reference(self):+ supplied = (*DENSE_FLAGS, "--baseline", "ndcg_at_10=0.3", "--baseline-source", "a paper")+ record, _ = self.run_official(InfoClient(), FakeGitHub(), *supplied)+ self.assertNotIn("official_lookup", record)+ record, _ = self.run_official(InfoClient(), FakeGitHub(), "--reference", str(reference_file(self.directory)))+ self.assertNotIn("official_lookup", record)++ def test_the_command_repeats_the_run_and_does_not_gain_a_baseline(self):+ plan = plan_quality(parse(*DENSE_FLAGS))+ record, _ = self.run_official(InfoClient(), FakeGitHub(), *DENSE_FLAGS)+ self.assertNotIn("--baseline", record["run"]["command"])+ self.assertEqual(plan_quality(parse(*shlex.split(record["run"]["command"])[5:])), plan)++ def test_score_py_recomputes_the_verdict_from_the_stored_value_with_no_network(self):+ record, result_path = self.run_official(InfoClient(), FakeGitHub(), *DENSE_FLAGS)+ stdout = io.StringIO()+ with (+ patch("score.load_qrels", return_value=judged_qrels()),+ patch("official.urllib.request.urlopen", side_effect=NO_LOOKUP) as urlopen,+ contextlib.redirect_stdout(stdout),+ ):+ _, rows, _ = score.rescore(result_path)+ score.main([str(result_path), "--write"])+ urlopen.assert_not_called()+ self.assertEqual(rows, record["metrics"])+ self.assertEqual(recompute_verdict(record, rows), record["verdict"])+ self.assertIn(f"from {record['baseline']['source']}", stdout.getvalue())+ written = json.loads(result_path.read_text(encoding="utf-8"))+ self.assertEqual(written["official_lookup"], record["official_lookup"])+ self.assertEqual(written["baseline"], record["baseline"])+++class OfficialCommandTest(TemporaryCase):+ def main(self, client, fetch, *argv):+ stdout, stderr = io.StringIO(), io.StringIO()+ seen = []++ def first_encode(model, items, **kwargs):+ seen.append(stdout.getvalue())+ return DenseClient.encode(client, model, items, **kwargs)++ client.encode = first_encode+ code = None+ with (+ contextlib.chdir(self.directory),+ patch.dict("os.environ", {}, clear=True),+ patch.object(run, "load_quality_data", side_effect=lambda plan: load_quality_data(plan, tiny_loaders())),+ patch.object(run, "SIEClient") as factory,+ patch.object(run, "http_fetch", fetch),+ contextlib.redirect_stdout(stdout),+ contextlib.redirect_stderr(stderr),+ ):+ factory.return_value.__enter__.return_value = client+ try:+ run.main(["quality", *argv, "--endpoint", LOCAL])+ except SystemExit as caught:+ code = caught.code+ return code, stdout.getvalue().splitlines(), stderr.getvalue(), seen++ def test_the_line_is_printed_before_the_first_inference_request(self):+ code, lines, stderr, seen = self.main(InfoClient(revision="rev-b"), FakeGitHub(), *DENSE_FLAGS)+ self.assertIsNone(code)+ self.assertEqual(stderr, "")+ self.assertTrue(lines[0].startswith("official: ndcg_at_10 0.31411 from https://github.com/"))+ self.assertTrue(lines[1].startswith("note: the official number is for model revision rev-a"))+ self.assertIn("official: ndcg_at_10", seen[0])+ self.assertTrue(lines[-1].startswith("verdict: "))+ self.assertIn(" against 0.31411 from https://github.com/", lines[-1])++ def test_a_lookup_failure_does_not_block_the_run(self):+ fetch = Failing("/commits/main", TimeoutError("slow"))+ code, lines, _, _ = self.main(InfoClient(), fetch, *DENSE_FLAGS)+ self.assertIsNone(code)+ self.assertEqual(+ lines[0],+ "official: none, the lookup failed (TimeoutError); the run reads MEASUREMENT unless you pass --baseline",+ )+ self.assertEqual(lines[-1], "verdict: MEASUREMENT no baseline")++ def test_a_supplied_baseline_never_calls_the_fetch(self):+ fetch = FakeGitHub()+ _, lines, _, _ = self.main(+ InfoClient(), fetch, *DENSE_FLAGS, "--baseline", "recall_at_1=1", "--baseline-source", "s"+ )+ self.assertEqual(fetch.urls, [])+ self.assertFalse([line for line in lines if line.startswith("official:")])++ def test_a_reference_run_never_calls_the_fetch_and_has_no_new_output_or_field(self):+ fetch = FakeGitHub()+ reference = reference_file(self.directory)+ client = FakeClient()+ client.get_model = lambda model: self.fail("a reference run must not ask for the model")+ _, lines, _, _ = self.main(client, fetch, "--reference", str(reference))+ self.assertEqual(fetch.urls, [])+ self.assertFalse([line for line in lines if line.startswith(("official:", "note:"))])+ (result_path,) = (self.directory / "results").glob("*-????????T??????Z.json")+ self.assertNotIn("official_lookup", json.loads(result_path.read_text(encoding="utf-8")))+++if __name__ == "__main__":+ unittest.main()diff --git a/examples/evaluations/published-benchmarks/tests/test_quality.py b/examples/evaluations/published-benchmarks/tests/test_quality.pyindex 5c90c0625..f53a92fca 100644--- a/examples/evaluations/published-benchmarks/tests/test_quality.py+++ b/examples/evaluations/published-benchmarks/tests/test_quality.py@@ -622,8 +622,8 @@ class CommandTest(unittest.TestCase):self.reference = reference_file(self.temporary.name)def command(self, fake, *flags, environ=None):- def measured(plan, data, client):- return run_quality(plan, data, fake, results_dir=Path(self.temporary.name) / "results", now=clock)+ def measured(plan, data, client, **kwargs):+ return run_quality(plan, data, fake, results_dir=Path(self.temporary.name) / "results", now=clock, **kwargs)def loader(plan):return load_quality_data(plan, tiny_loaders())@@ -635,6 +635,7 @@ class CommandTest(unittest.TestCase):patch.object(run, "load_quality_data", side_effect=loader) as self.loader,patch.object(run, "run_quality", side_effect=measured),patch.object(run, "SIEClient") as client,+ patch.object(run, "http_fetch", side_effect=AssertionError("a reference run must not look anything up")),contextlib.redirect_stdout(stdout),contextlib.redirect_stderr(stderr),):diff --git a/examples/evaluations/published-benchmarks/tests/test_tasks.py b/examples/evaluations/published-benchmarks/tests/test_tasks.pynew file mode 100644index 000000000..83675afd6--- /dev/null+++ b/examples/evaluations/published-benchmarks/tests/test_tasks.py@@ -0,0 +1,764 @@+import contextlib+import io+import json+import shlex+import tempfile+import tomllib+import unittest+from dataclasses import replace+from pathlib import Path+from typing import ClassVar+from unittest.mock import patch++import numpy as np+import test_performance+from datasets import Dataset+from test_quality import FakeClient, clock, parse, reference_file, tiny_loaders+from test_verdict import DENSE_FLAGS, DENSE_VECTORS, DenseClient, TemporaryCase, judged_qrels++import run+import score+from run import (+ DEFAULT_ENDPOINT,+ Loaders,+ candidate_batches,+ load_performance_data,+ load_quality_data,+ plan_performance,+ plan_quality,+ run_performance,+ run_quality,+)+from score import eval_split, parse_task_key, recompute_verdict++EXAMPLE_DIR = Path(__file__).resolve().parent.parent+LOCAL = "http://localhost:8080"+NEW_TASKS = {+ "mteb/MMarcoReranking": (+ "mteb/MMarcoReranking",+ "91c0f9d5cbd4cdc7ecd7039c5c2e57740cb62b00",+ "dev",+ "score",+ "map_at_1000",+ ),+ "mteb/T2Reranking": ("mteb/T2Reranking", "a34fe6bc0dff185af1228e49a0f6fb1de1565627", "dev", "score", "map_at_1000"),+ "mteb/CMedQAv1-reranking": (+ "mteb/CMedQAv1-reranking",+ "f77f0345c9b6ac0a2447a3a71483d5b27393cb35",+ "test",+ "score",+ "map_at_1000",+ ),+ "mteb/CMedQAv2-reranking": (+ "mteb/CMedQAv2-reranking",+ "01399b6956a4c6bf9edc5b6b90e176aeeb399686",+ "test",+ "score",+ "map_at_1000",+ ),+ "mteb/NanoFiQA2018Retrieval": (+ "zeta-alpha-ai/NanoFiQA2018",+ "4163ba032953d5044a7a6244261413f609c14342",+ "train",+ "encode",+ "ndcg_at_10",+ ),+}+RERANK_TASKS = [task for task, entry in NEW_TASKS.items() if entry[3] == "score"]+TWO_STAGE = "mteb/SciFact?candidates_model=org/encoder&candidates_k=2"+RERANKER = ("--model", "org/reranker")+ENCODE_SHAPE = ("--output", "dense", "--items-per-request", "2")+++def corpus_of(count):+ return {f"d{index}": {"title": "", "text": f"doc {index}"} for index in range(count)}+++def many_candidates(count):+ return Loaders(+ corpus=lambda name, revision: corpus_of(count),+ queries=lambda name, revision: {"q1": "only query"},+ qrels=lambda name, revision: {"q1": {"d0": 1}},+ top_ranked=lambda name, revision: {"q1": [f"d{index}" for index in range(count)]},+ )+++class GeneratedClient(FakeClient):+ """Dense vectors from the text; documents with a low number sit closest to the query."""++ def _encode_item(self, item, output_types):+ number = 0.0 if item["text"] == "only query" else float(item["text"].split()[-1])+ return {"id": item["id"], "dense": np.asarray([1.0, number], dtype=np.float32)}+++class ReversingClient(DenseClient):+ """A reranker that scores the retriever's last candidate highest, so its order is visible."""++ def score(self, model, query, items, **kwargs):+ result = super().score(model, query, items, **kwargs)+ result["scores"] = [+ {"item_id": item["id"], "score": float(position + 1), "rank": len(items) - position}+ for position, item in enumerate(items)+ ]+ return result+++class ZeroClient(FakeClient):+ def __init__(self, zero=("document", "query"), **kwargs):+ super().__init__(**kwargs)+ self.zero = zero++ def encode(self, model, items, **kwargs):+ self.is_query = kwargs["is_query"]+ return super().encode(model, items, **kwargs)++ def _encode_item(self, item, output_types):+ role = "query" if self.is_query else "document"+ vector = [0.0, 0.0] if role in self.zero else DENSE_VECTORS[item["text"]]+ return {"id": item["id"], "dense": np.asarray(vector, dtype=np.float32)}+++class TaskTablesTest(unittest.TestCase):+ def test_the_tables_name_each_new_task(self):+ for task, (dataset, revision, split, operation, main) in NEW_TASKS.items():+ with self.subTest(task):+ self.assertEqual(score.HF_DATASETS[task], (dataset, revision))+ self.assertEqual(score.MAIN_SCORE[task], main)+ self.assertEqual(eval_split(task), split)+ self.assertEqual(task in run.SCORE_TASKS, operation == "score")++ def test_every_table_covers_the_same_tasks_and_older_tasks_stay_on_test(self):+ self.assertEqual(set(score.HF_DATASETS), set(score.MAIN_SCORE))+ self.assertEqual(set(score.HF_DATASETS), set(score.ROLE_SPLITS))+ for task in set(score.HF_DATASETS) - set(NEW_TASKS):+ self.assertEqual(eval_split(task), "test")++ def test_each_new_task_plans_with_its_operation_and_revision(self):+ for task, (_, revision, _, operation, _) in NEW_TASKS.items():+ with self.subTest(task):+ shape = ENCODE_SHAPE if operation == "encode" else ()+ plan = plan_quality(parse("--model", "m", "--task", task, *shape))+ self.assertEqual((plan.operation, plan.task_name, plan.revision), (operation, task, revision))++ def test_the_rerank_tasks_refuse_an_output(self):+ for task in RERANK_TASKS:+ with self.subTest(task), self.assertRaises(ValueError):+ plan_quality(parse("--model", "m", "--task", task, *ENCODE_SHAPE))+++class LoaderTest(unittest.TestCase):+ RERANK_ROWS: ClassVar[dict] = {+ "corpus": {"_id": ["d1"], "text": ["body"], "title": ["A"]},+ "queries": {"_id": ["q1"], "text": ["query"]},+ "default": {"query-id": ["q1"], "corpus-id": ["d1"], "score": [2]},+ "top_ranked": {"query-id": ["q1"], "corpus-ids": [["d1"]]},+ }++ def test_a_rerank_task_reads_every_role_from_its_own_split(self):+ rows = {config: Dataset.from_dict(columns) for config, columns in self.RERANK_ROWS.items()}+ for task in RERANK_TASKS:+ dataset, revision, split, _, _ = NEW_TASKS[task]+ with (+ self.subTest(task),+ patch("score.load_dataset", side_effect=lambda _, config, **__: rows[config]) as load,+ ):+ self.assertEqual(score.load_corpus(task, revision), {"d1": {"title": "A", "text": "body"}})+ self.assertEqual(score.load_queries(task, revision), {"q1": "query"})+ self.assertEqual(score.load_qrels(task, revision), {"q1": {"d1": 2}})+ self.assertEqual(score.load_top_ranked(task, revision), {"q1": ["d1"]})+ self.assertEqual(+ [(call.args, call.kwargs) for call in load.call_args_list],+ [+ ((dataset, config), {"split": split, "revision": revision})+ for config in ("corpus", "queries", "default", "top_ranked")+ ],+ )++ def test_nano_has_no_title_its_qrels_config_and_grade_one(self):+ task = "mteb/NanoFiQA2018Retrieval"+ dataset, revision, split, _, _ = NEW_TASKS[task]+ rows = {+ "corpus": Dataset.from_dict({"_id": ["d1", "d2"], "text": ["one", "two"]}),+ "queries": Dataset.from_dict({"_id": ["q1"], "text": ["query"]}),+ "qrels": Dataset.from_dict({"query-id": ["q1", "q1"], "corpus-id": ["d1", "d2"]}),+ }+ with patch("score.load_dataset", side_effect=lambda _, config, **__: rows[config]) as load:+ self.assertEqual(+ score.load_corpus(task, revision),+ {"d1": {"title": "", "text": "one"}, "d2": {"title": "", "text": "two"}},+ )+ self.assertEqual(score.load_queries(task, revision), {"q1": "query"})+ self.assertEqual(score.load_qrels(task, revision), {"q1": {"d1": 1, "d2": 1}})+ self.assertEqual(+ [(call.args, call.kwargs) for call in load.call_args_list],+ [((dataset, config), {"split": split, "revision": revision}) for config in ("corpus", "queries", "qrels")],+ )++ def test_a_split_named_by_a_result_still_wins(self):+ rows = Dataset.from_dict(self.RERANK_ROWS["default"])+ with patch("score.load_dataset", return_value=rows) as load:+ score.load_qrels("mteb/T2Reranking", "r", "other")+ self.assertEqual(load.call_args.kwargs["split"], "other")+++class EvalSplitRecordTest(TemporaryCase):+ def test_a_quality_result_names_the_task_split_and_score_py_reads_it(self):+ for task, split in (("mteb/T2Reranking", "dev"), ("mteb/CMedQAv1-reranking", "test")):+ with self.subTest(task):+ record, result_path = self.run_flags(FakeClient(), "--model", "m", "--task", task)+ self.assertEqual(record["dataset"]["subset"], split)+ self.assertEqual(record["verdict"]["metric"], "main_score")+ with patch("score.load_qrels", return_value=judged_qrels()) as loader:+ _, rows, _ = score.rescore(result_path)+ loader.assert_called_once_with(task, NEW_TASKS[task][1], split)+ self.assertEqual(rows, record["metrics"])++ def test_nano_runs_as_an_encode_task_on_its_split(self):+ record, _ = self.run_flags(DenseClient(), "--model", "m", "--task", "mteb/NanoFiQA2018Retrieval", *ENCODE_SHAPE)+ self.assertEqual(record["dataset"]["subset"], "train")+ self.assertEqual(record["operation"], "encode")+ self.assertTrue(record["validity"]["valid"])++ def perf(self, key, *flags):+ return plan_performance(test_performance.parse("--model", "m", "--task", key, "--rate", "1", *flags))++ def test_the_performance_path_takes_the_task_split_and_records_it(self):+ plan = self.perf("mteb/T2Reranking?split=dev&limit=2&candidates-k=2", "--duration", "1", "--warmup", "0")+ plan = replace(plan, duration_s=0.1, settle_s=0.0, drain_s=0.0, rate=20.0)+ data = load_performance_data(plan, test_performance.tiny_loaders())+ record, _ = run_performance(+ plan, data, test_performance.FakeClient(), results_dir=self.directory / "results", now=clock+ )+ self.assertEqual(record["dataset"]["subset"], "dev")++ def test_the_performance_path_refuses_another_split(self):+ for key, split in (("mteb/T2Reranking?split=test", "dev"), ("mteb/SciFact?split=dev", "test")):+ with self.subTest(key), self.assertRaisesRegex(ValueError, f"only split={split} is available"):+ self.perf(+ key, *(() if key.startswith("mteb/T2") else ("--output", "dense", "--items-per-request", "1"))+ )++ def test_a_performance_score_request_stays_within_the_item_cap(self):+ with self.assertRaisesRegex(ValueError, "candidates-k must be at most 100"):+ self.perf("mteb/MMarcoReranking?split=dev&limit=1&candidates-k=101")+ plan = self.perf("mteb/MMarcoReranking?split=dev&limit=1")+ data = load_performance_data(plan, many_candidates(250))+ self.assertEqual(len(data.payloads[0][1]), 100)+ plan = self.perf("mteb/MMarcoReranking?split=dev&limit=1&candidates-k=100")+ self.assertEqual(len(load_performance_data(plan, many_candidates(250)).payloads[0][1]), 100)+++class AliasTest(TemporaryCase):+ ALIASES: ClassVar[dict] = {+ "mteb/CMedQAv1Reranking": "mteb/CMedQAv1-reranking",+ "mteb/CMedQAv2Reranking": "mteb/CMedQAv2-reranking",+ }++ def test_parse_normalises_and_keeps_the_parameters(self):+ for alias, canonical in self.ALIASES.items():+ with self.subTest(alias):+ self.assertEqual(parse_task_key(f"{alias}?limit=3"), (canonical, {"limit": "3"}))++ def test_the_users_key_stays_in_task_key_and_the_dataset_is_the_canonical_one(self):+ for alias, canonical in self.ALIASES.items():+ with self.subTest(alias):+ record, result_path = self.run_flags(FakeClient(), "--model", "m", "--task", alias)+ self.assertEqual(record["task_key"], alias)+ self.assertEqual(record["dataset"]["name"], canonical)+ self.assertEqual(record["dataset"]["revision"], score.HF_DATASETS[canonical][1])+ self.assertIn(alias, record["run"]["command"])+ with patch("score.load_qrels", return_value=judged_qrels()) as loader:+ _, rows, _ = score.rescore(result_path)+ loader.assert_called_once_with(canonical, score.HF_DATASETS[canonical][1], "test")+ self.assertEqual(rows, record["metrics"])++ def test_the_command_rebuilds_the_same_plan(self):+ plan = plan_quality(parse("--model", "m", "--task", "mteb/CMedQAv1Reranking"))+ self.assertEqual(plan_quality(parse(*shlex.split(run.quality_command_line(plan))[5:])), plan)++ def test_a_performance_key_takes_an_alias_too(self):+ plan = plan_performance(+ test_performance.parse("--model", "m", "--task", "mteb/CMedQAv2Reranking?limit=2", "--rate", "1")+ )+ self.assertEqual((plan.task_key, plan.task_name), ("mteb/CMedQAv2Reranking?limit=2", "mteb/CMedQAv2-reranking"))+++class CandidateSplitTest(unittest.TestCase):+ def run_rerank(self, client, count, task="mteb/MMarcoReranking"):+ plan = plan_quality(parse("--model", "m", "--task", task))+ data = load_quality_data(plan, many_candidates(count))+ with tempfile.TemporaryDirectory() as temporary:+ record, _ = run_quality(plan, data, client, results_dir=Path(temporary) / "results", now=clock)+ path = record["run"]["predictions_path"]+ predictions = json.loads(Path(path).read_text(encoding="utf-8")) if path else None+ return record, predictions++ def test_the_batches_keep_order_and_the_cap(self):+ ids = [str(index) for index in range(250)]+ batches = candidate_batches(ids)+ self.assertEqual([len(batch) for batch in batches], [100, 100, 50])+ self.assertEqual([item for batch in batches for item in batch], ids)+ self.assertEqual([len(batch) for batch in candidate_batches(ids[:100])], [100])+ self.assertEqual(candidate_batches([]), [])++ def test_a_query_is_split_and_its_scores_are_merged(self):+ client = FakeClient()+ record, predictions = self.run_rerank(client, 250)+ readiness, *measured = client.calls+ self.assertEqual(len(readiness[2][1]), 100)+ self.assertTrue(readiness[3]["wait_for_capacity"])+ self.assertEqual([len(call[2][1]) for call in measured], [100, 100, 50])+ self.assertEqual({call[2][0]["text"] for call in measured}, {"only query"})+ self.assertEqual(len(predictions["q1"]), 250)+ self.assertEqual(record["run"]["request_count"], 3)+ self.assertEqual(record["payload"]["items_per_request"], 100)++ def test_twenty_candidates_stay_one_request(self):+ client = FakeClient()+ record, predictions = self.run_rerank(client, 20, "mteb/AskUbuntuDupQuestions")+ self.assertEqual([len(call[2][1]) for call in client.calls], [20, 20])+ self.assertEqual(record["payload"]["items_per_request"], 20)+ self.assertEqual(len(predictions["q1"]), 20)++ def test_exactly_one_hundred_is_one_request(self):+ client = FakeClient()+ self.run_rerank(client, 100)+ self.assertEqual([len(call[2][1]) for call in client.calls], [100, 100])++ def test_a_failure_in_a_later_batch_is_a_failed_run(self):+ record, predictions = self.run_rerank(FakeClient(fail_at=2), 250)+ self.assertIsNone(predictions)+ self.assertEqual(record["validity"]["reasons"], ["request failed: RuntimeError: boom"])+ self.assertEqual((record["run"]["request_count"], record["run"]["failure_count"]), (2, 1))++ def test_a_batch_that_answers_with_other_ids_is_a_failed_run(self):+ class OtherIds(FakeClient):+ def score(self, model, query, items, **kwargs):+ result = super().score(model, query, items, **kwargs)+ if len(self.calls) == 3:+ result["scores"][0]["item_id"] = "d0"+ return result++ record, predictions = self.run_rerank(OtherIds(), 250)+ self.assertIsNone(predictions)+ self.assertIn("differ from the candidates", record["validity"]["reasons"][0])+++class TwoStagePlanTest(TemporaryCase):+ def test_a_key_plans_a_score_run_with_the_encoder_and_k(self):+ plan = plan_quality(parse(*RERANKER, "--task", TWO_STAGE))+ self.assertEqual((plan.operation, plan.output_contract, plan.items_per_request), ("score", "scores", None))+ self.assertEqual((plan.candidates_model, plan.candidates_k), ("org/encoder", 2))+ self.assertEqual((plan.route, plan.task_name), ("org/reranker", "mteb/SciFact"))+ self.assertEqual(plan.comparable_reasons, ["no reference"])+ self.assertIsNone(plan.baseline)++ def test_limit_goes_with_it_and_keeps_its_meaning(self):+ plan = plan_quality(parse(*RERANKER, "--task", f"{TWO_STAGE}&limit=2"))+ self.assertEqual(plan.task_params["limit"], "2")+ self.assertEqual(plan.comparable_reasons, ["no reference", f"smoke key {TWO_STAGE}&limit=2"])++ def test_every_encode_task_takes_it(self):+ for task in set(score.HF_DATASETS) - run.SCORE_TASKS:+ with self.subTest(task):+ key = f"{task}?candidates_model=org/encoder&candidates_k=5"+ self.assertEqual(plan_quality(parse(*RERANKER, "--task", key)).candidates_k, 5)++ def test_the_command_rebuilds_the_same_plan(self):+ for flags in (+ ("--task", TWO_STAGE),+ ("--task", f"{TWO_STAGE}&limit=2", "--endpoint", LOCAL),+ ("--task", TWO_STAGE, "--baseline", "ndcg_at_10=0.3", "--baseline-source", "the page"),+ ):+ with self.subTest(flags=flags):+ plan = plan_quality(parse(*RERANKER, *flags))+ self.assertEqual(plan_quality(parse(*shlex.split(run.quality_command_line(plan))[5:])), plan)++ def test_bad_forms_exit_2_before_any_request(self):+ for key, message in (+ ("mteb/SciFact?candidates_model=org/encoder", "go together"),+ ("mteb/SciFact?candidates_k=5", "go together"),+ ("mteb/SciFact?candidates_model=org/encoder&candidates_k=0", "candidates_k must be a positive integer"),+ ("mteb/SciFact?candidates_model=org/encoder&candidates_k=-1", "candidates_k must be a positive integer"),+ ("mteb/SciFact?candidates_model=org/encoder&candidates_k=abc", "candidates_k must be a positive integer"),+ ("mteb/SciFact?candidates_model=org/encoder&candidates_k=", "candidates_k must be a positive integer"),+ ("mteb/SciFact?candidates_model=org/encoder&candidates_k=1.5", "candidates_k must be a positive integer"),+ ("mteb/SciFact?candidates_model=&candidates_k=5", "plain <org>/<name>"),+ ("mteb/SciFact?candidates_model=noslash&candidates_k=5", "plain <org>/<name>"),+ ("mteb/SciFact?candidates_model=org/encoder:muvera&candidates_k=5", "plain <org>/<name>"),+ ("mteb/SciFact?candidates_model=org/a%20b&candidates_k=5", "plain <org>/<name>"),+ ("mteb/SciFact?candidates_model=org/encoder&candidates_k=5&candidates_k=6", "repeats a parameter"),+ ("mteb/SciFact?candidates_model=org/encoder&candidates_k=5&limit=0", "limit must be a positive integer"),+ ("mteb/SciFact?candidates_model=org/encoder&candidates_k=5&split=test", "takes only limit, got split"),+ (+ "mteb/AskUbuntuDupQuestions?candidates_model=org/encoder&candidates_k=5",+ "mteb/AskUbuntuDupQuestions is a score task",+ ),+ ("mteb/T2Reranking?candidates_model=org/encoder&candidates_k=5", "mteb/T2Reranking is a score task"),+ ):+ with self.subTest(key):+ self.assertIn(message, self.refused("quality", *RERANKER, "--task", key, "--endpoint", LOCAL))++ def test_the_fixed_flags_are_refused(self):+ for flags, message in (+ (("--output", "dense"), "--output and --items-per-request are not accepted"),+ (("--items-per-request", "2"), "--output and --items-per-request are not accepted"),+ (("--instruction", "x"), "--instruction is not accepted"),+ ):+ with self.subTest(flags=flags):+ stderr = self.refused("quality", *RERANKER, "--task", TWO_STAGE, "--endpoint", LOCAL, *flags)+ self.assertIn(message, stderr)++ def test_a_reference_run_and_a_performance_run_refuse_the_key(self):+ reference = reference_file(self.directory)+ self.assertIn("--task must equal", self.refused("quality", "--reference", str(reference), "--task", TWO_STAGE))+ stderr = self.refused(+ "performance",+ *RERANKER,+ "--task",+ TWO_STAGE,+ "--rate",+ "1",+ "--output",+ "dense",+ "--items-per-request",+ "1",+ "--endpoint",+ LOCAL,+ )+ self.assertIn("got candidates_k, candidates_model", stderr)+++class TwoStageRunTest(TemporaryCase):+ def run_key(self, client, key=TWO_STAGE, *flags):+ return self.run_flags(client, *RERANKER, "--task", key, *flags)++ def predictions(self, record):+ return json.loads(Path(record["run"]["predictions_path"]).read_text(encoding="utf-8"))++ def test_readiness_for_both_models_then_encode_then_score(self):+ client = DenseClient()+ self.run_key(client)+ encoder_ready, reranker_ready, *measured = client.calls+ self.assertEqual((encoder_ready[0], encoder_ready[1]), ("encode", "org/encoder"))+ self.assertTrue(encoder_ready[3]["wait_for_capacity"])+ self.assertEqual(encoder_ready[3]["output_types"], ["dense"])+ self.assertFalse(encoder_ready[3]["is_query"])+ self.assertEqual((reranker_ready[0], reranker_ready[1]), ("score", "org/reranker"))+ self.assertTrue(reranker_ready[3]["wait_for_capacity"])+ self.assertEqual(reranker_ready[2][0], {"text": "first query"})+ self.assertEqual([item["id"] for item in reranker_ready[2][1]], ["d1", "d2"])+ self.assertEqual([call[0] for call in measured], ["encode", "encode", "score", "score", "score"])+ documents, queries = measured[:2]+ self.assertEqual([item["id"] for item in documents[2]], ["d1", "d2", "d3", "d4", "d5"])+ self.assertEqual(documents[2][0]["text"], "Alpha alpha body")+ self.assertFalse(documents[3]["is_query"])+ self.assertEqual([item["id"] for item in queries[2]], ["q1", "q2", "q3"])+ self.assertTrue(queries[3]["is_query"])+ for call in (documents, queries):+ self.assertEqual(call[1], "org/encoder")+ self.assertEqual(call[3]["output_types"], ["dense"])+ self.assertNotIn("instruction", call[3])+ self.assertFalse(call[3]["wait_for_capacity"])+ self.assertEqual(call[3]["max_oom_retries"], 0)++ def test_only_the_top_k_by_cosine_reach_the_reranker_and_its_scores_rank_them(self):+ client = ReversingClient()+ record, _ = self.run_key(client)+ sent = [(call[2][0]["text"], [item["id"] for item in call[2][1]]) for call in client.calls[-3:]]+ self.assertEqual(+ sent,+ [("first query", ["d2", "d1"]), ("second query", ["d3", "d4"]), ("third query", ["d1", "d4"])],+ )+ self.assertEqual({call[1] for call in client.calls[-3:]}, {"org/reranker"})+ self.assertEqual(+ self.predictions(record),+ {"q1": {"d2": 1.0, "d1": 2.0}, "q2": {"d3": 1.0, "d4": 2.0}, "q3": {"d1": 1.0, "d4": 2.0}},+ )+ metrics = {row["name"]: row["value"] for row in record["metrics"]}+ self.assertEqual(metrics["mrr_at_1"], 1.0 / 3.0)+ self.assertEqual(metrics["main_score"], metrics["ndcg_at_10"])++ def test_ties_keep_corpus_order(self):+ client = DenseClient()+ self.run_key(client, "mteb/SciFact?candidates_model=org/encoder&candidates_k=4")+ self.assertEqual([item["id"] for item in client.calls[-1][2][1]], ["d1", "d4", "d2", "d3"])++ def test_the_encoder_batches_are_64_and_a_long_candidate_list_is_split(self):+ client = GeneratedClient()+ plan = plan_quality(parse(*RERANKER, "--task", "mteb/SciFact?candidates_model=org/encoder&candidates_k=150"))+ record, _ = run_quality(+ plan,+ load_quality_data(plan, many_candidates(250)),+ client,+ results_dir=self.directory / "results",+ now=clock,+ )+ self.assertEqual(len(client.calls[0][2]), 64)+ self.assertEqual(len(client.calls[1][2][1]), 100)+ encodes = [len(call[2]) for call in client.calls[2:] if call[0] == "encode"]+ self.assertEqual(encodes, [64, 64, 64, 58, 1])+ self.assertEqual([len(call[2][1]) for call in client.calls[2:] if call[0] == "score"], [100, 50])+ self.assertEqual(len(self.predictions(record)["q1"]), 150)+ self.assertEqual(record["payload"]["items_per_request"], 100)+ self.assertEqual(record["run"]["request_count"], 7)++ def test_a_k_larger_than_the_corpus_sends_the_corpus(self):+ record, _ = self.run_key(DenseClient(), "mteb/SciFact?candidates_model=org/encoder&candidates_k=999")+ self.assertEqual(len(self.predictions(record)["q1"]), 5)+ self.assertEqual(record["payload"]["items_per_request"], 5)++ def test_the_record_names_the_encoder_and_k_and_reads_measurement(self):+ record, _ = self.run_key(DenseClient())+ self.assertEqual(+ record["payload"],+ {+ "items_per_request": 2,+ "output_contract": "scores",+ "parameters": [+ {"name": "candidates_model", "value": "org/encoder"},+ {"name": "candidates_k", "value": 2},+ ],+ },+ )+ self.assertEqual(record["operation"], "score")+ self.assertEqual(record["task_key"], TWO_STAGE)+ self.assertEqual((record["verdict"]["verdict"], record["verdict"]["reason"]), ("MEASUREMENT", "no_baseline"))+ self.assertIsNone(record["baseline"])+ self.assertNotIn("--output", record["run"]["command"])++ def test_a_baseline_is_compared(self):+ record, _ = self.run_key(DenseClient(), TWO_STAGE, "--baseline", "recall_at_1=0.9", "--baseline-source", "page")+ self.assertEqual(record["baseline"]["kind"], "supplied")+ self.assertEqual(record["verdict"]["metric"], "recall_at_1")+ self.assertIn(record["verdict"]["reason"], {"below_margin", "within_margin", "above_margin"})++ def test_a_limit_scores_the_first_queries_and_is_a_measurement_even_with_a_baseline(self):+ client = DenseClient()+ record, _ = self.run_key(+ client, f"{TWO_STAGE}&limit=1", "--baseline", "recall_at_1=0.9", "--baseline-source", "page"+ )+ self.assertEqual(list(self.predictions(record)), ["q1"])+ self.assertEqual([item["id"] for item in client.calls[3][2]], ["q1"])+ self.assertEqual(record["verdict"]["reason"], "limited_run")++ def test_two_models_are_not_a_revision_change(self):+ client = DenseClient(revisions=("encoder-rev",) * 4 + ("reranker-rev",) * 3)+ record, _ = self.run_key(client)+ self.assertEqual(record["execution_revisions"], ["encoder-rev", "reranker-rev"])+ self.assertEqual(record["comparable_reasons"], ["no reference"])++ def test_a_change_inside_one_model_is_a_revision_change(self):+ for revisions in (+ ("rev", "rev", "encoder-1", "encoder-2", "reranker", "reranker", "reranker"),+ ("rev", "rev", "encoder", "encoder", "reranker-1", "reranker-2", "reranker-2"),+ ):+ with self.subTest(revisions=revisions):+ record, _ = self.run_key(DenseClient(revisions=revisions))+ self.assertEqual(record["comparable_reasons"], ["no reference", "execution revision changed"])++ def test_a_failure_at_each_stage_is_a_failed_run(self):+ for fail_at, reason, request_count in (+ (0, "readiness request failed: RuntimeError: boom", 0),+ (1, "readiness request failed: RuntimeError: boom", 0),+ (2, "request failed: RuntimeError: boom", 1),+ (3, "request failed: RuntimeError: boom", 2),+ (4, "request failed: RuntimeError: boom", 3),+ ):+ with self.subTest(fail_at=fail_at):+ record, _ = self.run_key(DenseClient(fail_at=fail_at))+ self.assertIsNone(record["run"]["predictions_path"])+ self.assertEqual(record["validity"]["reasons"], [reason])+ self.assertEqual(record["run"]["request_count"], request_count)+ self.assertEqual(record["verdict"]["reason"], "no_predictions")++ def test_an_sdk_retry_in_either_stage_invalidates_the_run(self):+ for retries in ((0, 0, 1), (0, 0, 0, 0, 1)):+ with self.subTest(retries=retries):+ record, _ = self.run_key(DenseClient(retries=retries))+ self.assertFalse(record["validity"]["valid"])+ self.assertEqual(record["validity"]["reasons"], ["sdk retries 1"])++ def test_score_py_recomputes_from_the_predictions_file(self):+ for key, flags in (+ (TWO_STAGE, ()),+ (TWO_STAGE, ("--baseline", "recall_at_1=0.9", "--baseline-source", "page")),+ (f"{TWO_STAGE}&limit=2", ()),+ ):+ with self.subTest(key=key, flags=flags):+ record, result_path = self.run_key(DenseClient(), key, *flags)+ with patch("score.load_qrels", return_value=judged_qrels()) as loader:+ _, rows, _ = score.rescore(result_path)+ loader.assert_called_once_with("mteb/SciFact", score.HF_DATASETS["mteb/SciFact"][1], "test")+ self.assertEqual(rows, record["metrics"])+ self.assertEqual(recompute_verdict(record, rows), record["verdict"])++ def test_an_encoder_that_returns_only_zeros_is_a_failed_run(self):+ record, _ = self.run_key(ZeroClient())+ self.assertIsNone(record["run"]["predictions_path"])+ self.assertIn("all zeros", record["validity"]["reasons"][0])+++class PerformanceKeyTest(TemporaryCase):+ def test_an_unknown_parameter_exits_2_before_any_request(self):+ shape = ("--output", "dense", "--items-per-request", "1")+ for key, parameter in (+ ("mteb/SciFact?Limit=5", "Limit"),+ ("mteb/SciFact?limit=5&foo=1", "foo"),+ ("mteb/SciFact?candidates_k=5", "candidates_k"),+ ):+ with self.subTest(key):+ stderr = self.refused(+ "performance", "--model", "m", "--task", key, "--rate", "1", *shape, "--endpoint", LOCAL+ )+ self.assertIn(f"got {parameter}", stderr)+ stderr = self.refused(+ "performance",+ "--model",+ "m",+ "--task",+ "mteb/AskUbuntuDupQuestions?Limit=5",+ "--rate",+ "1",+ "--endpoint",+ LOCAL,+ )+ self.assertIn("got Limit", stderr)++ def test_a_reference_with_an_unknown_parameter_exits_2(self):+ reference = test_performance.reference_file(self.directory, task_key="mteb/SciFact?Limit=5")+ self.assertIn("got Limit", self.refused("performance", "--reference", str(reference), "--endpoint", LOCAL))++ def test_every_committed_performance_reference_still_plans(self):+ paths = sorted((EXAMPLE_DIR / "references").glob("*-perf-*.json"))+ self.assertEqual(len(paths), 6)+ for path in paths:+ with self.subTest(path.name):+ plan_performance(test_performance.parse("--reference", str(path)))+++class CredentialsInOutputTest(TemporaryCase):+ SECRET = "s3cret"++ def command_stderr(self, environ, *argv):+ stderr = io.StringIO()+ with (+ patch.dict("os.environ", environ, clear=True),+ patch.object(run, "load_quality_data", side_effect=lambda plan: load_quality_data(plan, tiny_loaders())),+ patch.object(run, "load_performance_data"),+ patch.object(run, "run_quality", side_effect=SystemExit(0)),+ patch.object(run, "run_performance", side_effect=SystemExit(0)),+ patch.object(run, "SIEClient"),+ patch.object(run, "http_fetch", side_effect=ConnectionError),+ contextlib.redirect_stdout(io.StringIO()),+ contextlib.redirect_stderr(stderr),+ self.assertRaises(SystemExit),+ ):+ run.main(list(argv))+ return stderr.getvalue()++ def note(self, base_url):+ return self.command_stderr(+ {"SIE_API_KEY": "key", "SIE_BASE_URL": base_url},+ "quality",+ *DENSE_FLAGS,+ "--baseline",+ "ndcg_at_10=0.3",+ "--baseline-source",+ "s",+ "--endpoint",+ LOCAL,+ )++ def test_the_note_drops_credentials_from_the_base_url(self):+ stderr = self.note(f"https://user:{self.SECRET}@example.test:8443/base?token={self.SECRET}")+ self.assertNotIn(self.SECRET, stderr)+ self.assertNotIn("user", stderr)+ self.assertIn("scoped to https://example.test:8443/base and was not sent", stderr)++ def test_an_unparseable_base_url_is_not_echoed(self):+ for base_url in (+ f"http://user:{self.SECRET}@[bad",+ f"http://user:{self.SECRET}@[bad]:80",+ f"http://user:{self.SECRET}@host:port",+ f"user:{self.SECRET}@host:8080",+ f"ftp://user:{self.SECRET}@host",+ f"{self.SECRET}",+ ):+ with self.subTest(base_url=base_url):+ stderr = self.note(base_url)+ self.assertNotIn(self.SECRET, stderr)+ self.assertIn("an SIE_BASE_URL that is not an http(s) URL", stderr)++ def test_an_odd_endpoint_is_not_echoed(self):+ for endpoint in (+ f"http://user:{self.SECRET}@[bad",+ f"http://user:{self.SECRET}@[bad]:80",+ f"http://user:{self.SECRET}@[{self.SECRET}]",+ f"http://user:{self.SECRET}@host:port",+ f"user:{self.SECRET}@host:8080",+ f"ftp://user:{self.SECRET}@host",+ f"http://user:{self.SECRET}@:8080",+ f"http://user:{self.SECRET}@host:0",+ ):+ for command in (+ ("quality", *DENSE_FLAGS),+ ("performance", "--model", "m", "--task", "mteb/AskUbuntuDupQuestions", "--rate", "1"),+ ):+ with self.subTest(endpoint=endpoint, command=command[0]):+ stderr = self.refused(*command, f"--endpoint={endpoint}")+ self.assertNotIn(self.SECRET, stderr)+ self.assertIn("endpoint must be an http(s) URL", stderr)++ def test_the_default_endpoint_error_is_unchanged(self):+ stderr = self.command_stderr(+ {}, "quality", *DENSE_FLAGS, "--baseline", "ndcg_at_10=0.3", "--baseline-source", "s"+ )+ self.assertIn(f"SIE_API_KEY must be set in the environment for {DEFAULT_ENDPOINT}", stderr)+++class ZeroVectorTest(TemporaryCase):+ def test_all_zero_vectors_are_a_failed_run_on_either_side(self):+ for zero, role in ((("document", "query"), "document"), (("document",), "document"), (("query",), "query")):+ with self.subTest(zero=zero):+ record, _ = self.run_flags(ZeroClient(zero), *DENSE_FLAGS)+ self.assertFalse(record["validity"]["valid"])+ self.assertEqual(+ record["validity"]["reasons"],+ [f"request failed: ValueError: every returned dense {role} vector is all zeros"],+ )+ self.assertIsNone(record["run"]["predictions_path"])+ self.assertEqual(record["metrics"], [])+ self.assertEqual(+ (record["verdict"]["verdict"], record["verdict"]["reason"]), ("FAIL (no-output)", "no_predictions")+ )++ def test_a_few_zero_vectors_are_left_alone(self):+ class OneZero(DenseClient):+ def _encode_item(self, item, output_types):+ result = super()._encode_item(item, output_types)+ if item["text"] == "gamma body":+ result["dense"] = np.zeros(2, dtype=np.float32)+ return result++ record, _ = self.run_flags(OneZero(), *DENSE_FLAGS)+ self.assertTrue(record["validity"]["valid"])+ self.assertIsNotNone(record["run"]["predictions_path"])++ def test_the_command_exits_1_and_names_it(self):+ code, stdout, stderr = self.command(+ ZeroClient(), *DENSE_FLAGS, "--baseline", "ndcg_at_10=0.3", "--baseline-source", "s", "--endpoint", LOCAL+ )+ self.assertEqual(code, 1)+ self.assertIn("verdict: FAIL (no-output) no predictions", stdout)+ self.assertIn("invalid: request failed: ValueError: every returned dense document vector is all zeros", stderr)+++class ProjectDescriptionTest(unittest.TestCase):+ def test_the_description_says_it_also_tests_a_new_model(self):+ project = tomllib.loads((EXAMPLE_DIR / "pyproject.toml").read_text(encoding="utf-8"))["project"]+ self.assertIn("test a new model", project["description"])+++if __name__ == "__main__":+ unittest.main()diff --git a/examples/evaluations/published-benchmarks/tests/test_verdict.py b/examples/evaluations/published-benchmarks/tests/test_verdict.pyindex a88e98aa1..91aadcb4b 100644--- a/examples/evaluations/published-benchmarks/tests/test_verdict.py+++ b/examples/evaluations/published-benchmarks/tests/test_verdict.py@@ -16,6 +16,7 @@ from test_quality import FakeClient, clock, parse, reference_file, tiny_loadersimport runimport score+from official import NotFoundfrom run import (DEFAULT_ENDPOINT,Loaders,@@ -103,8 +104,8 @@ class TemporaryCase(unittest.TestCase):return run_quality(plan, data, client, results_dir=self.directory / "results", now=clock)def command(self, fake, *argv):- def measured(plan, data, client):- return run_quality(plan, data, fake, results_dir=self.directory / "results", now=clock)+ def measured(plan, data, client, **kwargs):+ return run_quality(plan, data, fake, results_dir=self.directory / "results", now=clock, **kwargs)def loader(plan):return load_quality_data(plan, tiny_loaders())@@ -116,6 +117,7 @@ class TemporaryCase(unittest.TestCase):patch.object(run, "load_quality_data", side_effect=loader),patch.object(run, "run_quality", side_effect=measured),patch.object(run, "SIEClient"),+ patch.object(run, "http_fetch", side_effect=NotFound),contextlib.redirect_stdout(stdout),contextlib.redirect_stderr(stderr),):@@ -1065,5 +1067,33 @@ class IdenticalIdsTest(TemporaryCase):self.assertEqual(rows, record["metrics"])+# A pinned table, so the band stays the one the 2% rule on the method page describes.+VERDICT_TABLE = (+ (0.5, 0.5, "PASS", "within_margin"),+ (0.5, 0.4901, "PASS", "within_margin"),+ (0.5, 0.4899, "FAIL (regression)", "below_margin"),+ (0.5, 0.5102, "PASS", "within_margin"),+ (0.5, 0.5103, "WARN (suspicious-improvement)", "above_margin"),+ (0.5, 0.0, "FAIL (no-output)", "current_zero"),+ (0.31411, 0.3079, "PASS", "within_margin"),+ (0.31411, 0.3078, "FAIL (regression)", "below_margin"),+ (0.59526, 0.61433, "WARN (suspicious-improvement)", "above_margin"),+)+++class TestVerdictTable(unittest.TestCase):+ def test_every_row(self):+ for baseline, current, label, reason in VERDICT_TABLE:+ with self.subTest(baseline=baseline, current=current):+ verdict = compute_verdict(+ {"ndcg_at_10": current},+ {"kind": "supplied", "metric": "ndcg_at_10", "value": baseline, "source": "table"},+ limited=False,+ )+ self.assertEqual((verdict["verdict"], verdict["reason"]), (label, reason))+ self.assertEqual(verdict["threshold_low"], baseline * 0.98)+ self.assertEqual(verdict["threshold_high"], baseline / 0.98)++if __name__ == "__main__":unittest.main()