tomaarsen's picture
download
raw
9.04 kB
# /// script
# requires-python = ">=3.12"
# dependencies = ["huggingface-hub==2.2.0", "numpy==2.2.6"]
# ///
"""Collect completed workers and publish a continuously updated comparison."""
from __future__ import annotations
import argparse
import csv
import io
import itertools
import json
import logging
import time
from datetime import datetime, timezone
from pathlib import Path
import numpy as np
from huggingface_hub import HfApi, hf_hub_download
REPO = "tomaarsen/encoder-comparison-20261014"
MODELS = [
"modernbert-base",
"ettin-encoder-150m",
"ultrabert-150m",
"modernbert-large",
"ettin-encoder-400m",
"ultrabert-380m",
]
TASKS = ["dense", "multivector", "reranker"]
def bootstrap_delta(left, right):
rng = np.random.default_rng(12)
means = []
for dataset in left["test"]:
a = {r["query_id"]: r["ndcg@10"] for r in left["test"][dataset]["per_query"]}
b = {r["query_id"]: r["ndcg@10"] for r in right["test"][dataset]["per_query"]}
assert a.keys() == b.keys()
differences = np.array([a[q] - b[q] for q in sorted(a)])
indices = rng.integers(len(differences), size=(10_000, len(differences)))
means.append(differences[indices].mean(axis=1))
low, high = np.quantile(np.mean(means, axis=0), [0.025, 0.975])
return {"delta": left["mean_ndcg@10"] - right["mean_ndcg@10"], "ci95_low": float(low), "ci95_high": float(high)}
def collect(api, jobs):
revision = api.dataset_info(REPO).sha
files = set(api.list_repo_files(REPO, repo_type="dataset", revision=revision))
effective_jobs = {(j["model"], j["task"]): j for j in jobs}
if "recovery_jobs.json" in files:
path = hf_hub_download(REPO, "recovery_jobs.json", repo_type="dataset", revision=revision)
for job in json.loads(Path(path).read_text()):
effective_jobs[job["model"], job["task"]] = job
selected = {}
for model, task in itertools.product(MODELS, TASKS):
name = f"results/{model}/{task}/selected.json"
if name in files:
path = hf_hub_download(REPO, name, repo_type="dataset", revision=revision)
selected[model, task] = json.loads(Path(path).read_text())
statuses = []
for job in effective_jobs.values():
state = api.inspect_job(job_id=job["id"], namespace="tomaarsen")
statuses.append({**job, "status": state.status.stage, "message": state.status.message})
rows = []
for (model, task), result in selected.items():
trial = result["selected_trial"]
rows.append(
{
"model": model,
"task": task,
"ndcg@10": result["mean_ndcg@10"],
"lr": trial["lr"],
"validation": trial["validation"],
"gpu": trial["gpu"],
"train_seconds": trial["train_seconds"],
"peak_vram_gb": trial["peak_vram_gb"],
"model_url": "https://huggingface.co/" + trial["hub_id"],
**{name + "_ndcg@10": value["metrics"]["ndcg@10"] for name, value in result["test"].items()},
}
)
comparisons = []
for group in (MODELS[:3], MODELS[3:]):
for task in TASKS:
for a, b in itertools.combinations(group, 2):
if (a, task) in selected and (b, task) in selected:
comparisons.append(
{"left": a, "right": b, "task": task, **bootstrap_delta(selected[a, task], selected[b, task])}
)
output = Path("report")
output.mkdir(exist_ok=True)
(output / "results.json").write_text(
json.dumps({"rows": rows, "comparisons": comparisons, "jobs": statuses}, indent=2)
)
if rows:
buffer = io.StringIO()
writer = csv.DictWriter(buffer, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
(output / "results.csv").write_text(buffer.getvalue())
stamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
lines = [
"# Encoder comparison, 14 October 2026",
"",
f"Updated {stamp}. Completed evaluations: **{len(selected)}/18**.",
"",
"Six pretrained backbones, three Sentence Transformers recipes, three learning rates per recipe. "
"All models and research artifacts are public under tomaarsen.",
"",
"| Backbone | Dense nDCG@10 | Multi-Vector nDCG@10 | Reranker nDCG@10 |",
"| --- | ---: | ---: | ---: |",
]
for model in MODELS:
cells = []
for task in TASKS:
item = selected.get((model, task))
cells.append(
f"[{item['mean_ndcg@10']:.4f}](https://huggingface.co/{item['selected_trial']['hub_id']})"
if item
else "Pending"
)
lines.append("| " + " | ".join([model, *cells]) + " |")
lines += [
"",
"Compare backbones within a column and size group. Dense and multi-vector search the full Nano corpora. "
"Rerankers receive identical BM25 top-100 candidates without injected positives. "
"Scores are the equally weighted mean over NanoNQ, NanoFiQA2018 and NanoSciFact.",
"",
"Training uses 32,768 MS MARCO triplets, one epoch maximum, seed 12. Learning rates are 3e-5, 1e-4 and 3e-4. "
"A disjoint 1,024-query validation set selects checkpoints and learning rates. "
"The reported test datasets never select checkpoints.",
"",
"Dense and multi-vector use query length 32 and passage length 256 including special tokens. "
"Rerankers use 32 query content tokens, 256 passage content tokens and a combined cap of 291. "
"This is a short-input, small-data comparison, not a reproduction of the UltraBERT paper.",
"",
"[Detailed results](report/results.json) include per-dataset means and paired bootstrap confidence intervals. "
"Intervals reflect sampled-query uncertainty with fixed trained models, not variation across training seeds. "
"They are exploratory and unadjusted for multiple comparisons. "
"[CSV table](report/results.csv). Raw rankings, all trial validation scores and logs are in the repository.",
"",
"## Jobs",
"",
"| Backbone | Recipe | Status |",
"| --- | --- | --- |",
]
for job in statuses:
label = job["task"] + (" (checkpoint recovery)" if job["phase"] == "recover" else "")
lines.append(f"| {job['model']} | {label} | [{job['status']}]({job['url']}) |")
lines += [
"",
"## Data and reproducibility",
"",
"Training source: sentence-transformers/msmarco-co-condenser-margin-mse-sym-mnrl-mean-v1, triplet-hard. "
"Test sources: zeta-alpha-ai/NanoNQ, zeta-alpha-ai/NanoFiQA2018 and zeta-alpha-ai/NanoSciFact. "
"Original dataset terms apply. See manifest.json for frozen revisions, sampling and content hashes. "
"Source scripts are in scripts/. Validation candidates include the positive, "
"the provided hard negative and BM25 distractors. Test candidates do not inject positives.",
"",
]
(output / "README.md").write_text("\n".join(lines), encoding="utf-8")
api.upload_folder(
repo_id=REPO,
repo_type="dataset",
folder_path=output,
path_in_repo="report",
commit_message=f"Refresh comparison report: {len(selected)}/18",
)
api.upload_file(
repo_id=REPO,
repo_type="dataset",
path_or_fileobj=str(output / "README.md"),
path_in_repo="README.md",
commit_message="Update public comparison summary",
)
return len(selected), all(s["status"] in {"COMPLETED", "ERROR", "CANCELED", "DELETED"} for s in statuses)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--watch", action="store_true")
args = parser.parse_args()
logging.basicConfig(level=logging.WARNING)
api = HfApi()
jobs = None
for attempt in range(6):
try:
revision = api.dataset_info(REPO).sha
jobs_file = hf_hub_download(REPO, "jobs.json", repo_type="dataset", revision=revision)
jobs = [r for r in json.loads(Path(jobs_file).read_text()) if r["phase"] == "train"]
assert len(jobs) == 18
break
except Exception:
if attempt == 5:
raise
time.sleep(10)
for _ in range(144):
try:
count, finished = collect(api, jobs)
print(f"REPORT_UPDATED completed={count}/18 workers_terminal={finished}", flush=True)
if count == 18 or not args.watch:
return
except Exception as error:
print(f"Report retry after {type(error).__name__}: {error}", flush=True)
if not args.watch:
raise
time.sleep(300)
raise SystemExit("Report monitor reached its 12-hour limit")
if __name__ == "__main__":
main()

Xet Storage Details

Size:
9.04 kB
·
Xet hash:
ee4f67a46dc5da3ea4592e54c9fed45b79c28e8b1cd1d52cf06cf575b4431aa9

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.