File size: 22,044 Bytes
36d9039 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | """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 "<p class='note'>no data yet</p>"
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'<svg viewBox="0 0 {w} {h}" class="chart" role="img">']
for g in range(5):
y = padt + ph - ph * g / 4
s.append(f'<line x1="{padl}" x2="{w-10}" y1="{y:.1f}" y2="{y:.1f}" class="grid"/>'
f'<text x="{padl-6}" y="{y+4:.1f}" class="ax" text-anchor="end">{maxv*g/4:.0f}</text>')
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'<rect x="{x:.1f}" y="{padt+ph-bh:.1f}" width="{bw-2:.1f}" height="{bh:.1f}" rx="2" fill="{col}"><title>{esc(lab)} · {esc(c)}: {fmt.format(v)}{unit}</title></rect>')
if bw >= 18:
s.append(f'<text x="{x+bw/2-1:.1f}" y="{padt+ph-bh-3:.1f}" class="bv" text-anchor="middle">{fmt.format(v)}</text>')
lab = c.replace("TextRetrieval", "").replace("2018", "")
s.append(f'<text x="{padl+i*gw+gw/2:.1f}" y="{padt+ph+16}" class="ax" text-anchor="middle">{esc(lab)}</text>')
s.append("</svg>")
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 "<p class='note'>no data yet</p>"
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'<svg viewBox="0 0 {w} {h}" class="chart" role="img">']
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'<line x1="{padl}" x2="{w-padr}" y1="{Y(t):.1f}" y2="{Y(t):.1f}" class="grid"/>'
f'<text x="{padl-6}" y="{Y(t)+4:.1f}" class="ax" text-anchor="end">{t:,.0f}</text>')
for i, x in enumerate(xs):
s.append(f'<text x="{X(i):.1f}" y="{h-padb+16}" class="ax" text-anchor="middle">{x}</text>')
s.append(f'<text x="{padl+pw/2}" y="{h-4}" class="ax" text-anchor="middle">{esc(xlab)}</text>')
s.append(f'<text x="12" y="{padt+ph/2}" class="ax" text-anchor="middle" transform="rotate(-90 12 {padt+ph/2})">{esc(ylab)}</text>')
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'<polyline points="{" ".join(f"{a:.1f},{b:.1f}" for a, b in pts)}" fill="none" stroke="{col}" stroke-width="2.2" {"stroke-dasharray=\"5 4\"" if dash else ""}/>')
for (a, b), v in zip(pts, [v for v in vs if v]):
s.append(f'<circle cx="{a:.1f}" cy="{b:.1f}" r="3.2" fill="{col}"><title>{esc(lab)}: {v:,.1f}</title></circle>')
s.append("</svg>")
return "".join(s)
def legend(items):
return '<div class="legend">' + "".join(f'<span><i class="dot" style="background:{c}"></i>{esc(l)}</span>' for l, c in items) + "</div>"
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'<td class="{"best" if i == bi else ""}">{f1(c["ndcg10"]) if c else "—"}<span class="sm"> / {f1(c["recall100"]) if c else "—"} / {f1(c["mrr10"]) if c else "—"}</span></td>'
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"<tr><td><b>{esc(t)}</b><br><span class='sm'>{lang} · {nd:,} docs</span></td>{tds}</tr>")
for grp, lab in (("en", "Avg English"), ("vn", "Avg VN-MTEB (translated)")):
tds = "".join(f"<td><b>{f1(avg[(s, grp)][0])}</b></td>" for s in MAIN)
rows_html.append(f"<tr class='avg'><td>{lab} nDCG@10</td>{tds}</tr>")
qtable = ("<div class='tbl'><table><tr><th>Task</th>" + "".join(f"<th><i class='dot' style='background:{COL[s]}'></i>{SPECNAME[s]}</th>" for s in MAIN)
+ "</tr>" + "".join(rows_html) + "</table></div><p class='note'>Cells: <b>nDCG@10</b> / Recall@100 / MRR@10 (×100). The best nDCG@10 per row is highlighted. Max 512 tokens. Dense retrieval only (no reranker).</p>")
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 += "<td>—</td>"
else:
cells += f"<td>{f1(en)} → {f1(vn['ndcg10'])} <b>({vn['ndcg10']-en:+.1f})</b></td>"
nq = next((dense(s, t + "-VN")["n_queries"] for s in MAIN if dense(s, t + "-VN")), "")
drop_rows += f"<tr><td>{esc(t)}<br><span class='sm'>{nq} paired queries</span></td>{cells}</tr>"
drop_tbl = ("<div class='tbl'><table><tr><th>EN → VN pair</th>" + "".join(f"<th>{SPECNAME[s]}</th>" for s in MAIN) + "</tr>" + drop_rows
+ "</table></div><p class='note'>nDCG@10 in English → Vietnamese (Δ), with both computed on <b>the same query subset</b>. 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.</p>")
# 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"<tr><td>{esc(r['mode'].replace('grid ', ''))}</td><td>{r['w']}</td><td>{f1(r['ndcg10'])}</td><td>{f1(r['mrr10'])}</td><td>{f1(r['recall100'])}</td></tr>" for r in grid)
zd = dense("bgem3-fp16", "ZacLegalTextRetrieval")
grid_tbl = (f"<div class='tbl'><table><tr><th>Mode</th><th>w (dense, sparse, colbert)</th><th>nDCG@10</th><th>MRR@10</th><th>R@100</th></tr>"
f"<tr><td>dense only</td><td>(1,0,0)</td><td>{f1(zd['ndcg10']) if zd else '—'}</td><td>{f1(zd['mrr10']) if zd else '—'}</td><td>{f1(zd['recall100']) if zd else '—'}</td></tr>{grid_rows}</table></div>") 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"<td>{f1(r['ndcg10']) if r else '—'}</td>")
rows.append(f"<tr><td>{esc(t)}</td>{''.join(cells)}</tr>")
if rows:
mrl_html += (f"<div class='card'><h3>{kind}: Matryoshka truncation, nDCG@10</h3><div class='tbl'><table><tr><th>Task</th>"
+ "".join(f"<th>{d}d</th>" for d in dims) + "</tr>" + "".join(rows) + "</table></div></div>")
# 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"<tr><td>{esc(t)}</td><td>{b['nan_docs']}</td><td>{cos}</td><td>{f1(a['ndcg10'],2)}</td><td>{f1(b['ndcg10'],2)}</td><td>{b['ndcg10']-a['ndcg10']:+.2f}</td><td>{a['docs_s']:.0f} → {b['docs_s']:.0f}</td></tr>")
fp16_tbl = ("<div class='tbl'><table><tr><th>Task</th><th>NaN docs (fp16)</th><th>cos(fp16, fp32) per doc</th><th>nDCG fp32</th><th>nDCG fp16</th><th>Δ</th><th>docs/s fp32 → fp16</th></tr>"
+ "".join(fp16_rows) + "</table></div>") if fp16_rows else "<p class='note'>pending</p>"
# Qwen L2048
l2 = dense("qwen-fp16-L2048", "ZacLegalTextRetrieval"); l5 = dense("qwen-fp16", "ZacLegalTextRetrieval")
l2_html = (f"<p>Zalo Legal, Qwen3-4B: max_len 512 → nDCG@10 <b>{f1(l5['ndcg10'])}</b>, MRR@10 {f1(l5['mrr10'])}, encode {l5['enc_s']/60:.1f} min · "
f"max_len 2048 → nDCG@10 <b>{f1(l2['ndcg10'])}</b>, 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}).</p>") if (l2 and l5) else "<p class='note'>pending</p>"
# 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"<tr><td><i class='dot' style='background:{COL[s]}'></i>{SPECNAME[s]}</td><td>{f1(bestat(s,512))}</td><td>{f1((bestat(s,512,'tok_s') or 0)/1e3)}k</td>"
f"<td>{f1(lat.get('p50_ms'))} / {f1(lat.get('p95_ms'))}</td><td>{f1(vr)}</td><td>{f1(cold)}</td>"
f"<td>{f1(tpw.get('en'),2)} / {f1(tpw.get('vi'),2)}</td><td>{', '.join(oom) or 'none'}</td><td>{f1(np.mean(clk) if clk else None,0)}</td></tr>")
sp_tbl = ("<div class='tbl'><table><tr><th>Model</th><th>docs/s @512</th><th>tok/s @512</th><th>query p50 / p95 ms</th><th>peak VRAM @512 (GiB)</th><th>cold load (s)</th><th>tok/word EN / VI</th><th>first OOM</th><th>mean SM MHz</th></tr>"
+ "".join(sp_rows) + "</table></div>")
# 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 "<p class='note'>Automated report. Interpretation is added after review.</p>"
CSS = open(Path(__file__).with_name("report.css")).read()
page = f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>run 1 Embedding Benchmark</title><style>{CSS}</style></head><body><main>
<h1>run 1 Embedding Benchmark</h1>
<p class="sub">EmbeddingGemma 2 · Qwen3-Embedding-4B · BGE-M3 · English + Vietnamese retrieval and speed · stage: <b>{esc(STAGE)}</b> · total encode time so far {tot_gpu/3600:.2f} h</p>
{legend([(SPECNAME[s], COL[s]) for s in MAIN] + [("EmbeddingGemma 2 fp16 (check)", COL['eg2-fp16'])])}
<div class="grid g4">{''.join(f'<div class="card kpi"><div class="n">{a}</div><div class="l">{esc(b)}</div><div class="w">{esc(c)}</div></div>' for a, b, c in kpis)}</div>
<h2>Conclusions</h2>{concl_html}
<h2>1 · Retrieval quality (nDCG@10)</h2><div class="card">{chart_q}</div>{qtable}
<h2>2 · English vs Vietnamese (same docs, machine-translated)</h2>{drop_tbl}
<h2>3 · BGE-M3: dense vs sparse vs multi-vector vs hybrid</h2>
<div class="card">{legend([(m, c) for m, c in zip(hy_modes, hy_cols)])}{chart_hy}
<p class="note">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.</p></div>
{('<h3>Weight grid on Zalo Legal (native Vietnamese)</h3>' + grid_tbl) if grid_tbl else ''}
<h2>4 · Matryoshka truncation</h2><div class="grid g2">{mrl_html or "<p class='note'>pending</p>"}</div>
<h2>5 · EmbeddingGemma 2: fp16 vs fp32 in run 1</h2>{fp16_tbl}
<p class="note">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.</p>
<h2>6 · Long context: Qwen3-4B at 2048 tokens</h2>{l2_html}
<h2>7 · Speed</h2>
<div class="grid g2"><div class="card"><h3>Throughput vs sequence length (tokens/s)</h3>{ch_tok}</div>
<div class="card"><h3>Docs/s vs sequence length</h3>{ch_docs}</div>
<div class="card"><h3>Batch-size scaling @ 512 tokens</h3>{ch_bs}</div>
<div class="card"><h3>Real corpus encode rate (docs/s, quality runs)</h3>{ch_rw}</div></div>
{sp_tbl}
<p class="note">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.</p>
<h2>Setup</h2>
<ul class="note"><li>Software: torch 2.15 cu132 · transformers 5.24 · sentence-transformers 6.3 · mteb 2.27 (datasets) · pytrec_eval (metrics)</li>
<li>EmbeddingGemma 2: <code>google/embeddinggemma-2</code>, text-only (vision/audio encoders off), fp32, query prefix <code>task: {{search result|question answering|fact checking}} | query:</code>, docs <code>title: {{t|none}} | text:</code></li>
<li>Qwen3-Embedding-4B: fp16, SDPA, left padding, last-token pooling, task-specific English instruction on queries only</li>
<li>BGE-M3: fp16, CLS dense + sparse + ColBERT heads (FlagEmbedding is incompatible with transformers 5, so the heads were reimplemented and validated)</li>
<li>All models: max 512 tokens unless stated; L2-normalised; cosine; exact top-100 search; mteb convention of dropping query-id self-hits (ArguAna)</li></ul>
</main></body></html>"""
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])
|