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): test a new model against an official number (#898)
Shai Shmuel3d62c0a81823
diff --git a/examples/README.md b/examples/README.mdindex 983c4f830..f71f2f0ce 100644--- a/examples/README.md+++ b/examples/README.md@@ -38,7 +38,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 benchmark numbers](./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 | `encode`, `score` | SIE Cloud with an SIE API key for a run, which spends credits; `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 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 71cdfa714..dbd00b249 100644--- a/examples/evaluations/published-benchmarks/README.md+++ b/examples/evaluations/published-benchmarks/README.md@@ -1,16 +1,21 @@-# Repeat the published benchmark numbers--This example repeats the method behind the benchmark numbers published on the-SIE website, six quality records and six fixed-rate performance records, from-one client process on your machine. 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 shape, the timing constants and-the published metrics. `run.py quality` sends the same requests through-`sie_sdk.SIEClient`, ranks in the client, scores the ranking with `pytrec_eval`-and writes one record-shaped result with the delta against every published-metric. `run.py performance` sends a record's requests at its published rate-and aggregates their timing the way the record did. Both print deltas and-never a verdict: no threshold, no pass, no fail.+# Repeat the published benchmarks or test a new model++This example does two things from one client process on your machine. It+repeats 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).++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+shape, the timing constants and the published metrics. `run.py quality` sends+the same requests through `sie_sdk.SIEClient`, ranks in the client, scores the+ranking with `pytrec_eval` and writes one record-shaped result with the delta+against every published metric. `run.py performance` sends a record's requests+at its published rate and aggregates their timing the way the record did. Both+print deltas. A quality run also prints a [verdict](#the-verdict) against a+baseline; a performance run has none. The verdict never changes the exit+status, and the example has no floor, target or gate.## Quality@@ -58,9 +63,11 @@ With `--reference`, model, profile, task, output contract, items per requestand 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` are-required; `--output sparse|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.+required; `--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).When a result is not valid, the command prints each reason to stderr.@@ -72,7 +79,10 @@ in `validity.reasons`:`comparable` with its reasons, the model, profile and task, the dataset nameand revision, the request shape, the observed `execution_revisions`, therun's request and failure counts, `validity` with the SDK retry count, every- recomputed metric and a `comparison` row per published metric with the delta.+ recomputed metric, a `comparison` row per published metric with the delta,+ the `baseline` and `verdict`, and `run.command`, the command that repeats the+ run. It is rebuilt from the plan, so credentials in a URL never reach the+ result.- `results/<id>-<utc>.predictions.json`: the ranked list per query, the top1000 documents with their scores, or the reranker's 20 candidates per query.Every metric is recomputed from this file.@@ -87,8 +97,11 @@ uv run python score.py results/<id>-<utc>.jsonpredictions file, loads the relevance judgements from the pinned datasetrevision named in the result with `datasets` (network or the local HuggingFace cache), recomputes every metric and prints each one beside the published-value and the delta. It rewrites nothing unless you pass `--write`, which-updates `metrics` and `comparison` in the result in place.+value and the delta, then recomputes the verdict from the result's `baseline`+and those metrics. A result with no `baseline` field, written before the+verdict existed, prints no verdict. It rewrites nothing unless you pass+`--write`, which updates `metrics`, `comparison` and `verdict` in the result in+place.### What is fixed by the method@@ -103,10 +116,14 @@ the example applies them to every run:- requests are sequential, one in flight, with no warmup beyond thatreadiness request;- documents are encoded with `is_query=False` in batches of the reference's- items per request, queries with `is_query=True`, and no instruction is sent;-- sparse vectors are scored by the raw dot product, multivector outputs by- MaxSim over L2-normalised token rows, and the reranker's own scores rank its- candidates;+ items per request, queries with `is_query=True`, and no instruction is sent+ unless `--instruction` gives one, which goes with queries only;+- sparse vectors are scored by the raw dot product, dense vectors by cosine+ over L2-normalised vectors, multivector outputs by MaxSim over L2-normalised+ token rows, and the reranker's own scores rank its candidates. A `muvera`+ profile is refused with `--output dense` on a quality run, because the+ published method scores those vectors by the similarity the profile declares,+ usually the raw dot product, and this example scores dense only by cosine;- the top 1000 documents per query are kept, ties broken by corpus order, andscored at k in 1, 3, 5, 10, 20, 100 and 1000 with pytrec_eval's `ndcg_cut`,`map_cut`, `recall` and `P`, rounded to five decimals; the published method@@ -138,10 +155,49 @@ reason `execution revision changed`. A self-hosted sie-server reacheddirectly sends no revision, so `execution_revisions` stays empty and thatcheck cannot fire there.-A delta is a number, not a result. The maintainers read a quality delta-against a 2% band when they decide whether a published number still holds;-that band is their reading policy, and this tool never prints it, nor any pass-threshold or quality floor.+A delta is a number. On a `--reference` run the [verdict](#the-verdict) reads+one number, `main_score`, against the 2% band the maintainers use when they decide whether+a published number still holds. It does not need `comparable: true`: a run+against another endpoint keeps `comparable: false` with its reason and still+gets a verdict.++### The verdict++After 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:++| Case | Verdict | Reason |+| --- | --- | --- |+| The run wrote no predictions | `FAIL (no-output)` | `no_predictions` |+| The metric is exactly 0 | `FAIL (no-output)` | `current_zero` |+| No baseline | `MEASUREMENT` | `no_baseline` |+| A task key with `limit` | `MEASUREMENT` | `limited_run` |+| Below the low bound | `FAIL (regression)` | `below_margin` |+| Above the high bound | `WARN (suspicious-improvement)` | `above_margin` |+| Otherwise | `PASS` | `within_margin` |++The line names the metric, its value, the baseline and where it comes from, the+difference in percent and the band. A `FAIL` also prints `expected:`, `got:`+and `reproduce:` lines on stdout. A `WARN` means the run scored above the band:+a real improvement, or a run that does not measure what the baseline measured.++One published reference reads `WARN` today. A full run of the Qwen3-Reranker-0.6B+quality record scores about 3% above its 0.59526, because that record predates the+server change that scores this reranker in float32 so its top candidates stop+tying. The 4B record stays inside the band.++The verdict is a report. The exit status does not follow it: the command exits+0 on a `FAIL (regression)` and 1 only when the run wrote no predictions. Nothing+it writes reaches the website or a published record, and it is no floor, target+or 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`.## Performance@@ -179,8 +235,8 @@ the record's published level, `--duration` to 60 and `--warmup` to 30,reference adds a `comparable_reasons` entry. Without a reference, `--model`,`--task` and `--rate` are required, `--output` and `--items-per-request` arerequired for the encode tasks and refused for the score task, and the timeout-and cap are 30 s and 64 for encode, 300 s and 128 for score. No other flags-exist.+and cap are 30 s and 64 for encode, 300 s and 128 for score. `--output` takes+`sparse`, `dense` or `multivector`. No other flags exist.### What is fixed by the method@@ -201,8 +257,8 @@ exist.a connection pool twice the cap; after every call the SDK's retry count isread and written on the request's row;- selection by the task key: `filter=nonempty` drops rows whose text is empty- after stripping whitespace; `role=corpus` takes the documents, queries- otherwise; the remaining rows are ordered by source id compared as strings+ after 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 stringsand `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-nativecandidates in source order; the chosen ids go to `dataset.selected_ids` in@@ -222,7 +278,8 @@ exist.Beside the quality envelope, the result carries `load_level_name`, `schedule`with the one level that ran, `timing` as in the reference, `run.requests_path`-and `validity`. The metrics use the record's names and aggregations:+and `validity`, and it has no `baseline` or `verdict`. The metrics use the+record's names and aggregations:`offered_requests_per_second` is the level rate; `achieved_requests_per_second`counts successes completed inside the duration window (60 s in the records)and `eventual_achieved_requests_per_second` all successes, each divided by@@ -321,7 +378,8 @@ What to expect:same pinned model revision should land in the same band as the publishednumbers, within numeric precision;- the smoke run above scores 20 queries, so its metrics are a check that the- path works, not a comparison with the record;+ path works, not a comparison with the record, and its verdict is+ `MEASUREMENT`;- performance numbers describe your hardware and your network path and arenot comparable with the record;- `execution_revisions` stays empty, because a sie-server reached directly@@ -332,6 +390,117 @@ On an Apple Silicon laptop with the Splade NFCorpus quality smoke, the serverwas ready in about half a minute, the cold model load took about 80 s, and a20-query smoke took about 30 s once warm.+## Test a new model++Before you open a pull request that adds a model, measure it against an+official number.++1. **Add the model config.** Add a YAML file to `packages/sie_server/models/`+ in your checkout, modelled on a neighbour. Its `sie_id` is the name you pass+ to `--model`.+2. **Serve it** with sie-server, from the root of the checkout:++ ```sh+ mise run serve -- --host 127.0.0.1 -m your-org/your-model+ ```++ The same rules as in+ [Run it against your own server](#run-it-against-your-own-server) apply: no+ key unless the server runs in token mode, and the first request loads the+ model.+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:++ ```sh+ uv run python run.py quality \+ --model your-org/your-model \+ --task mteb/NFCorpus \+ --output dense \+ --items-per-request 32 \+ --baseline ndcg_at_10=<official value> \+ --baseline-source "<link to the model card, paper or leaderboard>" \+ --endpoint http://localhost:8080+ ```++5. **Read the verdict**, the `verdict:` line after the metrics, in the table+ under [The verdict](#the-verdict). On a `FAIL`, `reproduce:` is the command+ that repeats the run.+6. **Attach the result**, `results/<id>-<utc>.json`, to the pull request. It+ holds the baseline with its source, the verdict and `run.command`. Keep the+ `.predictions.json` beside it: `score.py` needs that file to recompute the+ verdict.++### 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 ratio, finite, above 0 and at most 1, so a leaderboard that prints percent+needs dividing by 100. A bad form exits 2 before any request, and both flags are+refused beside `--reference`, which brings its own baseline.++Without a baseline the run still writes every metric, and the verdict is+`MEASUREMENT`, unless the run produced nothing to compare.++### The instruction trap++Some models expect a task instruction in the query, and their official number+was measured with it. The tool cannot detect this, because the models endpoint+does not expose a query template. Read `query_template` in the model's config:++- when it has an `{instruction}` placeholder, pass the instruction the official+ number used with `--instruction "<text>"`. Without the flag the query carries+ only what the config supplies by default, so a low score can be this mismatch+ and not the model;+- otherwise leave the flag off. A model with no query template can get the text+ 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.++### The limited-run rule++A task key with `limit`, such as `mteb/NFCorpus?limit=50`, scores part of the+queries, so its number cannot be compared with a full-dataset number. The+verdict is `MEASUREMENT` whatever the baseline says, unless the run produced+nothing to compare: `limited run, not compared with a full-dataset number`. Use it to check that the+path works, then run the key without `limit` to get a verdict. It still encodes+every document.++### Task keys++Each key is pinned to the dataset revision mteb 2.7.5 names; the revisions are+in `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` |++`mteb/FiQA2018` sets mteb's `ignore_identical_ids`: a document whose id equals+the query's id is removed from that query's ranking after the top-1000 cut and+before 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`.+## Validation`validation/` holds the example's own output from 2026-11-03: three@@ -461,7 +630,7 @@ The tests use a fake client, in-memory datasets and the committed## Not in this example- no publication path: nothing here writes to the website or to the published- records, and no floor, target, threshold or gate;+ records, 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 calibrationdiff --git a/examples/evaluations/published-benchmarks/run.py b/examples/evaluations/published-benchmarks/run.pyindex 385fab367..a7fcb13a6 100644--- a/examples/evaluations/published-benchmarks/run.py+++ b/examples/evaluations/published-benchmarks/run.py@@ -1,4 +1,4 @@-"""Repeat the method behind the published benchmark numbers from one client process."""+"""Repeat the published benchmark numbers, or test a new model the same way, from one client process."""import argparseimport contextlib@@ -7,6 +7,7 @@ import mathimport osimport platformimport re+import shleximport sysimport threadingimport time@@ -17,7 +18,7 @@ from datetime import UTC, datetimefrom fractions import Fractionfrom pathlib import Pathfrom typing import Any-from urllib.parse import urlsplit+from urllib.parse import urlsplit, urlunsplitimport httpximport numpy as np@@ -26,15 +27,19 @@ from scipy.sparse import csr_matrixfrom sie_sdk import SIEClientfrom score import (+ BASELINE_METRICS,HF_DATASETS,NS_PER_MS,NS_PER_S,PERFORMANCE_MODE,+ PRIMARY_METRIC,SCORER_ID,Qrels,Rows,compare,+ compute_verdict,format_rows,+ format_verdict,load_corpus,load_qrels,load_queries,@@ -55,9 +60,11 @@ DEFAULT_TIMEOUT_S = 300.0TOP_K = 1000DOCUMENT_CHUNK = 500QUERY_TOKEN_ROWS = 256+COSINE_NORM_FLOOR = 1e-12RESULTS_DIR = Path("results")SCORE_TASKS = frozenset({"mteb/AskUbuntuDupQuestions"})-ENCODE_OUTPUTS = ("sparse", "multivector")+ENCODE_OUTPUTS = ("sparse", "dense", "multivector")+MUVERA_PROFILE = "muvera"REFERENCE_KIND = "published-benchmark-reference"RESULT_KIND = "published-benchmark-reproduction"PERFORMANCE_LIMITS = {"encode": (30.0, 64), "score": (300.0, 128)}@@ -69,6 +76,7 @@ DEFAULT_READINESS_TIMEOUT_S = 300.0DEFAULT_LAG_TOLERANCE_MS = 20.0RETRY_POLICY = {"backoff": "none", "max_attempts": 1, "record_attempts": True}ROLES = ("queries", "corpus")+COMMAND_PREFIX = ("uv", "run", "python", "run.py")Corpus = dict[str, dict[str, str]]Queries = dict[str, str]@@ -98,6 +106,8 @@ class QualityPlan:endpoint: strmodel_version: str | Nonecomparable_reasons: list[str]+ baseline: dict[str, Any] | None = None+ instruction: str | None = None@propertydef route(self) -> str:@@ -196,8 +206,11 @@ 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="Repeat a published quality measurement")+ quality = commands.add_parser("quality", help="Measure quality against a published record 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")+ quality.add_argument("--instruction", help="Instruction sent with queries only, on encode tasks")performance = commands.add_parser("performance", help="Repeat a published fixed-rate performance measurement")_add_shared_arguments(performance)performance.add_argument("--rate", type=float, help="Requests per second; the reference's published level")@@ -267,10 +280,15 @@ def _resolve_api_key(parser: argparse.ArgumentParser, endpoint: str) -> str:return api_key+def _without_credentials(url: str) -> str:+ parts = urlsplit(url)+ return urlunsplit((parts.scheme, parts.netloc.rpartition("@")[2], parts.path, "", ""))++def _endpoint_reasons(endpoint: str) -> list[str]:if _endpoint_key(endpoint) == _endpoint_key(DEFAULT_ENDPOINT):return []- return [f"endpoint {endpoint} != {DEFAULT_ENDPOINT}"]+ return [f"endpoint {_without_credentials(endpoint)} != {DEFAULT_ENDPOINT}"]def _check_limit(params: Mapping[str, str]) -> None:@@ -337,6 +355,58 @@ 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+ if args.baseline is None or args.baseline_source is None or not args.baseline_source.strip():+ raise ValueError("--baseline and --baseline-source go together")+ if not args.baseline_source.isprintable():+ raise ValueError("--baseline-source must be one line of printable text")+ metric, _, value = args.baseline.partition("=")+ if metric not in BASELINE_METRICS:+ raise ValueError(f"--baseline names {metric!r}; known metrics: {', '.join(sorted(BASELINE_METRICS))}")+ try:+ parsed = float(value)+ except ValueError:+ raise ValueError(f"--baseline must be <metric>=<value>, got {args.baseline!r}") from None+ return {+ "kind": "supplied",+ "metric": metric,+ "value": _checked_baseline_value(parsed),+ "source": args.baseline_source,+ }+++def _published_baseline(reference: Mapping[str, Any]) -> dict[str, Any]:+ for row in reference["metrics"]:+ if row["name"] == PRIMARY_METRIC:+ return {+ "kind": "published",+ "metric": PRIMARY_METRIC,+ "value": _checked_baseline_value(float(row["value"])),+ "source": reference["reference_id"],+ }+ raise ValueError(f"the reference has no {PRIMARY_METRIC} metric")+++def _checked_instruction(args: argparse.Namespace, operation: str) -> str | None:+ if args.instruction is None:+ return None+ if operation == "score":+ raise ValueError("--instruction is not accepted for the score task")+ if not args.instruction.strip():+ raise ValueError("--instruction must not be empty")+ if not args.instruction.isprintable():+ raise ValueError("--instruction must be one line of printable text")+ return args.instruction++def _override(value: float | None, fixed: float, label: str, reasons: list[str]) -> float:if value is None or value == fixed:return fixed@@ -348,6 +418,13 @@ def _plan_from_reference(args: argparse.Namespace, reference: Mapping[str, Any])if reference.get("kind") != REFERENCE_KIND or reference.get("evaluation_mode") != "quality":raise ValueError("--reference must name a quality published-benchmark-reference file")_refuse_fixed_flags(args)+ for flag, value in (+ ("--baseline", args.baseline),+ ("--baseline-source", args.baseline_source),+ ("--instruction", args.instruction),+ ):+ if value is not None:+ raise ValueError(f"{flag} cannot be combined with --reference")reference_id = _plain_reference_id(reference)task_key = reference["task_key"]task_name, params = parse_task_key(task_key)@@ -377,6 +454,7 @@ def _plan_from_reference(args: argparse.Namespace, reference: Mapping[str, Any])endpoint=normalize_endpoint(args.endpoint),model_version=reference["model_version"],comparable_reasons=reasons,+ baseline=_published_baseline(reference),)@@ -384,10 +462,20 @@ 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"})+ if other_params:+ raise ValueError(f"a quality task key takes only limit, got {', '.join(other_params)}")_check_limit(params)model, _, profile = args.model.partition(":")operation = "score" if task_name in SCORE_TASKS else "encode"_check_output_flags(args, operation)+ if args.output == "dense" and profile.casefold() == MUVERA_PROFILE:+ raise ValueError(+ "--output dense is refused for a muvera profile: the published method scores these vectors by the "+ "similarity the profile declares, usually the raw dot product, and this example scores dense only by cosine"+ )+ baseline = _supplied_baseline(args)+ instruction = _checked_instruction(args, operation)reasons = ["no reference"]if "limit" in params:reasons.append(f"smoke key {args.task}")@@ -408,6 +496,8 @@ def _plan_from_flags(args: argparse.Namespace) -> QualityPlan:endpoint=normalize_endpoint(args.endpoint),model_version=None,comparable_reasons=reasons,+ baseline=baseline,+ instruction=instruction,)@@ -572,7 +662,8 @@ def load_performance_data(plan: PerformancePlan, loaders: Loaders | None = None)selected, [{"id": doc_id, "text": performance_text(corpus[doc_id])} for doc_id in selected])queries = loaders.queries(plan.task_name, plan.revision)- selected = select_ids(queries, params)+ judged = loaders.qrels(plan.task_name, plan.revision)+ selected = select_ids({query_id: text for query_id, text in queries.items() if query_id in judged}, params)return PerformanceData(selected, [{"id": query_id, "text": queries[query_id]} for query_id in selected])@@ -753,6 +844,7 @@ def encode_texts(size = plan.items_per_request or 0if size < 1:raise ValueError("encode tasks need a positive items_per_request")+ instruction = {"instruction": plan.instruction} if is_query and plan.instruction is not None else {}results: list[Any] = []for start in range(0, len(texts), size):batch_ids, batch_texts = ids[start : start + size], texts[start : start + size]@@ -768,6 +860,7 @@ def encode_texts(wait_for_capacity=False,provision_timeout_s=plan.request_timeout_s,max_oom_retries=0,+ **instruction,)if len(batch) != len(items):raise ValueError("encode returned a different number of results than items sent")@@ -800,14 +893,27 @@ def sparse_scores(queries: Sequence[Mapping[str, Any]], documents: Sequence[Mappreturn (sparse_matrix(queries, columns) @ sparse_matrix(documents, columns).T).toarray().astype(np.float32)-def normalized_rows(vectors: Any) -> np.ndarray:+def _rows_and_norms(vectors: Any) -> tuple[np.ndarray, np.ndarray]:rows = np.asarray(vectors, dtype=np.float32)if rows.ndim != 2 or rows.shape[0] == 0:- raise ValueError("a multivector needs at least one token row")- norms = np.linalg.norm(rows, axis=1, keepdims=True)+ raise ValueError("expected a non-empty two-dimensional array of vectors")+ return rows, np.linalg.norm(rows, axis=1, keepdims=True)+++def normalized_rows(vectors: Any) -> np.ndarray:+ rows, norms = _rows_and_norms(vectors)return rows / np.where(norms > 0, norms, 1.0)+def _cosine_rows(vectors: Any) -> np.ndarray:+ rows, norms = _rows_and_norms(vectors)+ return rows / np.maximum(norms, COSINE_NORM_FLOOR)+++def dense_scores(queries: Sequence[Any], documents: Sequence[Any]) -> np.ndarray:+ return _cosine_rows(queries) @ _cosine_rows(documents).T++def _query_groups(query_rows: Sequence[np.ndarray]) -> list[tuple[int, int]]:groups: list[tuple[int, int]] = []start, rows = 0, 0@@ -860,6 +966,8 @@ def encode_predictions(client: Any, plan: QualityPlan, data: QualityData, log: Cqueries = encode_texts(client, plan, query_ids, [data.queries[q] for q in query_ids], log, is_query=True)if 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])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)@@ -901,6 +1009,41 @@ def _slug(route: str, task_key: str) -> str:return re.sub(r"[^A-Za-z0-9._-]+", "-", f"{route}-{task_key}").strip("-")+def _common_flags(plan: QualityPlan | PerformancePlan) -> list[str]:+ flags = ["--model", plan.route, "--task", plan.task_key]+ if plan.operation == "encode":+ flags += ["--output", plan.output_contract, "--items-per-request", str(plan.items_per_request)]+ return flags+++def _endpoint_flags(endpoint: str) -> list[str]:+ return [] if endpoint == DEFAULT_ENDPOINT else ["--endpoint", endpoint]+++def quality_command_line(plan: QualityPlan) -> str:+ if plan.reference_id is not None:+ flags = ["--reference", f"references/{plan.reference_id}.json"]+ if "limit" in plan.task_params:+ flags += ["--task", plan.task_key]+ else:+ flags = _common_flags(plan)+ if plan.baseline is not None:+ 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:+ flags.append(f"--instruction={plan.instruction}")+ return shlex.join([*COMMAND_PREFIX, "quality", *flags, *_endpoint_flags(plan.endpoint)])+++def performance_command_line(plan: PerformancePlan) -> str:+ if plan.reference_id is not None:+ flags = ["--reference", f"references/{plan.reference_id}.json"]+ else:+ flags = _common_flags(plan)+ flags += ["--rate", str(plan.rate), "--duration", str(plan.duration_s), "--warmup", str(plan.warmup_s)]+ return shlex.join([*COMMAND_PREFIX, "performance", *flags, *_endpoint_flags(plan.endpoint)])++def comparison_basis(reference_id: str | None, comparable: bool, reasons: Sequence[str]) -> str | None:if reference_id is None:return None@@ -953,7 +1096,7 @@ def build_record("payload": {"items_per_request": plan.items_per_request or max(candidate_counts, default=0),"output_contract": plan.output_contract,- "parameters": [],+ "parameters": [{"name": "instruction", "value": plan.instruction}] if plan.instruction is not None else [],},"client": {"description": client_description(), "worker_count": 1, "processes_per_worker": 1},"scorer": {"id": SCORER_ID, "version": scorer_version(), "reference_scorer_matched": False},@@ -964,11 +1107,16 @@ def build_record("request_count": log.request_count,"failure_count": log.failure_count,"predictions_path": str(predictions_path) if predictions_path is not None else None,+ "command": quality_command_line(plan),},"validity": {"valid": not validity_reasons, "reasons": validity_reasons, "sdk_retries": log.sdk_retries},"metrics": rows,"comparison": compare(rows, plan.reference_metrics) if plan.reference_id is not None else [],"comparison_basis": comparison_basis(plan.reference_id, comparable, reasons),+ "baseline": plan.baseline,+ "verdict": compute_verdict(+ {row["name"]: row["value"] for row in rows}, plan.baseline, limited="limit" in plan.task_params+ ),}@@ -1060,6 +1208,7 @@ def build_performance_record("request_count": log.request_count,"failure_count": log.failure_count,"requests_path": str(requests_path) if requests_path is not None else None,+ "command": performance_command_line(plan),},"validity": performance_validity(plan, dispatcher, {row["name"]: row["value"] for row in rows}),"metrics": rows,@@ -1163,6 +1312,8 @@ def quality_command(parser: argparse.ArgumentParser, args: argparse.Namespace) -print(result_path)for line in format_rows(record["metrics"], record["comparison"]):print(line)+ for line in format_verdict(record["verdict"], record["baseline"], record["run"]["command"]):+ print(line)report_invalid(record)if record["run"]["predictions_path"] is None:raise SystemExit(1)diff --git a/examples/evaluations/published-benchmarks/score.py b/examples/evaluations/published-benchmarks/score.pyindex 2bc1c5949..9bdb0715c 100644--- a/examples/evaluations/published-benchmarks/score.py+++ b/examples/evaluations/published-benchmarks/score.py@@ -1,4 +1,4 @@-"""Recompute the published metrics from a result's predictions or requests file and print the deltas."""+"""Recompute a result's metrics from its predictions or requests file; print the deltas and any verdict."""import argparseimport importlib.metadata@@ -18,17 +18,39 @@ HF_DATASETS = {"mteb/SciFact": ("mteb/scifact", "d56462d0e63a25450459c4f213e49ffdb866f7f9"),"mteb/NFCorpus": ("mteb/nfcorpus", "ec0fa4fe99da2ff19ca1214b7966684033a58814"),"mteb/AskUbuntuDupQuestions": ("mteb/AskUbuntuDupQuestions", "c5691e3c48741d5f83b5cc8e630653d7a8cfc048"),+ "mteb/FiQA2018": ("mteb/fiqa", "27a168819829fe9bcd655c2df245fb19452e8e06"),+ "mteb/SCIDOCS": ("mteb/scidocs", "f8c2fcf00f625baaa80f62ec5bd9e1fff3b8ae88"),+ "mteb/CQADupstackPhysicsRetrieval": ("mteb/cqadupstack-physics", "79531abbd1fb92d06c6d6315a0cbbbf5bb247ea4"),+ "mteb/CosQA": ("CoIR-Retrieval/cosqa", "bc5efb7e9d437246ce393ed19d772e08e4a79535"),+ "mteb/StackOverflowQA": ("CoIR-Retrieval/stackoverflow-qa", "db8f169f3894c14a00251061f957b2063eef2bd5"),+ "mteb/LegalBenchConsumerContractsQA": (+ "mteb/legalbench_consumer_contracts_qa",+ "b23590301ec94e8087e2850b21d43d4956b1cca9",+ ),}MAIN_SCORE = {"mteb/SciFact": "ndcg_at_10","mteb/NFCorpus": "ndcg_at_10","mteb/AskUbuntuDupQuestions": "map_at_1000",+ "mteb/FiQA2018": "ndcg_at_10",+ "mteb/SCIDOCS": "ndcg_at_10",+ "mteb/CQADupstackPhysicsRetrieval": "ndcg_at_10",+ "mteb/CosQA": "ndcg_at_10",+ "mteb/StackOverflowQA": "ndcg_at_10",+ "mteb/LegalBenchConsumerContractsQA": "ndcg_at_10",}ROLE_SPLITS = {"mteb/SciFact": {"corpus": "corpus", "queries": "queries"},"mteb/NFCorpus": {"corpus": "corpus", "queries": "queries"},"mteb/AskUbuntuDupQuestions": {"corpus": "test", "queries": "test"},+ "mteb/FiQA2018": {"corpus": "corpus", "queries": "queries"},+ "mteb/SCIDOCS": {"corpus": "corpus", "queries": "queries"},+ "mteb/CQADupstackPhysicsRetrieval": {"corpus": "corpus", "queries": "queries"},+ "mteb/CosQA": {"corpus": "corpus", "queries": "queries"},+ "mteb/StackOverflowQA": {"corpus": "corpus", "queries": "queries"},+ "mteb/LegalBenchConsumerContractsQA": {"corpus": "corpus", "queries": "queries"},}+IGNORE_IDENTICAL_IDS = frozenset({"mteb/FiQA2018"})METRIC_UNIT = "ratio"AGGREGATION = "task_native"SCORER_ID = "pytrec-eval"@@ -50,6 +72,20 @@ PERFORMANCE_METRICS = {LATENCY_PERCENTILES = (50, 95, 99)NS_PER_S = 1_000_000_000NS_PER_MS = 1_000_000+PRIMARY_METRIC = "main_score"+BASELINE_METRICS = frozenset(+ {+ PRIMARY_METRIC,+ "accuracy",+ *(f"{family}_at_{k}" for family in ("ndcg", "map", "recall", "precision", "mrr") for k in K_VALUES),+ }+)+DEFAULT_MARGIN = 0.98+VERDICT_PASS = "PASS"+VERDICT_FAIL_REGRESSION = "FAIL (regression)"+VERDICT_FAIL_NO_OUTPUT = "FAIL (no-output)"+VERDICT_WARN_IMPROVEMENT = "WARN (suspicious-improvement)"+VERDICT_MEASUREMENT = "MEASUREMENT"Qrels = dict[str, dict[str, int]]Predictions = Mapping[str, Mapping[str, float]]@@ -141,6 +177,11 @@ def retrieval_metrics(predictions: Predictions, qrels: Qrels) -> dict[str, floatdef task_metrics(predictions: Predictions, qrels: Qrels, task_name: str) -> dict[str, float]:+ if task_name in IGNORE_IDENTICAL_IDS:+ predictions = {+ query_id: {doc_id: value for doc_id, value in doc_scores.items() if doc_id != query_id}+ for query_id, doc_scores in predictions.items()+ }metrics = retrieval_metrics(predictions, qrels)metrics["main_score"] = metrics[MAIN_SCORE[task_name]]return metrics@@ -232,6 +273,75 @@ def format_rows(rows: Sequence[Mapping[str, Any]], comparison: Sequence[Mapping[return lines+def compute_verdict(+ metrics: Mapping[str, float],+ baseline: Mapping[str, Any] | None,+ *,+ limited: bool,+ margin: float = DEFAULT_MARGIN,+) -> dict[str, Any]:+ out: dict[str, Any] = {+ "metric": PRIMARY_METRIC if baseline is None else baseline["metric"],+ "current": None,+ "baseline": None,+ "delta_pct": None,+ "threshold_low": None,+ "threshold_high": None,+ "margin": margin,+ }+ compared = None if limited else baseline+ if compared is not None:+ out["baseline"] = compared["value"]+ out["threshold_low"] = compared["value"] * margin+ out["threshold_high"] = compared["value"] / margin+ if not metrics:+ return {"verdict": VERDICT_FAIL_NO_OUTPUT, "reason": "no_predictions", **out}+ current = out["current"] = metrics[out["metric"]]+ if compared is not None:+ out["delta_pct"] = (current - compared["value"]) / compared["value"] * 100.0+ if current == 0.0:+ return {"verdict": VERDICT_FAIL_NO_OUTPUT, "reason": "current_zero", **out}+ if baseline is None:+ return {"verdict": VERDICT_MEASUREMENT, "reason": "no_baseline", **out}+ if limited:+ return {"verdict": VERDICT_MEASUREMENT, "reason": "limited_run", **out}+ if current < out["threshold_low"]:+ return {"verdict": VERDICT_FAIL_REGRESSION, "reason": "below_margin", **out}+ if current > out["threshold_high"]:+ return {"verdict": VERDICT_WARN_IMPROVEMENT, "reason": "above_margin", **out}+ return {"verdict": VERDICT_PASS, "reason": "within_margin", **out}+++def format_verdict(verdict: Mapping[str, Any], baseline: Mapping[str, Any] | None, command: str) -> list[str]:+ label, reason, metric = verdict["verdict"], verdict["reason"], verdict["metric"]+ if reason == "no_baseline":+ return [f"verdict: {label} no baseline"]+ if reason == "limited_run":+ return [f"verdict: {label} limited run, not compared with a full-dataset number"]+ current, value = verdict["current"], verdict["baseline"]+ band = f"{verdict['threshold_low']:.5f} to {verdict['threshold_high']:.5f}" if value is not None else ""+ source = baseline["source"] if baseline is not None else ""+ if reason == "no_predictions":+ lines = [f"verdict: {label} no predictions"]+ elif reason == "current_zero":+ lines = [f"verdict: {label} {metric} is exactly 0"]+ else:+ delta = f"{verdict['delta_pct']:+.2f}%"+ lines = [f"verdict: {label} {metric} {current:.5f} against {value:.5f} from {source} ({delta}, band {band})"]+ if label in {VERDICT_FAIL_REGRESSION, VERDICT_FAIL_NO_OUTPUT}:+ expected = f"{metric} above 0" if value is None else f"{metric} from {band}, {value:.5f} from {source}"+ got = "no predictions" if current is None else f"{metric} {current:.5f}"+ lines += [f"expected: {expected}", f"got: {got}", f"reproduce: {command}"]+ return lines+++def recompute_verdict(record: Mapping[str, Any], rows: Sequence[Mapping[str, Any]]) -> dict[str, Any] | None:+ if "baseline" not in record:+ return None+ _, params = parse_task_key(record["task_key"])+ return compute_verdict({row["name"]: row["value"] for row in rows}, record["baseline"], limited="limit" in params)++def scoped_qrels(qrels: Qrels, predictions: Predictions, params: Mapping[str, str]) -> Qrels:if "limit" not in params:return qrels@@ -296,7 +406,9 @@ def rescore(result_path: Path) -> tuple[dict[str, Any], Rows, Rows]:def main(argv: Sequence[str] | None = None) -> None:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("result", type=Path, help="A results/<id>-<utc>.json file written by run.py")- parser.add_argument("--write", action="store_true", help="Update metrics and comparison in the result file")+ parser.add_argument(+ "--write", action="store_true", help="Update metrics, comparison and verdict in the result file"+ )args = parser.parse_args(argv)try:record, rows, comparison = rescore(args.result)@@ -304,9 +416,15 @@ def main(argv: Sequence[str] | None = None) -> None:parser.error(str(exc))for line in format_rows(rows, comparison):print(line)+ verdict = recompute_verdict(record, rows)+ if verdict is not None:+ for line in format_verdict(verdict, record["baseline"], record["run"]["command"]):+ print(line)if args.write:record["metrics"] = rowsrecord["comparison"] = comparison+ if verdict is not None:+ record["verdict"] = verdictwrite_json(args.result, record)diff --git a/examples/evaluations/published-benchmarks/tests/test_performance.py b/examples/evaluations/published-benchmarks/tests/test_performance.pyindex ad7e59caf..91bb63306 100644--- a/examples/evaluations/published-benchmarks/tests/test_performance.py+++ b/examples/evaluations/published-benchmarks/tests/test_performance.py@@ -136,7 +136,7 @@ def tiny_loaders():return Loaders(corpus=lambda name, revision: {doc_id: dict(doc) for doc_id, doc in CORPUS.items()},queries=lambda name, revision: dict(QUERIES),- qrels=lambda name, revision: {},+ qrels=lambda name, revision: {query_id: {"9": 1} for query_id in QUERIES},top_ranked=lambda name, revision: {query_id: list(docs) for query_id, docs in TOP_RANKED.items()},)@@ -326,6 +326,30 @@ class SelectionTest(unittest.TestCase):self.assertEqual(data.selected_ids, ["q1", "q10"])self.assertEqual(data.payloads, [{"id": "q1", "text": "first query"}, {"id": "q10", "text": "tenth query"}])+ def test_queries_role_reads_only_judged_queries(self):+ plan = plan_performance(+ parse(+ "--model",+ "m",+ "--task",+ "mteb/SciFact?limit=2",+ "--output",+ "sparse",+ "--items-per-request",+ "1",+ "--rate",+ "1",+ )+ )+ loaders = tiny_loaders()+ judged = Loaders(+ corpus=loaders.corpus,+ queries=loaders.queries,+ qrels=lambda name, revision: {"q2": {"9": 1}},+ top_ranked=loaders.top_ranked,+ )+ self.assertEqual(load_performance_data(plan, judged).selected_ids, ["q2"])+def test_score_task_keeps_each_query_candidates_in_source_order(self):plan = plan_performance(parse("--model", "m", "--task", SCORE_KEY, "--rate", "1"))data = load_performance_data(plan, tiny_loaders())diff --git a/examples/evaluations/published-benchmarks/tests/test_quality.py b/examples/evaluations/published-benchmarks/tests/test_quality.pyindex 8e97e59a4..5c90c0625 100644--- a/examples/evaluations/published-benchmarks/tests/test_quality.py+++ b/examples/evaluations/published-benchmarks/tests/test_quality.py@@ -80,6 +80,8 @@ RESULT_KEYS = {"metrics","comparison","comparison_basis",+ "baseline",+ "verdict",}@@ -848,7 +850,13 @@ class ScoreCliTest(unittest.TestCase):self.assertEqual(again, record)self.assertEqual(rows, record["metrics"])self.assertEqual(comparison, record["comparison"])- self.assertEqual(output.getvalue().splitlines(), score.format_rows(rows, comparison))+ self.assertEqual(+ output.getvalue().splitlines(),+ [+ *score.format_rows(rows, comparison),+ "verdict: MEASUREMENT limited run, not compared with a full-dataset number",+ ],+ )self.assertEqual(json.loads(result_path.read_text(encoding="utf-8")), record)def test_rescore_refuses_a_result_whose_run_failed(self):diff --git a/examples/evaluations/published-benchmarks/tests/test_verdict.py b/examples/evaluations/published-benchmarks/tests/test_verdict.pynew file mode 100644index 000000000..a88e98aa1--- /dev/null+++ b/examples/evaluations/published-benchmarks/tests/test_verdict.py@@ -0,0 +1,1069 @@+import contextlib+import io+import json+import math+import shlex+import tempfile+import unittest+from dataclasses import replace+from pathlib import Path+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++import run+import score+from run import (+ DEFAULT_ENDPOINT,+ Loaders,+ load_performance_data,+ load_quality_data,+ plan_performance,+ plan_quality,+ run_performance,+ run_quality,+)+from score import BASELINE_METRICS, compute_verdict, format_verdict, recompute_verdict, task_metrics++EXAMPLE_DIR = Path(__file__).resolve().parent.parent+LOCAL = "http://localhost:8080"+FLAGS = (+ "--model",+ "example/sparse-encoder",+ "--task",+ "mteb/SciFact",+ "--output",+ "sparse",+ "--items-per-request",+ "2",+)+DENSE_FLAGS = ("--model", "example/dense", "--task", "mteb/SciFact", "--output", "dense", "--items-per-request", "2")+PROLOGUE = "uv run python run.py quality"+VERDICT_FIELDS = {+ "verdict",+ "reason",+ "metric",+ "current",+ "baseline",+ "delta_pct",+ "threshold_low",+ "threshold_high",+ "margin",+}+ADDED_DATASETS = {+ "mteb/FiQA2018": ("mteb/fiqa", "27a168819829fe9bcd655c2df245fb19452e8e06"),+ "mteb/SCIDOCS": ("mteb/scidocs", "f8c2fcf00f625baaa80f62ec5bd9e1fff3b8ae88"),+ "mteb/CQADupstackPhysicsRetrieval": ("mteb/cqadupstack-physics", "79531abbd1fb92d06c6d6315a0cbbbf5bb247ea4"),+ "mteb/CosQA": ("CoIR-Retrieval/cosqa", "bc5efb7e9d437246ce393ed19d772e08e4a79535"),+ "mteb/StackOverflowQA": ("CoIR-Retrieval/stackoverflow-qa", "db8f169f3894c14a00251061f957b2063eef2bd5"),+ "mteb/LegalBenchConsumerContractsQA": (+ "mteb/legalbench_consumer_contracts_qa",+ "b23590301ec94e8087e2850b21d43d4956b1cca9",+ ),+}+DENSE_VECTORS = {+ "Alpha alpha body": [10.0, 10.0],+ "beta body": [1.0, 0.0],+ "gamma body": [0.0, 5.0],+ "delta body": [3.0, 4.0],+ "epsilon body": [-1.0, 0.0],+ "first query": [1.0, 0.0],+ "second query": [0.0, 1.0],+ "third query": [1.0, 1.0],+}+++class DenseClient(FakeClient):+ def _encode_item(self, item, output_types):+ if output_types == ["dense"]:+ return {"id": item["id"], "dense": np.asarray(DENSE_VECTORS[item["text"]], dtype=np.float32)}+ return super()._encode_item(item, output_types)+++def supplied(metric="ndcg_at_10", value=0.32, source="model card"):+ return {"kind": "supplied", "metric": metric, "value": value, "source": source}+++def judged_qrels():+ return {query_id: dict(tiny_loaders().qrels("", "")[query_id]) for query_id in ("q1", "q2", "q3")}+++class TemporaryCase(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.directory = Path(self.temporary.name)++ def run_flags(self, client, *flags):+ plan = plan_quality(parse(*flags))+ data = load_quality_data(plan, tiny_loaders())+ 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 loader(plan):+ return load_quality_data(plan, tiny_loaders())++ stdout, stderr = io.StringIO(), io.StringIO()+ code = None+ with (+ patch.dict("os.environ", {}, clear=True),+ patch.object(run, "load_quality_data", side_effect=loader),+ patch.object(run, "run_quality", side_effect=measured),+ patch.object(run, "SIEClient"),+ contextlib.redirect_stdout(stdout),+ contextlib.redirect_stderr(stderr),+ ):+ try:+ run.main(["quality", *argv])+ except SystemExit as caught:+ code = caught.code+ return code, stdout.getvalue(), stderr.getvalue()++ def refused(self, *argv):+ stderr = io.StringIO()+ with (+ patch.dict("os.environ", {}, clear=True),+ patch.object(run, "load_quality_data") as loader,+ patch.object(run, "load_performance_data") as performance_loader,+ patch.object(run, "SIEClient") as client,+ contextlib.redirect_stdout(io.StringIO()),+ contextlib.redirect_stderr(stderr),+ self.assertRaises(SystemExit) as caught,+ ):+ run.main(list(argv))+ self.assertEqual(caught.exception.code, 2)+ loader.assert_not_called()+ performance_loader.assert_not_called()+ client.assert_not_called()+ return stderr.getvalue()+++class BandTest(unittest.TestCase):+ baseline = supplied(value=0.32)+ low = 0.32 * 0.98+ high = 0.32 / 0.98++ def verdict(self, current, **kwargs):+ return compute_verdict({"ndcg_at_10": current}, self.baseline, limited=False, **kwargs)++ def assert_verdict(self, verdict, label, reason):+ self.assertEqual((verdict["verdict"], verdict["reason"]), (label, reason))++ def test_exactly_at_the_low_bound_passes(self):+ self.assert_verdict(self.verdict(self.low), "PASS", "within_margin")++ def test_just_below_the_low_bound_fails(self):+ self.assert_verdict(self.verdict(math.nextafter(self.low, 0.0)), "FAIL (regression)", "below_margin")++ def test_exactly_at_the_high_bound_passes(self):+ self.assert_verdict(self.verdict(self.high), "PASS", "within_margin")++ def test_just_above_the_high_bound_warns(self):+ self.assert_verdict(+ self.verdict(math.nextafter(self.high, 1.0)), "WARN (suspicious-improvement)", "above_margin"+ )++ def test_zero_is_no_output_ahead_of_every_other_case(self):+ for baseline, limited in ((self.baseline, False), (self.baseline, True), (None, False), (None, True)):+ with self.subTest(baseline=baseline, limited=limited):+ metrics = {"ndcg_at_10": 0.0, "main_score": 0.0}+ verdict = compute_verdict(metrics, baseline, limited=limited)+ self.assert_verdict(verdict, "FAIL (no-output)", "current_zero")+ self.assertEqual(verdict["current"], 0.0)++ def test_no_predictions_is_no_output_ahead_of_every_other_case(self):+ for baseline, limited in ((self.baseline, False), (self.baseline, True), (None, False), (None, True)):+ with self.subTest(baseline=baseline, limited=limited):+ verdict = compute_verdict({}, baseline, limited=limited)+ self.assert_verdict(verdict, "FAIL (no-output)", "no_predictions")+ self.assertIsNone(verdict["current"])++ def test_a_limit_key_is_a_measurement_even_with_a_baseline_out_of_band(self):+ verdict = compute_verdict({"ndcg_at_10": 0.01}, self.baseline, limited=True)+ self.assert_verdict(verdict, "MEASUREMENT", "limited_run")+ self.assertEqual(verdict["current"], 0.01)+ for field in ("baseline", "delta_pct", "threshold_low", "threshold_high"):+ self.assertIsNone(verdict[field], field)++ def test_no_baseline_is_a_measurement_of_the_main_score(self):+ verdict = compute_verdict({"main_score": 0.4, "ndcg_at_10": 0.9}, None, limited=False)+ self.assert_verdict(verdict, "MEASUREMENT", "no_baseline")+ self.assertEqual((verdict["metric"], verdict["current"]), ("main_score", 0.4))+ for field in ("baseline", "delta_pct", "threshold_low", "threshold_high"):+ self.assertIsNone(verdict[field], field)++ def test_the_named_metric_is_compared_and_not_the_main_score(self):+ verdict = compute_verdict({"main_score": 0.9, "ndcg_at_10": 0.32}, self.baseline, limited=False)+ self.assert_verdict(verdict, "PASS", "within_margin")+ self.assertEqual((verdict["metric"], verdict["current"]), ("ndcg_at_10", 0.32))++ def test_field_names_and_arithmetic(self):+ verdict = self.verdict(0.3)+ self.assertEqual(set(verdict), VERDICT_FIELDS)+ self.assertEqual(verdict["baseline"], 0.32)+ self.assertEqual(verdict["margin"], 0.98)+ self.assertEqual(verdict["threshold_low"], 0.32 * 0.98)+ self.assertEqual(verdict["threshold_high"], 0.32 / 0.98)+ self.assertEqual(verdict["delta_pct"], (0.3 - 0.32) / 0.32 * 100.0)+++class VerdictLinesTest(unittest.TestCase):+ def lines(self, metrics, baseline=None, *, limited=False):+ return format_verdict(compute_verdict(metrics, baseline, limited=limited), baseline, "uv run python run.py")++ def test_a_pass_is_one_line_with_the_delta_and_the_band(self):+ baseline = supplied(value=0.3245, source="the paper")+ self.assertEqual(+ self.lines({"ndcg_at_10": 0.3199}, baseline),+ ["verdict: PASS ndcg_at_10 0.31990 against 0.32450 from the paper (-1.42%, band 0.31801 to 0.33112)"],+ )++ def test_a_warning_is_one_line(self):+ self.assertEqual(+ self.lines({"ndcg_at_10": 0.4}, supplied()),+ [+ (+ "verdict: WARN (suspicious-improvement) ndcg_at_10 0.40000 against 0.32000 from model card"+ " (+25.00%, band 0.31360 to 0.32653)"+ )+ ],+ )++ def test_measurements_say_why_there_is_no_comparison(self):+ self.assertEqual(self.lines({"main_score": 0.4}), ["verdict: MEASUREMENT no baseline"])+ self.assertEqual(+ self.lines({"ndcg_at_10": 0.4}, supplied(), limited=True),+ ["verdict: MEASUREMENT limited run, not compared with a full-dataset number"],+ )++ def test_a_regression_adds_expected_got_and_reproduce(self):+ self.assertEqual(+ self.lines({"ndcg_at_10": 0.25}, supplied()),+ [+ (+ "verdict: FAIL (regression) ndcg_at_10 0.25000 against 0.32000 from model card"+ " (-21.88%, band 0.31360 to 0.32653)"+ ),+ "expected: ndcg_at_10 from 0.31360 to 0.32653, 0.32000 from model card",+ "got: ndcg_at_10 0.25000",+ "reproduce: uv run python run.py",+ ],+ )++ def test_no_output_adds_expected_got_and_reproduce(self):+ self.assertEqual(+ self.lines({}, supplied()),+ [+ "verdict: FAIL (no-output) no predictions",+ "expected: ndcg_at_10 from 0.31360 to 0.32653, 0.32000 from model card",+ "got: no predictions",+ "reproduce: uv run python run.py",+ ],+ )+ self.assertEqual(+ self.lines({"main_score": 0.0}),+ [+ "verdict: FAIL (no-output) main_score is exactly 0",+ "expected: main_score above 0",+ "got: main_score 0.00000",+ "reproduce: uv run python run.py",+ ],+ )+++class BaselineFlagsTest(TemporaryCase):+ def test_bad_forms_are_refused_before_any_request(self):+ for baseline, message in (+ (("--baseline", "ndcg_at_10=0.3"), "go together"),+ (("--baseline-source", "model card"), "go together"),+ (("--baseline", "ndcg_at_10=0.3", "--baseline-source", " "), "go together"),+ (("--baseline", "bogus=0.3", "--baseline-source", "s"), "names 'bogus'"),+ (("--baseline", "ndcg=0.3", "--baseline-source", "s"), "names 'ndcg'"),+ (("--baseline", "ndcg_at_7=0.3", "--baseline-source", "s"), "names 'ndcg_at_7'"),+ (("--baseline", "NDCG_at_10=0.3", "--baseline-source", "s"), "names 'NDCG_at_10'"),+ (("--baseline", "ndcg_at_10", "--baseline-source", "s"), "must be <metric>=<value>"),+ (("--baseline", "ndcg_at_10=", "--baseline-source", "s"), "must be <metric>=<value>"),+ (("--baseline", "ndcg_at_10=high", "--baseline-source", "s"), "must be <metric>=<value>"),+ (("--baseline", "ndcg_at_10=0", "--baseline-source", "s"), "above 0 and at most 1"),+ (("--baseline", "ndcg_at_10=-0.3", "--baseline-source", "s"), "above 0 and at most 1"),+ (("--baseline", "ndcg_at_10=1.01", "--baseline-source", "s"), "above 0 and at most 1"),+ (("--baseline", "ndcg_at_10=nan", "--baseline-source", "s"), "above 0 and at most 1"),+ (("--baseline", "ndcg_at_10=inf", "--baseline-source", "s"), "above 0 and at most 1"),+ (("--baseline", "ndcg_at_10=-inf", "--baseline-source", "s"), "above 0 and at most 1"),+ (("--baseline", "ndcg_at_10=0.3", "--baseline-source", "a\nverdict: PASS"), "one line"),+ (("--baseline", "ndcg_at_10=0.3", "--baseline-source", "a\x85verdict: PASS"), "one line"),+ (("--baseline", "ndcg_at_10=0.3", "--baseline-source", "a\u2028verdict: PASS"), "one line"),+ (("--baseline", "ndcg_at_10=0.3", "--baseline-source", "caf\udcff"), "one line"),+ ):+ with self.subTest(baseline=baseline):+ stderr = self.refused("quality", *FLAGS, "--endpoint", LOCAL, *baseline)+ self.assertIn(message, stderr)++ def test_baseline_flags_are_refused_beside_a_reference(self):+ reference = reference_file(self.directory)+ for flags, name in (+ (("--baseline", "ndcg_at_10=0.3", "--baseline-source", "s"), "--baseline"),+ (("--baseline", "ndcg_at_10=0.3"), "--baseline"),+ (("--baseline-source", "s"), "--baseline-source"),+ ):+ with self.subTest(flags=flags):+ stderr = self.refused("quality", "--reference", str(reference), "--endpoint", LOCAL, *flags)+ self.assertIn(f"{name} cannot be combined with --reference", stderr)++ def test_performance_has_no_baseline_flags(self):+ for flag in ("--baseline", "--baseline-source"):+ with self.subTest(flag=flag):+ self.refused("performance", "--model", "m", "--task", "mteb/SciFact", "--rate", "1", flag, "x")++ def test_the_accepted_metrics_are_the_ones_a_quality_run_writes(self):+ written = task_metrics({"q": {"a": 1.0}}, {"q": {"a": 1}}, "mteb/SciFact")+ self.assertEqual(BASELINE_METRICS, set(written))+ for metric in sorted(BASELINE_METRICS):+ with self.subTest(metric=metric):+ plan = plan_quality(parse(*FLAGS, "--baseline", f"{metric}=0.5", "--baseline-source", "s"))+ self.assertEqual(plan.baseline["metric"], metric)++ def test_a_value_of_one_is_accepted_and_the_source_is_recorded(self):+ record, _ = self.run_flags(FakeClient(), *FLAGS, "--baseline", "recall_at_1=1", "--baseline-source", "a paper")+ self.assertEqual(+ record["baseline"], {"kind": "supplied", "metric": "recall_at_1", "value": 1.0, "source": "a paper"}+ )++ def test_a_score_task_takes_a_baseline(self):+ record, _ = self.run_flags(+ FakeClient(),+ "--model",+ "m",+ "--task",+ "mteb/AskUbuntuDupQuestions",+ "--baseline",+ "map_at_1000=1",+ "--baseline-source",+ "s",+ )+ self.assertEqual(record["verdict"]["verdict"], "PASS")+ self.assertEqual(record["verdict"]["metric"], "map_at_1000")+++class RecordTest(TemporaryCase):+ def test_a_run_without_a_baseline_records_a_measurement(self):+ record, _ = self.run_flags(FakeClient(), *FLAGS)+ self.assertIsNone(record["baseline"])+ self.assertEqual(record["schema_version"], 1)+ self.assertEqual(set(record["verdict"]), VERDICT_FIELDS)+ self.assertEqual((record["verdict"]["verdict"], record["verdict"]["reason"]), ("MEASUREMENT", "no_baseline"))++ def test_a_limit_key_records_a_measurement_and_keeps_the_baseline(self):+ record, _ = self.run_flags(+ FakeClient(),+ *FLAGS[:2],+ "--task",+ "mteb/SciFact?limit=2",+ *FLAGS[4:],+ "--baseline",+ "recall_at_1=0.1",+ "--baseline-source",+ "s",+ )+ self.assertEqual(record["baseline"]["value"], 0.1)+ self.assertEqual((record["verdict"]["verdict"], record["verdict"]["reason"]), ("MEASUREMENT", "limited_run"))++ def test_a_run_that_wrote_no_predictions_records_no_output(self):+ record, _ = self.run_flags(+ FakeClient(fail_at=1), *FLAGS, "--baseline", "recall_at_1=1", "--baseline-source", "s"+ )+ self.assertIsNone(record["run"]["predictions_path"])+ self.assertEqual(+ (record["verdict"]["verdict"], record["verdict"]["reason"]), ("FAIL (no-output)", "no_predictions")+ )++ def test_nothing_in_the_verdict_changes_validity_or_comparable(self):+ record, _ = self.run_flags(FakeClient(), *FLAGS, "--baseline", "recall_at_1=0.9", "--baseline-source", "s")+ self.assertEqual(record["verdict"]["verdict"], "FAIL (regression)")+ self.assertTrue(record["validity"]["valid"])+ self.assertEqual(record["comparable_reasons"], ["no reference"])+++class ReferenceBaselineTest(TemporaryCase):+ def test_every_committed_quality_reference_gets_its_published_main_score(self):+ paths = sorted((EXAMPLE_DIR / "references").glob("*-quality-*.json"))+ self.assertEqual(len(paths), 6)+ kinds = set()+ for path in paths:+ with self.subTest(path.name):+ reference = json.loads(path.read_text(encoding="utf-8"))+ main_score = next(row["value"] for row in reference["metrics"] if row["name"] == "main_score")+ plan = plan_quality(parse("--reference", str(path)))+ self.assertEqual(+ plan.baseline,+ {+ "kind": "published",+ "metric": "main_score",+ "value": main_score,+ "source": reference["reference_id"],+ },+ )+ kinds.add(reference["task_key"])+ if reference["task_key"] == "mteb/AskUbuntuDupQuestions":+ map_1000 = next(row["value"] for row in reference["metrics"] if row["name"] == "map_at_1000")+ self.assertEqual(main_score, map_1000)+ self.assertIn("mteb/AskUbuntuDupQuestions", kinds)++ def test_a_reference_without_a_main_score_is_refused(self):+ reference = reference_file(+ self.directory,+ metrics=[{"name": "ndcg_at_10", "unit": "ratio", "aggregation": "task_native", "value": 0.5}],+ )+ stderr = self.refused("quality", "--reference", str(reference), "--endpoint", LOCAL)+ self.assertIn("no main_score metric", stderr)++ def test_a_reference_run_is_compared_with_the_records_main_score(self):+ reference = reference_file(self.directory)+ record, _ = self.run_flags(FakeClient(), "--reference", str(reference))+ self.assertEqual(+ record["baseline"],+ {"kind": "published", "metric": "main_score", "value": 0.5, "source": "example-reference-quality-01"},+ )+ self.assertEqual(record["verdict"]["metric"], "main_score")+ self.assertEqual(record["verdict"]["baseline"], 0.5)+ self.assertEqual(record["verdict"]["verdict"], "WARN (suspicious-improvement)")++ def test_an_askubuntu_reference_run_is_compared_on_map_and_not_on_ndcg(self):+ reference = reference_file(+ self.directory,+ model="Qwen/Qwen3-Reranker-0.6B",+ operation="score",+ task_key="mteb/AskUbuntuDupQuestions",+ dataset={"name": "mteb/AskUbuntuDupQuestions", "revision": "0" * 40, "subset": "test", "parameters": []},+ payload={"items_per_request": 2, "output_contract": "scores", "parameters": []},+ metrics=[{"name": "main_score", "unit": "ratio", "aggregation": "task_native", "value": 1.0}],+ )+ record, _ = self.run_flags(FakeClient(), "--reference", str(reference))+ metrics = {row["name"]: row["value"] for row in record["metrics"]}+ self.assertEqual(metrics["main_score"], metrics["map_at_1000"])+ self.assertLess(metrics["ndcg_at_10"], 0.98)+ self.assertEqual(record["baseline"]["kind"], "published")+ self.assertEqual((record["verdict"]["verdict"], record["verdict"]["current"]), ("PASS", 1.0))++ def test_another_endpoint_keeps_comparable_false_and_still_gets_a_verdict(self):+ reference = reference_file(self.directory)+ record, _ = self.run_flags(FakeClient(), "--reference", str(reference), "--endpoint", LOCAL)+ self.assertFalse(record["comparable"])+ self.assertEqual(record["comparable_reasons"], [f"endpoint {LOCAL} != {DEFAULT_ENDPOINT}"])+ self.assertEqual(record["verdict"]["verdict"], "WARN (suspicious-improvement)")++ def test_a_smoke_key_keeps_the_published_baseline_and_is_a_measurement(self):+ reference = reference_file(self.directory)+ record, _ = self.run_flags(FakeClient(), "--reference", str(reference), "--task", "mteb/SciFact?limit=2")+ self.assertEqual(record["baseline"]["kind"], "published")+ self.assertEqual((record["verdict"]["verdict"], record["verdict"]["reason"]), ("MEASUREMENT", "limited_run"))+++class InstructionTest(TemporaryCase):+ def test_refused_beside_a_reference(self):+ reference = reference_file(self.directory)+ stderr = self.refused("quality", "--reference", str(reference), "--endpoint", LOCAL, "--instruction", "x")+ self.assertIn("--instruction cannot be combined with --reference", stderr)++ def test_refused_on_the_score_task(self):+ stderr = self.refused(+ "quality", "--model", "m", "--task", "mteb/AskUbuntuDupQuestions", "--endpoint", LOCAL, "--instruction", "x"+ )+ self.assertIn("--instruction is not accepted for the score task", stderr)++ def test_refused_when_empty(self):+ for text in ("", " "):+ with self.subTest(text=text):+ stderr = self.refused("quality", *FLAGS, "--endpoint", LOCAL, "--instruction", text)+ self.assertIn("--instruction must not be empty", stderr)++ def test_refused_when_not_one_printable_line(self):+ for text in ("a\nverdict: PASS", "a\u2029b", "caf\udcff"):+ with self.subTest(text=text):+ stderr = self.refused("quality", *FLAGS, "--endpoint", LOCAL, "--instruction", text)+ self.assertIn("--instruction must be one line", stderr)++ def test_performance_has_no_such_flag(self):+ self.refused("performance", "--model", "m", "--task", "mteb/SciFact", "--rate", "1", "--instruction", "x")++ def test_sent_with_queries_only_and_recorded(self):+ client = FakeClient()+ record, _ = self.run_flags(client, *FLAGS, "--instruction", "Find the passage")+ readiness, *measured = client.calls+ self.assertFalse(readiness[3]["is_query"])+ self.assertNotIn("instruction", readiness[3])+ queries = [kwargs for _, _, _, kwargs in measured if kwargs["is_query"]]+ documents = [kwargs for _, _, _, kwargs in measured if not kwargs["is_query"]]+ self.assertEqual(len(queries), 2)+ self.assertEqual(len(documents), 3)+ for kwargs in queries:+ self.assertEqual(kwargs["instruction"], "Find the passage")+ for kwargs in documents:+ self.assertNotIn("instruction", kwargs)+ self.assertEqual(record["payload"]["parameters"], [{"name": "instruction", "value": "Find the passage"}])++ def test_absent_unless_given(self):+ client = FakeClient()+ record, _ = self.run_flags(client, *FLAGS)+ for _, _, _, kwargs in client.calls:+ self.assertNotIn("instruction", kwargs)+ self.assertEqual(record["payload"]["parameters"], [])+++class DenseTest(TemporaryCase):+ def test_ranked_by_cosine_where_the_raw_dot_product_gives_another_order(self):+ record, _ = self.run_flags(DenseClient(), *DENSE_FLAGS)+ predictions = json.loads(Path(record["run"]["predictions_path"]).read_text(encoding="utf-8"))+ cosine_order = ["d2", "d1", "d4", "d3", "d5"]+ self.assertEqual(list(predictions["q1"]), cosine_order)+ self.assertAlmostEqual(predictions["q1"]["d2"], 1.0, places=6)+ self.assertAlmostEqual(predictions["q1"]["d1"], 1.0 / math.sqrt(2.0), places=6)+ self.assertAlmostEqual(predictions["q1"]["d4"], 0.6, places=6)+ self.assertAlmostEqual(predictions["q1"]["d5"], -1.0, places=6)+ documents = {+ doc_id: np.asarray(DENSE_VECTORS[text], dtype=np.float32)+ for doc_id, text in (+ ("d1", "Alpha alpha body"),+ ("d2", "beta body"),+ ("d3", "gamma body"),+ ("d4", "delta body"),+ ("d5", "epsilon body"),+ )+ }+ query = np.asarray(DENSE_VECTORS["first query"], dtype=np.float32)+ dot_order = sorted(documents, key=lambda doc_id: float(query @ documents[doc_id]), reverse=True)+ self.assertEqual(dot_order, ["d1", "d4", "d2", "d3", "d5"])+ self.assertNotEqual(dot_order, cosine_order)++ def test_a_row_below_the_norm_floor_is_divided_by_the_floor(self):+ self.assertAlmostEqual(float(run.dense_scores([[1.0, 0.0]], [[1e-13, 0.0]])[0, 0]), 0.1, places=5)+ self.assertAlmostEqual(float(run.dense_scores([[1e-13, 0.0]], [[1.0, 0.0]])[0, 0]), 0.1, places=5)++ def test_a_row_at_or_above_the_norm_floor_scores_its_cosine_and_a_zero_row_scores_zero(self):+ self.assertAlmostEqual(float(run.dense_scores([[1.0, 0.0]], [[3e-12, 4e-12]])[0, 0]), 0.6, places=5)+ self.assertEqual(float(run.dense_scores([[1.0, 0.0]], [[0.0, 0.0]])[0, 0]), 0.0)++ def test_the_norm_floor_is_on_the_dense_path_only(self):+ self.assertAlmostEqual(float(run.maxsim_scores([[[1.0, 0.0]]], [[[1e-13, 0.0]]])[0, 0]), 1.0, places=5)++ def test_a_quality_run_refuses_a_muvera_profile(self):+ stderr = self.refused(+ "quality",+ "--model",+ "lightonai/GTE-ModernColBERT-v1:muvera",+ "--task",+ "mteb/SciFact",+ "--output",+ "dense",+ "--items-per-request",+ "2",+ "--endpoint",+ LOCAL,+ )+ self.assertIn("muvera", stderr)+ self.assertIn("cosine", stderr)++ def test_the_muvera_refusal_ignores_case_as_the_gateway_does(self):+ task = ("--task", "mteb/SciFact", "--output", "dense", "--items-per-request", "2", "--endpoint", LOCAL)+ for model in ("m:MUVERA", "m:Muvera"):+ with self.subTest(model=model):+ self.assertIn("muvera", self.refused("quality", "--model", model, *task))++ def test_the_muvera_refusal_is_for_a_dense_quality_run_with_that_profile_only(self):+ task = ("--task", "mteb/SciFact", "--items-per-request", "2")+ other_profile = plan_quality(parse("--model", "m:other", "--output", "dense", *task))+ self.assertEqual((other_profile.profile, other_profile.output_contract), ("other", "dense"))+ other_output = plan_quality(parse("--model", "m:muvera", "--output", "sparse", *task))+ self.assertEqual((other_output.profile, other_output.output_contract), ("muvera", "sparse"))+ performance = plan_performance(+ test_performance.parse(+ "--model",+ "m:muvera",+ "--task",+ "mteb/SciFact?split=test&role=corpus&limit=4&filter=nonempty",+ "--output",+ "dense",+ "--items-per-request",+ "1",+ "--rate",+ "1",+ )+ )+ self.assertEqual((performance.profile, performance.output_contract), ("muvera", "dense"))++ def test_a_result_carries_the_dense_contract_and_every_request_asks_for_it(self):+ client = DenseClient()+ record, _ = self.run_flags(client, *DENSE_FLAGS)+ self.assertEqual(record["payload"]["output_contract"], "dense")+ self.assertEqual(len(client.calls), 6)+ for _, _, _, kwargs in client.calls:+ self.assertEqual(kwargs["output_types"], ["dense"])++ def test_a_response_of_the_wrong_shape_is_a_failed_run(self):+ record, _ = self.run_flags(FakeClient(), *DENSE_FLAGS)+ self.assertIsNone(record["run"]["predictions_path"])+ self.assertEqual(record["verdict"]["reason"], "no_predictions")++ def test_vectors_of_different_lengths_are_a_failed_run(self):+ class Uneven(DenseClient):+ def _encode_item(self, item, output_types):+ result = super()._encode_item(item, output_types)+ if item["text"] == "gamma body":+ result["dense"] = np.zeros(3, dtype=np.float32)+ return result++ record, _ = self.run_flags(Uneven(), *DENSE_FLAGS)+ self.assertIsNone(record["run"]["predictions_path"])+ self.assertFalse(record["validity"]["valid"])++ def test_the_score_task_still_refuses_an_output(self):+ stderr = self.refused(+ "quality", "--model", "m", "--task", "mteb/AskUbuntuDupQuestions", "--output", "dense", "--endpoint", LOCAL+ )+ self.assertIn("not accepted for the score task", stderr)+ stderr = self.refused(+ "performance",+ "--model",+ "m",+ "--task",+ "mteb/AskUbuntuDupQuestions",+ "--rate",+ "1",+ "--output",+ "dense",+ "--endpoint",+ LOCAL,+ )+ self.assertIn("not accepted for the score task", stderr)++ def test_a_performance_run_sends_dense_documents_and_has_no_verdict(self):+ key = "mteb/SciFact?split=test&role=corpus&limit=4&filter=nonempty"+ plan = plan_performance(+ test_performance.parse(+ "--model", "m", "--task", key, "--output", "dense", "--items-per-request", "1", "--rate", "20"+ )+ )+ plan = replace(plan, duration_s=0.1, warmup_s=0.0, settle_s=0.0, drain_s=0.0)+ client = test_performance.FakeClient()+ data = load_performance_data(plan, test_performance.tiny_loaders())+ record, _ = run_performance(plan, data, client, results_dir=self.directory / "results", now=clock)+ self.assertEqual(record["payload"]["output_contract"], "dense")+ self.assertEqual(len(client.calls), 3)+ for _, _, _, kwargs in client.calls:+ self.assertEqual(kwargs["output_types"], ["dense"])+ self.assertFalse(kwargs["is_query"])+ self.assertNotIn("instruction", kwargs)+ self.assertNotIn("baseline", record)+ self.assertNotIn("verdict", record)+++class CommandLineTest(TemporaryCase):+ def test_a_reference_run(self):+ reference = reference_file(self.directory)+ record, _ = self.run_flags(FakeClient(), "--reference", str(reference))+ self.assertEqual(+ record["run"]["command"], f"{PROLOGUE} --reference references/example-reference-quality-01.json"+ )++ def test_a_smoke_key_and_another_endpoint_are_kept(self):+ reference = reference_file(self.directory)+ record, _ = self.run_flags(+ FakeClient(), "--reference", str(reference), "--task", "mteb/SciFact?limit=2", "--endpoint", f"{LOCAL}/"+ )+ self.assertEqual(+ record["run"]["command"],+ f"{PROLOGUE} --reference references/example-reference-quality-01.json"+ f" --task 'mteb/SciFact?limit=2' --endpoint {LOCAL}",+ )++ def test_the_default_endpoint_is_left_out(self):+ for endpoint in (DEFAULT_ENDPOINT, f"{DEFAULT_ENDPOINT}/"):+ with self.subTest(endpoint=endpoint):+ record, _ = self.run_flags(FakeClient(), *FLAGS, "--endpoint", endpoint)+ self.assertNotIn("--endpoint", record["run"]["command"])++ def test_the_command_rebuilds_the_same_quality_plan(self):+ for flags in (+ FLAGS,+ (*DENSE_FLAGS, "--endpoint", f"{LOCAL}/sie"),+ (+ *DENSE_FLAGS,+ "--baseline",+ "ndcg_at_10=0.1234567890123",+ "--baseline-source",+ "the model's card",+ "--instruction",+ "Find the passage",+ "--endpoint",+ LOCAL,+ ),+ (+ *DENSE_FLAGS,+ "--baseline",+ "ndcg_at_10=0.3",+ "--baseline-source=-a dash first",+ "--instruction=--a dash first",+ ),+ (+ "--model",+ "BAAI/bge-m3:sparse",+ "--task",+ "mteb/SciFact",+ "--output",+ "sparse",+ "--items-per-request",+ "1",+ ),+ ("--model", "m", "--task", "mteb/AskUbuntuDupQuestions"),+ ):+ with self.subTest(flags=flags):+ plan = plan_quality(parse(*flags))+ command = run.quality_command_line(plan)+ self.assertEqual(shlex.split(command)[:5], shlex.split(PROLOGUE))+ self.assertEqual(plan_quality(parse(*shlex.split(command)[5:])), plan)++ def test_the_command_rebuilds_the_same_performance_plan(self):+ key = "mteb/SciFact?split=test&role=corpus&limit=4&filter=nonempty"+ for flags in (+ ("--model", "m", "--task", key, "--output", "dense", "--items-per-request", "1", "--rate", "0.25"),+ (+ "--model",+ "m",+ "--task",+ key,+ "--output",+ "sparse",+ "--items-per-request",+ "1",+ "--rate",+ "1",+ "--warmup",+ "0",+ ),+ ("--model", "m", "--task", "mteb/AskUbuntuDupQuestions?limit=2", "--rate", "2", "--endpoint", LOCAL),+ ):+ with self.subTest(flags=flags):+ plan = plan_performance(test_performance.parse(*flags))+ command = run.performance_command_line(plan)+ self.assertEqual(plan_performance(test_performance.parse(*shlex.split(command)[5:])), plan)++ def test_a_performance_reference_command_repeats_the_same_plan(self):+ reference = test_performance.reference_file(self.directory)+ plan = plan_performance(test_performance.parse("--reference", str(reference), "--rate", "2"))+ command = run.performance_command_line(plan)+ self.assertIn("--reference references/example-reference-performance-01.json", command)+ argv = shlex.split(command)[5:]+ argv[1] = str(reference)+ self.assertEqual(plan_performance(test_performance.parse(*argv)), plan)++ def test_url_credentials_reach_neither_a_quality_nor_a_performance_result(self):+ endpoint = "http://someone:s3cret@localhost:8080/sie?token=t0ken#fr4gment"+ reference = reference_file(self.directory)+ quality, _ = self.run_flags(FakeClient(), "--reference", str(reference), "--endpoint", endpoint)+ flags, _ = self.run_flags(FakeClient(), *FLAGS, "--endpoint", endpoint)++ performance_reference = test_performance.reference_file(self.directory)+ plan = plan_performance(+ test_performance.parse("--reference", str(performance_reference), "--endpoint", endpoint)+ )+ data = load_performance_data(plan, test_performance.tiny_loaders())+ performance, _ = run_performance(+ plan, data, test_performance.FakeClient(), results_dir=self.directory / "results", now=clock+ )+ for name, record in (("quality", quality), ("flags", flags), ("performance", performance)):+ with self.subTest(name):+ text = json.dumps(record)+ for secret in ("someone", "s3cret", "t0ken", "fr4gment"):+ self.assertNotIn(secret, text)+ self.assertTrue(record["run"]["command"].endswith("--endpoint http://localhost:8080/sie"))+ self.assertEqual(record["run"]["endpoint"], "http://localhost:8080/sie")+ self.assertIn(f"endpoint http://localhost:8080/sie != {DEFAULT_ENDPOINT}", record["comparable_reasons"])+++class ExitStatusTest(TemporaryCase):+ def test_a_regression_prints_its_lines_on_stdout_and_exits_0(self):+ code, stdout, stderr = self.command(+ FakeClient(),+ *FLAGS,+ "--baseline",+ "recall_at_1=0.9",+ "--baseline-source",+ "model card",+ "--endpoint",+ LOCAL,+ )+ self.assertIsNone(code)+ self.assertEqual(stderr, "")+ self.assertEqual(+ stdout.splitlines()[-4:],+ [+ (+ "verdict: FAIL (regression) recall_at_1 0.83333 against 0.90000 from model card"+ " (-7.41%, band 0.88200 to 0.91837)"+ ),+ "expected: recall_at_1 from 0.88200 to 0.91837, 0.90000 from model card",+ "got: recall_at_1 0.83333",+ (+ f"reproduce: {PROLOGUE} --model example/sparse-encoder --task mteb/SciFact --output sparse"+ " --items-per-request 2 --baseline recall_at_1=0.9 '--baseline-source=model card'"+ f" --endpoint {LOCAL}"+ ),+ ],+ )++ def test_a_warning_and_a_pass_exit_0(self):+ for value, label in (("0.5", "WARN (suspicious-improvement)"), ("0.83333", "PASS")):+ with self.subTest(label=label):+ code, stdout, _ = self.command(+ FakeClient(),+ *FLAGS,+ "--baseline",+ f"recall_at_1={value}",+ "--baseline-source",+ "s",+ "--endpoint",+ LOCAL,+ )+ self.assertIsNone(code)+ self.assertTrue(stdout.splitlines()[-1].startswith(f"verdict: {label} recall_at_1"))++ def test_the_verdict_comes_after_the_metrics(self):+ _, stdout, _ = self.command(FakeClient(), *FLAGS, "--endpoint", LOCAL)+ lines = stdout.splitlines()+ self.assertEqual(lines[-1], "verdict: MEASUREMENT no baseline")+ self.assertEqual(sum(line.startswith("verdict:") for line in lines), 1)+ self.assertTrue(lines[-2].startswith("recall_at_5"))++ def test_no_predictions_exits_1_and_prints_the_verdict(self):+ for fake in (FakeClient(fail_at=0), FakeClient(fail_at=1)):+ with self.subTest(fail_at=fake._fail_at):+ code, stdout, stderr = self.command(+ fake, *FLAGS, "--baseline", "recall_at_1=0.9", "--baseline-source", "s", "--endpoint", LOCAL+ )+ self.assertEqual(code, 1)+ self.assertEqual(+ stdout.splitlines()[-4:-1],+ [+ "verdict: FAIL (no-output) no predictions",+ "expected: recall_at_1 from 0.88200 to 0.91837, 0.90000 from s",+ "got: no predictions",+ ],+ )+ self.assertTrue(stdout.splitlines()[-1].startswith("reproduce: "))+ self.assertTrue(stderr.startswith("invalid: "))+++class ScoreVerdictTest(TemporaryCase):+ def rescored(self, result_path, *flags):+ stdout = io.StringIO()+ with patch("score.load_qrels", return_value=judged_qrels()), contextlib.redirect_stdout(stdout):+ score.main([str(result_path), *flags])+ return stdout.getvalue().splitlines()++ def stored(self, *flags):+ record, result_path = self.run_flags(FakeClient(), *FLAGS, *flags)+ return record, result_path++ def worsen_predictions(self, record):+ path = Path(record["run"]["predictions_path"])+ predictions = json.loads(path.read_text(encoding="utf-8"))+ predictions["q1"] = {doc_id: float(index) for index, doc_id in enumerate(predictions["q1"])}+ score.write_json(path, predictions)++ def test_the_stored_verdict_is_recomputed_the_same(self):+ for value, label in (+ ("0.83333", "PASS"),+ ("0.9", "FAIL (regression)"),+ ("0.5", "WARN (suspicious-improvement)"),+ ):+ with self.subTest(label=label):+ record, result_path = self.stored("--baseline", f"recall_at_1={value}", "--baseline-source", "a paper")+ self.assertEqual(record["verdict"]["verdict"], label)+ with patch("score.load_qrels", return_value=judged_qrels()):+ _, rows, _ = score.rescore(result_path)+ self.assertEqual(recompute_verdict(record, rows), record["verdict"])+ self.assertEqual(+ self.rescored(result_path)[-len(format_verdict(record["verdict"], record["baseline"], "x")) :],+ format_verdict(record["verdict"], record["baseline"], record["run"]["command"]),+ )++ def test_the_verdict_follows_the_predictions_and_not_the_stored_fields(self):+ record, result_path = self.stored("--baseline", "recall_at_1=0.83333", "--baseline-source", "s")+ self.assertEqual(record["verdict"]["verdict"], "PASS")+ self.worsen_predictions(record)+ lines = self.rescored(result_path)+ self.assertTrue(any(line.startswith("verdict: FAIL (regression)") for line in lines), lines)+ self.assertEqual(json.loads(result_path.read_text(encoding="utf-8")), record)++ def test_write_updates_the_verdict(self):+ record, result_path = self.stored("--baseline", "recall_at_1=0.83333", "--baseline-source", "s")+ self.worsen_predictions(record)+ self.rescored(result_path, "--write")+ written = json.loads(result_path.read_text(encoding="utf-8"))+ self.assertEqual(written["verdict"]["verdict"], "FAIL (regression)")+ self.assertEqual(+ written["verdict"]["current"], next(r["value"] for r in written["metrics"] if r["name"] == "recall_at_1")+ )++ def test_a_result_with_a_null_baseline_prints_a_measurement(self):+ _, result_path = self.stored()+ self.assertEqual(self.rescored(result_path)[-1], "verdict: MEASUREMENT no baseline")++ def test_a_result_with_no_baseline_field_prints_no_verdict(self):+ record, result_path = self.stored("--baseline", "recall_at_1=0.9", "--baseline-source", "s")+ older = {key: value for key, value in record.items() if key not in {"baseline", "verdict"}}+ score.write_json(result_path, older)+ lines = self.rescored(result_path, "--write")+ self.assertTrue(lines)+ self.assertFalse([line for line in lines if line.split(":")[0] in {"verdict", "expected", "got", "reproduce"}])+ written = json.loads(result_path.read_text(encoding="utf-8"))+ self.assertNotIn("verdict", written)+ self.assertNotIn("baseline", written)++ def test_a_committed_performance_result_prints_no_verdict(self):+ paths = [+ path+ for path in sorted((EXAMPLE_DIR / "validation").glob("*.json"))+ if json.loads(path.read_text(encoding="utf-8"))["evaluation_mode"] == score.PERFORMANCE_MODE+ ]+ self.assertTrue(paths)+ with contextlib.chdir(self.directory):+ for path in paths:+ with self.subTest(path.name):+ stdout = io.StringIO()+ with contextlib.redirect_stdout(stdout):+ score.main([str(path)])+ self.assertNotIn("verdict:", stdout.getvalue())+++class AddedDatasetsTest(TemporaryCase):+ def test_the_tables_name_the_revisions_and_the_main_score(self):+ for task_name, entry in ADDED_DATASETS.items():+ with self.subTest(task_name):+ self.assertEqual(score.HF_DATASETS[task_name], entry)+ self.assertEqual(score.MAIN_SCORE[task_name], "ndcg_at_10")+ self.assertEqual(score.ROLE_SPLITS[task_name], {"corpus": "corpus", "queries": "queries"})+ self.assertNotIn(task_name, run.SCORE_TASKS)++ def test_quality_and_performance_keys_are_accepted_as_encode_tasks(self):+ for task_name, (_, revision) in ADDED_DATASETS.items():+ with self.subTest(task_name):+ plan = plan_quality(+ parse("--model", "m", "--task", task_name, "--output", "dense", "--items-per-request", "2")+ )+ self.assertEqual((plan.operation, plan.task_name, plan.revision), ("encode", task_name, revision))+ performance = plan_performance(+ test_performance.parse(+ "--model",+ "m",+ "--task",+ f"{task_name}?split=test&role=corpus&limit=256&filter=nonempty",+ "--output",+ "dense",+ "--items-per-request",+ "1",+ "--rate",+ "1",+ )+ )+ self.assertEqual(+ (performance.operation, performance.task_name, performance.revision),+ ("encode", task_name, revision),+ )++ def test_each_role_loads_from_its_pinned_config_and_split(self):+ rows = {+ "corpus": Dataset.from_dict({"_id": ["d1"], "title": ["A"], "text": ["body"], "partition": ["x"]}),+ "queries": Dataset.from_dict({"_id": ["q1"], "text": ["query"], "language": ["en"]}),+ "default": Dataset.from_dict({"query-id": ["q1"], "corpus-id": ["d1"], "score": [1.0]}),+ }+ for task_name, (dataset, revision) in ADDED_DATASETS.items():+ with (+ self.subTest(task_name),+ patch("score.load_dataset", side_effect=lambda _, config, **__: rows[config]) as load,+ ):+ self.assertEqual(score.load_corpus(task_name, revision), {"d1": {"title": "A", "text": "body"}})+ self.assertEqual(score.load_queries(task_name, revision), {"q1": "query"})+ self.assertEqual(score.load_qrels(task_name, revision), {"q1": {"d1": 1}})+ self.assertEqual(+ [(call.args, call.kwargs) for call in load.call_args_list],+ [+ ((dataset, "corpus"), {"split": "corpus", "revision": revision}),+ ((dataset, "queries"), {"split": "queries", "revision": revision}),+ ((dataset, "default"), {"split": "test", "revision": revision}),+ ],+ )+++class QualityTaskKeyTest(TemporaryCase):+ ENCODE = ("--output", "sparse", "--items-per-request", "2")++ def test_a_parameter_other_than_limit_is_refused_before_any_request(self):+ baseline = ("--baseline", "ndcg_at_10=0.3", "--baseline-source", "model card")+ for key, shape, parameter in (+ ("mteb/SciFact?split=train", self.ENCODE, "split"),+ ("mteb/SciFact?split=test", self.ENCODE, "split"),+ ("mteb/SciFact?role=corpus", self.ENCODE, "role"),+ ("mteb/SciFact?Limit=5", self.ENCODE, "Limit"),+ ("mteb/SciFact?limit=5&filter=nonempty", self.ENCODE, "filter"),+ ("mteb/AskUbuntuDupQuestions?candidates-k=5", (), "candidates-k"),+ ):+ with self.subTest(key):+ stderr = self.refused("quality", "--model", "m", "--task", key, *shape, *baseline)+ self.assertIn(f"takes only limit, got {parameter}", stderr)++ def test_a_plain_key_and_a_limit_key_are_accepted(self):+ for key, params in (("mteb/SciFact", {}), ("mteb/SciFact?limit=5", {"limit": "5"})):+ with self.subTest(key):+ plan = plan_quality(parse("--model", "m", "--task", key, *self.ENCODE))+ self.assertEqual(plan.task_params, params)+++class IdenticalIdsTest(TemporaryCase):+ def test_only_fiqa_drops_a_document_with_the_query_id(self):+ predictions = {"7": {"7": 9.0, "a": 1.0}}+ qrels = {"7": {"a": 1}}+ self.assertEqual(score.IGNORE_IDENTICAL_IDS, {"mteb/FiQA2018"})+ fiqa = task_metrics(predictions, qrels, "mteb/FiQA2018")+ self.assertEqual((fiqa["recall_at_1"], fiqa["mrr_at_1"], fiqa["main_score"]), (1.0, 1.0, 1.0))+ for task_name in set(score.HF_DATASETS) - {"mteb/FiQA2018"}:+ with self.subTest(task_name):+ other = task_metrics(predictions, qrels, task_name)+ self.assertEqual((other["recall_at_1"], other["mrr_at_1"]), (0.0, 0.0))+ self.assertLess(other["ndcg_at_10"], 1.0)++ def test_the_input_is_left_as_it_was(self):+ predictions = {"7": {"7": 9.0, "a": 1.0}}+ task_metrics(predictions, {"7": {"a": 1}}, "mteb/FiQA2018")+ self.assertEqual(predictions, {"7": {"7": 9.0, "a": 1.0}})++ def test_the_run_and_score_py_agree_and_the_predictions_file_keeps_the_document(self):+ corpus = {"q1": {"title": "", "text": "beta body"}, "d4": {"title": "", "text": "delta body"}}+ loaders = Loaders(+ corpus=lambda name, revision: corpus,+ queries=lambda name, revision: {"q1": "first query"},+ qrels=lambda name, revision: {"q1": {"d4": 1}},+ top_ranked=lambda name, revision: {},+ )+ plan = plan_quality(+ parse("--model", "m", "--task", "mteb/FiQA2018", "--output", "sparse", "--items-per-request", "2")+ )+ data = load_quality_data(plan, loaders)+ record, result_path = run_quality(plan, data, FakeClient(), results_dir=self.directory / "results", now=clock)+ predictions = json.loads(Path(record["run"]["predictions_path"]).read_text(encoding="utf-8"))+ self.assertEqual(list(predictions["q1"]), ["q1", "d4"])+ metrics = {row["name"]: row["value"] for row in record["metrics"]}+ self.assertEqual(metrics["recall_at_1"], 1.0)+ with patch("score.load_qrels", return_value={"q1": {"d4": 1}}):+ _, rows, _ = score.rescore(result_path)+ self.assertEqual(rows, record["metrics"])+++if __name__ == "__main__":+ unittest.main()