Overview
You finish with a Git and DVC repository that benchmarks English-only and multilingual Transformers encoders on Amazon Mintaka across five languages. Two local Transformers judges grade the top retrieved English question-answer records and send every disagreement to a human-review CSV. A reactive marimo app filters metrics and raw query pairs live, backed by a 50-row manual precision audit.
- A reproducible DVC pipeline in
dvc.yamlanddvc.lockthat ties the raw Mintaka hash to deterministic Parquet splits and metric files. - A comparison file
metrics/retrieval_comparison.jsonlogging top-1 recall, top-5 recall, MRR, and the non-English recall margin betweenall-MiniLM-L6-v2andparaphrase-multilingual-MiniLM-L12-v2. - A two-model judging panel pairing
Qwen/Qwen3-0.6BwithMoritzLaurer/mDeBERTa-v3-base-mnli-xnlithat logs agreed counts inmetrics/judge_summary.jsonand writes disagreements toresults/human_review_queue.csv. - A 50-row manually labeled file
results/manual_audit_50.csvplusmetrics/manual_audit_scores.jsoncomparing each standalone judge against two-model agreed-only precision. - A reactive marimo notebook
notebooks/audit_app.pywhere language and agreement dropdowns recalculate metrics and refresh displayed query-candidate rows live.
Tools
- Hugging Face Datasets
The library is free Apache 2.0 software. Dataset licenses, gated access and any remote storage charges are separate.
- Transformers
Transformers is free Apache 2.0 software. Model checkpoints, remote model code and paid hosting have separate terms and costs.
- DVC
DVC is free Apache 2.0 software. Remote storage and any separate hosting service require their own accounts and may incur charges.
- marimo
The local marimo notebook is free Apache 2.0 software. Hosted products, optional assistants and remote data services have separate terms; their paid entitlements are not established here.
Datasets
- Amazon Mintaka Kaggle
Provides parallel multilingual question-answer records for testing cross-lingual retrieval of English QA entries across non-English queries.
Before you begin
Python 3.11 or newer
Free. Check with python --version on Windows or python3 --version on macOS and Linux; the Kaggle CLI and current transformers releases require Python 3.11 or later.
Git 2.x
Free. Check with git --version. DVC stores lightweight pointer files and pipeline hashes in Git while keeping dataset archives out of Git history.
A free Kaggle account
Needed to authenticate kaggle datasets download with kaggle auth login or KAGGLE_API_TOKEN. You can also download the dataset archive from the Kaggle web page.
At least 8 GB of RAM and 6 GB of free disk
The unzipped Mintaka JSON files take about 39 MB, and the four local Hugging Face checkpoints need roughly 3 GB of cache space. A GPU speeds up judging but is optional.
Working knowledge of Python, pandas, and basic Git
You should be comfortable activating a virtual environment, running CLI scripts, and reading JSON or CSV outputs in a terminal.
Internet access for initial downloads
Required once to pull the Kaggle dataset and the four public Hugging Face checkpoints. After caching locally, the pipeline runs offline.
Stage 01 · setup35 minutes
Set up Git, DVC, and the Python environment
Create an isolated project folder with Git, DVC, a local DVC remote, and verified Python packages.
Start with an empty folder so Git and DVC track every script and metric cleanly. Run every command in this walkthrough from the mintaka-audit folder with the virtual environment active.
mkdir -p mintaka-audit/src mintaka-audit/notebooks mintaka-audit/data/raw mintaka-audit/data/processed mintaka-audit/results mintaka-audit/metrics
cd mintaka-audit
python3 -m venv .venv
source .venv/bin/activateNew-Item -ItemType Directory -Force -Path mintaka-audit\src, mintaka-audit\notebooks, mintaka-audit\data\raw, mintaka-audit\data\processed, mintaka-audit\results, mintaka-audit\metrics | Out-Null
Set-Location mintaka-audit
python -m venv .venv
.\.venv\Scripts\Activate.ps1Create a requirements.txt file with the core libraries before installing anything. Pinning transformers to 4.51.0 or newer guarantees support for the Qwen/Qwen3-0.6B checkpoint, while sentencepiece and protobuf support the mDeBERTa-v3 tokenizer.
datasets>=3.0.0
transformers>=4.51.0
torch>=2.4.0
dvc>=3.50.0
marimo>=0.10.0
kaggle>=1.7.0
numpy>=1.26.0
pandas>=2.2.0
pyarrow>=16.0.0
pyyaml>=6.0.1
sentencepiece>=0.2.0
protobuf>=4.25.0python -m pip install --upgrade pip
pip install -r requirements.txtInitialize Git and DVC next, then add a .gitignore file so credentials, caches, and virtual environments never enter version control. You also register a local folder outside the repository as a DVC remote so you can test a clean checkout later without paying for cloud storage.
.venv/
__pycache__/
*.pyc
.kaggle/
kaggle.json
.env
.marimo/
git init
dvc init
dvc remote add -d local_store ../mintaka-dvc-store
git add .gitignore requirements.txt .dvc/.gitignore .dvc/config
git commit -m "Initialize repository with DVC and local remote"Review the target repository layout before writing pipeline scripts. Organizing raw data, processed Parquet files, result tables, and metrics JSON files into separate directories keeps dvc.yaml readable.
mintaka-audit/
.dvc/ # DVC metadata and remote config
data/
raw/ # DVC-tracked Amazon Mintaka JSON archive
processed/ # Deterministic Parquet candidate index and queries
metrics/ # JSON summaries for recall, judges, and manual audit
notebooks/
audit_app.py # Reactive marimo inspection app
results/ # Parquet retrieval outputs and human review CSVs
src/ # Pipeline scripts for prep, retrieval, judging, and audit
dvc.yaml # Reproducible DVC stage graph
params.yaml # Seed, languages, model IDs, and thresholds
requirements.txt # Python dependencies
README.md # Reproduction notes and CC BY 4.0 creditpython -c "import datasets, transformers, torch, dvc, marimo; print('transformers', transformers.__version__, 'datasets', datasets.__version__, 'cuda', torch.cuda.is_available())"
dvc --version
marimo --versiontransformers <your version> datasets <your version> cuda <True or False> <your dvc version> <your marimo version>
Git reports a clean initial commit, dvc remote list prints local_store, and the smoke check prints versions for transformers, datasets, dvc, and marimo with zero import errors.
Stage 02 · data55 minutes
Download Mintaka and build deterministic Datasets splits
Fetch the Amazon Mintaka dataset, track the raw files with DVC, and export deterministic English candidate and multilingual query Parquet tables.
Download the public Amazon Mintaka archive from Kaggle into data/raw and unzip it in place. Authenticate once with kaggle auth login if the CLI asks for credentials.
kaggle datasets download -d shivanshuman/amazon-research-mintaka-dataset -p data/raw --unzipInspect the downloaded files and print the keys of one test record before writing preprocessing code. Verifying field names on disk prevents silent bugs when Mintaka answers switch between entities, numbers, and booleans.
python -c "import json, pathlib; p = next(pathlib.Path('data/raw').rglob('mintaka_test.json')); rows = json.loads(p.read_text(encoding='utf-8')); print(p, len(rows)); print(list(rows[0].keys())); print(sorted(rows[0]['translations'].keys())); print(rows[0]['answer'])"data/raw/data/mintaka_test.json 4000
['id', 'question', 'translations', 'questionEntity', 'answer', 'category', 'complexityType']
['ar', 'de', 'es', 'fr', 'hi', 'it', 'ja', 'pt']
{'answerType': '<type>', 'answer': [...], 'mention': '<english answer>'}Track the entire data/raw directory with DVC so Git stores only a tiny data/raw.dvc hash file instead of 39 MB of JSON. Push the cached raw files to your local DVC remote right away.
dvc add data/raw
git add data/raw.dvc data/.gitignore
git commit -m "Track raw Amazon Mintaka dataset with DVC"
dvc pushCreate params.yaml to hold the fixed random seed, five evaluation languages, sample size, and model identifiers. Evaluating English alongside Hindi (hi), Arabic (ar), Japanese (ja), and Spanish (es) tests Latin and non-Latin scripts across 250 queries per language.
seed: 20261202
languages:
- en
- hi
- ar
- ja
- es
queries_per_language: 250
top_k: 5
batch_size: 64
retrieval_device: cpu
en_model: sentence-transformers/all-MiniLM-L6-v2
multilingual_model: sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2
judge_llm_model: Qwen/Qwen3-0.6B
judge_nli_model: MoritzLaurer/mDeBERTa-v3-base-mnli-xnli
nli_threshold: 0.5
audit_sample_size: 50
Write src/prepare_data.py to normalize the Mintaka test split into two typed Hugging Face Dataset tables saved as Parquet. Mintaka's answer.answer field mixes lists of entity objects, numbers, and booleans across rows, so parsing the JSON in Python before calling Dataset.from_list avoids PyArrow schema errors.
import hashlib
import json
import random
from pathlib import Path
import yaml
from datasets import Dataset
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(65536), b""):
digest.update(chunk)
return digest.hexdigest()
def extract_answer(ans_obj: dict) -> str:
if not isinstance(ans_obj, dict):
return ""
mention = ans_obj.get("mention")
if mention is not None and str(mention).strip():
return str(mention).strip()
raw_ans = ans_obj.get("answer")
if isinstance(raw_ans, list) and raw_ans:
parts = []
for item in raw_ans:
if isinstance(item, dict):
label = (item.get("label") or {}).get("en") or item.get("name")
if label:
parts.append(str(label))
elif item is not None:
parts.append(str(item))
return ", ".join(parts)
return "" if raw_ans is None else str(raw_ans).strip()
def main() -> None:
params = yaml.safe_load(Path("params.yaml").read_text(encoding="utf-8"))
raw_root = Path("data/raw")
test_path = next(raw_root.rglob("mintaka_test.json"))
records = json.loads(test_path.read_text(encoding="utf-8"))
languages = params["languages"]
non_en = [lang for lang in languages if lang != "en"]
candidates = []
eligible = []
for rec in sorted(records, key=lambda r: str(r["id"])):
question_en = str(rec.get("question") or "").strip()
answer_en = extract_answer(rec.get("answer") or {})
if not question_en or not answer_en:
continue
row = {
"id": str(rec["id"]),
"question_en": question_en,
"answer_en": answer_en,
"candidate_text": f"Question: {question_en} Answer: {answer_en}",
"category": str(rec.get("category") or "unknown"),
"complexity_type": str(rec.get("complexityType") or "unknown"),
}
candidates.append(row)
translations = rec.get("translations") or {}
if all(str(translations.get(lang) or "").strip() for lang in non_en):
eligible.append((row, translations))
rng = random.Random(int(params["seed"]))
rng.shuffle(eligible)
sampled = eligible[: int(params["queries_per_language"])]
queries = []
for row, translations in sampled:
for lang in languages:
q_text = row["question_en"] if lang == "en" else str(translations[lang]).strip()
queries.append({
"query_id": f"{row['id']}_{lang}",
"gold_id": row["id"],
"language": lang,
"query_text": q_text,
"gold_question_en": row["question_en"],
"gold_answer_en": row["answer_en"],
"category": row["category"],
"complexity_type": row["complexity_type"],
})
out_dir = Path("data/processed")
out_dir.mkdir(parents=True, exist_ok=True)
Dataset.from_list(candidates).to_parquet(str(out_dir / "candidates_en.parquet"))
Dataset.from_list(queries).to_parquet(str(out_dir / "queries.parquet"))
Path("metrics").mkdir(parents=True, exist_ok=True)
manifest = {
"source_file": test_path.as_posix(),
"source_sha256": sha256_file(test_path),
"seed": int(params["seed"]),
"languages": languages,
"candidate_count": len(candidates),
"queries_per_language": len(sampled),
"total_queries": len(queries),
}
Path("metrics/data_manifest.json").write_text(
json.dumps(manifest, indent=2) + "\n", encoding="utf-8"
)
print(json.dumps(manifest, indent=2))
if __name__ == "__main__":
main()
python src/prepare_data.py{
"source_file": "data/raw/data/mintaka_test.json",
"source_sha256": "<sha256 hash>",
"seed": 20261202,
"languages": ["en", "hi", "ar", "ja", "es"],
"candidate_count": <candidate count>,
"queries_per_language": 250,
"total_queries": 1250
}data/raw.dvc is committed to Git, data/processed/candidates_en.parquet and data/processed/queries.parquet exist on disk, and metrics/data_manifest.json reports 250 queries per language across all five languages.
Stage 03 · build60 minutes
Encode and score the English-only baseline
Write a reusable Transformers retrieval script and run the English-only all-MiniLM-L6-v2 encoder across every language split.
Build one script src/retrieve.py that encodes both the English candidate QA index and the five-language query table with any Hugging Face AutoModel checkpoint. Using the exact same pooling, normalization, and ranking code for both encoders keeps the baseline comparison fair.
Both sentence-transformers/all-MiniLM-L6-v2 and sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 publish the same official Transformers recipe: attention-masked mean pooling over token embeddings followed by L2 normalization. Running on cpu in float32 gives bitwise identical similarity scores across clean checkouts.
import argparse
import json
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
import yaml
from datasets import Dataset, load_dataset
from transformers import AutoModel, AutoTokenizer
def mean_pooling(model_output, attention_mask: torch.Tensor) -> torch.Tensor:
token_embeddings = model_output[0]
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
summed = torch.sum(token_embeddings * input_mask_expanded, dim=1)
counts = torch.clamp(input_mask_expanded.sum(dim=1), min=1e-9)
return summed / counts
def encode_texts(
texts: list[str],
model_name: str,
batch_size: int,
device: torch.device,
) -> np.ndarray:
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name).to(device)
model.eval()
chunks = []
with torch.no_grad():
for start in range(0, len(texts), batch_size):
batch = texts[start : start + batch_size]
encoded = tokenizer(
batch,
padding=True,
truncation=True,
max_length=128,
return_tensors="pt",
)
encoded = {k: v.to(device) for k, v in encoded.items()}
output = model(**encoded)
pooled = mean_pooling(output, encoded["attention_mask"])
normed = F.normalize(pooled, p=2, dim=1)
chunks.append(normed.cpu().numpy().astype(np.float32))
return np.vstack(chunks)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--model", required=True)
parser.add_argument("--out-parquet", required=True)
parser.add_argument("--out-metrics", required=True)
parser.add_argument("--device", default=None)
args = parser.parse_args()
params = yaml.safe_load(Path("params.yaml").read_text(encoding="utf-8"))
top_k = int(params["top_k"])
batch_size = int(params["batch_size"])
device_name = args.device or params.get("retrieval_device", "cpu")
if device_name == "auto":
device_name = "cuda" if torch.cuda.is_available() else "cpu"
device = torch.device(device_name)
cand_path = "data/processed/candidates_en.parquet"
query_path = "data/processed/queries.parquet"
candidates = load_dataset("parquet", data_files=cand_path, split="train")
queries = load_dataset("parquet", data_files=query_path, split="train")
cand_ids = list(candidates["id"])
cand_q = list(candidates["question_en"])
cand_a = list(candidates["answer_en"])
id_to_pos = {cid: idx for idx, cid in enumerate(cand_ids)}
cand_vecs = encode_texts(list(candidates["candidate_text"]), args.model, batch_size, device)
query_vecs = encode_texts(list(queries["query_text"]), args.model, batch_size, device)
scores = query_vecs @ cand_vecs.T
rows = []
per_lang: dict[str, dict[str, list[float]]] = {}
for idx, q in enumerate(queries):
row_scores = scores[idx]
order = np.argsort(-row_scores, kind="stable")
top_indices = order[:top_k]
top_ids = [cand_ids[i] for i in top_indices]
gold_pos = id_to_pos[q["gold_id"]]
rank = int(np.where(order == gold_pos)[0][0]) + 1
hit_1 = 1.0 if top_ids[0] == q["gold_id"] else 0.0
hit_5 = 1.0 if q["gold_id"] in top_ids else 0.0
rr = 1.0 / rank
lang = q["language"]
bucket = per_lang.setdefault(lang, {"r1": [], "r5": [], "mrr": []})
bucket["r1"].append(hit_1)
bucket["r5"].append(hit_5)
bucket["mrr"].append(rr)
top1 = int(top_indices[0])
rows.append({
"query_id": q["query_id"],
"gold_id": q["gold_id"],
"language": lang,
"category": q["category"],
"complexity_type": q["complexity_type"],
"query_text": q["query_text"],
"gold_question_en": q["gold_question_en"],
"gold_answer_en": q["gold_answer_en"],
"top1_id": cand_ids[top1],
"top1_question_en": cand_q[top1],
"top1_answer_en": cand_a[top1],
"top1_score": float(row_scores[top1]),
"top5_ids": top_ids,
"gold_rank": rank,
"hit_at_1": int(hit_1),
"hit_at_5": int(hit_5),
"reciprocal_rank": float(rr),
})
out_pq = Path(args.out_parquet)
out_pq.parent.mkdir(parents=True, exist_ok=True)
Dataset.from_list(rows).to_parquet(str(out_pq))
by_language = {}
for lang in sorted(per_lang):
b = per_lang[lang]
by_language[lang] = {
"count": len(b["r5"]),
"recall_at_1": round(float(np.mean(b["r1"])), 4),
"recall_at_5": round(float(np.mean(b["r5"])), 4),
"mrr": round(float(np.mean(b["mrr"])), 4),
}
metrics = {
"model": args.model,
"device": device_name,
"accessed_files": [cand_path, query_path, "params.yaml"],
"candidate_count": len(cand_ids),
"query_count": len(rows),
"by_language": by_language,
}
out_json = Path(args.out_metrics)
out_json.parent.mkdir(parents=True, exist_ok=True)
out_json.write_text(json.dumps(metrics, indent=2) + "\n", encoding="utf-8")
print(json.dumps(metrics, indent=2))
if __name__ == "__main__":
main()
python src/retrieve.py --model sentence-transformers/all-MiniLM-L6-v2 --out-parquet results/retrieval_en_only.parquet --out-metrics metrics/retrieval_en_only.json{
"model": "sentence-transformers/all-MiniLM-L6-v2",
"device": "cpu",
"accessed_files": ["data/processed/candidates_en.parquet", "data/processed/queries.parquet", "params.yaml"],
"candidate_count": <candidate count>,
"query_count": 1250,
"by_language": {
"ar": {"count": 250, "recall_at_1": <ar r1>, "recall_at_5": <ar r5>, "mrr": <ar mrr>},
"en": {"count": 250, "recall_at_1": <en r1>, "recall_at_5": <en r5>, "mrr": <en mrr>},
"es": {"count": 250, "recall_at_1": <es r1>, "recall_at_5": <es r5>, "mrr": <es mrr>},
"hi": {"count": 250, "recall_at_1": <hi r1>, "recall_at_5": <hi r5>, "mrr": <hi mrr>},
"ja": {"count": 250, "recall_at_1": <ja r1>, "recall_at_5": <ja r5>, "mrr": <ja mrr>}
}
}Look closely at the per-language breakdown in metrics/retrieval_en_only.json. English queries and Spanish queries that share Latin-script proper nouns will score higher than Arabic, Hindi, and Japanese queries, where an English-only tokenizer splits unfamiliar scripts into generic subwords.
results/retrieval_en_only.parquet holds 1,250 ranked rows and metrics/retrieval_en_only.json logs recall_at_1, recall_at_5, and mrr for ar, en, es, hi, and ja.
Stage 04 · build45 minutes
Run the multilingual encoder and log the margin
Evaluate paraphrase-multilingual-MiniLM-L12-v2 on the identical candidate index and record the per-language recall gains in JSON.
Run src/retrieve.py again with sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2. Because the script reads the exact same Parquet files and applies the same mean-pooling and cosine scoring logic, any change in recall comes directly from the encoder weights and tokenizer.
python src/retrieve.py --model sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 --out-parquet results/retrieval_multilingual.parquet --out-metrics metrics/retrieval_multilingual.jsonWrite src/compare_retrievers.py to join both metric files into one comparison artifact metrics/retrieval_comparison.json. The script logs per-language deltas alongside the macro-averaged non-English top-5 recall margin so you can verify the acceptance check directly.
import json
from pathlib import Path
import numpy as np
def main() -> None:
en_path = Path("metrics/retrieval_en_only.json")
multi_path = Path("metrics/retrieval_multilingual.json")
en_data = json.loads(en_path.read_text(encoding="utf-8"))
multi_data = json.loads(multi_path.read_text(encoding="utf-8"))
by_language = {}
non_en_en_r5 = []
non_en_multi_r5 = []
non_en_en_mrr = []
non_en_multi_mrr = []
for lang in sorted(multi_data["by_language"]):
base = en_data["by_language"][lang]
cand = multi_data["by_language"][lang]
by_language[lang] = {
"count": cand["count"],
"en_only_recall_at_1": base["recall_at_1"],
"multilingual_recall_at_1": cand["recall_at_1"],
"recall_at_1_margin": round(cand["recall_at_1"] - base["recall_at_1"], 4),
"en_only_recall_at_5": base["recall_at_5"],
"multilingual_recall_at_5": cand["recall_at_5"],
"recall_at_5_margin": round(cand["recall_at_5"] - base["recall_at_5"], 4),
"en_only_mrr": base["mrr"],
"multilingual_mrr": cand["mrr"],
"mrr_margin": round(cand["mrr"] - base["mrr"], 4),
}
if lang != "en":
non_en_en_r5.append(base["recall_at_5"])
non_en_multi_r5.append(cand["recall_at_5"])
non_en_en_mrr.append(base["mrr"])
non_en_multi_mrr.append(cand["mrr"])
avg_en_r5 = round(float(np.mean(non_en_en_r5)), 4)
avg_multi_r5 = round(float(np.mean(non_en_multi_r5)), 4)
margin_r5 = round(avg_multi_r5 - avg_en_r5, 4)
avg_en_mrr = round(float(np.mean(non_en_en_mrr)), 4)
avg_multi_mrr = round(float(np.mean(non_en_multi_mrr)), 4)
comparison = {
"en_only_model": en_data["model"],
"multilingual_model": multi_data["model"],
"accessed_files": [en_path.as_posix(), multi_path.as_posix()],
"non_english_avg_en_only_recall_at_5": avg_en_r5,
"non_english_avg_multilingual_recall_at_5": avg_multi_r5,
"non_english_avg_recall_at_5_margin": margin_r5,
"non_english_avg_en_only_mrr": avg_en_mrr,
"non_english_avg_multilingual_mrr": avg_multi_mrr,
"non_english_avg_mrr_margin": round(avg_multi_mrr - avg_en_mrr, 4),
"multilingual_beats_en_only_non_english": bool(margin_r5 > 0),
"by_language": by_language,
}
out_path = Path("metrics/retrieval_comparison.json")
out_path.write_text(json.dumps(comparison, indent=2) + "\n", encoding="utf-8")
print(json.dumps(comparison, indent=2))
if __name__ == "__main__":
main()
python src/compare_retrievers.py{
"en_only_model": "sentence-transformers/all-MiniLM-L6-v2",
"multilingual_model": "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
"non_english_avg_en_only_recall_at_5": <baseline avg r5>,
"non_english_avg_multilingual_recall_at_5": <multilingual avg r5>,
"non_english_avg_recall_at_5_margin": <positive margin>,
"multilingual_beats_en_only_non_english": true,
"by_language": { ... }
}| Metric field | Definition | What to check |
|---|---|---|
recall_at_1 | Fraction of queries whose gold English QA record ranks first. | Tracks strict top-1 retrieval accuracy before judging. |
recall_at_5 | Fraction of queries whose gold English QA record appears in the top five matches. | Primary retrieval metric checked across clean DVC checkouts. |
mrr | Mean of 1 / gold_rank across all 250 queries in the language split. | Rewards placing the right English QA record closer to rank 1. |
non_english_avg_recall_at_5_margin | Multilingual minus English-only top-5 recall averaged over ar, es, hi, and ja. | Must be positive so multilingual_beats_en_only_non_english is true. |
metrics/retrieval_comparison.json exists, shows multilingual_beats_en_only_non_english: true, and records positive top-5 recall margins on the non-English languages.
Stage 05 · build85 minutes
Build the two-model abstain judge and review queue
Grade every top-1 retrieved English QA record with two distinct local Transformers checkpoints, abstain on disagreements, and export a human-review CSV.
Pair two small checkpoints from different model families so their mistakes do not collapse into identical errors. Judge 1 is Qwen/Qwen3-0.6B (a 0.6B multilingual causal LLM under Apache 2.0) running with enable_thinking=False, and Judge 2 is MoritzLaurer/mDeBERTa-v3-base-mnli-xnli (a 279M DeBERTa-v3 cross-lingual NLI classifier under MIT).
Put the two model runners in src/judges.py so each judge stays self-contained and easy to swap later. Judge 1 runs Qwen/Qwen3-0.6B with enable_thinking=False, while Judge 2 keeps mDeBERTa-v3 in float32 as its model card advises and reads the entailment index from model.config.label2id.
import gc
import torch
from transformers import (
AutoModelForCausalLM,
AutoModelForSequenceClassification,
AutoTokenizer,
)
def parse_yes_no(reply: str) -> str:
cleaned = reply.strip().upper()
if cleaned.startswith("YES"):
return "yes"
if cleaned.startswith("NO"):
return "no"
return "invalid"
def run_llm_judge(rows: list[dict], model_name: str, device: torch.device) -> tuple[list[str], list[str]]:
tokenizer = AutoTokenizer.from_pretrained(model_name)
dtype = torch.bfloat16 if device.type == "cuda" else torch.float32
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=dtype).to(device)
model.eval()
verdicts = []
raw_replies = []
with torch.no_grad():
for row in rows:
messages = [
{
"role": "system",
"content": "You judge cross-lingual QA retrieval. Reply with one word: YES or NO.",
},
{
"role": "user",
"content": (
f"Query ({row['language']}): {row['query_text']}\n"
f"Retrieved English question: {row['top1_question_en']}\n"
f"Retrieved English answer: {row['top1_answer_en']}\n"
"Does this retrieved English QA record answer the query? Reply YES or NO."
),
},
]
prompt = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=False,
)
inputs = tokenizer([prompt], return_tensors="pt").to(device)
generated = model.generate(
**inputs,
do_sample=False,
max_new_tokens=4,
pad_token_id=tokenizer.eos_token_id,
)
new_tokens = generated[0][inputs["input_ids"].shape[1] :]
reply = tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
raw_replies.append(reply)
verdicts.append(parse_yes_no(reply))
del model
del tokenizer
gc.collect()
if device.type == "cuda":
torch.cuda.empty_cache()
return verdicts, raw_replies
def run_nli_judge(
rows: list[dict],
model_name: str,
threshold: float,
batch_size: int,
device: torch.device,
) -> tuple[list[str], list[float]]:
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name, torch_dtype=torch.float32).to(device)
model.eval()
label2id = {k.lower(): int(v) for k, v in model.config.label2id.items()}
entail_idx = label2id["entailment"]
premises = [
f"Query: {r['query_text']}\nRetrieved English QA: {r['top1_question_en']} Answer: {r['top1_answer_en']}"
for r in rows
]
hypotheses = ["The retrieved English QA correctly answers the query."] * len(rows)
verdicts = []
probs = []
with torch.no_grad():
for start in range(0, len(rows), batch_size):
enc = tokenizer(
premises[start : start + batch_size],
hypotheses[start : start + batch_size],
padding=True,
truncation=True,
max_length=256,
return_tensors="pt",
)
enc = {k: v.to(device) for k, v in enc.items()}
logits = model(**enc).logits
entail_scores = torch.softmax(logits, dim=-1)[:, entail_idx].cpu().tolist()
for score in entail_scores:
probs.append(round(float(score), 4))
verdicts.append("yes" if score >= threshold else "no")
del model
del tokenizer
gc.collect()
if device.type == "cuda":
torch.cuda.empty_cache()
return verdicts, probs
Next write src/judge_panel.py to grade all 1,250 top-1 rows from results/retrieval_multilingual.parquet and apply the abstention gate. Whenever Judge 1 and Judge 2 disagree, or whenever Judge 1 returns an invalid token, the panel emits abstain and writes that row to results/human_review_queue.csv.
import argparse
import json
from pathlib import Path
import pandas as pd
import torch
import yaml
from datasets import Dataset, load_dataset
from judges import run_llm_judge, run_nli_judge
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--device", default="auto")
parser.add_argument("--limit", type=int, default=0)
args = parser.parse_args()
params = yaml.safe_load(Path("params.yaml").read_text(encoding="utf-8"))
device_name = args.device
if device_name == "auto":
device_name = "cuda" if torch.cuda.is_available() else "cpu"
device = torch.device(device_name)
in_path = "results/retrieval_multilingual.parquet"
ds = load_dataset("parquet", data_files=in_path, split="train")
rows = [dict(r) for r in ds]
if args.limit > 0:
rows = rows[: args.limit]
j1_verdicts, j1_raw = run_llm_judge(rows, params["judge_llm_model"], device)
j2_verdicts, j2_probs = run_nli_judge(
rows,
params["judge_nli_model"],
float(params["nli_threshold"]),
int(params["batch_size"]),
device,
)
graded = []
review_rows = []
by_lang: dict[str, dict[str, int]] = {}
for row, v1, raw1, v2, p2 in zip(rows, j1_verdicts, j1_raw, j2_verdicts, j2_probs):
if v1 in ("yes", "no") and v1 == v2:
panel = v1
agreement = "agreed"
else:
panel = "abstain"
agreement = "abstained"
lang = row["language"]
counts = by_lang.setdefault(
lang,
{"total": 0, "agreed_yes": 0, "agreed_no": 0, "abstained_disagreements": 0},
)
counts["total"] += 1
if panel == "yes":
counts["agreed_yes"] += 1
elif panel == "no":
counts["agreed_no"] += 1
else:
counts["abstained_disagreements"] += 1
record = {
**row,
"judge_1_verdict": v1,
"judge_1_raw": raw1,
"judge_2_verdict": v2,
"judge_2_entail_prob": p2,
"panel_verdict": panel,
"agreement": agreement,
}
graded.append(record)
if agreement == "abstained":
review_rows.append({
"query_id": row["query_id"],
"language": lang,
"query_text": row["query_text"],
"gold_question_en": row["gold_question_en"],
"gold_answer_en": row["gold_answer_en"],
"top1_question_en": row["top1_question_en"],
"top1_answer_en": row["top1_answer_en"],
"judge_1_verdict": v1,
"judge_2_verdict": v2,
"judge_2_entail_prob": p2,
"panel_verdict": panel,
})
Dataset.from_list(graded).to_parquet("results/judge_verdicts.parquet")
pd.DataFrame(review_rows).to_csv("results/human_review_queue.csv", index=False)
agreed_yes = sum(c["agreed_yes"] for c in by_lang.values())
agreed_no = sum(c["agreed_no"] for c in by_lang.values())
abstained = sum(c["abstained_disagreements"] for c in by_lang.values())
total = len(graded)
summary = {
"judge_1_model": params["judge_llm_model"],
"judge_2_model": params["judge_nli_model"],
"nli_threshold": float(params["nli_threshold"]),
"device": device_name,
"accessed_files": [in_path, "params.yaml"],
"total_graded": total,
"agreed_total": agreed_yes + agreed_no,
"agreed_yes": agreed_yes,
"agreed_no": agreed_no,
"abstained_disagreements": abstained,
"abstention_rate": round(abstained / total, 4) if total else 0.0,
"by_language": {
lang: {
**c,
"agreed_total": c["agreed_yes"] + c["agreed_no"],
"abstention_rate": round(c["abstained_disagreements"] / c["total"], 4),
}
for lang, c in sorted(by_lang.items())
},
}
Path("metrics/judge_summary.json").write_text(
json.dumps(summary, indent=2) + "\n", encoding="utf-8"
)
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()
python src/judge_panel.py{
"judge_1_model": "Qwen/Qwen3-0.6B",
"judge_2_model": "MoritzLaurer/mDeBERTa-v3-base-mnli-xnli",
"total_graded": 1250,
"agreed_total": <agreed count>,
"agreed_yes": <agreed yes>,
"agreed_no": <agreed no>,
"abstained_disagreements": <abstained count>,
"abstention_rate": <abstention rate>,
"by_language": { ... }
}metrics/judge_summary.json reports agreed_total, agreed_yes, agreed_no, and abstained_disagreements summing to 1,250, and results/human_review_queue.csv holds one row per abstained disagreement.
Stage 06 · test55 minutes
Wire the DVC pipeline and test clean reproduction
Define every stage in dvc.yaml, commit dvc.lock, and confirm a clean checkout reproduces identical top-5 recall numbers.
Write dvc.yaml to link data/raw, params.yaml, and every script to its exact outputs and metric files. When you run dvc repro, DVC hashes every input and skips unchanged stages automatically.
stages:
prepare:
cmd: python src/prepare_data.py
deps:
- data/raw
- src/prepare_data.py
params:
- seed
- languages
- queries_per_language
outs:
- data/processed/candidates_en.parquet
- data/processed/queries.parquet
metrics:
- metrics/data_manifest.json
retrieve_en:
cmd: python src/retrieve.py --model sentence-transformers/all-MiniLM-L6-v2 --out-parquet results/retrieval_en_only.parquet --out-metrics metrics/retrieval_en_only.json
deps:
- data/processed/candidates_en.parquet
- data/processed/queries.parquet
- src/retrieve.py
params:
- top_k
- batch_size
- retrieval_device
- en_model
outs:
- results/retrieval_en_only.parquet
metrics:
- metrics/retrieval_en_only.json
retrieve_multi:
cmd: python src/retrieve.py --model sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 --out-parquet results/retrieval_multilingual.parquet --out-metrics metrics/retrieval_multilingual.json
deps:
- data/processed/candidates_en.parquet
- data/processed/queries.parquet
- src/retrieve.py
params:
- top_k
- batch_size
- retrieval_device
- multilingual_model
outs:
- results/retrieval_multilingual.parquet
metrics:
- metrics/retrieval_multilingual.json
compare:
cmd: python src/compare_retrievers.py
deps:
- metrics/retrieval_en_only.json
- metrics/retrieval_multilingual.json
- src/compare_retrievers.py
metrics:
- metrics/retrieval_comparison.json
judge:
cmd: python src/judge_panel.py
deps:
- results/retrieval_multilingual.parquet
- src/judges.py
- src/judge_panel.py
params:
- judge_llm_model
- judge_nli_model
- nli_threshold
- batch_size
outs:
- results/judge_verdicts.parquet
- results/human_review_queue.csv
metrics:
- metrics/judge_summary.json
Run dvc repro so DVC records the full dependency graph and output hashes in dvc.lock. Inspect the stage graph with dvc dag and view tracked metrics with dvc metrics show, then commit the pipeline metadata to Git and push cached outputs to your local remote.
dvc repro
dvc dag
dvc metrics show
git add dvc.yaml dvc.lock params.yaml src/ data/processed/.gitignore results/.gitignore metrics/.gitignore
git commit -m "Define DVC retrieval and two-model judge pipeline"
dvc push +--------------+
| data/raw.dvc |
+--------------+
*
|
*
+---------+
| prepare |
+---------+
** **
* *
* *
+-------------+ +----------------+
| retrieve_en | | retrieve_multi |
+-------------+ +----------------+
* * *
* * |
* * *
+---------+ +-------+
| compare | | judge |
+---------+ +-------+Verify reproducibility from a clean checkout in a sibling folder. Pulling only data/raw.dvc and forcing dvc repro --force compare rebuilds prepare, retrieve_en, retrieve_multi, and compare from scratch without touching cached retrieval outputs.
git clone . ../mintaka-audit-clean
python -c "import subprocess; subprocess.run(['dvc', 'pull', 'data/raw.dvc'], cwd='../mintaka-audit-clean', check=True); subprocess.run(['dvc', 'repro', '--force', 'compare'], cwd='../mintaka-audit-clean', check=True)"
python -c "import json, pathlib; a = json.loads(pathlib.Path('metrics/retrieval_comparison.json').read_text())['by_language']; b = json.loads(pathlib.Path('../mintaka-audit-clean/metrics/retrieval_comparison.json').read_text())['by_language']; assert a == b, (a, b); print('Clean checkout top-5 recall matches for all languages:', sorted(a))"Clean checkout top-5 recall matches for all languages: ['ar', 'en', 'es', 'hi', 'ja']
dvc dag displays the five-stage graph rooted at data/raw.dvc, and the clean checkout assertion confirms identical per-language top-5 recall numbers.
Stage 07 · test65 minutes
Run the 50-query manual precision audit
Sample 50 graded queries across all languages, label them by hand, and measure single-judge accuracy against two-model agreed-only precision.
Automated judges can still share blind spots on translations, numeric answers, or entity aliases. A 50-row manual check grounds your report in human labels and shows whether abstaining on disagreements actually raises precision.
Write src/sample_audit.py to draw a deterministic 50-row stratified sample (10 rows per language) from results/judge_verdicts.parquet. For each language, the script mixes agreed rows and abstained rows so both failure modes appear in your manual check.
import random
from pathlib import Path
import pandas as pd
import yaml
from datasets import load_dataset
def main() -> None:
params = yaml.safe_load(Path("params.yaml").read_text(encoding="utf-8"))
seed = int(params["seed"])
sample_size = int(params["audit_sample_size"])
languages = params["languages"]
per_lang = sample_size // len(languages)
ds = load_dataset("parquet", data_files="results/judge_verdicts.parquet", split="train")
rows = [dict(r) for r in ds]
rng = random.Random(seed)
chosen = []
for lang in languages:
subset = [r for r in rows if r["language"] == lang]
agreed = [r for r in subset if r["agreement"] == "agreed"]
abstained = [r for r in subset if r["agreement"] == "abstained"]
rng.shuffle(agreed)
rng.shuffle(abstained)
half = per_lang // 2
pick = abstained[:half] + agreed[: per_lang - min(half, len(abstained))]
if len(pick) < per_lang:
remaining = [r for r in subset if r["query_id"] not in {x["query_id"] for x in pick}]
rng.shuffle(remaining)
pick.extend(remaining[: per_lang - len(pick)])
chosen.extend(pick[:per_lang])
export = [
{
"query_id": r["query_id"],
"language": r["language"],
"query_text": r["query_text"],
"gold_question_en": r["gold_question_en"],
"gold_answer_en": r["gold_answer_en"],
"top1_question_en": r["top1_question_en"],
"top1_answer_en": r["top1_answer_en"],
"hit_at_1": r["hit_at_1"],
"judge_1_verdict": r["judge_1_verdict"],
"judge_2_verdict": r["judge_2_verdict"],
"panel_verdict": r["panel_verdict"],
"agreement": r["agreement"],
"human_label": "",
"human_note": "",
}
for r in chosen
]
out_path = Path("results/manual_audit_50.csv")
pd.DataFrame(export).to_csv(out_path, index=False)
print(f"Wrote {len(export)} rows to {out_path.as_posix()}")
if __name__ == "__main__":
main()
python src/sample_audit.pyOpen results/manual_audit_50.csv in any spreadsheet editor or text editor and label all 50 rows before scoring. Judge whether the retrieved English QA record answers the source query, and rely on gold_question_en and gold_answer_en as your translation reference.
- Open
results/manual_audit_50.csvwith UTF-8 encoding so Arabic, Hindi, and Japanese scripts render cleanly. - Compare
gold_question_enandgold_answer_enagainsttop1_question_enandtop1_answer_enfor each row. - Enter
yesinhuman_labelwhen the retrieved English QA record answers the query accurately, ornowhen it answers a different question or gives the wrong entity. - Write a short phrase in
human_noteexplaining tricky near-misses such as wrong entity dates or partial overlaps, then save the CSV.
Write src/score_audit.py to score your 50 human labels and save metrics/manual_audit_scores.json. The script compares Judge 1 standalone accuracy and precision, Judge 2 standalone accuracy and precision, two-model agreed-only precision, and the panel abstention rate.
import json
from pathlib import Path
import pandas as pd
def precision(pred: pd.Series, truth: pd.Series) -> float:
positives = pred == "yes"
if int(positives.sum()) == 0:
return 0.0
return round(float((truth[positives] == "yes").mean()), 4)
def accuracy(pred: pd.Series, truth: pd.Series) -> float:
if len(pred) == 0:
return 0.0
return round(float((pred == truth).mean()), 4)
def main() -> None:
audit_path = Path("results/manual_audit_50.csv")
df = pd.read_csv(audit_path)
df["human_label"] = df["human_label"].fillna("").astype(str).str.strip().str.lower()
valid = df["human_label"].isin(["yes", "no"])
if not bool(valid.all()) or len(df) < 50:
missing = int((~valid).sum())
raise SystemExit(f"Label all 50 rows with yes or no before scoring ({missing} unlabeled).")
agreed = df[df["agreement"] == "agreed"]
abstained = df[df["agreement"] == "abstained"]
scores = {
"audit_file": audit_path.as_posix(),
"rows_audited": int(len(df)),
"agreed_rows": int(len(agreed)),
"abstained_rows": int(len(abstained)),
"abstention_rate": round(len(abstained) / len(df), 4),
"judge_1_standalone_accuracy": accuracy(df["judge_1_verdict"], df["human_label"]),
"judge_1_standalone_precision": precision(df["judge_1_verdict"], df["human_label"]),
"judge_2_standalone_accuracy": accuracy(df["judge_2_verdict"], df["human_label"]),
"judge_2_standalone_precision": precision(df["judge_2_verdict"], df["human_label"]),
"panel_agreed_only_accuracy": accuracy(agreed["panel_verdict"], agreed["human_label"]),
"panel_agreed_only_precision": precision(agreed["panel_verdict"], agreed["human_label"]),
}
out_path = Path("metrics/manual_audit_scores.json")
out_path.write_text(json.dumps(scores, indent=2) + "\n", encoding="utf-8")
print(json.dumps(scores, indent=2))
if __name__ == "__main__":
main()
python src/score_audit.py{
"audit_file": "results/manual_audit_50.csv",
"rows_audited": 50,
"agreed_rows": <agreed rows>,
"abstained_rows": <abstained rows>,
"abstention_rate": <sample abstention rate>,
"judge_1_standalone_accuracy": <j1 acc>,
"judge_1_standalone_precision": <j1 prec>,
"judge_2_standalone_accuracy": <j2 acc>,
"judge_2_standalone_precision": <j2 prec>,
"panel_agreed_only_accuracy": <panel acc>,
"panel_agreed_only_precision": <panel prec>
}results/manual_audit_50.csv contains 50 human-labeled rows and metrics/manual_audit_scores.json reports standalone accuracy alongside two-model agreed-only precision and abstention rate.
Stage 08 · ship80 minutes
Build the reactive marimo notebook and package deliverables
Create a reactive marimo audit notebook with live language and agreement filters, verify live updates, and write the CC BY 4.0 README.
Create notebooks/audit_app.py as a pure-Python marimo notebook so Git diffs stay readable and every UI interaction updates dependent cells automatically. Keep variable definitions immutable across cells so marimo's dependency graph reacts cleanly when you change a dropdown.
import marimo
__generated_with = "0.10.0"
app = marimo.App(width="medium")
@app.cell
def _():
import json
from pathlib import Path
import marimo as mo
import pandas as pd
return Path, json, mo, pd
@app.cell
def _(Path, json, pd):
verdicts_df = pd.read_parquet("results/judge_verdicts.parquet")
retrieval_cmp = json.loads(Path("metrics/retrieval_comparison.json").read_text(encoding="utf-8"))
judge_summary = json.loads(Path("metrics/judge_summary.json").read_text(encoding="utf-8"))
audit_file = Path("metrics/manual_audit_scores.json")
audit_scores = json.loads(audit_file.read_text(encoding="utf-8")) if audit_file.exists() else None
return audit_scores, judge_summary, retrieval_cmp, verdicts_df
@app.cell
def _(mo, verdicts_df):
languages = ["all"] + sorted(verdicts_df["language"].unique().tolist())
lang_select = mo.ui.dropdown(options=languages, value="all", label="Language")
agree_select = mo.ui.dropdown(
options=["all", "agreed", "abstained"],
value="all",
label="Judge agreement",
)
mo.vstack([
mo.md("# Mintaka Cross-Lingual Retrieval and Judge Audit"),
mo.hstack([lang_select, agree_select], justify="start", gap="1.5rem"),
])
return agree_select, lang_select
@app.cell
def _(agree_select, audit_scores, judge_summary, lang_select, mo, pd, retrieval_cmp, verdicts_df):
filtered = verdicts_df.copy()
if lang_select.value != "all":
filtered = filtered[filtered["language"] == lang_select.value]
if agree_select.value != "all":
filtered = filtered[filtered["agreement"] == agree_select.value]
row_count = len(filtered)
r1 = float(filtered["hit_at_1"].mean()) if row_count else 0.0
r5 = float(filtered["hit_at_5"].mean()) if row_count else 0.0
mrr = float(filtered["reciprocal_rank"].mean()) if row_count else 0.0
abstained = int((filtered["agreement"] == "abstained").sum()) if row_count else 0
abstain_rate = abstained / row_count if row_count else 0.0
cards = mo.hstack([
mo.stat(value=str(row_count), label="Filtered Queries"),
mo.stat(value=f"{r1:.3f}", label="Top-1 Recall"),
mo.stat(value=f"{r5:.3f}", label="Top-5 Recall"),
mo.stat(value=f"{mrr:.3f}", label="MRR"),
mo.stat(value=f"{abstain_rate:.1%}", label="Abstention Rate", caption=f"{abstained} rows"),
], justify="start", gap="1rem")
panel_md = mo.md(
f"**Judge panel:** `{judge_summary['judge_1_model']}` + `{judge_summary['judge_2_model']}` "
f"(NLI threshold `{judge_summary['nli_threshold']}`, total abstentions `{judge_summary['abstained_disagreements']}`)."
)
cmp_rows = [
{"language": lang, **vals}
for lang, vals in retrieval_cmp["by_language"].items()
if lang_select.value == "all" or lang == lang_select.value
]
cmp_table = mo.ui.table(data=pd.DataFrame(cmp_rows), pagination=False)
audit_md = (
mo.md(
f"**50-row manual audit:** Judge 1 accuracy `{audit_scores['judge_1_standalone_accuracy']:.3f}`, "
f"Judge 2 accuracy `{audit_scores['judge_2_standalone_accuracy']:.3f}`, "
f"agreed-only precision `{audit_scores['panel_agreed_only_precision']:.3f}`, "
f"sample abstention `{audit_scores['abstention_rate']:.1%}`."
)
if audit_scores
else mo.md("Run `python src/score_audit.py` to display the 50-row manual audit summary.")
)
mo.vstack([cards, panel_md, audit_md, mo.md("## English-Only vs Multilingual Retrieval"), cmp_table])
return (filtered,)
@app.cell
def _(filtered, mo):
cols = [
"query_id",
"language",
"query_text",
"top1_question_en",
"top1_answer_en",
"gold_answer_en",
"hit_at_5",
"judge_1_verdict",
"judge_2_verdict",
"panel_verdict",
"agreement",
]
inspect_table = mo.ui.table(data=filtered[cols].reset_index(drop=True), pagination=True)
mo.vstack([mo.md("## Source Queries and Matched English QA Entries"), inspect_table])
return (inspect_table,)
if __name__ == "__main__":
app.run()
Launch the notebook in app mode with marimo run or open the interactive editor with marimo edit. Changing the Language or Judge agreement dropdown immediately recalculates the top-1 recall, top-5 recall, MRR, and abstention cards and refreshes the query-and-candidate table with zero manual cell reruns.
marimo run notebooks/audit_app.pyWrite README.md with your reproduction steps, exact model IDs, and the mandatory CC BY 4.0 credit for Amazon Mintaka. Commit the notebook, your completed 50-row manual audit CSV, the scored audit JSON, and README.md to Git.
# Mintaka Cross-Lingual Retrieval and Judge Audit
## Reproduction
1. Create a Python 3.11+ virtual environment and run `pip install -r requirements.txt`.
2. Pull the raw dataset with `dvc pull data/raw.dvc` (or download `shivanshuman/amazon-research-mintaka-dataset` into `data/raw`).
3. Run `dvc repro` to rebuild all splits, retrieval metrics, judge verdicts, and `results/human_review_queue.csv`.
4. Launch the interactive audit workbench with `marimo run notebooks/audit_app.py`.
## Models
- English-only encoder: `sentence-transformers/all-MiniLM-L6-v2` (Apache 2.0)
- Multilingual encoder: `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` (Apache 2.0)
- Judge 1: `Qwen/Qwen3-0.6B` (Apache 2.0)
- Judge 2: `MoritzLaurer/mDeBERTa-v3-base-mnli-xnli` (MIT)
## Dataset Attribution
This project uses the Amazon Mintaka dataset (Sen, Aji, and Saffari, COLING 2022, "Mintaka: A Complex, Natural, and Multilingual Dataset for End-to-End Question Answering"), accessed via Kaggle (`shivanshuman/amazon-research-mintaka-dataset`) under Attribution 4.0 International (CC BY 4.0).
git add notebooks/audit_app.py src/sample_audit.py src/score_audit.py results/manual_audit_50.csv metrics/manual_audit_scores.json README.md
git commit -m "Add reactive marimo audit notebook, 50-row manual audit, and README"
git statusmarimo run notebooks/audit_app.py opens cleanly, changing either dropdown updates all metrics and table rows automatically, and git status shows a clean working tree with all deliverables committed.
Troubleshooting
kaggle datasets download fails with a 401 Unauthorized error or missing credentials message.
Run kaggle auth login to complete OAuth in your browser, or export KAGGLE_API_TOKEN from your Kaggle API settings page. Confirm your token file lives in your user ~/.kaggle/access_token directory and never inside the Git repository.
KeyError: 'qwen3' appears when loading Qwen/Qwen3-0.6B in src/judges.py.
Upgrade Transformers inside your active virtual environment with pip install -U "transformers>=4.51.0". Earlier releases lack the qwen3 model type.
mDeBERTa-v3-base-mnli-xnli raises a tokenizer import error mentioning SentencePiece or protobuf.
Install both packages inside .venv with pip install sentencepiece protobuf and re-run python src/judge_panel.py.
PyArrow raises ArrowInvalid if you try to load data/raw/data/mintaka_test.json directly with datasets.load_dataset('json', ...).
Mintaka's answer.answer field mixes entity dictionaries, numbers, and booleans across rows. Use src/prepare_data.py to normalize every answer into a plain string before building the Hugging Face Dataset.
src/judge_panel.py runs out of RAM or CUDA VRAM while grading 1,250 pairs.
Keep the sequential unloading logic (del model and gc.collect()) between Judge 1 and Judge 2 in src/judges.py, lower batch_size in params.yaml to 16, or run python src/judge_panel.py --device cpu.
dvc repro in the clean checkout prints a different float in the fourth decimal place on GPU.
Set retrieval_device: cpu in params.yaml for the encoder stages. GPU matrix kernels can reorder floating-point reductions slightly, whereas CPU float32 reproduces identical recall scores across checkouts.
Changing a dropdown in notebooks/audit_app.py raises a marimo multiple-definition or mutation warning.
Check that filtered = verdicts_df.copy() creates a fresh DataFrame inside the filtering cell instead of mutating verdicts_df in place, and confirm each global variable name is returned by only one @app.cell.
Done when
- Running the DVC pipeline from a clean checkout reproduces identical top-5 recall numbers for every evaluated language.
- The multilingual embedding model beats the English-only baseline on non-English top-5 recall by a logged margin in the results JSON.
- The judging script outputs separate counts for agreed verdicts and abstained disagreements, plus a CSV queue for human review.
- A manual check on at least 50 sampled queries compares single-judge accuracy against the two-model agreed-only precision.
- Changing the language or agreement selector in the marimo notebook recalculates summary metrics and updates displayed source queries and matched QA entries without manual cell reruns.
Deliverables
- Git and DVC repository containing the reproducible pipeline definition alongside the retrieval and two-model judging scripts, crediting the dataset as its license requires.
- Reactive marimo Python notebook file that renders per-language recall tables and inspectable disagreement rows.
- Fifty-row manually labeled audit CSV comparing single-judge precision against two-model agreed precision and abstention rate.
How to measure it
Compare monolingual English against multilingual sentence encoders using top-5 recall and mean reciprocal rank broken down across at least 200 queries per language. Grade the two-model panel on 50 manually verified pairs by reporting abstention rate alongside agreed-verdict precision versus each standalone judge.
Going further
- Break down English-only and multilingual recall by Mintaka's
complexity_typecolumn (multihop,ordinal,superlative,intersection,difference,count,comparative,yesno) to find which question types drop most. - Add a BM25 lexical retrieval baseline over English-translated queries to measure where dense multilingual embeddings beat keyword overlap and where rare proper nouns still favor exact matching.
- Sweep
nli_thresholdinparams.yamlfrom0.3to0.8across repeateddvc reproruns and chart how abstention rate trades off against agreed-only precision. - Use the built-in export menu in
mo.ui.tableto save filtered error slices by language and complexity type for domain reviewers who do not run Python locally.
Bounty stretch goals
- Add an exact-match formatting consistency check inspired by Humanity's First Exam by paraphrasing 40 queries and measuring how often retrieval rank shifts.
- Swap in a third local judge checkpoint and plot precision against abstention rate as the consensus rule moves from unanimous to majority vote.
- Log every DVC run's file access manifest into a JSON audit file so researchers can inspect exactly which split each judge read.
References
- Amazon Mintaka dataset on Kaggle
- Amazon Science Mintaka official README and schema
- Kaggle CLI authentication and setup documentation
- Kaggle CLI datasets download reference
- Hugging Face Datasets loading documentation
- Hugging Face Transformers installation documentation
- sentence-transformers/all-MiniLM-L6-v2 model card
- sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 model card
- Qwen/Qwen3-0.6B model card and non-thinking mode reference
- MoritzLaurer/mDeBERTa-v3-base-mnli-xnli model card
- DVC dvc add command reference
- DVC dvc.yaml pipeline schema reference
- DVC dvc repro command reference
- DVC dvc remote add command reference
- marimo quickstart documentation
- marimo reactivity guide
- marimo dropdown input API documentation
- marimo table input API documentation
- marimo stat layout API documentation
Reporting behind this quest
An AI guide writer drafted this walkthrough against the official documentation above, automated template and style checks validated every block, and an independent AI reviewer verified commands, flags and claims before publication.
