File size: 22,743 Bytes
36d9039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4342a6b
36d9039
 
 
 
4342a6b
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
"""Static HTML report (no JS needed) for the GPU Vietnamese embedding benchmark; sends it to Telegram."""
import json, os, math, html, uuid, urllib.request, sys
from pathlib import Path
import numpy as np

ROOT = Path("~/embed/run2"); R = ROOT / "results"
OUT = Path("~/embed/report/run2-vietnamese-report.html")
esc = html.escape
NATIVE = ["ZacLegalTextRetrieval", "TVPLRetrieval", "GreenNodeTableMarkdownRetrieval", "WebFAQRetrieval:vie", "VieQuADRetrieval",
          "MLQARetrieval:vie-vie", "XQuADRetrieval:vi", "BelebeleRetrieval:vie_Latn-vie_Latn", "PublicHealthQA:vietnamese"]
CORE4 = NATIVE[:4]
TRANS = ["SciFact-VN", "NFCorpus-VN", "ArguAna-VN", "FiQA2018-VN"]
SHORT = {"ZacLegalTextRetrieval": "Zalo Legal", "TVPLRetrieval": "TVPL legal", "GreenNodeTableMarkdownRetrieval": "Tables",
         "WebFAQRetrieval:vie": "WebFAQ", "VieQuADRetrieval": "ViQuAD", "MLQARetrieval:vie-vie": "MLQA", "XQuADRetrieval:vi": "XQuAD",
         "BelebeleRetrieval:vie_Latn-vie_Latn": "Belebele", "PublicHealthQA:vietnamese": "PublicHealth",
         "SciFact-VN": "SciFact-VN", "NFCorpus-VN": "NFCorpus-VN", "ArguAna-VN": "ArguAna-VN", "FiQA2018-VN": "FiQA-VN"}
PARAMS = {"harrier-0.6b": 0.596, "harrier-270m": 0.268, "f2llm-v2-8b": 7.57, "f2llm-v2-4b": 4.02, "f2llm-v2-1.7b": 1.72, "f2llm-v2-0.6b": 0.596, "f2llm-v2-330m": 0.334, "f2llm-v2-160m": 0.159, "f2llm-v2-80m": 0.08, "jina-v3": 0.572, "jina-v4": 3.75, "jina-v5-small": 0.596, "jina-v5-nano": 0.212, "aiteamvn-vn": 0.568, "aiteamvn-vn-v2": 0.568, "vintern-emb-1b": 0.938, "dvt-vn-emb": 0.135, "dvt-vn-doc-emb": 0.305, "me5-small": 0.118, "me5-large": 0.56, "nemotron35-8b": 8.38, "nemotron35-8b-nvfp4": 8.38, "nemotron35-1b": 1.56, "nemotron35-1b-nvfp4": 1.56, "granite-311m-multi-r2": 0.312, "nemotron3-8b": 7.95, "openembed-9b": 8.39, "openembed-4b": 4.54, "nemotron3-1b": 1.14, "omnievie-4b": 4.54, "openembed-2b": 2.21, "mistral-embed-1b": 1.24, "openembed-0.8b": 0.85, "qwen3-0.6b": 0.60,
          "skill-venus-0.6b": 0.60, "nandi-450m": 0.44, "embeddinggemma-300m": 0.30, "nandi-150m": 0.146, "para-multi-minilm-l12": 0.118,
          "all-mpnet-base": 0.109, "bge-base-en-v1.5": 0.109, "granite-97m-multi-r2": 0.097, "all-minilm-l12": 0.033, "all-minilm-l6": 0.023,
          "qwen-fp16": 4.02, "bgem3-fp16": 0.568, "eg2-fp32": 0.271,
          "qwen3-8b": 7.57, "qwen3-4b": 4.02, "text-embedding-3-small": None, "text-embedding-3-large": None, "gemini-embedding-2": None, "gemini-embedding-001": None, "voyage-4-lite": None, "pplx-embed-v1-0.6b": 0.6, "octen-8b": 7.57, "octen-4b": 4.02, "octen-0.6b": 0.60, "bge-m3": 0.568, "bge-m3-all": 0.568, "embeddinggemma-2": 0.271}
VI_SUPPORT = {"harrier-0.6b": "yes", "harrier-270m": "yes", "f2llm-v2-8b": "yes", "f2llm-v2-4b": "yes", "f2llm-v2-1.7b": "yes", "f2llm-v2-0.6b": "yes", "f2llm-v2-330m": "yes", "f2llm-v2-160m": "yes", "f2llm-v2-80m": "yes", "jina-v3": "yes", "jina-v4": "multilingual", "jina-v5-small": "multilingual", "jina-v5-nano": "multilingual", "aiteamvn-vn": "yes", "aiteamvn-vn-v2": "yes", "vintern-emb-1b": "yes", "dvt-vn-emb": "yes", "dvt-vn-doc-emb": "yes", "me5-small": "yes", "me5-large": "yes", "nemotron35-8b": "yes", "nemotron35-8b-nvfp4": "yes", "nemotron35-1b": "yes", "nemotron35-1b-nvfp4": "yes", "granite-311m-multi-r2": "yes", "nemotron3-8b": "yes", "nemotron3-1b": "yes", "openembed-9b": "EN card", "openembed-4b": "EN card", "omnievie-4b": "?", "openembed-2b": "EN card", "openembed-0.8b": "EN card", "mistral-embed-1b": "yes", "qwen3-0.6b": "yes",
              "skill-venus-0.6b": "via Qwen3", "nandi-450m": "no", "nandi-150m": "no", "embeddinggemma-300m": "yes", "para-multi-minilm-l12": "yes",
              "all-mpnet-base": "no", "bge-base-en-v1.5": "no", "granite-97m-multi-r2": "yes", "all-minilm-l12": "no", "all-minilm-l6": "no",
              "qwen3-8b": "yes", "qwen3-4b": "yes", "text-embedding-3-small": "API", "text-embedding-3-large": "API", "gemini-embedding-2": "API", "gemini-embedding-001": "API", "voyage-4-lite": "API", "pplx-embed-v1-0.6b": "API", "octen-8b": "multilingual", "octen-4b": "multilingual", "octen-0.6b": "multilingual", "bge-m3": "yes", "bge-m3-all": "yes", "embeddinggemma-2": "yes"}
T4KEYS = {"qwen3-4b": "Qwen3-Embedding-4B (run 1)", "bge-m3": "BGE-M3 (run 1)", "bge-m3-all": "BGE-M3 all three modes (run 1)", "embeddinggemma-2": "EmbeddingGemma 2 (run 1)"}

jobs = json.load(open(R / "jobs.json"))
M = {}  # (model, task, dim or 'main') -> rec
for p in sorted((R / "metrics").glob("*.jsonl")):
    lines = [json.loads(l) for l in p.read_text().splitlines() if l.strip()]
    for i, r in enumerate(lines):
        if i == 0:
            M[(r["model"], r["task"], "main")] = r
        M[(r["model"], r["task"], r.get("dim"))] = r
run 1 = json.load(open(ROOT / "t4_baselines.json"))
SMOKE = {}
for _l in open(R / "smoke.jsonl"):
    _r = json.loads(_l)
    if not _r.get("error"):
        SMOKE[_r["key"]] = _r
STAGE = next((a for a in sys.argv[1:] if not a.startswith("--")), "final")
T4HF = {"qwen3-4b": "Qwen/Qwen3-Embedding-4B", "bge-m3": "BAAI/bge-m3", "bge-m3-all": "BAAI/bge-m3 (dense+sparse+ColBERT)", "embeddinggemma-2": "google/embeddinggemma-2"}
for key, label in T4KEYS.items():
    for x in run 1:
        if x["model"] == label and (key, x["task"], "main") not in M:
            M[(key, x["task"], "main")] = {**x, "model": key, "hf": T4HF[key], "max_len": 512, "from_t4": True}
models = sorted({k[0] for k in M if "@" not in k[0] and "#" not in k[0]})
models = [m for m in models if m not in T4KEYS or all((m, t, "main") in M for t in CORE4)]
NO_VI = {"all-mpnet-base", "all-minilm-l6", "all-minilm-l12", "bge-base-en-v1.5", "nandi-150m", "nandi-450m"}  # removed: no Vietnamese support
models = [m for m in models if m not in NO_VI]  # run-1 models only once their native sets are in


def g(m, t, key="ndcg10", v="main"):
    r = M.get((m, t, v))
    return None if r is None else r.get(key)


def avg(m, ts, key="ndcg10"):
    xs = [g(m, t, key) for t in ts]
    return float(np.mean(xs)) if xs and all(x is not None for x in xs) else None


f1 = lambda v, d=1: "—" if v is None else f"{v:.{d}f}"
rank = sorted(models, key=lambda m: -(avg(m, CORE4) or -1))

# ---------- leaderboard ----------
mx = max([(avg(m, CORE4) or 0) for m in models] or [1]) or 1
lb = ""
for i, m in enumerate(rank):
    a = avg(m, CORE4)
    w = 0 if a is None else a / mx * 120
    t4note = " · run-1 model: Zalo + translated from run 1, other sets re-run on GPU" if m in T4KEYS else ""
    lb += (f"<tr class='{'t4m' if m in T4KEYS else ''}'><td>{i+1}</td><td><b>{esc(m)}</b><br><span class='sm'>{esc(M[(m, CORE4[0], 'main')]['hf'] if (m, CORE4[0], 'main') in M else '')}{t4note}</span></td>"
           f"<td>{(f'{PARAMS[m]:.2f}B' if PARAMS.get(m) else 'API')}</td><td>{VI_SUPPORT.get(m, '')}</td>"
           f"<td><span class='bar' style='width:{w:.0f}px'></span><b>{f1(a)}</b></td><td>{f1(avg(m, CORE4, 'p1'))}</td><td>{f1(avg(m, CORE4, 'mrr10'))}</td>"
           f"<td>{f1(avg(m, CORE4, 'recall10'))}</td><td>{f1(avg(m, CORE4, 'recall100'))}</td>"
           f"<td>{f1(g(m, 'ZacLegalTextRetrieval'))}</td><td>{f1(g(m, 'ZacLegalTextRetrieval', 'p1'))}</td><td>{f1(avg(m, NATIVE))}</td><td>{f1(avg(m, TRANS))}</td></tr>")
# run-1 models (not re-tested): only Zalo Legal + translated sets exist
_t4rows = [(b, par, vi) for b, par, vi in [("Qwen3-Embedding-4B (run 1)", 4.02, "yes"), ("BGE-M3 all three modes (run 1)", 0.568, "yes"), ("BGE-M3 (run 1)", 0.568, "yes"), ("EmbeddingGemma 2 (run 1)", 0.271, "yes")]
            if not any(T4KEYS.get(m) == b for m in models)]
if _t4rows:
    lb += "<tr class='t4sep'><td colspan='13'><b>run 1 benchmark (previous run)</b>: only Zalo Legal and the 4 translated sets so far, so native-4 is n/a</td></tr>"
for b, par, vi in _t4rows:
    rec = {x["task"]: x for x in run 1 if x["model"] == b}
    z = rec.get("ZacLegalTextRetrieval", {})
    tr = float(np.mean([rec[t]["ndcg10"] for t in TRANS])) if all(t in rec for t in TRANS) else None
    prec = "fp32" if "Gemma" in b else "fp16"
    lb += (f"<tr class='run1'><td>run 1</td><td><i>{esc(b)}</i><br><span class='sm'>GPU · {prec}{' · dense + sparse + multi-vector, re-scored top 100' if 'all three' in b else ''}</span></td>"
           f"<td>{par:.2f}B</td><td>{vi}</td><td class='na'>n/a</td><td class='na'>n/a</td><td class='na'>n/a</td><td class='na'>n/a</td><td class='na'>n/a</td>"
           f"<td><b>{f1(z.get('ndcg10'))}</b></td><td>{f1(z.get('p1'))}</td><td class='na'>n/a</td><td>{f1(tr)}</td></tr>")

# ---------- heatmap ----------
def cell(v, lo=0, hi=100):
    if v is None:
        return "<td>—</td>"
    a = max(0.06, min(1, (v - lo) / (hi - lo)))
    return f"<td style='background:rgba(37,99,235,{a*0.75:.2f});color:{'#fff' if a > 0.55 else 'inherit'}'>{v:.1f}</td>"


hm = "<tr><th>Model</th>" + "".join(f"<th>{SHORT[t]}</th>" for t in NATIVE) + "<th class='sep'></th>" + "".join(f"<th>{SHORT[t]}</th>" for t in TRANS) + "</tr>"
for m in rank:
    hm += f"<tr><td><b>{esc(m)}</b></td>" + "".join(cell(g(m, t)) for t in NATIVE) + "<td class='sep'></td>" + "".join(cell(g(m, t)) for t in TRANS) + "</tr>"
for b in [b for b in ["Qwen3-Embedding-4B (run 1)", "BGE-M3 (run 1)", "BGE-M3 all three modes (run 1)", "EmbeddingGemma 2 (run 1)"] if not any(T4KEYS.get(m) == b for m in models)]:
    rec = {x["task"]: x for x in run 1 if x["model"] == b}
    hm += (f"<tr class='run1'><td><i>{esc(b)}</i></td>" + "".join(cell(rec[t]["ndcg10"]) if t in rec else "<td class='na'>n/a</td>" for t in NATIVE)
           + "<td class='sep'></td>" + "".join(cell(rec[t]["ndcg10"]) if t in rec else "<td>—</td>" for t in TRANS) + "</tr>")

# ---------- overlap comparison with run 1 (Zalo + translated) ----------
OV = ["ZacLegalTextRetrieval"] + TRANS
ovrows = []
for m in models:
    ovrows.append((m, avg(m, OV), avg(m, OV, "p1"), g(m, "ZacLegalTextRetrieval"), g(m, "ZacLegalTextRetrieval", "p1"), g(m, "ZacLegalTextRetrieval", "mrr10"), False))
for b in ["Qwen3-Embedding-4B (run 1)", "BGE-M3 (run 1)", "BGE-M3 all three modes (run 1)", "EmbeddingGemma 2 (run 1)"]:
    rec = {x["task"]: x for x in run 1 if x["model"] == b}
    a = float(np.mean([rec[t]["ndcg10"] for t in OV])) if all(t in rec for t in OV) else None
    p = float(np.mean([rec[t]["p1"] for t in OV])) if all(t in rec and rec[t]["p1"] is not None for t in OV) else None
    z = rec.get("ZacLegalTextRetrieval", {})
    ovrows.append((b, a, p, z.get("ndcg10"), z.get("p1"), z.get("mrr10"), True))
ovrows.sort(key=lambda x: -(x[1] or -1))
ov = "".join(f"<tr class='{'run1' if run1 else ''}'><td>{'<i>' if run1 else '<b>'}{esc(n)}{'</i>' if run1 else '</b>'}</td><td>{f1(a)}</td><td>{f1(p)}</td><td>{f1(z)}</td><td>{f1(zp)}</td><td>{f1(zm)}</td></tr>"
             for n, a, p, z, zp, zm, run1 in ovrows)

# ---------- scatter: params vs Zalo nDCG ----------
def scatter():
    pts = [(PARAMS[m], g(m, "ZacLegalTextRetrieval"), m, False) for m in models if g(m, "ZacLegalTextRetrieval") is not None and PARAMS.get(m)]
    for spec, name in [("qwen-fp16", "Qwen3-4B (run 1)"), ("bgem3-fp16", "BGE-M3 (run 1)"), ("eg2-fp32", "EmbeddingGemma 2 (run 1)")]:
        z = [x for x in run 1 if x["spec"] == spec and x["task"] == "ZacLegalTextRetrieval"]
        if z:
            pts.append((PARAMS[spec], z[0]["ndcg10"], name, True))
    W, H, pl, pb, pt, pr = 760, 380, 50, 40, 12, 150
    lx = lambda p: pl + (math.log10(p) - math.log10(0.02)) / (math.log10(6) - math.log10(0.02)) * (W - pl - pr)
    ly = lambda v: pt + (1 - v / 100) * (H - pt - pb)
    s = [f'<svg viewBox="0 0 {W} {H}" class="chart">']
    for v in range(0, 101, 20):
        s.append(f'<line x1="{pl}" x2="{W-pr}" y1="{ly(v):.0f}" y2="{ly(v):.0f}" class="grid"/><text x="{pl-6}" y="{ly(v)+4:.0f}" class="ax" text-anchor="end">{v}</text>')
    for p in [0.03, 0.1, 0.3, 1, 3]:
        s.append(f'<text x="{lx(p):.0f}" y="{H-pb+16}" class="ax" text-anchor="middle">{p}B</text>')
    s.append(f'<text x="{pl+(W-pl-pr)/2}" y="{H-4}" class="ax" text-anchor="middle">parameters (log scale)</text>')
    for p, v, n, run1 in sorted(pts, key=lambda x: x[1]):
        c = "var(--accent)" if run1 else "var(--c1)"
        s.append(f'<circle cx="{lx(p):.1f}" cy="{ly(v):.1f}" r="5" fill="{c}"><title>{esc(n)}: {v:.1f}</title></circle>'
                 f'<text x="{lx(p)+8:.1f}" y="{ly(v)+4:.1f}" class="pl">{esc(n)} {v:.1f}</text>')
    s.append("</svg>")
    return "".join(s)

# ---------- speed / tokenization ----------
sp = ""
for m in rank:
    big = [M.get((m, t, "main")) for t in CORE4 + ["FiQA2018-VN"]]
    big = [x for x in big if x]
    if not big:
        continue
    sm = SMOKE.get(m, {})
    dps = sm.get("docs_per_s", float("nan"))
    tpw = np.mean([x["tok_per_word"] for x in big if "tok_per_word" in x]) if any("tok_per_word" in x for x in big) else None
    tr = np.mean([x["frac_truncated"] for x in big if "frac_truncated" in x]) * 100 if any("frac_truncated" in x for x in big) else None
    vr = max(x.get("peak_vram_gib", 0) for x in big)
    tot = sum(x.get("enc_docs_s", 0) + x.get("enc_q_s", 0) for x in M.values() if x["model"] == m and x.get("enc_docs_s") and (x["model"], x["task"], "main") in M and M[(x["model"], x["task"], "main")] is x)
    sp += f"<tr><td>{esc(m)}</td><td>{big[0].get('max_len', 512)}</td><td>{f1(tpw,2)}</td><td>{f1(tr)}%</td><td>{dps:,.0f}</td><td>{vr:.1f}</td><td>{tot/60:.1f}</td></tr>"

# ---------- MRL + OmniEVIE dims + fp16 ----------
mrl = ""
for m in rank:
    dims = sorted({k[2] for k in M if k[0] == m and isinstance(k[2], int)}, reverse=True)
    if len(dims) < 2:
        continue
    mrl += f"<tr><td>{esc(m)}</td>" + "".join(f"<td>{d}d: <b>{f1(avg_dim)}</b></td>" for d in dims
                                            for avg_dim in [float(np.mean([M[(m, t, d)]['ndcg10'] for t in CORE4])) if all((m, t, d) in M for t in CORE4) else None]) + "</tr>"
fp = ""
for t in ["ZacLegalTextRetrieval", "SciFact-VN"]:
    a, b = M.get(("qwen3-0.6b", t, "main")), M.get(("qwen3-0.6b@fp16", t, "main"))
    if a and b:
        fp += f"<tr><td>{SHORT[t]}</td><td>{a['ndcg10']:.2f}</td><td>{b['ndcg10']:.2f}</td><td>{b['ndcg10']-a['ndcg10']:+.2f}</td><td>{a['p1']:.2f} → {b['p1']:.2f}</td><td>{b.get('nan_rows',0)}</td></tr>"

LC = ["GreenNodeTableMarkdownRetrieval", "ZacLegalTextRetrieval", "TVPLRetrieval"]
lc = ""
for m in sorted({k[0].split("#")[0] for k in M if "#L" in k[0]}):
    row = f"<tr><td>{esc(m)}</td>"
    for t in LC:
        a, b = g(m, t), g(m + "#L2048", t)
        tr = M.get((m, t, "main"), {}).get("frac_truncated")
        row += f"<td>{f1(a)} → <b>{f1(b)}</b> ({'—' if a is None or b is None else f'{b-a:+.1f}'})<br><span class='sm'>{'' if tr is None else f'{tr*100:.0f}% of docs cut at 512'}</span></td>"
    lc += row + "</tr>"
done = len(list((R / "done").glob("*.done"))); failed = sorted(p.stem for p in (R / "done").glob("*.failed"))
concl = ROOT / "conclusions_pro.html"
CSS = (Path("~/embed/bench/report.css").read_text() +
       ".bar{display:inline-block;height:10px;border-radius:3px;background:var(--gemma);margin-right:6px;vertical-align:middle}"
       ".chart .pl{fill:var(--ink);font-size:10.5px}:root{--c1:var(--qwen)} tr.run1 td{color:var(--muted)} tr.t4sep td{background:var(--track);font-size:12.5px} tr.t4m td:first-child{border-left:3px solid var(--accent)} td.sep,th.sep{width:6px;padding:0;border:none} td.na{color:var(--muted2);font-size:11px}")
best = rank[0] if rank else "—"
small = [m for m in rank if (PARAMS.get(m) or 9) < 0.35]
page = f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Vietnamese Embedding Benchmark</title><style>{CSS}</style></head><body><main>
<h1>Vietnamese Embedding Benchmark</h1>
<p class="sub">{len(models)} embedding models (bf16) incl. Qwen3-Embedding-8B and the re-run run-1 models · 9 native Vietnamese + 4 machine-translated retrieval sets · {done}/{len(jobs)} jobs ({len(failed)} failed) · stage: {STAGE} · compared with the run-1 Qwen3-Embedding-4B, BGE-M3 and EmbeddingGemma 2 where the tasks overlap · built {__import__('datetime').datetime.now(__import__('zoneinfo').ZoneInfo('Asia/Ho_Chi_Minh')).strftime('%Y-%m-%d %H:%M')} GMT+7</p>
<div class="grid g4">
<div class="card kpi"><div class="n">{esc(best)}</div><div class="l">best native Vietnamese accuracy (avg nDCG@10 over the 4 large native sets: {f1(avg(best, CORE4))})</div></div>
<div class="card kpi"><div class="n">{esc(max(models, key=lambda m: avg(m, CORE4, 'p1') or -1)) if models else '—'}</div><div class="l">best P@1 on native Vietnamese (first result correct: {f1(max([(avg(m, CORE4, 'p1') or 0) for m in models] or [0]))}%)</div></div>
<div class="card kpi"><div class="n">{esc(small[0]) if small else '—'}</div><div class="l">best model under 350M params ({f1(avg(small[0], CORE4)) if small else '—'} nDCG@10)</div></div>
<div class="card kpi"><div class="n">{done}/{len(jobs)}</div><div class="l">jobs completed{(' · failed: ' + ', '.join(failed)) if failed else ''}</div></div>
</div>
<h2>Conclusions</h2>{concl.read_text() if concl.exists() else "<p class='note'>Interpretation is added after review.</p>"}
<h2>1 · Vietnamese leaderboard</h2>
<div class="tbl"><table><tr><th>#</th><th>Model</th><th>Params</th><th>VI in card</th><th>Native-4 nDCG@10</th><th>P@1</th><th>MRR@10</th><th>R@10</th><th>R@100</th><th>Zalo Legal nDCG@10</th><th>Zalo P@1</th><th>All 9 native nDCG</th><th>Translated-4 nDCG</th></tr>{lb}</table></div>
<p class="note">Native-4 = the four large human-written sets (Zalo Legal 818 q, TVPL 9,985 q, TableMarkdown 35,791 q, WebFAQ 10,000 q), averaged with equal weight. "All 9" adds ViQuAD, MLQA, XQuAD, Belebele and PublicHealthQA (smaller or easier, mostly Wikipedia QA). Max sequence length = min(model default, 512). The Zalo Legal and Translated-4 columns are the ones shared with the run 1 benchmark, so compare the grey run 1 rows on those two columns. BGE-M3 all three modes has no P@1 because the run 1 hybrid run didn't record it.</p>
<h2>2 · nDCG@10 per task (heatmap)</h2>
<div class="tbl"><table class="hm">{hm}</table></div>
<p class="note">Left block: native Vietnamese · right block: machine-translated VN-MTEB. Grey italic rows are the run-1 models (not re-tested, per decision). They only have scores where tasks overlap; "n/a" marks native sets they were never run on.</p>
<h2>3 · Head-to-head with the run-1 models (overlapping tasks)</h2>
<div class="tbl"><table><tr><th>Model</th><th>Avg nDCG@10 (Zalo + 4 translated)</th><th>Avg P@1</th><th>Zalo nDCG@10</th><th>Zalo P@1</th><th>Zalo MRR@10</th></tr>{ov}</table></div>
<h2>4 · Size vs Vietnamese legal accuracy (Zalo Legal nDCG@10)</h2><div class="card">{scatter()}</div>
<p class="note">Orange = run-1 models. Purple = models tested on the GPU.</p>
<h2>5 · Tokenization, truncation and throughput (measured during the run)</h2>
<div class="tbl"><table><tr><th>Model</th><th>Max len</th><th>Tokens / VI word</th><th>Docs truncated</th><th>Encode docs/s (smoke test, 1 job per GPU)</th><th>Peak VRAM GiB</th><th>Total encode min</th></tr>{sp}</table></div>
<p class="note">Throughput comes from the smoke test (one job per GPU, mixed real Vietnamese documents), because the full run deliberately ran 2 jobs per GPU (and some jobs on a gpu-b) to keep the GPUs at 100%, so its per-job timings aren't comparable. Tokens per word and truncation share come from the native-4 + FiQA-VN corpora with each model's own tokenizer (with its document prefix). English-only vocabularies break Vietnamese into many more tokens, and with 128–256-token windows they read only part of each document.</p>
<h2>6 · Embedding size: Matryoshka truncation (native-4 avg nDCG@10)</h2>
<div class="tbl"><table>{mrl or "<tr><td>pending</td></tr>"}</table></div>

<h2>7 · Long documents: 512 → 2,048 tokens (nDCG@10)</h2>
<div class="tbl"><table><tr><th>Model</th>""" + "".join(f"<th>{SHORT[t]}</th>" for t in LC) + f"""</tr>{lc or "<tr><td>pending</td></tr>"}</table></div>
<p class="note">Extra tier run after the main queue to keep the GPUs busy: the four long-context models with Vietnamese support, re-encoded with a 2,048-token window on the three native sets that have the longest documents.</p>
<h2>8 · bf16 vs fp16 spot-check (Qwen3-Embedding-0.6B)</h2>
<div class="tbl"><table><tr><th>Task</th><th>nDCG bf16</th><th>nDCG fp16</th><th>Δ</th><th>P@1 bf16 → fp16</th><th>NaN rows fp16</th></tr>{fp or "<tr><td>pending</td></tr>"}</table></div>
<h2>Method</h2>
<ul class="note">
<li>Software: torch 2.15 cu13.2, transformers 5.25.1, sentence-transformers 6.3.0, mteb 2.27 (datasets), pytrec_eval (metrics). Models pinned to the 2026-12-03 Hugging Face commits.</li>
<li>Each model uses its own input format: Qwen-style instruction on queries (Qwen3-0.6B, Skill-Venus), EmbeddingGemma prompts (embeddinggemma-300m, EmbeddingGemma 2), and plain text for the others. OpenEmbed's card has no text-search instruction, so <code>Find a passage that answers the given query.</code> is an assumption.</li>
<li>Exact search (no ANN): cosine top-100. Self-hits dropped (mteb convention). Metrics: nDCG@10, P@1, MRR@10, Recall@10, Recall@100.</li>
<li>run 1 rows: recomputed from the cached run 1 embeddings (dense) or taken from the run 1 hybrid run. Quality doesn't depend on the hardware; precision was fp16 (Qwen3-4B, BGE-M3) and fp32 (EmbeddingGemma 2).</li>
<li>EdgeCoder-31M was excluded (D6): it is a backbone, not an embedding model, and failed the smoke-test sanity pairs. OmniEVIE-4B was removed at your request before any of its jobs finished.</li><li>Jobs were shared through one queue across 2× GPU and 1× GPU (same library versions and model commits). Quality doesn't depend on which GPU ran a job; the throughput columns mix both GPU types (see the gpu field in the metrics files).</li>
</ul>
</main></body></html>"""
OUT.write_text(page)
print("wrote", OUT)
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
    body = (f"--{b}\r\nContent-Disposition: form-data; name=\"chat_id\"\r\n\r\n{chat}\r\n--{b}\r\nContent-Disposition: form-data; name=\"caption\"\r\n\r\n"
            f"📈 Vietnamese embedding benchmark ({STAGE}): 14 models (GPU + gpu-b) + run 1 baselines\r\n--{b}\r\nContent-Disposition: form-data; name=\"document\"; "
            f"filename=\"vietnamese-embedding-benchmark.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()[:80])