"""Rebuild the per-condition (15-atom) results matrix for all 16 eMCR baselines straight from the raw ``runs/*/emcr__all.json`` files. Why this script exists ----------------------- Table 4 (condition-type) in the paper was regenerated by hand at some point and its "Q3E8" (Qwen3-Embedding-8B) column turned out to be sourced from the WRONG run directory. Root cause, confirmed by matching every run's *overall* P@1 against the published Table 2 numbers: Table 2 label -> actual run directory (folder name is misleading!) "Qwen3-Embedding-8B" (55.3) -> runs/qwen3_emb_4B_nebula/ (folder says 4B) "Qwen3-Embedding-4B" (55.2) -> runs/qwen3_emb_8B_nebula/ (folder says 8B) The three text rerankers all rerank the top-30 from ``qwen3_emb_4B_nebula`` (confirmed: its dense P@1 = 55.31, matching the *true* "8B" row, and the rerankers' own overall P@1 exactly match Table 2's reranking rows). So the rerankers were correctly built on top of the strongest text-dense model, but Table 4's Q3E8 reference column was pulled from the *other* (weaker) folder, silently comparing "Q3R8" against the wrong baseline when computing Delta_rk = Q3R8 - Q3E8. CANONICAL_RUNS below hard-codes the *verified* mapping (verified by matching each run's overall P@1 against the numbers already published in Table 2, see the `verify_table2` command). Do not "fix" the folder names without re-running this verification -- the point of this script is to be robust to that naming bug, not to paper over it. Usage ----- python scripts/build_condition_matrix.py verify_table2 # sanity check python scripts/build_condition_matrix.py table4 # regenerate Table 4 python scripts/build_condition_matrix.py matrix # full 16x15 matrix """ from __future__ import annotations import json import math import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] RUNS = ROOT / "runs" # --------------------------------------------------------------------------- # Canonical (model -> run dir) mapping, verified against Table 2 overall P@1. # `dense_dir` is used for retrieval-only models; `rerank_dir` (if any) is the # run whose "rerank" stage holds the reranked results; `first_stage` names the # *model key* (into this same dict) that the reranker actually reranked, so # Delta_rk can always be computed against the correct baseline. # --------------------------------------------------------------------------- CANONICAL_RUNS = { # -- sparse -- "BM25": dict(dir="bm25_full", stage="dense"), # -- text dense -- "BGE-M3": dict(dir="bge_m3_nebula", stage="dense"), "GritLM-7B": dict(dir="gritlm_nebula", stage="dense"), "E5-Mistral-7B": dict(dir="e5_mistral_nebula", stage="dense"), # NOTE the swap: folder names are misleading, see module docstring. "Qwen3-Emb-4B": dict(dir="qwen3_emb_8B_nebula", stage="dense"), "Qwen3-Emb-8B": dict(dir="qwen3_emb_4B_nebula", stage="dense"), # -- multimodal dense -- "MM-Embed": dict(dir="mm_embed_nebula", stage="dense"), "VLM2Vec-V2": dict(dir="vlm2vec_v2_nebula", stage="dense"), "Qwen3-VL-Emb-2B": dict(dir="qwen3_vl_2B_nebula", stage="dense"), "Qwen3-VL-Emb-8B": dict(dir="qwen3_vl_8B_nebula", stage="dense"), # -- text reranking (all built on the TRUE Qwen3-Emb-8B pool) -- "BGE-Reranker-v2-m3": dict(dir="qwen3_emb_4B_rerank_cross_encoder_nebula", stage="rerank", first_stage="Qwen3-Emb-8B"), "Qwen3-Reranker-4B": dict(dir="qwen3_emb_4B_rerank_qwen3_reranker_4b_nebula", stage="rerank", first_stage="Qwen3-Emb-8B"), "Qwen3-Reranker-8B": dict(dir="qwen3_emb_4B_rerank_qwen3_reranker_8b_nebula", stage="rerank", first_stage="Qwen3-Emb-8B"), # -- multimodal reranking (all built on Qwen3-VL-Emb-8B pool) -- "Jina-Reranker-m0": dict(dir="qwen3_vl_8B_rerank_jina_reranker_m0_nebula", stage="rerank", first_stage="Qwen3-VL-Emb-8B"), "Qwen3-VL-Reranker-2B": dict(dir="qwen3_vl_8B_rerank_qwen3_vl_reranker_2b_nebula", stage="rerank", first_stage="Qwen3-VL-Emb-8B"), "Qwen3-VL-Reranker-8B": dict(dir="qwen3_vl_8B_rerank_qwen3_vl_reranker_8b_nebula", stage="rerank", first_stage="Qwen3-VL-Emb-8B"), } # Published Table 2 overall P@1 (%), used only by `verify_table2`. TABLE2_P1 = { "BM25": 43.2, "BGE-M3": 51.9, "GritLM-7B": 54.2, "E5-Mistral-7B": 47.1, "Qwen3-Emb-4B": 55.2, "Qwen3-Emb-8B": 55.3, "BGE-Reranker-v2-m3": 62.2, "Qwen3-Reranker-4B": 61.4, "Qwen3-Reranker-8B": 67.9, "MM-Embed": 43.6, "VLM2Vec-V2": 44.6, "Qwen3-VL-Emb-2B": 36.6, "Qwen3-VL-Emb-8B": 56.7, "Jina-Reranker-m0": 64.7, "Qwen3-VL-Reranker-2B": 70.2, "Qwen3-VL-Reranker-8B": 74.7, } # 15 atomic conditions -> (source_field, key_in_that_field) # 14 of them live in `condition_class`; price_query only exists as a pure # single-atom entry in `task_type` (condition_class has no price bucket). ATOM_SOURCE = { "paraphrase": ("condition_class", "rewrite"), "expand": ("condition_class", "expand"), "restructure": ("condition_class", "transform"), "correction": ("condition_class", "correction"), "content_intent": ("condition_class", "content_intent"), "sku_intent": ("condition_class", "sku"), "knowledge": ("condition_class", "knowledge"), "general_sem.": ("condition_class", "general"), "attribute_scene": ("condition_class", "attribute"), "implicit_intent": ("condition_class", "implicit"), "brand": ("condition_class", "brand"), "style": ("condition_class", "style"), "negative_intent": ("condition_class", "negative_intent"), "price_query": ("task_type", "price_query"), "image_clue": ("condition_class", "image_clue"), } def _load(run_key: str) -> dict: cfg = CANONICAL_RUNS[run_key] path = RUNS / cfg["dir"] / "emcr__all.json" with open(path, encoding="utf-8") as f: return json.load(f) def _overall_p1(run_key: str) -> float: d = _load(run_key) stage = CANONICAL_RUNS[run_key]["stage"] return d[stage]["metrics"]["precision@1"] * 100 def _atom_cell(run_key: str, atom: str) -> tuple[float | None, int | None]: d = _load(run_key) stage = CANONICAL_RUNS[run_key]["stage"] field, key = ATOM_SOURCE[atom] bucket = d[stage]["stratified"].get(field, {}).get(key) if bucket is None: return None, None return bucket["precision@1"] * 100, int(bucket["_n_queries"]) def wilson_ci(p_pct: float, n: int, z: float = 1.96) -> tuple[float, float]: """95% Wilson score interval for a binomial proportion, returned as %. P@1 (and P@1-derived metrics like these atom-level cells) are Bernoulli per query, so this is the right substitute for a bootstrap CI when only the aggregated (p, n) is available -- no per-query hit/miss array is persisted in the run JSONs, so a literal resample isn't possible without re-scoring from raw qrels. """ if n == 0: return (float("nan"), float("nan")) p = p_pct / 100.0 denom = 1 + z * z / n center = p + z * z / (2 * n) half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) lo, hi = (center - half) / denom, (center + half) / denom return lo * 100, hi * 100 # --------------------------------------------------------------------------- # Commands # --------------------------------------------------------------------------- def cmd_verify_table2(): print(f"{'model':24s} {'table2':>7s} {'actual':>7s} {'diff':>6s} dir") bad = [] for name, target in TABLE2_P1.items(): actual = _overall_p1(name) diff = actual - target flag = " <-- MISMATCH" if abs(diff) > 0.15 else "" if flag: bad.append(name) print(f"{name:24s} {target:7.1f} {actual:7.2f} {diff:+6.2f}{flag} {CANONICAL_RUNS[name]['dir']}") print() if bad: print(f"MISMATCHES: {bad}") else: print("All 16 models reproduce their Table 2 overall P@1 within 0.15pp. Mapping is verified correct.") def cmd_table4(): reps = ["BM25", "Qwen3-Emb-8B", "Qwen3-Reranker-8B", "Qwen3-VL-Reranker-8B"] short = {"BM25": "BM25", "Qwen3-Emb-8B": "Q3E8", "Qwen3-Reranker-8B": "Q3R8", "Qwen3-VL-Reranker-8B": "VLR8"} rows = [] for atom in ATOM_SOURCE: vals = {} for rk in reps: p1, n = _atom_cell(rk, atom) vals[rk] = p1 d_rk = vals["Qwen3-Reranker-8B"] - vals["Qwen3-Emb-8B"] d_mm = vals["Qwen3-VL-Reranker-8B"] - vals["Qwen3-Reranker-8B"] rows.append((atom, vals["BM25"], vals["Qwen3-Emb-8B"], vals["Qwen3-Reranker-8B"], vals["Qwen3-VL-Reranker-8B"], d_rk, d_mm)) print(f"{'atom':18s} {'BM25':>6s} {'Q3E8':>6s} {'Q3R8':>6s} {'VLR8':>6s} {'Drk':>7s} {'Dmm':>7s}") for r in rows: print(f"{r[0]:18s} {r[1]:6.1f} {r[2]:6.1f} {r[3]:6.1f} {r[4]:6.1f} {r[5]:+7.1f} {r[6]:+7.1f}") print("\nLaTeX rows:") for r in rows: atom_tex = r[0].replace("_", "\\_") print(f"{atom_tex} & {r[1]:.1f} & {r[2]:.1f} & {r[3]:.1f} & {r[4]:.1f} & " f"${'+' if r[5]>=0 else '$-$'}{abs(r[5]):.1f}$".replace("$$-$", "$-$") + f" & ${'+' if r[6]>=0 else '$-$'}{abs(r[6]):.1f}$".replace("$$-$", "$-$") + r" \\") def cmd_matrix(): out = {"models": {}} for name in CANONICAL_RUNS: overall = _overall_p1(name) cells = {} for atom in ATOM_SOURCE: p1, n = _atom_cell(name, atom) if p1 is None: cells[atom] = None continue lo, hi = wilson_ci(p1, n) cells[atom] = {"p1": round(p1, 2), "n": n, "ci95": [round(lo, 1), round(hi, 1)]} row = {"overall_p1": round(overall, 2), "atoms": cells} fs = CANONICAL_RUNS[name].get("first_stage") if fs: row["first_stage_model"] = fs drk_atoms = {} for atom in ATOM_SOURCE: a = cells[atom] b_p1, b_n = _atom_cell(fs, atom) if a is not None and b_p1 is not None: drk_atoms[atom] = round(a["p1"] - b_p1, 2) row["delta_vs_first_stage"] = drk_atoms out["models"][name] = row dest = ROOT / "docs" / "condition_matrix.json" dest.write_text(json.dumps(out, indent=2, ensure_ascii=False), encoding="utf-8") print(f"wrote {dest}") # also a flat CSV for quick pivoting / plotting import csv csv_path = ROOT / "docs" / "condition_matrix.csv" with open(csv_path, "w", newline="", encoding="utf-8") as f: w = csv.writer(f) w.writerow(["model", "overall_p1", "atom", "p1", "n", "ci_lo", "ci_hi", "delta_vs_first_stage"]) for name, row in out["models"].items(): drk = row.get("delta_vs_first_stage", {}) for atom, cell in row["atoms"].items(): if cell is None: continue w.writerow([name, row["overall_p1"], atom, cell["p1"], cell["n"], cell["ci95"][0], cell["ci95"][1], drk.get(atom, "")]) print(f"wrote {csv_path}") if __name__ == "__main__": cmd = sys.argv[1] if len(sys.argv) > 1 else "verify_table2" {"verify_table2": cmd_verify_table2, "table4": cmd_table4, "matrix": cmd_matrix}[cmd]()