"""Build a static (no-JS-needed) HTML report from results/ and send it to Telegram.""" import sys, json, os, html, math, pickle, urllib.request, uuid from pathlib import Path import numpy as np from common import RES, CACHE, tg STAGE = sys.argv[1] if len(sys.argv) > 1 else "core" OUTF = Path("~/embed/report") / "benchmark-report.html" OUTF.parent.mkdir(exist_ok=True) NAMES = {"eg2-fp32-L512": "EmbeddingGemma 2 (fp32)", "eg2-fp16-L512": "EmbeddingGemma 2 (fp16)", "qwen-fp16-L512": "Qwen3-Embedding-4B", "qwen-fp16-L2048": "Qwen3-4B L2048", "bgem3-fp16-L512": "BGE-M3 (dense)"} COL = {"eg2-fp32": "var(--gemma)", "eg2-fp16": "var(--gemma2)", "qwen-fp16": "var(--qwen)", "qwen-fp16-L2048": "var(--qwen2)", "bgem3-fp16": "var(--bge)"} SPECNAME = {"eg2-fp32": "EmbeddingGemma 2 fp32", "eg2-fp16": "EmbeddingGemma 2 fp16", "qwen-fp16": "Qwen3-Emb-4B fp16", "qwen-fp16-L2048": "Qwen3-4B fp16 L2048", "bgem3-fp16": "BGE-M3 fp16"} MAIN = ["bgem3-fp16", "eg2-fp32", "qwen-fp16"] EN = ["SciFact", "NFCorpus", "ArguAna", "FiQA2018", "TRECCOVID"] VN = [t + "-VN" for t in EN] esc = html.escape def jl(p): return [json.loads(l) for l in open(p)] if p.exists() else [] Q = {} for spec in ["bgem3-fp16", "eg2-fp32", "eg2-fp16", "qwen-fp16", "qwen-fp16-L2048"]: for r in jl(RES / "quality" / f"{spec}.jsonl"): Q[(spec, r["task"], r["mode"], r.get("dim"))] = r S = {s: jl(RES / "speed" / f"{s}.jsonl") for s in ["bgem3-fp16", "eg2-fp32", "eg2-fp16", "qwen-fp16"]} def dense(spec, task): for k, v in Q.items(): if k[0] == spec and k[1] == task and k[2] == "dense" and v.get("n_docs"): return v return None def tasks_present(): ts = sorted({k[1] for k in Q}) order = EN + ["ZacLegalTextRetrieval"] + VN return [t for t in order if t in ts] # ---------- SVG helpers ---------- def grouped_bars(cats, series, maxv=None, w=760, h=280, unit="", fmt="{:.1f}"): """series: list of (label, color, [values or None])""" vals = [v for _, _, vs in series for v in vs if v is not None] if not vals: return "

no data yet

" maxv = maxv or max(vals) * 1.12 padl, padb, padt = 40, 58, 10 pw, ph = w - padl - 10, h - padb - padt gw = pw / len(cats) bw = min(26, (gw - 10) / len(series)) s = [f''] for g in range(5): y = padt + ph - ph * g / 4 s.append(f'' f'{maxv*g/4:.0f}') for i, c in enumerate(cats): x0 = padl + i * gw + (gw - bw * len(series)) / 2 for j, (lab, col, vs) in enumerate(series): v = vs[i] if v is None: continue bh = ph * v / maxv x = x0 + j * bw s.append(f'{esc(lab)} · {esc(c)}: {fmt.format(v)}{unit}') if bw >= 18: s.append(f'{fmt.format(v)}') lab = c.replace("TextRetrieval", "").replace("2018", "") s.append(f'{esc(lab)}') s.append("") return "".join(s) def line_chart(xs, series, w=760, h=280, ylab="", logy=False, xlab=""): vals = [v for _, _, vs, _ in series for v in vs if v] if not vals: return "

no data yet

" padl, padb, padt, padr = 58, 40, 12, 12 pw, ph = w - padl - padr, h - padb - padt ymin, ymax = (min(vals) / 1.5, max(vals) * 1.5) if logy else (0, max(vals) * 1.12) ty = (lambda v: (math.log10(v) - math.log10(ymin)) / (math.log10(ymax) - math.log10(ymin))) if logy else (lambda v: (v - ymin) / (ymax - ymin)) X = lambda i: padl + pw * i / (len(xs) - 1) Y = lambda v: padt + ph - ph * ty(v) s = [f''] ticks = [10 ** e * m for e in range(-1, 7) for m in (1, 3)] if logy else [ymax * g / 4 for g in range(5)] for t in ticks: if ymin <= t <= ymax: s.append(f'' f'{t:,.0f}') for i, x in enumerate(xs): s.append(f'{x}') s.append(f'{esc(xlab)}') s.append(f'{esc(ylab)}') for lab, col, vs, dash in series: pts = [(X(i), Y(v)) for i, v in enumerate(vs) if v] if not pts: continue s.append(f'') for (a, b), v in zip(pts, [v for v in vs if v]): s.append(f'{esc(lab)}: {v:,.1f}') s.append("") return "".join(s) def legend(items): return '
' + "".join(f'{esc(l)}' for l, c in items) + "
" def f1(v, d=1): return "—" if v is None else f"{v:.{d}f}" # ---------- sections ---------- tasks = tasks_present() en_t = [t for t in tasks if t in EN] vn_t = [t for t in tasks if t in VN] avg = {} for spec in MAIN: for grp, ts in (("en", en_t), ("vn", vn_t), ("zalo", ["ZacLegalTextRetrieval"])): xs = [dense(spec, t) for t in ts] xs = [x for x in xs if x] avg[(spec, grp)] = (np.mean([x["ndcg10"] for x in xs]) if xs and len(xs) == len(ts) else None, np.mean([x["mrr10"] for x in xs]) if xs and len(xs) == len(ts) else None) kpis = [] def best(grp, idx=0): c = [(avg[(s, grp)][idx], s) for s in MAIN if avg[(s, grp)][idx] is not None] return max(c) if c else (None, None) for grp, lab, idx in (("en", "English avg nDCG@10", 0), ("vn", "VN-MTEB (translated) avg nDCG@10", 0), ("zalo", "Zalo Legal (native VI) MRR@10", 1)): v, s = best(grp, idx) kpis.append((f1(v), lab, SPECNAME.get(s, "—"))) sp_best = {} for spec in MAIN: rows = [r for r in S.get(spec, []) if r.get("kind") == "sweep" and r["L"] == 512 and not r.get("oom")] if rows: sp_best[spec] = max(rows, key=lambda r: r["docs_s"]) if sp_best: s = max(sp_best, key=lambda k: sp_best[k]["docs_s"]) kpis.append((f"{sp_best[s]['docs_s']:.0f} docs/s", "fastest encode @512 tok", SPECNAME[s])) # quality table rows_html = [] for t in tasks: cells = [] for spec in MAIN: d = dense(spec, t) cells.append(d) vals = [c["ndcg10"] if c else -1 for c in cells] bi = int(np.argmax(vals)) if max(vals) >= 0 else -1 tds = "".join( f'{f1(c["ndcg10"]) if c else "—"} / {f1(c["recall100"]) if c else "—"} / {f1(c["mrr10"]) if c else "—"}' for i, c in enumerate(cells)) lang = "🇻🇳 native" if t.startswith("Zac") else ("🇻🇳 translated" if t.endswith("-VN") else "🇬🇧") nd = next((dense(s, t)["n_docs"] for s in MAIN if dense(s, t)), "") rows_html.append(f"{esc(t)}
{lang} · {nd:,} docs{tds}") for grp, lab in (("en", "Avg English"), ("vn", "Avg VN-MTEB (translated)")): tds = "".join(f"{f1(avg[(s, grp)][0])}" for s in MAIN) rows_html.append(f"{lab} nDCG@10{tds}") qtable = ("
" + "".join(f"" for s in MAIN) + "" + "".join(rows_html) + "
Task{SPECNAME[s]}

Cells: nDCG@10 / Recall@100 / MRR@10 (×100). The best nDCG@10 per row is highlighted. Max 512 tokens. Dense retrieval only (no reranker).

") ser = [(SPECNAME[s], COL[s], [dense(s, t)["ndcg10"] if dense(s, t) else None for t in tasks]) for s in MAIN] chart_q = grouped_bars(tasks, ser, maxv=100) # paired EN vs VN: rescore EN on exactly the VN query subset (same ids, identical qrels) from cached embeddings pairs = [t for t in en_t if t + "-VN" in vn_t] def en_on_vn_subset(spec, t): try: import data, pytrec_eval cf = CACHE / spec / f"{t}.pkl" if not cf.exists(): return None C = pickle.load(open(cf, "rb")) corpus, queries, qrels = data.load_task(t) _, _, qv = data.load_task(t + "-VN") keep = [i for i, q in enumerate(queries) if q["id"] in qv] Qe = C["q"][0] if isinstance(C["q"], tuple) else C["q"] Qe = np.nan_to_num(Qe[keep]); D = np.nan_to_num(C["docs"]["dense"]) dids = [d["id"] for d in corpus] run = {} for k, i in enumerate(keep): qid = queries[i]["id"] sc = D @ Qe[k] ix = np.argpartition(-sc, 101)[:101] ix = ix[np.argsort(-sc[ix])] run[qid] = {dids[j]: float(sc[j]) for j in ix if dids[j] != qid} sub = {q: qrels[q] for q in run} ev = pytrec_eval.RelevanceEvaluator(sub, {"ndcg_cut.10"}) return float(np.mean([v["ndcg_cut_10"] for v in ev.evaluate(run).values()]) * 100) except Exception as e: print("paired failed", spec, t, e) return None PAIRED = {(s, t): en_on_vn_subset(s, t) for s in MAIN for t in pairs if dense(s, t + "-VN")} drop_rows = "" for t in pairs: cells = "" for s in MAIN: en, vn = PAIRED.get((s, t)), dense(s, t + "-VN") if en is None or not vn: cells += "—" else: cells += f"{f1(en)} → {f1(vn['ndcg10'])} ({vn['ndcg10']-en:+.1f})" nq = next((dense(s, t + "-VN")["n_queries"] for s in MAIN if dense(s, t + "-VN")), "") drop_rows += f"{esc(t)}
{nq} paired queries{cells}" drop_tbl = ("
" + "".join(f"" for s in MAIN) + "" + drop_rows + "
EN → VN pair{SPECNAME[s]}

nDCG@10 in English → Vietnamese (Δ), with both computed on the same query subset. VN-MTEB keeps only some of the English queries (e.g. SciFact 134/300), with identical relevance labels, so English is re-scored on that subset from the cached embeddings. Same documents, machine-translated. More negative means a larger loss in Vietnamese.

") # BGE-M3 hybrid hy_modes = ["dense", "sparse", "multivector", "dense+sparse", "all", "dense+sparse(long)", "all(long)"] hy_cols = ["var(--bge)", "var(--muted2)", "var(--bge2)", "var(--accent2)", "var(--accent)", "var(--accent2l)", "var(--accentl)"] hy_tasks = [t for t in tasks if ("bgem3-fp16", t, "sparse", None) in Q] hy_ser = [] for m, c in zip(hy_modes, hy_cols): vs = [] for t in hy_tasks: r = dense("bgem3-fp16", t) if m == "dense" else Q.get(("bgem3-fp16", t, m, None)) vs.append(r["ndcg10"] if r else None) hy_ser.append((m, c, vs)) chart_hy = grouped_bars(hy_tasks, hy_ser, maxv=100) grid = sorted([v for k, v in Q.items() if k[0] == "bgem3-fp16" and k[1] == "ZacLegalTextRetrieval" and k[2].startswith("grid")], key=lambda r: r["mode"]) grid_rows = "".join(f"{esc(r['mode'].replace('grid ', ''))}{r['w']}{f1(r['ndcg10'])}{f1(r['mrr10'])}{f1(r['recall100'])}" for r in grid) zd = dense("bgem3-fp16", "ZacLegalTextRetrieval") grid_tbl = (f"
" f"{grid_rows}
Modew (dense, sparse, colbert)nDCG@10MRR@10R@100
dense only(1,0,0){f1(zd['ndcg10']) if zd else '—'}{f1(zd['mrr10']) if zd else '—'}{f1(zd['recall100']) if zd else '—'}
") if grid else "" # MRL mrl_html = "" for kind, spec, dims in (("Qwen3-4B", "qwen-fp16", [2560, 1024, 512, 256]), ("EmbeddingGemma 2", "eg2-fp32", [768, 512, 256, 128])): rows = [] for t in tasks: full = dense(spec, t) if not full: continue cells = [] for d in dims: r = full if d == dims[0] else Q.get((spec, t, "dense", d)) cells.append(f"{f1(r['ndcg10']) if r else '—'}") rows.append(f"{esc(t)}{''.join(cells)}") if rows: mrl_html += (f"

{kind}: Matryoshka truncation, nDCG@10

" + "".join(f"" for d in dims) + "" + "".join(rows) + "
Task{d}d
") # EG2 fp16 vs fp32 fp16_rows = [] for t in tasks: a, b = dense("eg2-fp32", t), dense("eg2-fp16", t) if not (a and b): continue cos = "—" try: A = pickle.load(open(CACHE / "eg2-fp32" / f"{t}.pkl", "rb"))["docs"]["dense"] B = pickle.load(open(CACHE / "eg2-fp16" / f"{t}.pkl", "rb"))["docs"]["dense"] c = (A * B).sum(1) cos = f"min {np.nanmin(c):.4f} · mean {np.nanmean(c):.5f}" except Exception: pass fp16_rows.append(f"{esc(t)}{b['nan_docs']}{cos}{f1(a['ndcg10'],2)}{f1(b['ndcg10'],2)}{b['ndcg10']-a['ndcg10']:+.2f}{a['docs_s']:.0f} → {b['docs_s']:.0f}") fp16_tbl = ("
" + "".join(fp16_rows) + "
TaskNaN docs (fp16)cos(fp16, fp32) per docnDCG fp32nDCG fp16Δdocs/s fp32 → fp16
") if fp16_rows else "

pending

" # Qwen L2048 l2 = dense("qwen-fp16-L2048", "ZacLegalTextRetrieval"); l5 = dense("qwen-fp16", "ZacLegalTextRetrieval") l2_html = (f"

Zalo Legal, Qwen3-4B: max_len 512 → nDCG@10 {f1(l5['ndcg10'])}, MRR@10 {f1(l5['mrr10'])}, encode {l5['enc_s']/60:.1f} min · " f"max_len 2048 → nDCG@10 {f1(l2['ndcg10'])}, MRR@10 {f1(l2['mrr10'])}, encode {l2['enc_s']/60:.1f} min. " f"{l5['frac_gt512']*100:.1f}% of documents exceed 512 tokens (mean {l5['tok_mean']:.0f}, p95 {l5['tok_p95']:.0f}).

") if (l2 and l5) else "

pending

" # speed charts LENS = [64, 128, 256, 512, 1024, 2048] SPS = [s for s in ["bgem3-fp16", "eg2-fp32", "eg2-fp16", "qwen-fp16"] if S.get(s)] def bestat(s, L, key="docs_s"): r = [x for x in S[s] if x.get("kind") == "sweep" and x["L"] == L and not x.get("oom")] return max((x[key] for x in r), default=None) ch_tok = line_chart(LENS, [(SPECNAME[s], COL[s], [bestat(s, L, "tok_s") for L in LENS], s == "eg2-fp16") for s in SPS], ylab="tokens / s (best batch)", xlab="sequence length (tokens)") ch_docs = line_chart(LENS, [(SPECNAME[s], COL[s], [bestat(s, L) for L in LENS], s == "eg2-fp16") for s in SPS], ylab="docs / s (log)", logy=True, xlab="sequence length (tokens)") BS = [1, 8, 16, 32, 64, 128] def at(s, L, bs, key): r = [x for x in S[s] if x.get("kind") == "sweep" and x["L"] == L and x["bs"] == bs and not x.get("oom")] return r[0][key] if r else None ch_bs = line_chart(BS, [(SPECNAME[s], COL[s], [at(s, 512, b, "docs_s") for b in BS], s == "eg2-fp16") for s in SPS], ylab="docs / s @ 512 tok", logy=True, xlab="batch size") sp_rows = [] for s in SPS: cold = next((x["seconds"] for x in S[s] if x["kind"] == "cold_load"), None) lat = next((x for x in S[s] if x["kind"] == "latency"), {}) tpw = next((x for x in S[s] if x["kind"] == "tok_per_word"), {}) vr = max((x.get("peak_vram_gib", 0) for x in S[s] if x.get("kind") == "sweep" and x["L"] == 512 and not x.get("oom")), default=None) oom = [f"L{x['L']}·bs{x['bs']}" for x in S[s] if x.get("oom") and not x.get("skipped")] clk = [x["sm_clock_mean"] for x in S[s] if x.get("sm_clock_mean")] sp_rows.append(f"{SPECNAME[s]}{f1(bestat(s,512))}{f1((bestat(s,512,'tok_s') or 0)/1e3)}k" f"{f1(lat.get('p50_ms'))} / {f1(lat.get('p95_ms'))}{f1(vr)}{f1(cold)}" f"{f1(tpw.get('en'),2)} / {f1(tpw.get('vi'),2)}{', '.join(oom) or 'none'}{f1(np.mean(clk) if clk else None,0)}") sp_tbl = ("
" + "".join(sp_rows) + "
Modeldocs/s @512tok/s @512query p50 / p95 mspeak VRAM @512 (GiB)cold load (s)tok/word EN / VIfirst OOMmean SM MHz
") # real workload throughput rw = [] for t in tasks: rw.append((t, [dense(s, t)["docs_s"] if dense(s, t) else None for s in MAIN])) ch_rw = grouped_bars([t for t, _ in rw], [(SPECNAME[s], COL[s], [v[i] for _, v in rw]) for i, s in enumerate(MAIN)], fmt="{:.0f}") tot_gpu = sum(v.get("enc_s", 0) + v.get("q_s", 0) for k, v in Q.items() if v.get("n_docs")) concl = Path("~/embed/report/conclusions.html") concl_html = concl.read_text() if concl.exists() else "

Automated report. Interpretation is added after review.

" CSS = open(Path(__file__).with_name("report.css")).read() page = f""" run 1 Embedding Benchmark

run 1 Embedding Benchmark

EmbeddingGemma 2 · Qwen3-Embedding-4B · BGE-M3 · English + Vietnamese retrieval and speed · stage: {esc(STAGE)} · total encode time so far {tot_gpu/3600:.2f} h

{legend([(SPECNAME[s], COL[s]) for s in MAIN] + [("EmbeddingGemma 2 fp16 (check)", COL['eg2-fp16'])])}
{''.join(f'
{a}
{esc(b)}
{esc(c)}
' for a, b, c in kpis)}

Conclusions

{concl_html}

1 · Retrieval quality (nDCG@10)

{chart_q}
{qtable}

2 · English vs Vietnamese (same docs, machine-translated)

{drop_tbl}

3 · BGE-M3: dense vs sparse vs multi-vector vs hybrid

{legend([(m, c) for m, c in zip(hy_modes, hy_cols)])}{chart_hy}

Sparse = full lexical retrieval. Other non-dense modes re-rank the union of the dense and sparse top-100 lists. Weights: dense+sparse (1, 0.3, 0); all (1, 0.3, 1); "long" variants (0.2, 0.8, 0) and (0.15, 0.5, 0.35), taken from the M3 paper. Heads reimplemented and checked against the BGE-M3 README reference outputs.

{('

Weight grid on Zalo Legal (native Vietnamese)

' + grid_tbl) if grid_tbl else ''}

4 · Matryoshka truncation

{mrl_html or "

pending

"}

5 · EmbeddingGemma 2: fp16 vs fp32 in run 1

{fp16_tbl}

Google says not to use fp16 for EmbeddingGemma 2. This table tests that claim on real corpora: NaN count, per-document cosine with fp32, and Δ nDCG.

6 · Long context: Qwen3-4B at 2048 tokens

{l2_html}

7 · Speed

Throughput vs sequence length (tokens/s)

{ch_tok}

Docs/s vs sequence length

{ch_docs}

Batch-size scaling @ 512 tokens

{ch_bs}

Real corpus encode rate (docs/s, quality runs)

{ch_rw}
{sp_tbl}

Synthetic 50/50 EN/VI texts trimmed to the exact token length; median of 3 runs after warm-up; end-to-end sentence-transformers encode including tokenization. Latency: 1,000 real queries (300 SciFact EN + 700 Zalo VI) at batch=1 with each model's query prompt. Cold load = process start → first vector, with weights in the page cache.

Setup

""" OUTF.write_text(page) print("wrote", OUTF) # send to Telegram tok, chat = os.environ.get("TELEGRAM_BOT_TOKEN"), os.environ.get("TELEGRAM_CHAT_ID") if tok and chat and "--no-send" not in sys.argv: b = uuid.uuid4().hex cap = f"📈 run 1 embedding benchmark report ({STAGE})" body = (f"--{b}\r\nContent-Disposition: form-data; name=\"chat_id\"\r\n\r\n{chat}\r\n" f"--{b}\r\nContent-Disposition: form-data; name=\"caption\"\r\n\r\n{cap}\r\n" f"--{b}\r\nContent-Disposition: form-data; name=\"document\"; filename=\"run1-embedding-benchmark-{STAGE}.html\"\r\nContent-Type: text/html\r\n\r\n").encode() + page.encode() + f"\r\n--{b}--\r\n".encode() req = urllib.request.Request(f"https://api.telegram.org/bot{tok}/sendDocument", body, {"Content-Type": f"multipart/form-data; boundary={b}"}) print(urllib.request.urlopen(req, timeout=60).read()[:100])