Commit ·
36d9039
0
Parent(s):
README charts: fix label overlaps, dodge overlapping dots, distinct hybrid colour, 2,048 status labels
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributesAdded+41
- README.mdAdded+94
- assets/bge_m3_modes.pngAdded
- assets/heatmap.pngAdded
- assets/leaderboard.pngAdded
- assets/long_context.pngAdded
- assets/mrl.pngAdded
- assets/size_vs_accuracy.pngAdded
- code/run1/data.pyAdded+15
- code/run1/gate.pyAdded+57
- code/run1/models.pyAdded+153
- code/run1/quality.pyAdded+180
- code/run1/report.cssAdded+16
- code/run1/report.pyAdded+360
- code/run1/speed.pyAdded+115
- code/run2/build8b.pyAdded+32
- code/run2/data.pyAdded+66
- code/run2/m3.pyAdded+120
- code/run2/plan_jobs.pyAdded+23
- code/run2/report_pro.pyAdded+242
- code/run2/score8b.pyAdded+108
- code/run2/shard8b.pyAdded+98
- code/run2/smoke.pyAdded+95
- code/run2/worker.pyAdded+241
- code/run2/zoo.pyAdded+148
- docs/datasets.mdAdded+43
- docs/methodology.mdAdded+57
- docs/models.mdAdded+34
- docs/results.mdAdded+38
- reports/run1-benchmark-report.htmlAdded+76
- reports/run2-vietnamese-benchmark-report.htmlAdded+77
- results/README.mdAdded+51
- results/per_query/bge-m3/arguana-vn__L512-fp16.csv.gzAdded+3
- results/per_query/bge-m3/arguana__L512-fp16.csv.gzAdded+3
- results/per_query/bge-m3/fiqa-vn__L512-fp16.csv.gzAdded+3
- results/per_query/bge-m3/fiqa__L512-fp16.csv.gzAdded+3
- results/per_query/bge-m3/nfcorpus-vn__L512-fp16.csv.gzAdded+3
- results/per_query/bge-m3/nfcorpus__L512-fp16.csv.gzAdded+3
- results/per_query/bge-m3/scifact-vn__L512-fp16.csv.gzAdded+3
- results/per_query/bge-m3/scifact__L512-fp16.csv.gzAdded+3
- results/per_query/bge-m3/trec-covid-vn__L512-fp16.csv.gzAdded+3
- results/per_query/bge-m3/trec-covid__L512-fp16.csv.gzAdded+3
- results/per_query/bge-m3/zalo-legal__L512-fp16.csv.gzAdded+3
- results/per_query/embeddinggemma-2/arguana-vn__L512-fp32.csv.gzAdded+3
- results/per_query/embeddinggemma-2/arguana__L512-fp32.csv.gzAdded+3
- results/per_query/embeddinggemma-2/belebele-vie__L512.csv.gzAdded+3
- results/per_query/embeddinggemma-2/fiqa-vn__L512-fp16.csv.gzAdded+3
- results/per_query/embeddinggemma-2/fiqa-vn__L512-fp32.csv.gzAdded+3
- results/per_query/embeddinggemma-2/fiqa__L512-fp32.csv.gzAdded+3
- results/per_query/embeddinggemma-2/mlqa-vie__L512.csv.gzAdded+3
1234567891011121314151617181920212223242526272829303132333435363738394041*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textassets/heatmap.png filter=lfs diff=lfs merge=lfs -textassets/leaderboard.png filter=lfs diff=lfs merge=lfs -textassets/size_vs_accuracy.png filter=lfs diff=lfs merge=lfs -textassets/bge_m3_modes.png filter=lfs diff=lfs merge=lfs -textassets/long_context.png filter=lfs diff=lfs merge=lfs -textassets/mrl.png filter=lfs diff=lfs merge=lfs -text12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394---license: apache-2.0language:- vi- entags:- embeddings- benchmark- retrieval- vietnamese- mteb---
# Vietnamese embedding benchmark
**21 open embedding models** scored on **Vietnamese retrieval**: 9 human-written Vietnamese datasets plus 4 machine-translated ones (≈ 340k documents, 80k queries). Exact search, no reranker.Updated 2026-12-03 23:37 GMT+7 · run in progress

<sub>¹ Zalo Legal and translated-set scores for these models come from run 1; the other sets from run 2. Same harness and metrics.</sub>
## Scores per dataset

## Accuracy vs model size

## Leaderboard table
| # | Model | Native-4 nDCG@10 | P@1 | MRR@10 | Zalo Legal | Translated-4 ||---:|---|---:|---:|---:|---:|---:|| 1 | [gemini-embedding-2](https://openrouter.ai/google/gemini-embedding-2) | **75.9** | 66.0 | 72.9 | 80.2 | 59.2 || 2 | [bge-m3-all](https://huggingface.co/BAAI/bge-m3) ¹ | **72.4** | — | 69.0 | 74.7 | 45.2 || 3 | [octen-8b](https://huggingface.co/Octen/Octen-Embedding-8B) | **71.2** | 60.2 | 67.8 | 73.8 | 56.8 || 4 | [qwen3-8b](https://huggingface.co/Qwen/Qwen3-Embedding-8B) | **70.7** | 59.5 | 67.3 | 75.1 | 54.2 || 5 | [octen-4b](https://huggingface.co/Octen/Octen-Embedding-4B) | **70.1** | 58.9 | 66.8 | 73.6 | 54.2 || 6 | [pplx-embed-v1-0.6b](https://openrouter.ai/perplexity/pplx-embed-v1-0.6b) | **70.0** | 58.7 | 66.5 | 70.1 | 47.5 || 7 | [openembed-2b](https://huggingface.co/UCSC-VLAA/OpenEmbed-2B) | **69.7** | 57.8 | 66.2 | 71.8 | 47.3 || 8 | [bge-m3](https://huggingface.co/BAAI/bge-m3) ¹ | **69.3** | 57.6 | 65.6 | 71.6 | 44.4 || 9 | [voyage-4-lite](https://openrouter.ai/mongodb/voyage-4-lite) | **69.1** | 57.5 | 65.6 | 68.2 | 50.8 || 10 | [qwen3-4b](https://huggingface.co/Qwen/Qwen3-Embedding-4B) ¹ | **68.4** | 57.3 | 65.1 | 76.7 | 52.8 || 11 | [skill-venus-0.6b](https://huggingface.co/inclusionAI/Skill-Venus-Embedding-0.6B) | **68.2** | 56.3 | 64.5 | 70.5 | 44.8 || 12 | [embeddinggemma-300m](https://huggingface.co/google/embeddinggemma-300m) | **66.8** | 54.1 | 63.1 | 67.9 | 47.1 || 13 | [openembed-0.8b](https://huggingface.co/UCSC-VLAA/OpenEmbed-0.8B) | **66.6** | 54.5 | 62.9 | 69.6 | 43.3 || 14 | [text-embedding-3-large](https://platform.openai.com/docs/guides/embeddings) | **66.5** | 53.7 | 62.6 | 65.3 | 46.4 || 15 | [octen-0.6b](https://huggingface.co/Octen/Octen-Embedding-0.6B) | **65.1** | 53.4 | 61.5 | 66.3 | 48.0 || 16 | [embeddinggemma-2](https://huggingface.co/google/embeddinggemma-2) ¹ | **65.1** | 53.2 | 61.5 | 69.6 | 45.9 || 17 | [qwen3-0.6b](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B) | **62.9** | 51.3 | 59.3 | 67.1 | 46.9 || 18 | [granite-97m-multi-r2](https://huggingface.co/ibm-granite/granite-embedding-97m-multilingual-r2) | **61.9** | 50.4 | 58.3 | 62.8 | 37.7 || 19 | [text-embedding-3-small](https://platform.openai.com/docs/guides/embeddings) | **58.4** | 46.2 | 54.4 | 56.5 | 35.8 || 20 | [mistral-embed-1b](https://huggingface.co/mistralai/Mistral-Multimodal-Embed-1B) | **39.9** | 27.6 | 35.8 | 35.2 | 28.2 || 21 | [para-multi-minilm-l12](https://huggingface.co/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2) | **39.4** | 28.6 | 35.7 | 41.3 | 28.1 |
Native-4 = mean over **Zalo Legal, TVPL, Table-Markdown, WebFAQ** (the four large human-written sets). Translated-4 = VN-MTEB SciFact / NFCorpus / ArguAna / FiQA. Metrics ×100.
## More findings



## Datasets
| Dataset | Domain | Docs | Queries | Source ||---|---|---:|---:|---|| Zalo AI Legal | Legal articles | 61,425 | 818 | [`GreenNode/zalo-ai-legal-text-retrieval-vn`](https://huggingface.co/datasets/GreenNode/zalo-ai-legal-text-retrieval-vn) || TVPL | Legal Q&A (thuvienphapluat) | 10,576 | 9,985 | [`GreenNode/TVPL-Retrieval-VN`](https://huggingface.co/datasets/GreenNode/TVPL-Retrieval-VN) || Table-Markdown | Tables (finance, encyclopedic) in Markdown | 44,678 | 35,791 | [`GreenNode/GreenNode-Table-Markdown-Retrieval-VN`](https://huggingface.co/datasets/GreenNode/GreenNode-Table-Markdown-Retrieval-VN) || WebFAQ (vie) | Web FAQ | 123,972 | 10,000 | [`mteb/WebFAQRetrieval`](https://huggingface.co/datasets/mteb/WebFAQRetrieval) || UIT-ViQuAD 2.0 | Wikipedia QA | 2,490 | 2,048 | [`taidng/UIT-ViQuAD2.0`](https://huggingface.co/datasets/taidng/UIT-ViQuAD2.0) || MLQA (vie-vie) | Wikipedia QA | 451 | 511 | [`mteb/MLQARetrieval`](https://huggingface.co/datasets/mteb/MLQARetrieval) || XQuAD (vi) | Wikipedia QA | 240 | 1,182 | [`mteb/XQuADRetrieval`](https://huggingface.co/datasets/mteb/XQuADRetrieval) || Belebele (vie) | Reading comprehension | 488 | 900 | [`mteb/belebele`](https://huggingface.co/datasets/mteb/belebele) || PublicHealthQA (vi) | Public health FAQ | 77 | 77 | [`xhluca/publichealth-qa`](https://huggingface.co/datasets/xhluca/publichealth-qa) || SciFact-VN (translated) | Scientific claims | 5,183 | 134 | [`GreenNode/scifact-vn`](https://huggingface.co/datasets/GreenNode/scifact-vn) || NFCorpus-VN (translated) | Medical | 3,618 | 166 | [`GreenNode/nfcorpus-vn`](https://huggingface.co/datasets/GreenNode/nfcorpus-vn) || ArguAna-VN (translated) | Counter-arguments | 8,674 | 1,295 | [`GreenNode/arguana-vn`](https://huggingface.co/datasets/GreenNode/arguana-vn) || FiQA-VN (translated) | Finance Q&A | 57,638 | 384 | [`GreenNode/fiqa-vn`](https://huggingface.co/datasets/GreenNode/fiqa-vn) |
Run 1 also covered English BEIR (SciFact, NFCorpus, ArguAna, FiQA, TREC-COVID) and TREC-COVID-VN; see [docs/datasets.md](docs/datasets.md).
## Documentation
- [docs/methodology.md](docs/methodology.md): how each model is benchmarked (input formats, pooling, precision, search, metrics, checks)- [docs/datasets.md](docs/datasets.md): every dataset, its source, size, domain and license- [docs/models.md](docs/models.md): every model, its size, input format and licence- [docs/results.md](docs/results.md): raw-data formats- `results/`: **raw data for analysis**, both runs merged. `scores.csv` (every model × dataset × configuration), `per_query/` (per-query metrics), `top10/` (ranked document ids per query), `speed/`- `reports/`: full HTML reports · `code/`: the harness123456789101112131415import mteb
def load_task(name): t = mteb.get_task(name) t.load_data() ds = t.dataset sub = ds[list(ds.keys())[0]] s = sub["test"] if "test" in sub else sub[list(sub.keys())[0]] corpus = [{"id": str(r["id"]), "title": r.get("title") or "", "text": r["text"] or ""} for r in s["corpus"]] queries = [{"id": str(r["id"]), "text": r["text"]} for r in s["queries"]] qrels = {str(q): {str(d): int(v) for d, v in docs.items()} for q, docs in s["relevant_docs"].items()} qids = set(qrels) queries = [q for q in queries if q["id"] in qids] return corpus, queries, qrels123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657"""Correctness gate: must pass before timing/quality runs."""import json, sys, time, gc, numpy as np, torchfrom common import RES, tgimport models
PAIRS = [ ("What causes the northern lights?", "The northern lights are caused by charged particles from the sun colliding with the atmosphere."), ("How do vaccines train the immune system?", "Vaccines expose the immune system to a harmless antigen so it can build memory cells."), ("Thời hạn nộp thuế thu nhập cá nhân là khi nào?", "Người nộp thuế phải quyết toán thuế thu nhập cá nhân chậm nhất là ngày cuối cùng của tháng thứ tư kể từ ngày kết thúc năm dương lịch."), ("Mức phạt khi vượt đèn đỏ đối với xe máy là bao nhiêu?", "Người điều khiển xe mô tô không chấp hành hiệu lệnh của đèn tín hiệu giao thông bị phạt tiền từ 4.000.000 đồng đến 6.000.000 đồng."), ("Phở bò Hà Nội được nấu như thế nào?", "Nước dùng phở bò được ninh từ xương bò cùng quế, hồi, gừng nướng và hành nướng trong nhiều giờ."), ("What is the capital of Australia?", "Canberra is the capital city of Australia, located in the Australian Capital Territory."),]
def check(spec, ref=None): t0 = time.time() m = models.load(spec) load_s = time.time() - t0 q = [p[0] for p in PAIRS] * 6 d = [{"title": "", "text": p[1]} for p in PAIRS] * 6 qe = m.encode_queries(q, "ZacLegalTextRetrieval") qe = qe[0] if isinstance(qe, tuple) else qe de = m.encode_docs(d)["dense"] nan = int(np.isnan(qe).sum() + np.isnan(de).sum()) n = len(PAIRS) S = qe[:n] @ de[:n].T top1 = float((S.argmax(1) == np.arange(n)).mean()) rec = {"spec": spec, "load_s": load_s, "nan": nan, "top1_pairs": top1, "diag_mean": float(np.diag(S).mean()), "offdiag_mean": float((S.sum() - np.trace(S)) / (n * n - n)), "peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30} if spec.startswith("qwen"): enc = m.tok(["short", "a much longer piece of text here"], padding=True) rec["left_pad_ok"] = enc["input_ids"][0][-1] == enc["input_ids"][1][-1] # both end in EOS rec["ends_with_eos"] = m.tok.decode(enc["input_ids"][0][-1:]) if ref is not None: cos = (qe * ref[0]).sum(1).tolist() + (de * ref[1]).sum(1).tolist() rec["cos_vs_fp32_min"] = float(np.nanmin(cos)) if not np.all(np.isnan(cos)) else None rec["cos_vs_fp32_mean"] = float(np.nanmean(cos)) if not np.all(np.isnan(cos)) else None print(json.dumps(rec), flush=True) del m; gc.collect(); torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats() return rec, (qe, de)
if __name__ == "__main__": out = [] r, ref = check("eg2-fp32"); out.append(r) r, _ = check("eg2-fp16", ref); out.append(r) r, _ = check("qwen-fp16"); out.append(r) r, _ = check("bgem3-fp16"); out.append(r) json.dump(out, open(RES / "gate" / "gate.json", "w"), indent=1) ok = all(x["nan"] == 0 and x["top1_pairs"] == 1.0 for x in out if x["spec"] != "eg2-fp16") ok = ok and out[2].get("left_pad_ok", False) lines = [f" {x['spec']}: NaN={x['nan']} top1={x['top1_pairs']:.2f} load={x['load_s']:.0f}s VRAM={x['peak_vram_gib']:.1f}GiB" + (f" cos_vs_fp32 min={x['cos_vs_fp32_min']}" if 'cos_vs_fp32_min' in x else "") for x in out] tg(("✅" if ok else "❌") + " Step 1: correctness gate\n" + "\n".join(lines)) sys.exit(0 if ok else 1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153"""Per-model encoder wrappers: prompts, pooling, precision handled explicitly."""import numpy as np, torchfrom huggingface_hub import snapshot_download
EG2 = "google/embeddinggemma-2"QWEN = "Qwen/Qwen3-Embedding-4B"BGE = "BAAI/bge-m3"
# Qwen3: query-only instruction (English, also for VI tasks, as recommended by Qwen)QWEN_INST = { "SciFact": "Given a scientific claim, retrieve documents that support or refute the claim", "NFCorpus": "Given a question, retrieve relevant documents that best answer the question", "ArguAna": "Given a claim, find documents that refute the claim", "FiQA2018": "Given a financial question, retrieve user replies that best answer the question", "TRECCOVID": "Given a query on COVID-19, retrieve documents that answer the query", "ZacLegalTextRetrieval": "Given a legal question, retrieve relevant legal articles that answer the question",}# EmbeddingGemma 2: task prefix per model-card use-case tableEG2_TASK = { "SciFact": "fact checking", "FiQA2018": "question answering", "ZacLegalTextRetrieval": "question answering",}
def base_task(task): return task[:-3] if task.endswith("-VN") else task
def doc_plain(d): t = (d.get("title") or "").strip() return (t + " " + d["text"]).strip() if t else d["text"]
class STEncoder: """sentence-transformers backed (EmbeddingGemma 2, Qwen3-Embedding-4B)."""
def __init__(self, kind, dtype="fp32", max_len=512, batch_size=32): from sentence_transformers import SentenceTransformer self.kind, self.dtype_name, self.max_len, self.bs = kind, dtype, max_len, batch_size dt = {"fp32": torch.float32, "fp16": torch.float16, "bf16": torch.bfloat16}[dtype] mk = {"torch_dtype": dt, "attn_implementation": "sdpa"} if kind == "eg2": self.m = SentenceTransformer(EG2, device="cuda", model_kwargs=mk, config_kwargs={"vision_config": None, "audio_config": None}) else: self.m = SentenceTransformer(QWEN, device="cuda", model_kwargs=mk, tokenizer_kwargs={"padding_side": "left"}) assert self.m.tokenizer.padding_side == "left", "Qwen3 needs left padding" self.m.max_seq_length = max_len self.tok = self.m.tokenizer self.name = f"{kind}-{dtype}-L{max_len}"
def query_prefix(self, task): bt = base_task(task) if self.kind == "eg2": return f"task: {EG2_TASK.get(bt, 'search result')} | query: " return f"Instruct: {QWEN_INST.get(bt, 'Given a web search query, retrieve relevant passages that answer the query')}\nQuery:"
def doc_text(self, d): if self.kind == "eg2": t = (d.get("title") or "").strip() or "none" return f"title: {t} | text: {d['text']}" return doc_plain(d)
def encode_texts(self, texts, batch_size=None): return self.m.encode(texts, batch_size=batch_size or self.bs, normalize_embeddings=True, convert_to_numpy=True, show_progress_bar=False).astype(np.float32)
def encode_queries(self, texts, task): p = self.query_prefix(task) return self.encode_texts([p + t for t in texts])
def encode_docs(self, docs, **kw): return {"dense": self.encode_texts([self.doc_text(d) for d in docs])}
class BGEM3Encoder: """BGE-M3 dense (CLS) + sparse (relu(linear)) + ColBERT heads, reimplemented from FlagEmbedding's BGEM3 inference (FlagEmbedding is incompatible with transformers 5)."""
def __init__(self, dtype="fp16", max_len=512, batch_size=64): from transformers import AutoModel, AutoTokenizer path = snapshot_download(BGE) dt = {"fp32": torch.float32, "fp16": torch.float16}[dtype] self.tok = AutoTokenizer.from_pretrained(path) self.model = AutoModel.from_pretrained(path, torch_dtype=dt, attn_implementation="sdpa").cuda().eval() self.colbert = torch.nn.Linear(1024, 1024) self.colbert.load_state_dict(torch.load(f"{path}/colbert_linear.pt", map_location="cpu")) self.sparse = torch.nn.Linear(1024, 1) self.sparse.load_state_dict(torch.load(f"{path}/sparse_linear.pt", map_location="cpu")) self.colbert = self.colbert.to("cuda", dt).eval() self.sparse = self.sparse.to("cuda", dt).eval() self.unused = {self.tok.cls_token_id, self.tok.eos_token_id, self.tok.pad_token_id, self.tok.unk_token_id} self.max_len, self.bs, self.dtype_name = max_len, batch_size, dtype self.name = f"bgem3-{dtype}-L{max_len}"
@torch.inference_mode() def _encode(self, texts, want_sparse=True, want_colbert=False, batch_size=None): bs = batch_size or self.bs order = np.argsort([-len(t) for t in texts]) dense = np.zeros((len(texts), 1024), np.float32) sparse = [None] * len(texts) colb = [None] * len(texts) for i in range(0, len(texts), bs): idx = order[i:i + bs] enc = self.tok([texts[j] for j in idx], padding=True, truncation=True, max_length=self.max_len, return_tensors="pt").to("cuda") h = self.model(**enc).last_hidden_state d = torch.nn.functional.normalize(h[:, 0].float(), dim=-1) dense[idx] = d.cpu().numpy() if want_sparse: w = torch.relu(self.sparse(h)).squeeze(-1).float().cpu().numpy() ids = enc["input_ids"].cpu().numpy() for r, j in enumerate(idx): sw = {} for t, v in zip(ids[r], w[r]): if t in self.unused or v <= 0: continue if v > sw.get(t, 0): sw[int(t)] = float(v) sparse[j] = sw if want_colbert: c = self.colbert(h[:, 1:]) * enc["attention_mask"][:, 1:, None] c = torch.nn.functional.normalize(c.float(), dim=-1) lens = enc["attention_mask"][:, 1:].sum(1).tolist() for r, j in enumerate(idx): colb[j] = c[r, :lens[r]].half().cpu().numpy() return dense, sparse, colb
def encode_texts(self, texts, batch_size=None): return self._encode(texts, want_sparse=False, batch_size=batch_size)[0]
def encode_queries(self, texts, task, colbert=False): d, s, c = self._encode(texts, True, colbert) return d, s, c
def encode_docs(self, docs, colbert=False): d, s, c = self._encode([doc_plain(x) for x in docs], True, colbert) return {"dense": d, "sparse": s, "colbert": c}
def load(spec): """spec: 'eg2-fp32', 'eg2-fp16', 'qwen-fp16', 'qwen-fp16-L2048', 'bgem3-fp16'""" parts = spec.split("-") kind, dtype = parts[0], parts[1] max_len = int(parts[2][1:]) if len(parts) > 2 else 512 if kind == "bgem3": return BGEM3Encoder(dtype, max_len) bs = {"eg2": 32, "qwen": 16}[kind] if max_len > 1024: bs = max(2, bs * 512 // max_len) return STEncoder(kind, dtype, max_len, bs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180"""Quality runs: encode (cached), dense retrieval, metrics, MRL ablation, BGE-M3 hybrid."""import sys, time, json, pickle, gcimport numpy as np, torch, pytrec_evalfrom common import RES, CACHE, append_jsonl, tgimport models, data
spec = sys.argv[1]tasks = sys.argv[2].split(",")OUT = RES / "quality" / f"{spec}.jsonl"K = 100MRL = {"qwen": [1024, 512, 256], "eg2": [512, 256, 128]}
def evaluate(qrels, run): ev = pytrec_eval.RelevanceEvaluator(qrels, {"ndcg_cut.10", "recall.100"}) r = ev.evaluate(run) nd = np.mean([v["ndcg_cut_10"] for v in r.values()]) rc = np.mean([v["recall_100"] for v in r.values()]) mrr = [] for q, docs in run.items(): rel = {d for d, s in qrels.get(q, {}).items() if s > 0} top = sorted(docs.items(), key=lambda x: -x[1])[:10] mrr.append(next((1 / (i + 1) for i, (d, _) in enumerate(top) if d in rel), 0.0)) return {"ndcg10": float(nd * 100), "recall100": float(rc * 100), "mrr10": float(np.mean(mrr) * 100)}
def topk_dense(Q, D, qids, dids, k=K): Dt = torch.from_numpy(D).cuda().half() run, cand = {}, {} for i in range(0, len(Q), 256): q = torch.from_numpy(Q[i:i + 256]).cuda().half() s = (q @ Dt.T).float() v, ix = s.topk(min(k + 1, s.shape[1]), dim=1) v, ix = v.cpu().numpy(), ix.cpu().numpy() for r in range(len(q)): qid = qids[i + r] res = {dids[j]: float(x) for j, x in zip(ix[r], v[r]) if dids[j] != qid} # mteb drops self-hits res = dict(list(res.items())[:k]) run[qid] = res cand[qid] = [j for j in ix[r] if dids[j] != qid][:k] del Dt; torch.cuda.empty_cache() return run, cand
def renorm(X, d): X = X[:, :d] return X / np.linalg.norm(X, axis=1, keepdims=True)
def sparse_matrix(sp, V=250002): from scipy.sparse import csr_matrix rows, cols, vals = [], [], [] for i, s in enumerate(sp): rows += [i] * len(s); cols += list(s.keys()); vals += list(s.values()) return csr_matrix((np.array(vals, np.float32), (rows, cols)), shape=(len(sp), V))
def run_task(m, task): corpus, queries, qrels = data.load_task(task) qids, dids = [q["id"] for q in queries], [d["id"] for d in corpus] cdir = CACHE / spec; cdir.mkdir(exist_ok=True) cf = cdir / f"{task}.pkl" info = {"spec": spec, "task": task, "n_docs": len(corpus), "n_queries": len(queries)} if cf.exists(): C = pickle.load(open(cf, "rb")) else: doc_tok = m.tok([models.doc_plain(d) for d in corpus], add_special_tokens=False)["input_ids"] lens = np.array([len(x) for x in doc_tok]) torch.cuda.synchronize(); torch.cuda.reset_peak_memory_stats(); t = time.time() enc = m.encode_docs(corpus) torch.cuda.synchronize(); td = time.time() - t t = time.time() qe = m.encode_queries([q["text"] for q in queries], task) tq = time.time() - t C = {"docs": enc, "q": qe, "enc_s": td, "q_s": tq, "tok_mean": float(lens.mean()), "tok_p95": float(np.percentile(lens, 95)), "frac_gt512": float((lens > 510).mean()), "tok_total": int(np.minimum(lens, 510).sum()), "peak_vram": torch.cuda.max_memory_allocated() / 2**30} pickle.dump(C, open(cf, "wb"), protocol=4) info.update({k: C[k] for k in ("enc_s", "q_s", "tok_mean", "tok_p95", "frac_gt512", "tok_total", "peak_vram")}) info["docs_s"] = len(corpus) / C["enc_s"] D = C["docs"]["dense"] Q = C["q"][0] if isinstance(C["q"], tuple) else C["q"] info["nan_docs"] = int(np.isnan(D).any(1).sum()); info["nan_q"] = int(np.isnan(Q).any(1).sum()) D = np.nan_to_num(D); Q = np.nan_to_num(Q) run, cand = topk_dense(Q, D, qids, dids) res = {**info, "mode": "dense", "dim": D.shape[1], **evaluate(qrels, run)} append_jsonl(OUT, res); print(json.dumps(res), flush=True) out = [res] for d in MRL.get(spec.split("-")[0], []): r2, _ = topk_dense(renorm(Q, d), renorm(D, d), qids, dids) rr = {"spec": spec, "task": task, "mode": "dense", "dim": d, **evaluate(qrels, r2)} append_jsonl(OUT, rr); out.append(rr) if spec.startswith("bgem3"): out += hybrid(m, task, corpus, queries, qrels, qids, dids, C, Q, D, cand) return out
def hybrid(m, task, corpus, queries, qrels, qids, dids, C, Q, D, dense_cand): t0 = time.time() Qs = sparse_matrix(C["q"][1]); Ds = sparse_matrix(C["docs"]["sparse"]).T.tocsc() S_sp = (Qs @ Ds).toarray() if len(qids) * len(dids) < 3e8 else None run_sp, cand = {}, {} for i, qid in enumerate(qids): s = S_sp[i] if S_sp is not None else (Qs[i] @ Ds).toarray()[0] ix = np.argpartition(-s, K + 1)[:K + 1] ix = ix[np.argsort(-s[ix])] ix = [j for j in ix if dids[j] != qid][:K] run_sp[qid] = {dids[j]: float(s[j]) for j in ix} cand[qid] = sorted(set(ix) | set(dense_cand[qid])) out = [] res = {"spec": spec, "task": task, "mode": "sparse", **evaluate(qrels, run_sp)} append_jsonl(OUT, res); out.append(res) # candidate scores: dense, sparse, colbert for union(dense top100, sparse top100) pairs = {qid: np.array(cand[qid]) for qid in qids} dense_s = {qid: Q[i] @ D[pairs[qid]].T for i, qid in enumerate(qids)} sp_s = {} for i, qid in enumerate(qids): sp_s[qid] = S_sp[i][pairs[qid]] if S_sp is not None else (Qs[i] @ Ds[:, pairs[qid]]).toarray()[0] # ColBERT: re-encode queries + candidate docs with colbert head, chunked over docs _, _, qc = m._encode([q["text"] for q in queries], False, True) qc_t = [torch.from_numpy(x).cuda() for x in qc] need = {} for i, qid in enumerate(qids): for pos, j in enumerate(pairs[qid]): need.setdefault(int(j), []).append((i, pos)) col_s = {qid: np.zeros(len(pairs[qid]), np.float32) for qid in qids} docs_needed = sorted(need) for c in range(0, len(docs_needed), 2048): chunk = docs_needed[c:c + 2048] _, _, dc = m._encode([models.doc_plain(corpus[j]) for j in chunk], False, True) for j, v in zip(chunk, dc): dv = torch.from_numpy(v).cuda() for i, pos in need[j]: s = (qc_t[i] @ dv.T).float().max(1).values.mean() col_s[qids[i]][pos] = s.item() info = {"colbert_docs": len(docs_needed), "hybrid_s": time.time() - t0}
def fused(w): run = {} for qid in qids: s = w[0] * dense_s[qid] + w[1] * sp_s[qid] + w[2] * col_s[qid] o = np.argsort(-s)[:K] run[qid] = {dids[pairs[qid][j]]: float(s[j]) for j in o} return run
combos = {"multivector": (0, 0, 1), "dense+sparse": (1, 0.3, 0), "all": (1, 0.3, 1), "dense+sparse(long)": (0.2, 0.8, 0), "all(long)": (0.15, 0.5, 0.35), "dense(rerank)": (1, 0, 0)} if task.startswith("ZacLegal"): for w2 in (0.1, 0.2, 0.5, 0.8, 1.0, 1.5): combos[f"grid d+s w2={w2}"] = (1, w2, 0) combos[f"grid all w2={w2}"] = (1, w2, 1) for name, w in combos.items(): res = {"spec": spec, "task": task, "mode": name, "w": w, **evaluate(qrels, fused(w)), **info} append_jsonl(OUT, res); out.append(res) return out
if __name__ == "__main__": m = models.load(spec) allres = [] for task in tasks: t = time.time() try: r = run_task(m, task) except Exception as e: import traceback; traceback.print_exc() tg(f"❌ {spec} on {task} failed: {type(e).__name__}: {str(e)[:300]}") continue allres += r d = r[0] extra = "" if spec.startswith("bgem3"): g = {x["mode"]: x for x in r} extra = (f"\n sparse {g['sparse']['ndcg10']:.1f} · multivec {g['multivector']['ndcg10']:.1f} · " f"d+s {g['dense+sparse']['ndcg10']:.1f} · all {g['all']['ndcg10']:.1f}") tg(f"📊 {spec} · {task}\n nDCG@10 {d['ndcg10']:.2f} · R@100 {d['recall100']:.2f} · MRR@10 {d['mrr10']:.2f}" f"\n {d['n_docs']} docs encoded in {d['enc_s']:.0f}s ({d['docs_s']:.0f} docs/s), NaN docs={d['nan_docs']}{extra}" f"\n task wall time {time.time()-t:.0f}s") gc.collect(); torch.cuda.empty_cache()12345678910111213141516:root{--bg:#f7f7f5;--panel:#fff;--ink:#1d1d1f;--muted:#5f6368;--muted2:#b9bcc2;--line:#e3e3e0;--track:#eeeeeb;--accent:#c2410c;--accentl:#f4a77c;--accent2:#d97706;--accent2l:#f5cf8a;--gemma:#2563eb;--gemma2:#93c5fd;--qwen:#7c3aed;--qwen2:#c4b5fd;--bge:#0f8a6a;--bge2:#5cc4a5;--best:#ecfdf5}@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#121214;--panel:#1b1b1f;--ink:#ececef;--muted:#a0a3aa;--muted2:#55585f;--line:#2c2c31;--track:#26262b;--accent:#fb923c;--accentl:#9a4a1c;--accent2:#fbbf24;--accent2l:#8a6a1c;--gemma:#60a5fa;--gemma2:#1e4f8f;--qwen:#a78bfa;--qwen2:#4c3a85;--bge:#34d399;--bge2:#1d7a5e;--best:#0d2a20}}:root[data-theme="dark"]{--bg:#121214;--panel:#1b1b1f;--ink:#ececef;--muted:#a0a3aa;--muted2:#55585f;--line:#2c2c31;--track:#26262b;--accent:#fb923c;--accentl:#9a4a1c;--accent2:#fbbf24;--accent2l:#8a6a1c;--gemma:#60a5fa;--gemma2:#1e4f8f;--qwen:#a78bfa;--qwen2:#4c3a85;--bge:#34d399;--bge2:#1d7a5e;--best:#0d2a20}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif}main{max-width:1100px;margin:0 auto;padding:28px 16px 64px}h1{font-size:28px;margin:0 0 6px}h2{font-size:20px;margin:38px 0 12px;padding-bottom:6px;border-bottom:1px solid var(--line)}h3{font-size:15px;margin:4px 0 8px}.sub{color:var(--muted);margin:0 0 14px}.grid{display:grid;gap:14px;margin:12px 0}.g4{grid-template-columns:repeat(auto-fit,minmax(200px,1fr))}.g2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}.card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px 16px;min-width:0;margin-bottom:12px}.kpi .n{font-size:24px;font-weight:700}.kpi .l{color:var(--muted);font-size:13px}.kpi .w{font-size:13px;font-weight:600;margin-top:2px}.dot{display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:6px;vertical-align:middle}.legend span{margin-right:14px;font-size:13px;white-space:nowrap}.tbl{width:100%;overflow-x:auto}table{border-collapse:collapse;width:100%;font-size:13.5px}th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:top}th{color:var(--muted);font-weight:600;font-size:12px;text-transform:uppercase;letter-spacing:.03em}td.best{background:var(--best);font-weight:700}tr.avg td{border-top:2px solid var(--line)}.sm{font-size:11.5px;color:var(--muted);font-weight:400}.note{font-size:12.5px;color:var(--muted)}code{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;background:var(--track);padding:1px 5px;border-radius:4px}.chart{width:100%;height:auto;display:block}.chart .grid{stroke:var(--line);stroke-width:1}.chart .ax{fill:var(--muted);font-size:11px}.chart .bv{fill:var(--ink);font-size:9.5px}.callout{border-radius:8px;padding:10px 14px;margin:10px 0;font-size:14px;background:var(--track)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360"""Build a static (no-JS-needed) HTML report from results/ and send it to Telegram."""import sys, json, os, html, math, pickle, urllib.request, uuidfrom pathlib import Pathimport numpy as npfrom 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"))] = rS = {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 tablerows_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 embeddingspairs = [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 hybridhy_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 ""
# MRLmrl_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 fp32fp16_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 L2048l2 = 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 chartsLENS = [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 Nonech_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 throughputrw = []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 Telegramtok, 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])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115"""Speed sweep: seq-length bucket x batch size, query latency, VRAM, cold load, clocks."""import sys, time, json, statistics, gcT_START = time.time()import numpy as np, torchfrom common import RES, GpuMonitor, append_jsonl, tgimport models, data
spec = sys.argv[1]OUT = RES / "speed" / f"{spec}.jsonl"OUT.unlink(missing_ok=True)
EN = ("The northern lights are caused by charged particles from the sun colliding with gases in the " "Earth's upper atmosphere. Researchers measure these interactions with satellites and ground stations, " "and the resulting data helps forecast geomagnetic storms that can affect power grids and GPS. ")VI = ("Người nộp thuế phải quyết toán thuế thu nhập cá nhân chậm nhất là ngày cuối cùng của tháng thứ tư " "kể từ ngày kết thúc năm dương lịch. Trường hợp chậm nộp hồ sơ sẽ bị xử phạt vi phạm hành chính theo " "quy định của pháp luật về quản lý thuế và các văn bản hướng dẫn thi hành. ")
m = models.load(spec)tok = m.tok_ = m.encode_texts(["warm up"])torch.cuda.synchronize()cold = time.time() - T_STARTappend_jsonl(OUT, {"spec": spec, "kind": "cold_load", "seconds": cold})
def make_texts(L, n): """n texts of ~L tokens each (half EN, half VI), varied offsets so batches are not identical.""" out = [] for i in range(n): base = (EN if i % 2 == 0 else VI) * (L // 20 + 4) ids = tok(base[i % 37:], add_special_tokens=False)["input_ids"][: max(1, L - 2)] out.append(tok.decode(ids)) return out
# tokens/word inflation for VI vs ENen_w, vi_w = len(EN.split()), len(VI.split())append_jsonl(OUT, {"spec": spec, "kind": "tok_per_word", "en": len(tok(EN, add_special_tokens=False)["input_ids"]) / en_w, "vi": len(tok(VI, add_special_tokens=False)["input_ids"]) / vi_w})
LENS = [64, 128, 256, 512, 1024, 2048]BS = [1, 8, 16, 32, 64, 128]mon = GpuMonitor()for L in LENS: if L > 512: # models' max_seq_length is 512 for the quality runs; raise for this sweep if hasattr(m, "m"): m.m.max_seq_length = L else: m.max_len = L oom = False for bs in BS: if oom: append_jsonl(OUT, {"spec": spec, "kind": "sweep", "L": L, "bs": bs, "oom": True, "skipped": True}) continue n = max(bs * 2, int(np.ceil(16384 / L))) n = int(np.ceil(n / bs) * bs) texts = make_texts(L, n) real_tok = sum(len(x) for x in tok(texts, truncation=True, max_length=L)["input_ids"]) try: torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats() m.encode_texts(texts[:bs], batch_size=bs) # warmup torch.cuda.synchronize() times = [] with mon: for _ in range(3): t = time.time(); m.encode_texts(texts, batch_size=bs); torch.cuda.synchronize() times.append(time.time() - t) dt = statistics.median(times) rec = {"spec": spec, "kind": "sweep", "L": L, "bs": bs, "n": n, "seconds": dt, "docs_s": n / dt, "tok_s": real_tok / dt, "peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30, **mon.summary()} except torch.OutOfMemoryError: oom = True rec = {"spec": spec, "kind": "sweep", "L": L, "bs": bs, "oom": True} gc.collect(); torch.cuda.empty_cache() append_jsonl(OUT, rec) print(json.dumps(rec), flush=True) if hasattr(m, "m"): m.m.max_seq_length = 512 else: m.max_len = 512
# query latency: 1000 real queries (SciFact EN + ZacLegal VI), batch=1, with the model's query prompt_, qs1, _ = data.load_task("SciFact")_, qs2, _ = data.load_task("ZacLegalTextRetrieval")qs = [("SciFact", q["text"]) for q in qs1[:300]] + [("ZacLegalTextRetrieval", q["text"]) for q in qs2[:700]]for task, q in qs[:20]: m.encode_queries([q], task)torch.cuda.synchronize()lat = []with mon: for task, q in qs: t = time.perf_counter(); m.encode_queries([q], task); torch.cuda.synchronize() lat.append((time.perf_counter() - t) * 1000)lat = np.array(lat)rec = {"spec": spec, "kind": "latency", "n": len(lat), "p50_ms": float(np.percentile(lat, 50)), "p95_ms": float(np.percentile(lat, 95)), "p99_ms": float(np.percentile(lat, 99)), "mean_ms": float(lat.mean()), **mon.summary()}append_jsonl(OUT, rec)print(json.dumps(rec), flush=True)
rows = [json.loads(l) for l in open(OUT)]best512 = max((r for r in rows if r.get("kind") == "sweep" and r["L"] == 512 and not r.get("oom")), key=lambda r: r["docs_s"], default=None)best128 = max((r for r in rows if r.get("kind") == "sweep" and r["L"] == 128 and not r.get("oom")), key=lambda r: r["docs_s"], default=None)thr = max((r.get("throttle_frac", 0) for r in rows if "throttle_frac" in r), default=0)tg(f"⚡ Speed: {spec}\n" f" cold load → first vector: {cold:.1f}s\n" f" L=128 best: {best128['docs_s']:.0f} docs/s ({best128['tok_s']/1e3:.1f}k tok/s, bs={best128['bs']})\n" f" L=512 best: {best512['docs_s']:.0f} docs/s ({best512['tok_s']/1e3:.1f}k tok/s, bs={best512['bs']}, {best512['peak_vram_gib']:.1f} GiB)\n" f" query latency bs=1: p50 {rec['p50_ms']:.1f} ms · p95 {rec['p95_ms']:.1f} ms\n" f" max throttled-sample fraction: {thr:.0%}")1234567891011121314151617181920212223242526272829303132"""Build $R8/jobs.json: ~5,000-doc shards per set (512 tier = prio 0; 2,048 tier on Zalo/Tables/TVPL = prio 1) + one query job per set.sec = Qwen-tokenizer tokens / assumed GPU throughput (tok/s from the smoke test, passed as argv[1])."""import os, sys, jsonfrom pathlib import Pathimport numpy as npfrom transformers import AutoTokenizerimport data, zoo
R8 = Path(os.path.expanduser(os.environ.get("R8", "~/embed/r8b"))); R8.mkdir(parents=True, exist_ok=True)TPS = float(sys.argv[1]) if len(sys.argv) > 1 else 6600.0tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-Embedding-8B")enc = zoo.MODELS["qwen3-8b"]SH = 5000jobs = []for tier, L, tasks in ((0, 512, data.TIER1 + data.TIER2), (1, 2048, ["GreenNodeTableMarkdownRetrieval", "ZacLegalTextRetrieval", "TVPLRetrieval"])): for t in tasks: corpus, queries, _ = data.load_task(t) texts = [data.doc_plain(d) for d in corpus] lens = np.array([len(x) for x in tok(texts, add_special_tokens=False)["input_ids"]]) capped = np.minimum(lens + 1, L) speed = TPS if L == 512 else TPS * 0.8 # longer sequences: attention costs more for s in range(0, len(corpus), SH): e = min(len(corpus), s + SH) jobs.append({"id": f"L{L}__{t.replace(':', '_')}__d{s:07d}", "type": "docs", "task": t, "L": L, "start": s, "end": e, "tokens": int(capped[s:e].sum()), "sec": float(capped[s:e].sum() / speed), "prio": tier}) if L == 512: # queries are short; the 2,048 tier reuses the 512 query embeddings jobs.append({"id": f"L512__{t.replace(':', '_')}__q", "type": "queries", "task": t, "L": 512, "start": 0, "end": len(queries), "tokens": len(queries) * 40, "sec": len(queries) * 40 / TPS, "prio": 0})json.dump(jobs, open(R8 / "jobs.json", "w"), indent=0)for p in (0, 1): js = [j for j in jobs if j["prio"] == p] print(f"tier {p}: {len(js)} jobs, {sum(j['tokens'] for j in js)/1e6:.1f}M tokens, {sum(j['sec'] for j in js)/3600:.2f} PRO-GPU-h")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""Task loading for the GPU run. Task spec: 'Name' or 'Name:hf_subset'.Handles both mteb dataset layouts (task.dataset[subset][split] and legacy task.corpus/queries/relevant_docs)."""import os, picklefrom pathlib import Pathimport mteb
DATA = Path(os.path.expanduser(os.environ.get("EMBED_DATA", "~/embed/data"))); DATA.mkdir(parents=True, exist_ok=True)
TIER1 = ["ZacLegalTextRetrieval", "TVPLRetrieval", "GreenNodeTableMarkdownRetrieval", "WebFAQRetrieval:vie", "VieQuADRetrieval", "MLQARetrieval:vie-vie", "XQuADRetrieval:vi", "BelebeleRetrieval:vie_Latn-vie_Latn", "PublicHealthQA:vietnamese"]TIER2 = ["SciFact-VN", "NFCorpus-VN", "ArguAna-VN", "FiQA2018-VN"]
def _pick(d, sub, split): if d is None: return None if sub is not None and sub in d: d = d[sub] elif sub is None and len(d) == 1 and split not in d: d = d[list(d.keys())[0]] if split in d: d = d[split] return d
def _load(spec): name, sub = (spec.split(":", 1) + [None])[:2] t = mteb.get_task(name, hf_subsets=[sub]) if sub else mteb.get_task(name) t.load_data() split = t.metadata.eval_splits[0] if t.dataset: ds = t.dataset s = ds[sub] if sub and sub in ds else ds[list(ds.keys())[0]] s = s[split] if split in s else s[list(s.keys())[0]] corpus = [{"id": str(r["id"]), "title": r.get("title") or "", "text": r["text"] or ""} for r in s["corpus"]] queries = [{"id": str(r["id"]), "text": r["text"]} for r in s["queries"]] rel = s["relevant_docs"] else: c, q, rel = _pick(t.corpus, sub, split), _pick(t.queries, sub, split), _pick(t.relevant_docs, sub, split) corpus = [{"id": str(k), "title": (v.get("title") or "") if isinstance(v, dict) else "", "text": (v.get("text") or "") if isinstance(v, dict) else str(v)} for k, v in c.items()] queries = [{"id": str(k), "text": v if isinstance(v, str) else v.get("text", "")} for k, v in q.items()] qrels = {str(q): {str(d): int(v) for d, v in docs.items()} for q, docs in rel.items()} queries = [q for q in queries if q["id"] in qrels] return corpus, queries, qrels
def load_task(spec): f = DATA / (spec.replace(":", "__").replace("/", "_") + ".pkl") if f.exists(): return pickle.load(open(f, "rb")) out = _load(spec) pickle.dump(out, open(f, "wb"), protocol=4) return out
def doc_plain(d): t = (d.get("title") or "").strip() return (t + " " + d["text"]).strip() if t else d["text"]
if __name__ == "__main__": for s in TIER1 + TIER2: c, q, r = load_task(s) print(f"DS\t{s}\t{len(c)}\t{len(q)}\t{sum(len(v) for v in r.values())}", flush=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120"""BGE-M3 on the GPU: dense + sparse + ColBERT heads (same reimplementation as run 1, validated against theBGE-M3 README), with the same hybrid modes: candidates = union(dense top-100, sparse top-100), then re-scored."""import timeimport numpy as np, torchfrom huggingface_hub import snapshot_download
K = 100
class M3: def __init__(self, max_len=512, bs=128): from transformers import AutoModel, AutoTokenizer import os hub = os.path.join(os.environ.get("HF_HOME", os.path.expanduser("~/.cache/huggingface")), "hub", "models--BAAI--bge-m3") path = os.path.join(hub, "snapshots", open(os.path.join(hub, "refs", "main")).read().strip()) # local copy (onnx/imgs not downloaded) self.tok = AutoTokenizer.from_pretrained(path) self.model = AutoModel.from_pretrained(path, dtype=torch.float16, attn_implementation="sdpa").cuda().eval() self.colbert = torch.nn.Linear(1024, 1024); self.colbert.load_state_dict(torch.load(f"{path}/colbert_linear.pt", map_location="cpu")) self.sparse = torch.nn.Linear(1024, 1); self.sparse.load_state_dict(torch.load(f"{path}/sparse_linear.pt", map_location="cpu")) self.colbert = self.colbert.to("cuda", torch.float16).eval(); self.sparse = self.sparse.to("cuda", torch.float16).eval() self.unused = {self.tok.cls_token_id, self.tok.eos_token_id, self.tok.pad_token_id, self.tok.unk_token_id} self.max_len, self.bs = max_len, bs
@torch.inference_mode() def encode(self, texts, sparse=True, colbert=False): order = np.argsort([-len(t) for t in texts]) dense = np.zeros((len(texts), 1024), np.float32); sp = [None] * len(texts); cb = [None] * len(texts) for i in range(0, len(texts), self.bs): idx = order[i:i + self.bs] enc = self.tok([texts[j] for j in idx], padding=True, truncation=True, max_length=self.max_len, return_tensors="pt").to("cuda") h = self.model(**enc).last_hidden_state dense[idx] = torch.nn.functional.normalize(h[:, 0].float(), dim=-1).cpu().numpy() if sparse: w = torch.relu(self.sparse(h)).squeeze(-1).float().cpu().numpy(); ids = enc["input_ids"].cpu().numpy() for r, j in enumerate(idx): d = {} for t, v in zip(ids[r], w[r]): if t not in self.unused and v > 0 and v > d.get(int(t), 0): d[int(t)] = float(v) sp[j] = d if colbert: c = torch.nn.functional.normalize((self.colbert(h[:, 1:]) * enc["attention_mask"][:, 1:, None]).float(), dim=-1) lens = enc["attention_mask"][:, 1:].sum(1).tolist() for r, j in enumerate(idx): cb[j] = c[r, :lens[r]].half() # stays on GPU return dense, sp, cb
def _csr(sp, V=250002): from scipy.sparse import csr_matrix rows, cols, vals = [], [], [] for i, s in enumerate(sp): rows += [i] * len(s); cols += list(s.keys()); vals += list(s.values()) return csr_matrix((np.array(vals, np.float32), (rows, cols)), shape=(len(sp), V))
def run_m3(m3, corpus, queries, qrels, task, doc_text, evaluate, to_run): """Returns list of metric dicts (mode=dense/sparse/multivector/dense+sparse/all).""" qids, dids = [q["id"] for q in queries], [d["id"] for d in corpus] t0 = time.time() Dd, Ds, _ = m3.encode([doc_text(d) for d in corpus], True, False) Qd, Qs, Qc = m3.encode([q["text"] for q in queries], True, True) enc_s = time.time() - t0 # dense top-100 (GPU) Dt = torch.from_numpy(Dd).cuda().half(); dense_ix, out = [], {} for i in range(0, len(Qd), 1024): v, ix = (torch.from_numpy(Qd[i:i + 1024]).cuda().half() @ Dt.T).float().topk(min(K + 1, len(dids)), dim=1) dense_ix.append(ix.cpu().numpy()); out.setdefault("dv", []).append(v.cpu().numpy()) dense_ix = np.concatenate(dense_ix); dv = np.concatenate(out["dv"]); del Dt res = {"dense": to_run(dv, dense_ix, qids, dids)} # sparse full retrieval (CPU, chunked) QS, DS = _csr(Qs), _csr(Ds).T.tocsc() sp_ix, sp_v = [], [] for i in range(0, len(qids), 2000): S = (QS[i:i + 2000] @ DS).toarray() ix = np.argpartition(-S, min(K + 1, S.shape[1] - 1), axis=1)[:, :K + 1] sv = np.take_along_axis(S, ix, 1); o = np.argsort(-sv, 1) sp_ix.append(np.take_along_axis(ix, o, 1)); sp_v.append(np.take_along_axis(sv, o, 1)) sp_ix = np.concatenate(sp_ix); res["sparse"] = to_run(np.concatenate(sp_v), sp_ix, qids, dids) # candidate union per query; dense + sparse scores for every candidate cand = [np.unique(np.concatenate([dense_ix[i], sp_ix[i]])) for i in range(len(qids))] dsc = [Qd[i] @ Dd[c].T for i, c in enumerate(cand)] ssc = [np.asarray((QS[i] @ DS[:, c]).todense()).ravel() for i, c in enumerate(cand)] # ColBERT: per doc chunk, score each doc against all queries that have it as a candidate (doc vectors computed once) need = {} for i, c in enumerate(cand): for pos, j in enumerate(c): need.setdefault(int(j), []).append((i, pos)) csc = [np.zeros(len(c), np.float32) for c in cand] Lq = max(x.shape[0] for x in Qc) QC = torch.zeros(len(Qc), Lq, 1024, dtype=torch.float16, device="cuda"); QM = torch.zeros(len(Qc), Lq, device="cuda") for i, x in enumerate(Qc): QC[i, :len(x)] = x; QM[i, :len(x)] = 1 qlen = QM.sum(1) docs = sorted(need, key=lambda j: len(doc_text(corpus[j]))) for c0 in range(0, len(docs), 256): chunk = docs[c0:c0 + 256] _, _, DC = m3.encode([doc_text(corpus[j]) for j in chunk], False, True) for j, dvec in zip(chunk, DC): pairs = need[j]; qi = torch.tensor([p[0] for p in pairs], device="cuda") for b in range(0, len(pairs), 4096): q = QC[qi[b:b + 4096]] # [B, Lq, h] s = torch.einsum("bqh,lh->bql", q, dvec).float().amax(-1) # [B, Lq] s = (s * QM[qi[b:b + 4096]]).sum(1) / qlen[qi[b:b + 4096]] for (i, pos), v in zip(pairs[b:b + 4096], s.tolist()): csc[i][pos] = v recs = [] for name, run in res.items(): recs.append({"mode": name, **evaluate(qrels, run)}) for name, w in {"multivector": (0, 0, 1), "dense+sparse": (1, 0.3, 0), "all": (1, 0.3, 1)}.items(): run = {} for i, qid in enumerate(qids): s = w[0] * dsc[i] + w[1] * ssc[i] + w[2] * csc[i] o = np.argsort(-s) run[qid] = {dids[cand[i][k]]: float(s[k]) for k in o if dids[cand[i][k]] != qid} run[qid] = dict(list(run[qid].items())[:K]) recs.append({"mode": name, "w": w, **evaluate(qrels, run)}) for r in recs: r.update({"enc_s": enc_s, "total_s": time.time() - t0}) return recs1234567891011121314151617181920212223"""Build results/jobs.json from smoke-test projections (sec per model x task)."""import json, osfrom pathlib import Pathimport dataR = Path(os.path.expanduser("~/embed/results"))proj = {}for l in open(R / "smoke.jsonl"): r = json.loads(l) if not r.get("error"): proj[r["key"]] = r["proj"]jobs = []for m, p in proj.items(): if m == "edgecoder-31m": # D6: dropped continue for t in data.TIER1 + data.TIER2: j = {"model": m, "task": t, "sec": p[t]["sec"]} if m == "omnievie-4b" and t in ("ZacLegalTextRetrieval", "TVPLRetrieval"): j["dim512"] = True # D8-C jobs.append(j)for t in ("ZacLegalTextRetrieval", "SciFact-VN"): # D2 fp16 spot-check jobs.append({"model": "qwen3-0.6b@fp16", "task": t, "sec": proj["qwen3-0.6b"][t]["sec"]})json.dump(jobs, open(R / "jobs.json", "w"), indent=0)print(len(jobs), "jobs, total %.2f GPU-h" % (sum(j["sec"] for j in jobs) / 3600))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242"""Static HTML report (no JS needed) for the GPU Vietnamese embedding benchmark; sends it to Telegram."""import json, os, math, html, uuid, urllib.request, sysfrom pathlib import Pathimport numpy as np
ROOT = Path("~/embed/run2"); R = ROOT / "results"OUT = Path("~/embed/report/run2-vietnamese-report.html")esc = html.escapeNATIVE = ["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 = {"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 = {"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') -> recfor 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"))] = rrun 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"]] = _rSTAGE = 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 supportmodels = [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 1lb = ""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"] + TRANSovrows = []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])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""Local (CPU) merge + exact search + metrics for Qwen3-8B, per set as soon as all its shards are here.Writes results/metrics/qwen3-8b__<task>.jsonl (and qwen3-8b#L2048__...) in the report's format; Telegram per set; final report at the end."""import os, json, time, subprocess, urllib.request, urllib.parsefrom pathlib import Pathimport numpy as np, pytrec_evalos.environ.setdefault("EMBED_DATA", "~/embed/run2/data_relay")import data
ROOT = Path(os.path.expanduser(os.environ.get("SCORE_ROOT", "~/embed/run2"))); R8 = ROOT / "r8b"; MET = ROOT / "results" / "metrics"MET.mkdir(parents=True, exist_ok=True)STATE = R8 / "score_state.json"st = json.loads(STATE.read_text()) if STATE.exists() else {"scored": [], "final": False, "start": time.time(), "hb": 0}K = 100
def tg(msg): tok, chat = os.environ.get("TELEGRAM_BOT_TOKEN"), os.environ.get("TELEGRAM_CHAT_ID") print("[tg]", msg, flush=True) if tok and chat: try: urllib.request.urlopen(f"https://api.telegram.org/bot{tok}/sendMessage", urllib.parse.urlencode({"chat_id": chat, "text": msg[:4000]}).encode(), timeout=30).read() except Exception as e: print("tg fail", e)
def evaluate(qrels, run): ev = pytrec_eval.RelevanceEvaluator(qrels, {"ndcg_cut.10", "recall.10", "recall.100", "P.1"}).evaluate(run) m = lambda k: float(np.mean([v[k] for v in ev.values()]) * 100) mrr = [] for q, docs in run.items(): rel = {d for d, s in qrels.get(q, {}).items() if s > 0} top = sorted(docs.items(), key=lambda x: -x[1])[:10] mrr.append(next((1 / (i + 1) for i, (d, _) in enumerate(top) if d in rel), 0.0)) return {"ndcg10": m("ndcg_cut_10"), "p1": m("P_1"), "mrr10": float(np.mean(mrr) * 100), "recall10": m("recall_10"), "recall100": m("recall_100")}
def search(Q, D, qids, dids): run = {} for i in range(0, len(Q), 512): S = Q[i:i + 512] @ D.T ix = np.argpartition(-S, min(K + 1, S.shape[1] - 1), axis=1)[:, :K + 1] for r in range(len(S)): o = ix[r][np.argsort(-S[r, ix[r]])] qid = qids[i + r] run[qid] = {dids[j]: float(S[r, j]) for j in o if dids[j] != qid} return run
def norm(X, d=None): X = X[:, :d] if d else X return X / np.linalg.norm(X, axis=1, keepdims=True)
jobs = json.load(open(R8 / "jobs.json"))done = {p.stem for p in (R8 / "done").glob("*.done")}failed = {p.stem for p in (R8 / "done").glob("*.failed")} - donegroups = {}for j in jobs: groups.setdefault((j["L"], j["task"]), []).append(j)
for (L, task), js in sorted(groups.items(), key=lambda x: (x[0][0], x[0][1])): key = f"L{L}__{task}" if key in st["scored"] or not all(j["id"] in done for j in js): continue if L == 2048 and f"L512__{task}" not in st["scored"] and not all(x["id"] in done for x in groups[(512, task)] if x["type"] == "queries"): continue t0 = time.time() corpus, queries, qrels = data.load_task(task) edir = R8 / "emb" / f"L{L}" / task.replace(":", "_") D = np.concatenate([np.load(edir / f"docs_{j['start']:07d}.npy") for j in sorted(js, key=lambda x: x["start"]) if j["type"] == "docs"]).astype(np.float32) Q = np.load(R8 / "emb" / "L512" / task.replace(":", "_") / "queries.npy").astype(np.float32) assert len(D) == len(corpus) and len(Q) == len(queries), (len(D), len(corpus), len(Q), len(queries)) nan = int(np.isnan(D).any(1).sum() + np.isnan(Q).any(1).sum()) D, Q = np.nan_to_num(D), np.nan_to_num(Q) qids, dids = [q["id"] for q in queries], [d["id"] for d in corpus] stats = [json.loads((R8 / "done" / f"{j['id']}.done").read_text()) for j in js] enc_s = sum(s["s"] for s in stats) model = "qwen3-8b" if L == 512 else "qwen3-8b#L2048" base = {"model": model, "hf": "Qwen/Qwen3-Embedding-8B", "task": task, "dtype": "bf16", "max_len": L, "n_docs": len(corpus), "n_queries": len(queries), "enc_docs_s": enc_s, "docs_per_s": len(corpus) / max(enc_s, 1e-9), "nan_rows": nan, "peak_vram_gib": max(s.get("vram", 0) for s in stats), "gpus": sorted({s["gpu"] for s in stats})} recs = [{**base, "dim": D.shape[1], **evaluate(qrels, search(Q, D, qids, dids))}] if L == 512: for d in (1024, 512, 256): recs.append({**base, "dim": d, "mrl": True, **evaluate(qrels, search(norm(Q, d), norm(D, d), qids, dids))}) with open(MET / f"{model}__{task.replace(':', '_')}.jsonl", "w") as f: for r in recs: f.write(json.dumps(r) + "\n") st["scored"].append(key); STATE.write_text(json.dumps(st)) r = recs[0] tg(f"📊 Qwen3-8B · {task.split(':')[0]} (L{L})\n nDCG@10 {r['ndcg10']:.1f} · P@1 {r['p1']:.1f} · MRR@10 {r['mrr10']:.1f} · R@100 {r['recall100']:.1f}\n" f" {len(js)} jobs on GPUs {','.join(base['gpus'])} · NaN {nan} · scored in {time.time()-t0:.0f}s")
for f in sorted(failed - set(st.get("failed_seen", []))): tg(f"⚠️ Qwen3-8B shard failed (re-queued for another GPU): {f}") st.setdefault("failed_seen", []).append(f)
now = time.time()if now - st["hb"] > 1800 and not st["final"]: left = sum(j["sec"] for j in jobs if j["id"] not in done) tg(f"💓 Qwen3-8B: {len(done)}/{len(jobs)} shard jobs done · {len(st['scored'])}/{len(groups)} sets scored · ≈ {left/60/2.5:.0f} min of work left on 3 GPUs") st["hb"] = now
if len(st["scored"]) == len(groups) and not st["final"]: st["final"] = True; STATE.write_text(json.dumps(st)) tg(f"🏁 Qwen3-8B finished: {len(groups)} sets scored in {(now - st['start'])/3600:.2f} h.")STATE.write_text(json.dumps(st))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""Qwen3-8B sharded encoding (option B).GPU: python shard8b.py worker <wid> -> claims jobs from $R8/jobs.json under $R8/queue.lockgpu-b: python shard8b.py runner <wid> -> takes jobs from $R8/inbox/<wid>/job.json (written by the local driver)Job: {"id","type":"docs"|"queries","task","L","start","end","sec","prio"} -> $R8/emb/L<L>/<task>/docs_<start>.npy | queries.npy"""import os, sys, json, time, fcntl, tracebackfrom pathlib import Pathimport numpy as np, torchimport zoo, data
MODE, WID = sys.argv[1], sys.argv[2]R8 = Path(os.path.expanduser(os.environ.get("R8", "~/embed/r8b")))for d in ("claimed", "done", "logs", "emb"): (R8 / d).mkdir(parents=True, exist_ok=True)LOG = open(R8 / "logs" / f"w{WID}.log", "a")
def log(m): line = f"{time.strftime('%H:%M:%S')} [w{WID}] {m}"; print(line, flush=True); LOG.write(line + "\n"); LOG.flush()
def out_path(j): d = R8 / "emb" / f"L{j['L']}" / j["task"].replace(":", "_"); d.mkdir(parents=True, exist_ok=True) return d / ("queries.npy" if j["type"] == "queries" else f"docs_{j['start']:07d}.npy")
def claim(): with open(R8 / "queue.lock", "w") as lk: fcntl.flock(lk, fcntl.LOCK_EX) jobs = json.load(open(R8 / "jobs.json")) taken = {f.stem for f in (R8 / "claimed").glob("*.claim")} rem = [j for j in jobs if j["id"] not in taken] if not rem: return None p = min(j.get("prio", 0) for j in rem) j = max([x for x in rem if x.get("prio", 0) == p], key=lambda x: x["sec"]) (R8 / "claimed" / f"{j['id']}.claim").write_text(WID) return j
ENC, CACHE = None, {}
def run(j): global ENC if ENC is None: t = time.time(); ENC = zoo.Enc("qwen3-8b"); log(f"loaded qwen3-8b in {time.time()-t:.0f}s bs={ENC.bs}") ENC.max_len = j["L"]; ENC.m.max_seq_length = j["L"] bs0 = int(os.environ.get("EMBED_BS", zoo.MODELS["qwen3-8b"][3])) ENC.bs = max(2, bs0 * 512 // j["L"]) if j["task"] not in CACHE: CACHE.clear(); CACHE[j["task"]] = data.load_task(j["task"]) corpus, queries, _ = CACHE[j["task"]] t = time.time() if j["type"] == "queries": E = ENC.encode_queries([q["text"] for q in queries], j["task"]) else: E = ENC.encode_docs(corpus[j["start"]:j["end"]]) torch.cuda.synchronize(); dt = time.time() - t nan = int(np.isnan(E).any(1).sum()) tmp = out_path(j).with_suffix(".tmp.npy"); np.save(tmp, E.astype(np.float16)); tmp.rename(out_path(j)) (R8 / "done" / f"{j['id']}.done").write_text(json.dumps({"s": dt, "n": len(E), "nan": nan, "gpu": WID, "vram": torch.cuda.max_memory_allocated() / 2**30})) log(f"DONE {j['id']} n={len(E)} {dt:.0f}s ({len(E)/dt:.1f}/s) nan={nan}")
def main(): if MODE == "worker": for f in (R8 / "claimed").glob("*.claim"): # release own stale claims if f.read_text().strip() == WID and not (R8 / "done" / f"{f.stem}.done").exists(): f.unlink() while True: j = claim() if j is None: log("QUEUE_EMPTY"); return try: run(j) except Exception as e: (R8 / "done" / f"{j['id']}.failed").write_text(traceback.format_exc()) (R8 / "claimed" / f"{j['id']}.claim").unlink(missing_ok=True) # let another GPU retry it log(f"FAILED {j['id']}: {type(e).__name__}: {str(e)[:200]}"); torch.cuda.empty_cache(); time.sleep(10) else: inbox = R8 / "inbox" / WID; inbox.mkdir(parents=True, exist_ok=True) log("runner ready") while True: jf = inbox / "job.json" if not jf.exists(): time.sleep(1); continue j = json.loads(jf.read_text()) try: run(j) except Exception as e: (R8 / "done" / f"{j['id']}.failed").write_text(traceback.format_exc()) log(f"FAILED {j['id']}: {type(e).__name__}: {str(e)[:200]}"); torch.cuda.empty_cache() jf.unlink()
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""Smoke test: load, sanity-gate and time each model on real Vietnamese samples, then project the full-run time.Usage: CUDA_VISIBLE_DEVICES=N python smoke.py key1 key2 ..."""import sys, time, json, gc, osT0 = time.time()import numpy as np, torchimport zoo, data
OUT = os.path.expanduser(os.environ.get("SMOKE_OUT", "~/embed/results/smoke.jsonl"))TASKS = data.TIER1 + data.TIER2PAIRS = [ ("What causes the northern lights?", "The northern lights are caused by charged particles from the sun colliding with the atmosphere."), ("How do vaccines train the immune system?", "Vaccines expose the immune system to a harmless antigen so it can build memory cells."), ("Thời hạn nộp thuế thu nhập cá nhân là khi nào?", "Người nộp thuế phải quyết toán thuế thu nhập cá nhân chậm nhất là ngày cuối cùng của tháng thứ tư kể từ ngày kết thúc năm dương lịch."), ("Mức phạt khi vượt đèn đỏ đối với xe máy là bao nhiêu?", "Người điều khiển xe mô tô không chấp hành hiệu lệnh của đèn tín hiệu giao thông bị phạt tiền từ 4.000.000 đồng đến 6.000.000 đồng."), ("Phở bò Hà Nội được nấu như thế nào?", "Nước dùng phở bò được ninh từ xương bò cùng quế, hồi, gừng nướng và hành nướng trong nhiều giờ."), ("What is the capital of Australia?", "Canberra is the capital city of Australia, located in the Australian Capital Territory."),]
# load all task texts once (cached pickles)ALL = {t: data.load_task(t) for t in TASKS}rng = np.random.default_rng(0)SAMPLE_DOCS = []for t in ["ZacLegalTextRetrieval", "GreenNodeTableMarkdownRetrieval", "WebFAQRetrieval:vie", "TVPLRetrieval", "FiQA2018-VN"]: c = ALL[t][0] SAMPLE_DOCS += [c[i] for i in rng.choice(len(c), 400, replace=False)]SAMPLE_Q = []for t in ["ZacLegalTextRetrieval", "GreenNodeTableMarkdownRetrieval", "TVPLRetrieval", "WebFAQRetrieval:vie"]: q = ALL[t][1] SAMPLE_Q += [(t, q[i]["text"]) for i in rng.choice(len(q), 256, replace=False)]
def sim(a, b): if isinstance(a, list): # multi-vector MaxSim S = np.zeros((len(a), len(b))) for i, x in enumerate(a): for j, y in enumerate(b): S[i, j] = (x.float() @ y.float().T).max(1).values.sum().item() return S return a @ b.T
for key in sys.argv[1:]: rec = {"key": key, "hf": zoo.MODELS[key][0], "gpu": os.environ.get("CUDA_VISIBLE_DEVICES")} try: torch.cuda.reset_peak_memory_stats() t = time.time(); m = zoo.Enc(key); rec["load_s"] = time.time() - t rec["max_len"] = m.max_len # gate qe = m.encode_queries([p[0] for p in PAIRS], "ZacLegalTextRetrieval") de = m.encode_docs([{"title": "", "text": p[1]} for p in PAIRS]) S = sim(qe, de) rec["nan"] = int(np.isnan(np.asarray(S)).sum()) rec["top1"] = float((np.asarray(S).argmax(1) == np.arange(len(PAIRS))).mean()) rec["top1_vi"] = float((np.asarray(S)[2:5].argmax(1) == np.arange(2, 5)).mean()) # throughput on real VN docs (warm-up first) m.encode_docs(SAMPLE_DOCS[:64]); torch.cuda.synchronize() dt_tok = m.count_tokens([m.dtext(d) for d in SAMPLE_DOCS]) t = time.time(); m.encode_docs(SAMPLE_DOCS); torch.cuda.synchronize(); td = time.time() - t qt = [m.qprefix(tk) + q for tk, q in SAMPLE_Q] q_tok = m.count_tokens(qt) t = time.time() for tk in sorted({x[0] for x in SAMPLE_Q}): m.encode_queries([q for k, q in SAMPLE_Q if k == tk], tk) torch.cuda.synchronize(); tq = time.time() - t rec.update(doc_s=td, docs_per_s=len(SAMPLE_DOCS) / td, q_per_s=len(SAMPLE_Q) / tq, doc_tok_per_s=(float(dt_tok.sum()) / td) if dt_tok is not None else None, q_tok_per_s=(float(q_tok.sum()) / tq) if q_tok is not None else None, peak_vram_gib=torch.cuda.max_memory_allocated() / 2**30) # project full run per task from exact token counts with this model's tokenizer proj = {} for tk in TASKS: c, q, _ = ALL[tk] if dt_tok is not None: ntd = int(m.count_tokens([m.dtext(d) for d in c]).sum()) ntq = int(m.count_tokens([m.qprefix(tk) + x["text"] for x in q]).sum()) sec = ntd / rec["doc_tok_per_s"] + ntq / rec["q_tok_per_s"] else: sec = len(c) / rec["docs_per_s"] + len(q) / rec["q_per_s"] proj[tk] = {"docs": len(c), "queries": len(q), "sec": sec} rec["proj"] = proj rec["proj_tier1_s"] = sum(proj[t]["sec"] for t in data.TIER1) rec["proj_tier2_s"] = sum(proj[t]["sec"] for t in data.TIER2) rec["ok"] = rec["nan"] == 0 and rec["top1"] >= 5 / 6 except Exception as e: import traceback; traceback.print_exc() rec["ok"] = False; rec["error"] = f"{type(e).__name__}: {str(e)[:300]}" print(json.dumps({k: v for k, v in rec.items() if k != "proj"}), flush=True) with open(OUT, "a") as f: f.write(json.dumps(rec) + "\n") try: del m except NameError: pass gc.collect(); torch.cuda.empty_cache()print("SMOKE_DONE", time.time() - T0, flush=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241"""GPU worker: claims (model, task) jobs from a shared queue, encodes, retrieves, scores, writes results.Usage: CUDA_VISIBLE_DEVICES=N python worker.py <worker_id>Resumable: finished jobs have results/done/<job>.done; stale claims of this worker are released on start."""import os, sys, json, time, gzip, fcntl, gc, tracebackfrom pathlib import Pathimport numpy as np, torch, pytrec_evalimport zoo, data
WID = sys.argv[1]R = Path(os.path.expanduser(os.environ.get("RESULTS", "~/embed/results")))for d in ("done", "claimed", "metrics", "runs", "logs"): (R / d).mkdir(parents=True, exist_ok=True)JOBS = json.load(open(R / "jobs.json"))LOCK = R / "queue.lock"K = 100LOG = open(R / "logs" / f"worker{WID}.log", "a")
def log(msg): line = f"{time.strftime('%H:%M:%S')} [w{WID}] {msg}" print(line, flush=True); LOG.write(line + "\n"); LOG.flush()
def jid(j): return f"{j['model']}__{j['task'].replace(':', '_')}"
def release_own_stale(): for f in (R / "claimed").glob("*.claim"): if f.read_text().strip() == WID and not (R / "done" / (f.stem + ".done")).exists(): f.unlink()
def claim(loaded): with open(LOCK, "w") as lk: fcntl.flock(lk, fcntl.LOCK_EX) jobs = json.load(open(R / "jobs.json")) # re-read: jobs may be appended while running taken = {f.stem for f in (R / "claimed").glob("*.claim")} rem = [j for j in jobs if jid(j) not in taken] if not rem: return None p = min(j.get("prio", 0) for j in rem) rem = [j for j in rem if j.get("prio", 0) == p] # main queue first, extras after same = [j for j in rem if j["model"] == loaded] j = max(same or rem, key=lambda x: x["sec"]) (R / "claimed" / (jid(j) + ".claim")).write_text(WID) return j
def evaluate(qrels, run): ev = pytrec_eval.RelevanceEvaluator(qrels, {"ndcg_cut.10", "recall.10", "recall.100", "P.1"}) r = ev.evaluate(run) m = lambda k: float(np.mean([v[k] for v in r.values()]) * 100) mrr = [] for q, docs in run.items(): rel = {d for d, s in qrels.get(q, {}).items() if s > 0} top = sorted(docs.items(), key=lambda x: -x[1])[:10] mrr.append(next((1 / (i + 1) for i, (d, _) in enumerate(top) if d in rel), 0.0)) return {"ndcg10": m("ndcg_cut_10"), "p1": m("P_1"), "mrr10": float(np.mean(mrr) * 100), "recall10": m("recall_10"), "recall100": m("recall_100"), "n_eval_q": len(r)}
def to_run(scores_top, idx_top, qids, dids): run = {} for r, qid in enumerate(qids): res = {} for j, s in zip(idx_top[r], scores_top[r]): d = dids[j] if d != qid: # mteb convention: drop self-hits res[d] = float(s) if len(res) >= K: break run[qid] = res return run
def dense_topk(Q, D): Dt = torch.from_numpy(D).cuda().to(torch.bfloat16) S_all, I_all = [], [] for i in range(0, len(Q), 1024): q = torch.from_numpy(Q[i:i + 1024]).cuda().to(torch.bfloat16) s = (q @ Dt.T).float() v, ix = s.topk(min(K + 1, s.shape[1]), dim=1) S_all.append(v.cpu().numpy()); I_all.append(ix.cpu().numpy()) del Dt; torch.cuda.empty_cache() return np.concatenate(S_all), np.concatenate(I_all)
def _pad(vecs, dev): L = max(v.shape[0] for v in vecs) X = torch.zeros(len(vecs), L, vecs[0].shape[1], dtype=torch.bfloat16, device=dev) M = torch.zeros(len(vecs), L, dtype=torch.bool, device=dev) for i, v in enumerate(vecs): X[i, :v.shape[0]] = v.to(dev); M[i, :v.shape[0]] = True return X, M
def norm_slice(vecs, d): out = [] for v in vecs: x = v[:, :d].float() out.append(torch.nn.functional.normalize(x, dim=-1).to(torch.bfloat16)) return out
def maxsim_topk(Qv, Dv): """Exact MaxSim over the whole corpus, chunked. Docs sorted by length to limit padding.""" dev = "cuda" order = np.argsort([v.shape[0] for v in Dv]) nq = len(Qv) best_s = torch.full((nq, K + 1), -1e9, device=dev); best_i = torch.zeros((nq, K + 1), dtype=torch.long, device=dev) dchunks = [] for c in range(0, len(order), 256): ids = order[c:c + 256] X, M = _pad([Dv[i] for i in ids], dev) dchunks.append((torch.as_tensor(ids, device=dev), X, M)) for qs in range(0, nq, 64): Xq, Mq = _pad(Qv[qs:qs + 64], dev) bq = Xq.shape[0] cs, ci = [best_s[qs:qs + bq]], [best_i[qs:qs + bq]] for ids, X, M in dchunks: s = torch.einsum("qid,njd->qinj", Xq, X).float() # [bq, Lq, nd, Ld] s = s.masked_fill(~M[None, None], -1e4).amax(-1) # [bq, Lq, nd] s = (s * Mq[:, :, None]).sum(1) # [bq, nd] cs.append(s); ci.append(ids[None].expand(bq, -1)) if len(cs) > 16: S = torch.cat(cs, 1); I = torch.cat(ci, 1) v, ix = S.topk(K + 1, dim=1); cs, ci = [v], [torch.gather(I, 1, ix)] S = torch.cat(cs, 1); I = torch.cat(ci, 1) v, ix = S.topk(K + 1, dim=1) best_s[qs:qs + bq] = v; best_i[qs:qs + bq] = torch.gather(I, 1, ix) return best_s.cpu().numpy(), best_i.cpu().numpy()
def make_enc(spec): """spec: key[@dtype][#L<max_len>]""" if spec.startswith("bge-m3"): import m3 L = int(spec.partition("#L")[2] or 512) return m3.M3(max_len=L, bs=max(16, 128 * 512 // L)) spec, _, L = spec.partition("#L") key, _, dt = spec.partition("@") return zoo.Enc(key, dtype=dt or "bf16", max_len=int(L) if L else None)
def run_job(enc, j): task = j["task"] corpus, queries, qrels = data.load_task(task) if j["model"].startswith("bge-m3"): import m3 torch.cuda.reset_peak_memory_stats() recs = m3.run_m3(enc, corpus, queries, qrels, task, data.doc_plain, evaluate, to_run) suffix = j["model"][len("bge-m3"):] # "" or "#L2048" base = {"hf": "BAAI/bge-m3", "task": task, "dtype": "fp16", "max_len": enc.max_len, "n_docs": len(corpus), "n_queries": len(queries), "peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30, "gpu": WID} out = [{**base, "model": "bge-m3" + suffix, "dim": 1024, **r} for r in recs] dense = [r for r in out if r["mode"] == "dense"]; allm = [r for r in out if r["mode"] == "all"] with open(R / "metrics" / f"bge-m3-all{suffix}__{task.replace(':', '_')}.jsonl", "w") as f: f.write(json.dumps({**allm[0], "model": "bge-m3-all" + suffix}) + "\n") return dense + [r for r in out if r["mode"] != "dense"] qids, dids = [q["id"] for q in queries], [d["id"] for d in corpus] # length stats (untruncated) on a sample: truncation share + VI tokens/word samp = [enc.dtext(d) for d in corpus[:: max(1, len(corpus) // 2000)]] if enc.tok is not None: L = np.array([len(x) for x in enc.tok(samp, add_special_tokens=True, truncation=False)["input_ids"]]) words = np.array([max(1, len(s.split())) for s in samp]) lstats = {"tok_mean": float(L.mean()), "frac_truncated": float((L > enc.max_len).mean()), "tok_per_word": float((L / words).mean())} else: lstats = {} torch.cuda.reset_peak_memory_stats(); torch.cuda.synchronize() t = time.time(); De = enc.encode_docs(corpus); torch.cuda.synchronize(); td = time.time() - t t = time.time(); Qe = enc.encode_queries([q["text"] for q in queries], task); torch.cuda.synchronize(); tq = time.time() - t vram = torch.cuda.max_memory_allocated() / 2**30 base = {"model": j["model"], "hf": zoo.MODELS[enc.key][0], "task": task, "dtype": enc.dtype_name, "max_len": enc.max_len, "n_docs": len(corpus), "n_queries": len(queries), "enc_docs_s": td, "enc_q_s": tq, "docs_per_s": len(corpus) / td, "peak_vram_gib": vram, "gpu": WID, **lstats} results = [] if enc.kind == "multivec": variants = [(128, norm_slice(Qe, 128), norm_slice(De, 128))] if j.get("dim512"): variants.append((512, Qe, De)) for dim, Qv, Dv in variants: t = time.time(); S, I = maxsim_topk(Qv, Dv); ts = time.time() - t run = to_run(S, I, qids, dids) results.append({**base, "dim": dim, "score_s": ts, **evaluate(qrels, run)}) torch.cuda.empty_cache() else: nan = int(np.isnan(De).any(1).sum() + np.isnan(Qe).any(1).sum()) De = np.nan_to_num(De); Qe = np.nan_to_num(Qe) t = time.time(); S, I = dense_topk(Qe, De); ts = time.time() - t run = to_run(S, I, qids, dids) results.append({**base, "dim": De.shape[1], "nan_rows": nan, "score_s": ts, **evaluate(qrels, run)}) if "#L" not in j["model"] and zoo.MODELS[enc.key][0].startswith(("Qwen/", "google/embeddinggemma", "FrontiersMind")): # MRL ablation for d in (512, 256, 128): if d < De.shape[1]: nq = Qe[:, :d] / np.linalg.norm(Qe[:, :d], axis=1, keepdims=True) nd = De[:, :d] / np.linalg.norm(De[:, :d], axis=1, keepdims=True) S2, I2 = dense_topk(nq, nd) results.append({**base, "dim": d, "mrl": True, **evaluate(qrels, to_run(S2, I2, qids, dids))}) # save top-10 run of the main variant for later analysis top10 = {q: dict(sorted(v.items(), key=lambda x: -x[1])[:10]) for q, v in run.items()} if enc.kind != "multivec" else None (R / "runs" / j["model"]).mkdir(exist_ok=True) if top10 is not None: with gzip.open(R / "runs" / j["model"] / (task.replace(":", "_") + ".json.gz"), "wt") as f: json.dump(top10, f) return results
def main(): release_own_stale() enc, loaded = None, None while True: j = claim(loaded) if j is None: # wait for newly queued jobs instead of exiting (stop with: touch $RESULTS/STOP_WORKERS) if (R / "STOP_WORKERS").exists(): log("QUEUE_EMPTY, stop file present"); break time.sleep(60); continue name = jid(j) try: if loaded != j["model"]: enc = None; gc.collect(); torch.cuda.empty_cache() t = time.time() enc = make_enc(j["model"]); loaded = j["model"] log(f"loaded {j['model']} in {time.time()-t:.1f}s") t = time.time() res = run_job(enc, j) with open(R / "metrics" / f"{name}.jsonl", "w") as f: for r in res: f.write(json.dumps({**r, "wall_s": time.time() - t}) + "\n") (R / "done" / f"{name}.done").write_text(str(time.time())) m = res[0] log(f"DONE {name} nDCG@10={m['ndcg10']:.2f} P@1={m['p1']:.2f} MRR@10={m['mrr10']:.2f} R@100={m['recall100']:.2f} ({time.time()-t:.0f}s)") except Exception as e: (R / "done" / f"{name}.failed").write_text(traceback.format_exc()) (R / "done" / f"{name}.done").write_text("FAILED") log(f"FAILED {name}: {type(e).__name__}: {str(e)[:300]}") enc, loaded = None, None; gc.collect(); torch.cuda.empty_cache()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""Model recipes for the GPU run (bf16; each model's own input format; max_len = min(model default, 512))."""import osimport numpy as np, torchfrom sentence_transformers import SentenceTransformer
BF16 = torch.bfloat16QWEN_INST = { "ZacLegalTextRetrieval": "Given a legal question, retrieve relevant legal articles that answer the question", "TVPLRetrieval": "Given a legal question, retrieve relevant legal documents that answer the question", "GreenNodeTableMarkdownRetrieval": "Given a question, retrieve the table that contains the answer", "WebFAQRetrieval": "Given a question, retrieve the FAQ answer that answers it", "SciFact-VN": "Given a scientific claim, retrieve documents that support or refute the claim", "NFCorpus-VN": "Given a question, retrieve relevant documents that best answer the question", "ArguAna-VN": "Given a claim, find documents that refute the claim", "FiQA2018-VN": "Given a financial question, retrieve user replies that best answer the question",}QWEN_DEFAULT = "Given a question, retrieve passages that answer the question"EG_TASK = {"SciFact-VN": "fact checking", "FiQA2018-VN": "question answering", "ZacLegalTextRetrieval": "question answering", "TVPLRetrieval": "question answering", "WebFAQRetrieval": "question answering", "VieQuADRetrieval": "question answering", "MLQARetrieval": "question answering", "XQuADRetrieval": "question answering", "BelebeleRetrieval": "question answering", "PublicHealthQA": "question answering"}OPENEMBED_Q = "Find a passage that answers the given query." # README gives no text-to-text instruction; assumption, see planBGE_Q = "Represent this sentence for searching relevant passages: "NEMO_Q, NEMO_D = "query: ", "passage: " # Nemotron-3-Embed card + config_sentence_transformers.json prompts
# key: (hf id, kind, max_len, batch)MODELS = { "nemotron3-1b": ("nvidia/Nemotron-3-Embed-1B-BF16", "nemotron", 512, 128), "nemotron3-8b": ("nvidia/Nemotron-3-Embed-8B-BF16", "nemotron", 512, 64), "openembed-4b": ("UCSC-VLAA/OpenEmbed-4B", "openembed", 512, 32), "openembed-9b": ("UCSC-VLAA/OpenEmbed-9B", "openembed", 512, 32), "omnievie-4b": ("tencent/OmniEVIE-4B", "multivec", 512, 32), "openembed-2b": ("UCSC-VLAA/OpenEmbed-2B", "openembed", 512, 64), "mistral-embed-1b": ("mistralai/Mistral-Multimodal-Embed-1B", "plain_trc", 512, 128), "openembed-0.8b": ("UCSC-VLAA/OpenEmbed-0.8B", "openembed", 512, 128), "qwen3-0.6b": ("Qwen/Qwen3-Embedding-0.6B", "qwen", 512, 128), "qwen3-8b": ("Qwen/Qwen3-Embedding-8B", "qwen", 512, 64), "qwen3-4b": ("Qwen/Qwen3-Embedding-4B", "qwen", 512, 64), # run-1 model, re-run on the missing native sets "octen-8b": ("Octen/Octen-Embedding-8B", "octen", 512, 64), # LoRA fine-tunes of Qwen3-Embedding "octen-4b": ("Octen/Octen-Embedding-4B", "octen", 512, 64), "octen-0.6b": ("Octen/Octen-Embedding-0.6B", "octen", 512, 128), "embeddinggemma-2": ("google/embeddinggemma-2", "eg2", 512, 128), # run-1 model (text-only path) "skill-venus-0.6b": ("inclusionAI/Skill-Venus-Embedding-0.6B", "qwen", 512, 128), "nandi-450m": ("FrontiersMind/EmbeddingNandi-450M", "eg_trc", 512, 256), "embeddinggemma-300m": ("google/embeddinggemma-300m", "eg", 512, 256), "nandi-150m": ("FrontiersMind/EmbeddingNandi-150M", "eg_trc", 512, 256), "para-multi-minilm-l12": ("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2", "plain", 128, 512), "all-mpnet-base": ("sentence-transformers/all-mpnet-base-v2", "plain", 384, 512), "bge-base-en-v1.5": ("BAAI/bge-base-en-v1.5", "bge", 512, 512), "granite-97m-multi-r2": ("ibm-granite/granite-embedding-97m-multilingual-r2", "plain", 512, 512), "all-minilm-l12": ("sentence-transformers/all-MiniLM-L12-v2", "plain", 128, 512), "edgecoder-31m": ("knowledgator/EdgeCoder-31M", "plain", 512, 512), "all-minilm-l6": ("sentence-transformers/all-MiniLM-L6-v2", "plain", 256, 512),}
def base(task): return task.split(":")[0]
class Enc: def __init__(self, key, dtype="bf16", max_len=None): self.key, self.dtype_name = key, dtype self.hf, self.kind, self.max_len, self.bs = MODELS[key] override = max_len if os.environ.get("EMBED_BS"): self.bs = int(os.environ["EMBED_BS"]) mk = {"dtype": {"bf16": BF16, "fp16": torch.float16, "fp32": torch.float32}[dtype]} trc = self.kind in ("plain_trc", "eg_trc") if self.kind == "multivec": from sentence_transformers import MultiVectorEncoder self.m = MultiVectorEncoder(self.hf, device="cuda", model_kwargs=mk) elif self.kind == "nemotron": # bidirectional Ministral3 encoder, mean pooling + normalize from its ST config self.m = SentenceTransformer(self.hf, device="cuda", model_kwargs={**mk, "attn_implementation": "sdpa"}) elif self.kind in ("qwen", "octen"): self.m = SentenceTransformer(self.hf, device="cuda", model_kwargs={**mk, "attn_implementation": "sdpa"}, processor_kwargs={"padding_side": "left"}) elif self.kind == "eg2": self.m = SentenceTransformer(self.hf, device="cuda", model_kwargs=mk, config_kwargs={"vision_config": None, "audio_config": None}) else: self.m = SentenceTransformer(self.hf, device="cuda", model_kwargs=mk, trust_remote_code=trc) cfg_max = getattr(self.m, "max_seq_length", None) if override: # long-context extra runs (E): explicit window, smaller batch self.max_len = override # only queued for models whose context is >= 2048 self.bs = max(4, self.bs * 512 // self.max_len) elif cfg_max and cfg_max < self.max_len: self.max_len = cfg_max # D3: never exceed the model's own default try: self.m.max_seq_length = self.max_len except Exception: pass self.tok = getattr(self.m, "tokenizer", None) if self.tok is not None and hasattr(self.tok, "tokenizer"): self.tok = self.tok.tokenizer self.pretrunc = self.kind in ("multivec", "plain_trc", "openembed") # these repos disable truncation
def _cap(self, texts): if not self.pretrunc or self.tok is None: return texts enc = self.tok(texts, add_special_tokens=False, truncation=True, max_length=self.max_len - 16)["input_ids"] return self.tok.batch_decode(enc)
def qprefix(self, task): b = base(task) if self.kind in ("qwen", "octen"): return f"Instruct: {QWEN_INST.get(b, QWEN_DEFAULT)}\nQuery:" if self.kind in ("eg", "eg_trc", "eg2"): return f"task: {EG_TASK.get(b, 'search result')} | query: " if self.kind == "openembed": return OPENEMBED_Q + " " if self.kind == "bge": return BGE_Q if self.kind == "nemotron": return NEMO_Q return ""
def dtext(self, d): if self.kind in ("eg", "eg_trc", "eg2"): return f"title: {(d.get('title') or '').strip() or 'none'} | text: {d['text']}" t = (d.get("title") or "").strip() txt = (t + " " + d["text"]).strip() if t else d["text"] if self.kind == "nemotron": return NEMO_D + txt return " " + txt if self.kind == "octen" else txt # Octen's configured document prompt is a single space
@torch.inference_mode() def _encode(self, texts, query): texts = self._cap(texts) if self.kind == "multivec": f = self.m.encode_query if query else self.m.encode_document out = f(texts, batch_size=self.bs, truncate_dim=128, show_progress_bar=False) return [o.to(torch.bfloat16).cpu() for o in out] e = self.m.encode(texts, batch_size=self.bs, normalize_embeddings=True, convert_to_numpy=True, show_progress_bar=False) return e.astype(np.float32)
def encode_queries(self, qs, task): p = self.qprefix(task) return self._encode([p + q for q in qs], True)
def encode_docs(self, docs): return self._encode([self.dtext(d) for d in docs], False)
def count_tokens(self, texts): if self.tok is None: return None ids = self.tok(texts, add_special_tokens=True, truncation=True, max_length=self.max_len)["input_ids"] return np.array([len(x) for x in ids])12345678910111213141516171819202122232425262728293031323334353637383940414243# Datasets
All datasets are loaded through [`mteb`](https://github.com/embeddings-benchmark/mteb) (v2.27) using each task's evaluation split. Queries without relevance judgements are dropped; documents are `title + " " + text` when a title exists.
## Native Vietnamese (human-written)
| Dataset | mteb task | Hugging Face source | Domain | Docs | Queries | License ||---|---|---|---|---:|---:|---|| Zalo AI Legal | `ZacLegalTextRetrieval` | [`GreenNode/zalo-ai-legal-text-retrieval-vn`](https://huggingface.co/datasets/GreenNode/zalo-ai-legal-text-retrieval-vn) | Legal articles | 61,425 | 818 | MIT || TVPL | `TVPLRetrieval` | [`GreenNode/TVPL-Retrieval-VN`](https://huggingface.co/datasets/GreenNode/TVPL-Retrieval-VN) | Legal Q&A (thuvienphapluat) | 10,576 | 9,985 | CC-BY-SA-4.0 || Table-Markdown | `GreenNodeTableMarkdownRetrieval` | [`GreenNode/GreenNode-Table-Markdown-Retrieval-VN`](https://huggingface.co/datasets/GreenNode/GreenNode-Table-Markdown-Retrieval-VN) | Tables (finance, encyclopedic) in Markdown | 44,678 | 35,791 | MIT || WebFAQ (vie) | `WebFAQRetrieval` | [`mteb/WebFAQRetrieval`](https://huggingface.co/datasets/mteb/WebFAQRetrieval) | Web FAQ | 123,972 | 10,000 | CC-BY-4.0 || UIT-ViQuAD 2.0 | `VieQuADRetrieval` | [`taidng/UIT-ViQuAD2.0`](https://huggingface.co/datasets/taidng/UIT-ViQuAD2.0) | Wikipedia QA | 2,490 | 2,048 | MIT || MLQA (vie-vie) | `MLQARetrieval` | [`mteb/MLQARetrieval`](https://huggingface.co/datasets/mteb/MLQARetrieval) | Wikipedia QA | 451 | 511 | CC-BY-SA-3.0 || XQuAD (vi) | `XQuADRetrieval` | [`mteb/XQuADRetrieval`](https://huggingface.co/datasets/mteb/XQuADRetrieval) | Wikipedia QA | 240 | 1,182 | CC-BY-SA-4.0 || Belebele (vie) | `BelebeleRetrieval` | [`mteb/belebele`](https://huggingface.co/datasets/mteb/belebele) | Reading comprehension | 488 | 900 | CC-BY-SA-4.0 || PublicHealthQA (vi) | `PublicHealthQA` | [`xhluca/publichealth-qa`](https://huggingface.co/datasets/xhluca/publichealth-qa) | Public health FAQ | 77 | 77 | CC-BY-NC-SA-3.0 |
The **native-4** average used on the leaderboard covers the four large sets (Zalo Legal, TVPL, Table-Markdown, WebFAQ). The five smaller sets (mostly Wikipedia QA) are reported per dataset and in the "all 9" average; most multilingual models are near the ceiling on them.
## Machine-translated Vietnamese (VN-MTEB)
VN-MTEB (GreenNode, EACL 2026 Findings) translates English MTEB tasks with LLMs. Useful for continuity with English benchmarks, but it carries translation artifacts, and models that have seen the English originals can look better than they are. Run-2 queries are the VN-MTEB subset, whose relevance labels are identical to the English originals.
| Dataset | mteb task | Hugging Face source | Domain | Docs | Queries | License ||---|---|---|---|---:|---:|---|| SciFact-VN | `SciFact-VN` | [`GreenNode/scifact-vn`](https://huggingface.co/datasets/GreenNode/scifact-vn) | Scientific claims | 5,183 | 134 | CC-BY-SA-4.0 || NFCorpus-VN | `NFCorpus-VN` | [`GreenNode/nfcorpus-vn`](https://huggingface.co/datasets/GreenNode/nfcorpus-vn) | Medical | 3,618 | 166 | CC-BY-SA-4.0 || ArguAna-VN | `ArguAna-VN` | [`GreenNode/arguana-vn`](https://huggingface.co/datasets/GreenNode/arguana-vn) | Counter-arguments | 8,674 | 1,295 | CC-BY-SA-4.0 || FiQA-VN | `FiQA2018-VN` | [`GreenNode/fiqa-vn`](https://huggingface.co/datasets/GreenNode/fiqa-vn) | Finance Q&A | 57,638 | 384 | CC-BY-SA-4.0 || TREC-COVID-VN | `TRECCOVID-VN` | [`GreenNode/trec-covid-vn`](https://huggingface.co/datasets/GreenNode/trec-covid-vn) | Biomedical (run 1 only) | 171,332 | 44 | CC-BY-SA-4.0 |
## English (run 1 only)
| Dataset | Hugging Face source | Docs | Queries | License ||---|---|---:|---:|---|| SciFact | [`mteb/scifact`](https://huggingface.co/datasets/mteb/scifact) | 5,183 | 300 | CC-BY-NC-4.0 || NFCorpus | [`mteb/nfcorpus`](https://huggingface.co/datasets/mteb/nfcorpus) | 3,633 | 323 | not specified || ArguAna | [`mteb/arguana`](https://huggingface.co/datasets/mteb/arguana) | 8,674 | 1,406 | CC-BY-SA-4.0 || FiQA-2018 | [`mteb/fiqa`](https://huggingface.co/datasets/mteb/fiqa) | 57,638 | 648 | not specified || TREC-COVID | [`mteb/trec-covid`](https://huggingface.co/datasets/mteb/trec-covid) | 171,332 | 50 | not specified |
Dataset licenses are those listed in the mteb task metadata; check each source before reusing the data.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657# How the models are benchmarked
## 1. Pipeline
For every **model × dataset** pair:
1. **Load** the dataset with `mteb` (corpus, queries, relevance labels).2. **Encode** all documents and all queries with the model, in its own input format (§2), max length = min(model default, 512 tokens), L2-normalised.3. **Search**: exact cosine top-100 over the whole corpus (no ANN, no reranker). As in mteb, a hit whose id equals the query id is dropped.4. **Score** with `pytrec_eval`: **nDCG@10** (primary), **P@1** (first result correct), **MRR@10**, **Recall@10**, **Recall@100**.5. **Save** metrics (JSONL), the top-10 ids per query, and token statistics (tokens per Vietnamese word, share of documents cut at the window).
Jobs (model × dataset, or document shards of 5,000 docs for 8B models) are pulled from a shared queue by several workers; shard embeddings are merged before search, so results are identical to a single pass.
## 2. Input formats (per model family)
| Family | Query | Document | Pooling ||---|---|---|---|| Qwen3-Embedding, Octen, Skill-Venus | `Instruct: {task instruction}\nQuery:{query}` (task-specific English instruction, also for Vietnamese) | raw text (Octen: its configured `" "` prefix) | last token, left padding || EmbeddingGemma (300m, 2), EmbeddingNandi | `task: {search result / question answering / fact checking} \| query: {query}` | `title: {title or "none"} \| text: {text}` | mean (model config) || BGE-M3 | raw text | raw text | CLS (dense); ReLU token weights (sparse); per-token vectors (ColBERT) || bge-base-en-v1.5 | `Represent this sentence for searching relevant passages: ` + query | raw text | CLS || OpenEmbed | `Find a passage that answers the given query. ` + query *(assumed: the card lists no text-search instruction)* | raw text | last token || others (paraphrase-multilingual, granite, Mistral-Embed) | raw text | raw text | model config || OpenAI text-embedding-3-small (API) | raw text, first 512 tokens (cl100k_base) | raw text, first 512 tokens | API (1,536-d; Matryoshka rows = first 1024/512/256 dims re-normalised) |
Models are pinned to the Hugging Face commit downloaded on 2026-12-03. API models: OpenAI models through the **Batch API** (50% price; text-embedding-3-small ≈ $0.93), and Gemini / Voyage / Perplexity through **OpenRouter** (≈ $13.7 for all three). All API inputs are cut to the first 512 tokens with the cl100k_base tokenizer, because the providers' own tokenizers aren't public. Precision: bf16 in run 2; run 1 used fp16 (EmbeddingGemma 2: fp32).
## 3. Hybrid retrieval (BGE-M3)
Dense and sparse each retrieve a top-100. Their union is re-scored with `s = w_dense·dense + w_sparse·sparse + w_colbert·colbert`; "all three" uses (1, 0.3, 1), "dense+sparse" uses (1, 0.3, 0). The heads are re-implemented from FlagEmbedding and checked against the reference values in the BGE-M3 README (dense 0.626, lexical 0.1955, ColBERT 0.7796).
## 4. Extra experiments
- **Long input window**: selected long-context models re-encoded at 2,048 tokens on Zalo Legal, Table-Markdown and TVPL, where 9–36% of documents exceed 512 tokens.- **Matryoshka truncation**: for MRL models, the first *d* dimensions are kept and re-normalised (Qwen3: 1024/512/256; EmbeddingGemma / Nandi: 512/256/128).- **bf16 vs fp16**: Qwen3-Embedding-0.6B in both (Zalo 67.08 vs 67.10).- **English → Vietnamese** (run 1): English scores are re-computed on exactly the VN-MTEB query subset, so the drop compares the same queries.
## 5. Checks before a model is scored
- **Smoke test**: 6 sanity pairs (3 English + 3 Vietnamese) must rank correctly with no NaN; Qwen-family models must use left padding with an EOS last token.- **Throughput** is measured on 2,000 real Vietnamese documents in the smoke test (one job per GPU). The full runs deliberately share GPUs, so their timings are not used for speed.- **Harness sanity**: BGE-M3 dense on Zalo Legal reproduces the published MRR@10 (65.4 vs 64.4 in the BKAI paper); SciFact matches MTEB (64.1).
## 6. Caveats
- Several models appear to have seen English benchmark data: scores drop much more on the translated copy of the same queries (e.g. SciFact, ArguAna, FiQA). The **native Vietnamese** sets are the fairest comparison.- The five small native sets are mostly Wikipedia QA and near the ceiling, so they separate models less than the large four.- OpenEmbed is CC-BY-NC (non-commercial).- One instruction was written per dataset for instruction-tuned models; a different wording can move scores (Table-Markdown is the most sensitive).- **ViQuAD and the Qwen3 models (explained):** Qwen3-Embedding-0.6B / 4B score 11 / 17 nDCG@10 on ViQuAD, against ~50–60 for comparable models. The cause is the dataset build plus a property of these models, **not a harness bug**: - The mteb ViQuAD retrieval corpus mixes passages with the **answer strings themselves as separate documents**. 47% of its 2,490 documents are under 40 characters ("Roosevelt", "Mỹ", "1932"), and every query has two relevant documents: the passage and its short answer. - Qwen3 gives very short texts a high similarity to almost any question. For "How many Iraqi jets fled to Iran?" it scores unrelated one-word documents like "Stalin" at 0.55 and "Roosevelt" at 0.51, close to the correct passage (0.58). Skill-Venus, a Qwen3-0.6B fine-tune, scores the same strings at 0.18–0.22. - As a result, Qwen3 ranks a short, wrong entity string first for **93–97% of queries**; one document ("Roosevelt") is the top hit for 64 different questions. Skill-Venus does this for 41% and EmbeddingGemma-300m for 6%. - Ruled out: padding/batching (the same short documents encoded alone vs in a mixed batch give cosine 1.00), id collisions (no query id equals a document id) and duplicate documents (none). - ViQuAD is not part of the native-4 leaderboard average. It still reflects a real risk: **with Qwen3, keep very short chunks (titles, single entities) out of the index, or filter them**.12345678910111213141516171819202122232425262728293031323334# Models
Each model is run with its own recommended input format. Max input = min(model default, 512 tokens); some models also get a 2,048-token run on the long-document sets.
| Model key | Hugging Face | Params | Vietnamese in model card | Input format | License | Run ||---|---|---:|---|---|---|---|| `qwen3-8b` | [`Qwen/Qwen3-Embedding-8B`](https://huggingface.co/Qwen/Qwen3-Embedding-8B) | 7.57B | yes | instruction on queries · last-token pooling · left padding | Apache-2.0 | 2 || `octen-8b` | [`Octen/Octen-Embedding-8B`](https://huggingface.co/Octen/Octen-Embedding-8B) | 7.57B | multilingual | Qwen3 format (LoRA fine-tune) · doc prompt ' ' | Apache-2.0 | 2 || `qwen3-4b` | [`Qwen/Qwen3-Embedding-4B`](https://huggingface.co/Qwen/Qwen3-Embedding-4B) | 4.02B | yes | instruction on queries · last-token pooling · left padding | Apache-2.0 | 1 + 2 || `octen-4b` | [`Octen/Octen-Embedding-4B`](https://huggingface.co/Octen/Octen-Embedding-4B) | 4.02B | multilingual | Qwen3 format (LoRA fine-tune) · doc prompt ' ' | Apache-2.0 | 2 || `openembed-2b` | [`UCSC-VLAA/OpenEmbed-2B`](https://huggingface.co/UCSC-VLAA/OpenEmbed-2B) | 2.21B | EN card, multilingual base | query: 'Find a passage that answers the given query.' (assumed) | CC-BY-NC-4.0 | 2 || `mistral-embed-1b` | [`mistralai/Mistral-Multimodal-Embed-1B`](https://huggingface.co/mistralai/Mistral-Multimodal-Embed-1B) | 1.24B | multilingual text tower | plain text | Apache-2.0 | 2 || `openembed-0.8b` | [`UCSC-VLAA/OpenEmbed-0.8B`](https://huggingface.co/UCSC-VLAA/OpenEmbed-0.8B) | 0.85B | EN card, multilingual base | as OpenEmbed-2B | CC-BY-NC-4.0 | 2 || `qwen3-0.6b` | [`Qwen/Qwen3-Embedding-0.6B`](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B) | 0.6B | yes | instruction on queries · last-token pooling | Apache-2.0 | 2 || `octen-0.6b` | [`Octen/Octen-Embedding-0.6B`](https://huggingface.co/Octen/Octen-Embedding-0.6B) | 0.6B | multilingual | Qwen3 format (LoRA fine-tune) · doc prompt ' ' | Apache-2.0 | 2 || `skill-venus-0.6b` | [`inclusionAI/Skill-Venus-Embedding-0.6B`](https://huggingface.co/inclusionAI/Skill-Venus-Embedding-0.6B) | 0.6B | via Qwen3 | Qwen3 format (skill-search fine-tune) | Apache-2.0 | 2 || `bge-m3` | [`BAAI/bge-m3`](https://huggingface.co/BAAI/bge-m3) | 0.568B | yes | plain text · CLS dense | MIT | 1 + 2 || `bge-m3-all` | [`BAAI/bge-m3`](https://huggingface.co/BAAI/bge-m3) | 0.568B | yes | weights (1, 0.3, 1) re-scoring dense∪sparse top-100 | MIT | 1 + 2 || `embeddinggemma-300m` | [`google/embeddinggemma-300m`](https://huggingface.co/google/embeddinggemma-300m) | 0.3B | yes | task: … | query: / title: … | text: | Gemma | 2 || `embeddinggemma-2` | [`google/embeddinggemma-2`](https://huggingface.co/google/embeddinggemma-2) | 0.271B | yes | task: … | query: / title: … | text: (text-only path) | Apache-2.0 | 1 + 2 || `para-multi-minilm-l12` | [`sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2`](https://huggingface.co/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2) | 0.118B | yes | plain text · 128 tokens | Apache-2.0 | 2 || `granite-97m-multi-r2` | [`ibm-granite/granite-embedding-97m-multilingual-r2`](https://huggingface.co/ibm-granite/granite-embedding-97m-multilingual-r2) | 0.097B | yes | plain text | Apache-2.0 | 2 || `text-embedding-3-small` | [OpenAI text-embedding-3-small (API)](https://platform.openai.com/docs/guides/embeddings) | n/a | multilingual | plain text · first 512 cl100k tokens · OpenAI Batch API | commercial API | 2 || `text-embedding-3-large` | [OpenAI text-embedding-3-large (API)](https://platform.openai.com/docs/guides/embeddings) | n/a | multilingual | plain text · first 512 cl100k tokens · OpenAI Batch API | commercial API | 2 || `gemini-embedding-2` | [google/gemini-embedding-2 (API via OpenRouter)](https://openrouter.ai/google/gemini-embedding-2) | n/a | multilingual | task: search result | query: … / title: … | text: … · first 512 cl100k tokens | commercial API | 2 || `gemini-embedding-001` | [google/gemini-embedding-001 (API via OpenRouter)](https://openrouter.ai/google/gemini-embedding-001) | n/a | multilingual | query / document task handling per provider docs · first 512 cl100k tokens | commercial API | 2 || `voyage-4-lite` | [mongodb/voyage-4-lite (API via OpenRouter)](https://openrouter.ai/mongodb/voyage-4-lite) | n/a | multilingual | input_type query / document · first 512 cl100k tokens | commercial API | 2 || `pplx-embed-v1-0.6b` | [perplexity/pplx-embed-v1-0.6b (API via OpenRouter)](https://openrouter.ai/perplexity/pplx-embed-v1-0.6b) | 0.6B | multilingual | plain text (input_type has no effect) · first 512 cl100k tokens | commercial API | 2 |
## Excluded
- **No Vietnamese support** (tested, then removed from this benchmark): [`sentence-transformers/all-MiniLM-L12-v2`](https://huggingface.co/sentence-transformers/all-MiniLM-L12-v2), [`FrontiersMind/EmbeddingNandi-450M`](https://huggingface.co/FrontiersMind/EmbeddingNandi-450M), [`FrontiersMind/EmbeddingNandi-150M`](https://huggingface.co/FrontiersMind/EmbeddingNandi-150M), [`sentence-transformers/all-MiniLM-L6-v2`](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2), [`sentence-transformers/all-mpnet-base-v2`](https://huggingface.co/sentence-transformers/all-mpnet-base-v2), [`BAAI/bge-base-en-v1.5`](https://huggingface.co/BAAI/bge-base-en-v1.5).- `knowledgator/EdgeCoder-31M`: a backbone for fine-tuning, not an embedding model; failed the sanity check.- `tencent/OmniEVIE-4B`: removed before any result.1234567891011121314151617181920212223242526272829303132333435363738# Raw results: file formats
Everything under `results/` comes from both runs, in one schema. Run 1 covered Qwen3-Embedding-4B, BGE-M3 and EmbeddingGemma 2 on English + Vietnamese sets (incl. a speed sweep). Run 2 covered all other models plus the run-1 models on the native Vietnamese sets. The `run` column records the source.
## `results/scores.csv` (also `scores.jsonl`)
One row per **model × dataset × configuration**.
| Column | Meaning ||---|---|| `model`, `hf_id`, `params_b` | model key (see docs/models.md), Hugging Face id, parameters (billions) || `run` | 1 or 2 (source run) || `dataset`, `mteb_task`, `dataset_group` | short name, mteb task name, `vi-native` / `vi-translated` / `en` || `max_len` | input window in tokens (512 = default runs; 2048 = long-window runs; 128/256/384 for models whose own limit is lower) || `precision` | bf16 (run 2), fp16 / fp32 (run 1) || `dim` | embedding dimensions used for search || `mode` | `dense` for all models. BGE-M3 also has `sparse`, `multivector`, `dense+sparse` (1, 0.3, 0), `all` (1, 0.3, 1), `dense+sparse(long)`, `all(long)` and `grid …` weight-sweep rows (run 1, Zalo Legal) || `matryoshka_truncated` | true for rows where the embedding was cut to `dim` and re-normalised || `ndcg10`, `p1`, `mrr10`, `recall10`, `recall100` | metrics ×100 (pytrec_eval; MRR@10 computed directly). Empty where a run did not record it || `n_docs`, `n_queries` | corpus and evaluated-query counts || `tok_per_word`, `frac_docs_truncated` | tokens per word with the model's tokenizer on the corpus, and share of documents longer than `max_len` || `ndcg10_per_query_check` | nDCG@10 recomputed from the per-query files (cross-check). Usually within 0.5 of `ndcg10`. Larger gaps (up to ~2) come from exact score ties in bf16/fp16 on small or near-duplicate corpora: `ndcg10` (pytrec_eval) breaks ties by document id, while the per-query files keep the stored ranking order |
## `results/per_query/<model>/<dataset>__L<max_len>[-<precision>].csv.gz`
One row per query: `qid, ndcg10, p1, rr10, recall10, n_relevant`. Use it for significance tests, per-query wins/losses between models, or error analysis. Precision is omitted from the file name for bf16.
## `results/top10/<model>/<dataset>__L<max_len>[-<precision>].jsonl.gz`
One JSON object per query: `{"qid": "...", "top10": [["doc_id", score], ...]}`, best first, cosine scores. Document and query ids are the mteb dataset ids (see docs/datasets.md for sources), so you can join them with the original texts.
## `results/speed/`
- `throughput_vietnamese.csv`: encode speed on 2,000 real Vietnamese documents (mixed sets), one job per GPU, bf16.- `sweep_run1.csv`: run-1 sweep over sequence length × batch size (docs/s, tokens/s, peak memory, OOM).- `latency_run1.csv`: run-1 single-query latency (p50/p95/p99 ms over 1,000 real queries).
Absolute speeds depend on the hardware; compare models within one file only.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576<!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>:root{--bg:#f7f7f5;--panel:#fff;--ink:#1d1d1f;--muted:#5f6368;--muted2:#b9bcc2;--line:#e3e3e0;--track:#eeeeeb;--accent:#c2410c;--accentl:#f4a77c;--accent2:#d97706;--accent2l:#f5cf8a;--gemma:#2563eb;--gemma2:#93c5fd;--qwen:#7c3aed;--qwen2:#c4b5fd;--bge:#0f8a6a;--bge2:#5cc4a5;--best:#ecfdf5}@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#121214;--panel:#1b1b1f;--ink:#ececef;--muted:#a0a3aa;--muted2:#55585f;--line:#2c2c31;--track:#26262b;--accent:#fb923c;--accentl:#9a4a1c;--accent2:#fbbf24;--accent2l:#8a6a1c;--gemma:#60a5fa;--gemma2:#1e4f8f;--qwen:#a78bfa;--qwen2:#4c3a85;--bge:#34d399;--bge2:#1d7a5e;--best:#0d2a20}}:root[data-theme="dark"]{--bg:#121214;--panel:#1b1b1f;--ink:#ececef;--muted:#a0a3aa;--muted2:#55585f;--line:#2c2c31;--track:#26262b;--accent:#fb923c;--accentl:#9a4a1c;--accent2:#fbbf24;--accent2l:#8a6a1c;--gemma:#60a5fa;--gemma2:#1e4f8f;--qwen:#a78bfa;--qwen2:#4c3a85;--bge:#34d399;--bge2:#1d7a5e;--best:#0d2a20}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif}main{max-width:1100px;margin:0 auto;padding:28px 16px 64px}h1{font-size:28px;margin:0 0 6px}h2{font-size:20px;margin:38px 0 12px;padding-bottom:6px;border-bottom:1px solid var(--line)}h3{font-size:15px;margin:4px 0 8px}.sub{color:var(--muted);margin:0 0 14px}.grid{display:grid;gap:14px;margin:12px 0}.g4{grid-template-columns:repeat(auto-fit,minmax(200px,1fr))}.g2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}.card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px 16px;min-width:0;margin-bottom:12px}.kpi .n{font-size:24px;font-weight:700}.kpi .l{color:var(--muted);font-size:13px}.kpi .w{font-size:13px;font-weight:600;margin-top:2px}.dot{display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:6px;vertical-align:middle}.legend span{margin-right:14px;font-size:13px;white-space:nowrap}.tbl{width:100%;overflow-x:auto}table{border-collapse:collapse;width:100%;font-size:13.5px}th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:top}th{color:var(--muted);font-weight:600;font-size:12px;text-transform:uppercase;letter-spacing:.03em}td.best{background:var(--best);font-weight:700}tr.avg td{border-top:2px solid var(--line)}.sm{font-size:11.5px;color:var(--muted);font-weight:400}.note{font-size:12.5px;color:var(--muted)}code{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;background:var(--track);padding:1px 5px;border-radius:4px}.chart{width:100%;height:auto;display:block}.chart .grid{stroke:var(--line);stroke-width:1}.chart .ax{fill:var(--muted);font-size:11px}.chart .bv{fill:var(--ink);font-size:9.5px}.callout{border-radius:8px;padding:10px 14px;margin:10px 0;font-size:14px;background:var(--track)}</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>final</b> · total encode time so far 31.07 h</p><div class="legend"><span><i class="dot" style="background:var(--bge)"></i>BGE-M3 fp16</span><span><i class="dot" style="background:var(--gemma)"></i>EmbeddingGemma 2 fp32</span><span><i class="dot" style="background:var(--qwen)"></i>Qwen3-Emb-4B fp16</span><span><i class="dot" style="background:var(--gemma2)"></i>EmbeddingGemma 2 fp16 (check)</span></div><div class="grid g4"><div class="card kpi"><div class="n">69.9</div><div class="l">English avg nDCG@10</div><div class="w">Qwen3-Emb-4B fp16</div></div><div class="card kpi"><div class="n">58.4</div><div class="l">VN-MTEB (translated) avg nDCG@10</div><div class="w">Qwen3-Emb-4B fp16</div></div><div class="card kpi"><div class="n">71.1</div><div class="l">Zalo Legal (native VI) MRR@10</div><div class="w">Qwen3-Emb-4B fp16</div></div><div class="card kpi"><div class="n">56 docs/s</div><div class="l">fastest encode @512 tok</div><div class="w">BGE-M3 fp16</div></div></div><h2>Conclusions</h2><div class="callout"><b>Verdict for a single run 1.</b> Qwen3-Embedding-4B gives the best retrieval quality everywhere, but costs about 10× more GPU time than BGE-M3. BGE-M3 with all three modes (dense + sparse + multi-vector) is the best quality per GPU-second for Vietnamese. EmbeddingGemma 2 is roughly as good as BGE-M3 dense on trustworthy tasks, should run in fp16 in run 1 (no quality loss here, 2.4× faster), and has the lowest memory use. Its real advantage is multimodal and code inputs, which this text benchmark does not test.</div>
<div class="tbl"><table><tr><th>Average nDCG@10</th><th>English (3 tasks, without SciFact)</th><th>VN-MTEB translated (4)</th><th>Zalo Legal (native VI)</th><th>Encode docs/s @512</th><th>GPU memory</th></tr><tr><td><i class="dot" style="background:var(--qwen)"></i><b>Qwen3-Embedding-4B</b> fp16</td><td><b>59.2</b></td><td><b>52.8</b></td><td><b>76.6</b></td><td>~4–11</td><td>~8–10 GiB</td></tr><tr><td><i class="dot" style="background:var(--bge)"></i><b>BGE-M3 all three modes</b></td><td>43.1</td><td>45.2</td><td>74.7</td><td>~56–117 (+1 extra pass)</td><td>~1–2 GiB</td></tr><tr><td><i class="dot" style="background:var(--bge)"></i>BGE-M3 dense</td><td>42.3</td><td>44.5</td><td>71.7</td><td>56–117</td><td>~1–2 GiB</td></tr><tr><td><i class="dot" style="background:var(--gemma)"></i><b>EmbeddingGemma 2</b> fp32 (fp16 ≈ same)</td><td>42.4</td><td>45.8</td><td>69.5</td><td>16–38 (fp16: 40–83)</td><td>~1.2–4 GiB</td></tr></table></div>
<h3>Key findings</h3><ol><li><b>Qwen3-4B wins by a wide margin in English (+16 points)</b> but only modestly on native Vietnamese: +1.9 points over BGE-M3 with all three modes on Zalo Legal. On the translated Vietnamese sets its English lead shrinks a lot (paired queries: ArguAna 74.7→57.8, FiQA 62.2→41.8).</li><li><b>BGE-M3 with all three modes is the value pick for Vietnamese.</b> On Zalo Legal it lifts nDCG@10 by +3.0 and MRR@10 by +4.0 over dense, getting within 2 points of Qwen3-4B while using about 6× less GPU time and about 5× less memory. The paper's default weights (1, 0.3, 1) are close to optimal here; the sparse-heavy weights the paper suggests for long documents hurt.</li><li><b>Sparse (word matching) hurts on argument-retrieval tasks</b> (ArguAna EN/VN), where queries and documents paraphrase each other. Leave combined modes off for that kind of workload.</li><li><b>EmbeddingGemma 2 in fp16 is safe for this text workload, despite Google's warning.</b> 0 NaN across 124k documents, per-document cosine with fp32 ≥ 0.9995, identical nDCG and 2.3–2.4× faster. Still check before using it for longer inputs or other modalities.</li><li><b>EmbeddingGemma 2's SciFact score (85.2) looks contaminated.</b> On the same 134 queries it drops 17.9 points on the translated copy (BGE-M3 drops 2.8), consistent with having learned the English SciFact text, so SciFact is left out of the English average above. Qwen3-4B shows the same pattern on ArguAna (−16.9) and FiQA (−20.5, against −4.4 for EmbeddingGemma 2), both datasets with widely used training splits. Part of its English lead is probably familiarity with the benchmarks, which makes the native Vietnamese Zalo result the fairest comparison.</li>
<li><b>Long context helps legal text:</b> Qwen3-4B at max_len 2048 on Zalo Legal reaches nDCG@10 78.8 / MRR@10 73.3 (+2.2 / +2.2 over 512), because 21% of the articles are longer than 512 tokens. The cost is 195 min of encoding instead of 144. Chunking long articles at about 512 tokens is the cheaper alternative.</li><li><b>TREC-COVID (171k docs, overnight tier):</b> nDCG@10 English / Vietnamese: Qwen3-4B 93.5 / 80.7, EmbeddingGemma 2 79.5 / 68.2, BGE-M3 all three modes 59.4 / 66.7 (dense 55.1 / 66.9). Order: Qwen > EmbeddingGemma 2 > BGE-M3. Both larger models lose 11–13 points in Vietnamese while BGE-M3 gains, the same English-benchmark-familiarity pattern as above. Only 50 / 44 queries, so treat as indicative. Qwen3-4B took 6.1 h + 7 h to encode, against about 35 min each for BGE-M3.</li><li><b>Matryoshka truncation:</b> Qwen3-4B 2560→1024 is essentially lossless (Zalo 76.6→76.3, FiQA 61.7→62.3). EmbeddingGemma 2 768→512 is lossless, but 256 loses 1–5 points and 128 loses 8–15.</li></ol>
<h3>Recommendation</h3><ul><li><b>Best quality, offline indexing, corpus up to a few hundred thousand chunks:</b> Qwen3-Embedding-4B fp16, max_len 512, instruction on queries, truncated to 1024 dims (−0.3 nDCG on Zalo, 2.5× smaller index). Budget about 2.2k tokens/s, roughly 8 M tokens per hour.</li><li><b>Vietnamese production search in run 1 with high throughput or a low-latency query path:</b> BGE-M3, dense for the first pass, then re-score the top 100 with sparse and multi-vector using (1, 0.3, 1).</li><li><b>Multimodal or code, or sharing the GPU with other services:</b> EmbeddingGemma 2 in fp16, text-only loading, 512-dim MRL (lossless here; 256-dim costs about 2–5 points). Check fp16 on your own data first.</li></ul>
<h2>1 · Retrieval quality (nDCG@10)</h2><div class="card"><svg viewBox="0 0 760 280" class="chart" role="img"><line x1="40" x2="750" y1="222.0" y2="222.0" class="grid"/><text x="34" y="226.0" class="ax" text-anchor="end">0</text><line x1="40" x2="750" y1="169.0" y2="169.0" class="grid"/><text x="34" y="173.0" class="ax" text-anchor="end">25</text><line x1="40" x2="750" y1="116.0" y2="116.0" class="grid"/><text x="34" y="120.0" class="ax" text-anchor="end">50</text><line x1="40" x2="750" y1="63.0" y2="63.0" class="grid"/><text x="34" y="67.0" class="ax" text-anchor="end">75</text><line x1="40" x2="750" y1="10.0" y2="10.0" class="grid"/><text x="34" y="14.0" class="ax" text-anchor="end">100</text><rect x="45.0" y="86.1" width="16.2" height="135.9" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · SciFact: 64.1</title></rect><text x="53.1" y="83.1" class="bv" text-anchor="middle">64.1</text><rect x="63.2" y="41.4" width="16.2" height="180.6" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · SciFact: 85.2</title></rect><text x="71.3" y="38.4" class="bv" text-anchor="middle">85.2</text><rect x="81.4" y="56.0" width="16.2" height="166.0" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · SciFact: 78.3</title></rect><text x="89.5" y="53.0" class="bv" text-anchor="middle">78.3</text><text x="72.3" y="238" class="ax" text-anchor="middle">SciFact</text><rect x="109.5" y="154.9" width="16.2" height="67.1" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · NFCorpus: 31.7</title></rect><text x="117.6" y="151.9" class="bv" text-anchor="middle">31.7</text><rect x="127.7" y="143.9" width="16.2" height="78.1" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · NFCorpus: 36.9</title></rect><text x="135.8" y="140.9" class="bv" text-anchor="middle">36.9</text><rect x="145.9" y="135.1" width="16.2" height="86.9" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · NFCorpus: 41.0</title></rect><text x="154.0" y="132.1" class="bv" text-anchor="middle">41.0</text><text x="136.8" y="238" class="ax" text-anchor="middle">NFCorpus</text><rect x="174.1" y="107.4" width="16.2" height="114.6" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · ArguAna: 54.1</title></rect><text x="182.2" y="104.4" class="bv" text-anchor="middle">54.1</text><rect x="192.3" y="97.7" width="16.2" height="124.3" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · ArguAna: 58.6</title></rect><text x="200.4" y="94.7" class="bv" text-anchor="middle">58.6</text><rect x="210.5" y="63.3" width="16.2" height="158.7" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · ArguAna: 74.9</title></rect><text x="218.5" y="60.3" class="bv" text-anchor="middle">74.9</text><text x="201.4" y="238" class="ax" text-anchor="middle">ArguAna</text><rect x="238.6" y="135.0" width="16.2" height="87.0" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · FiQA2018: 41.1</title></rect><text x="246.7" y="132.0" class="bv" text-anchor="middle">41.1</text><rect x="256.8" y="154.8" width="16.2" height="67.2" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · FiQA2018: 31.7</title></rect><text x="264.9" y="151.8" class="bv" text-anchor="middle">31.7</text><rect x="275.0" y="91.3" width="16.2" height="130.7" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · FiQA2018: 61.7</title></rect><text x="283.1" y="88.3" class="bv" text-anchor="middle">61.7</text><text x="265.9" y="238" class="ax" text-anchor="middle">FiQA</text><rect x="303.2" y="105.3" width="16.2" height="116.7" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · TRECCOVID: 55.1</title></rect><text x="311.3" y="102.3" class="bv" text-anchor="middle">55.1</text><rect x="321.4" y="53.5" width="16.2" height="168.5" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · TRECCOVID: 79.5</title></rect><text x="329.5" y="50.5" class="bv" text-anchor="middle">79.5</text><rect x="339.5" y="23.9" width="16.2" height="198.1" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · TRECCOVID: 93.5</title></rect><text x="347.6" y="20.9" class="bv" text-anchor="middle">93.5</text><text x="330.5" y="238" class="ax" text-anchor="middle">TRECCOVID</text><rect x="367.7" y="70.1" width="16.2" height="151.9" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · ZacLegalTextRetrieval: 71.7</title></rect><text x="375.8" y="67.1" class="bv" text-anchor="middle">71.7</text><rect x="385.9" y="74.6" width="16.2" height="147.4" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · ZacLegalTextRetrieval: 69.5</title></rect><text x="394.0" y="71.6" class="bv" text-anchor="middle">69.5</text><rect x="404.1" y="59.6" width="16.2" height="162.4" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · ZacLegalTextRetrieval: 76.6</title></rect><text x="412.2" y="56.6" class="bv" text-anchor="middle">76.6</text><text x="395.0" y="238" class="ax" text-anchor="middle">ZacLegal</text><rect x="432.3" y="90.0" width="16.2" height="132.0" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · SciFact-VN: 62.3</title></rect><text x="440.4" y="87.0" class="bv" text-anchor="middle">62.3</text><rect x="450.5" y="77.1" width="16.2" height="144.9" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · SciFact-VN: 68.4</title></rect><text x="458.5" y="74.1" class="bv" text-anchor="middle">68.4</text><rect x="468.6" y="68.0" width="16.2" height="154.0" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · SciFact-VN: 72.6</title></rect><text x="476.7" y="65.0" class="bv" text-anchor="middle">72.6</text><text x="459.5" y="238" class="ax" text-anchor="middle">SciFact-VN</text><rect x="496.8" y="156.4" width="16.2" height="65.6" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · NFCorpus-VN: 31.0</title></rect><text x="504.9" y="153.4" class="bv" text-anchor="middle">31.0</text><rect x="515.0" y="152.0" width="16.2" height="70.0" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · NFCorpus-VN: 33.0</title></rect><text x="523.1" y="149.0" class="bv" text-anchor="middle">33.0</text><rect x="533.2" y="139.7" width="16.2" height="82.3" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · NFCorpus-VN: 38.8</title></rect><text x="541.3" y="136.7" class="bv" text-anchor="middle">38.8</text><text x="524.1" y="238" class="ax" text-anchor="middle">NFCorpus-VN</text><rect x="561.4" y="115.0" width="16.2" height="107.0" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · ArguAna-VN: 50.5</title></rect><text x="569.5" y="112.0" class="bv" text-anchor="middle">50.5</text><rect x="579.5" y="108.3" width="16.2" height="113.7" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · ArguAna-VN: 53.6</title></rect><text x="587.6" y="105.3" class="bv" text-anchor="middle">53.6</text><rect x="597.7" y="99.4" width="16.2" height="122.6" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · ArguAna-VN: 57.8</title></rect><text x="605.8" y="96.4" class="bv" text-anchor="middle">57.8</text><text x="588.6" y="238" class="ax" text-anchor="middle">ArguAna-VN</text><rect x="625.9" y="149.7" width="16.2" height="72.3" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · FiQA2018-VN: 34.1</title></rect><text x="634.0" y="146.7" class="bv" text-anchor="middle">34.1</text><rect x="644.1" y="162.5" width="16.2" height="59.5" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · FiQA2018-VN: 28.1</title></rect><text x="652.2" y="159.5" class="bv" text-anchor="middle">28.1</text><rect x="662.3" y="133.5" width="16.2" height="88.5" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · FiQA2018-VN: 41.8</title></rect><text x="670.4" y="130.5" class="bv" text-anchor="middle">41.8</text><text x="653.2" y="238" class="ax" text-anchor="middle">FiQA-VN</text><rect x="690.5" y="80.3" width="16.2" height="141.7" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · TRECCOVID-VN: 66.9</title></rect><text x="698.5" y="77.3" class="bv" text-anchor="middle">66.9</text><rect x="708.6" y="77.4" width="16.2" height="144.6" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · TRECCOVID-VN: 68.2</title></rect><text x="716.7" y="74.4" class="bv" text-anchor="middle">68.2</text><rect x="726.8" y="50.8" width="16.2" height="171.2" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · TRECCOVID-VN: 80.7</title></rect><text x="734.9" y="47.8" class="bv" text-anchor="middle">80.7</text><text x="717.7" y="238" class="ax" text-anchor="middle">TRECCOVID-VN</text></svg></div><div class='tbl'><table><tr><th>Task</th><th><i class='dot' style='background:var(--bge)'></i>BGE-M3 fp16</th><th><i class='dot' style='background:var(--gemma)'></i>EmbeddingGemma 2 fp32</th><th><i class='dot' style='background:var(--qwen)'></i>Qwen3-Emb-4B fp16</th></tr><tr><td><b>SciFact</b><br><span class='sm'>🇬🇧 · 5,183 docs</span></td><td class="">64.1<span class="sm"> / 90.4 / 60.8</span></td><td class="best">85.2<span class="sm"> / 97.7 / 83.3</span></td><td class="">78.3<span class="sm"> / 97.7 / 74.2</span></td></tr><tr><td><b>NFCorpus</b><br><span class='sm'>🇬🇧 · 3,633 docs</span></td><td class="">31.7<span class="sm"> / 28.4 / 52.5</span></td><td class="">36.9<span class="sm"> / 36.6 / 57.0</span></td><td class="best">41.0<span class="sm"> / 38.8 / 62.7</span></td></tr><tr><td><b>ArguAna</b><br><span class='sm'>🇬🇧 · 8,674 docs</span></td><td class="">54.1<span class="sm"> / 98.2 / 45.7</span></td><td class="">58.6<span class="sm"> / 98.2 / 51.1</span></td><td class="best">74.9<span class="sm"> / 99.6 / 68.6</span></td></tr><tr><td><b>FiQA2018</b><br><span class='sm'>🇬🇧 · 57,638 docs</span></td><td class="">41.1<span class="sm"> / 71.0 / 50.2</span></td><td class="">31.7<span class="sm"> / 65.8 / 39.2</span></td><td class="best">61.7<span class="sm"> / 90.8 / 69.6</span></td></tr><tr><td><b>TRECCOVID</b><br><span class='sm'>🇬🇧 · 171,332 docs</span></td><td class="">55.1<span class="sm"> / 10.0 / 70.9</span></td><td class="">79.5<span class="sm"> / 14.8 / 96.0</span></td><td class="best">93.5<span class="sm"> / 19.7 / 99.0</span></td></tr><tr><td><b>ZacLegalTextRetrieval</b><br><span class='sm'>🇻🇳 native · 61,425 docs</span></td><td class="">71.7<span class="sm"> / 97.8 / 65.4</span></td><td class="">69.5<span class="sm"> / 96.8 / 64.4</span></td><td class="best">76.6<span class="sm"> / 99.0 / 71.1</span></td></tr><tr><td><b>SciFact-VN</b><br><span class='sm'>🇻🇳 translated · 5,183 docs</span></td><td class="">62.3<span class="sm"> / 89.2 / 60.2</span></td><td class="">68.4<span class="sm"> / 93.3 / 65.1</span></td><td class="best">72.6<span class="sm"> / 98.5 / 69.0</span></td></tr><tr><td><b>NFCorpus-VN</b><br><span class='sm'>🇻🇳 translated · 3,618 docs</span></td><td class="">31.0<span class="sm"> / 27.6 / 49.7</span></td><td class="">33.0<span class="sm"> / 31.3 / 50.8</span></td><td class="best">38.8<span class="sm"> / 34.7 / 57.9</span></td></tr><tr><td><b>ArguAna-VN</b><br><span class='sm'>🇻🇳 translated · 8,674 docs</span></td><td class="">50.5<span class="sm"> / 97.3 / 41.6</span></td><td class="">53.6<span class="sm"> / 97.8 / 44.9</span></td><td class="best">57.8<span class="sm"> / 98.5 / 48.6</span></td></tr><tr><td><b>FiQA2018-VN</b><br><span class='sm'>🇻🇳 translated · 57,638 docs</span></td><td class="">34.1<span class="sm"> / 63.6 / 40.9</span></td><td class="">28.1<span class="sm"> / 57.3 / 34.6</span></td><td class="best">41.8<span class="sm"> / 73.3 / 50.7</span></td></tr><tr><td><b>TRECCOVID-VN</b><br><span class='sm'>🇻🇳 translated · 171,332 docs</span></td><td class="">66.9<span class="sm"> / 11.7 / 83.9</span></td><td class="">68.2<span class="sm"> / 13.1 / 87.5</span></td><td class="best">80.7<span class="sm"> / 17.3 / 92.0</span></td></tr><tr class='avg'><td>Avg English nDCG@10</td><td><b>49.2</b></td><td><b>58.4</b></td><td><b>69.9</b></td></tr><tr class='avg'><td>Avg VN-MTEB (translated) nDCG@10</td><td><b>48.9</b></td><td><b>50.3</b></td><td><b>58.4</b></td></tr></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><h2>2 · English vs Vietnamese (same docs, machine-translated)</h2><div class='tbl'><table><tr><th>EN → VN pair</th><th>BGE-M3 fp16</th><th>EmbeddingGemma 2 fp32</th><th>Qwen3-Emb-4B fp16</th></tr><tr><td>SciFact<br><span class='sm'>134 paired queries</span></td><td>65.1 → 62.3 <b>(-2.8)</b></td><td>86.3 → 68.4 <b>(-17.9)</b></td><td>79.4 → 72.6 <b>(-6.8)</b></td></tr><tr><td>NFCorpus<br><span class='sm'>166 paired queries</span></td><td>33.0 → 31.0 <b>(-2.0)</b></td><td>37.2 → 33.0 <b>(-4.1)</b></td><td>42.3 → 38.8 <b>(-3.5)</b></td></tr><tr><td>ArguAna<br><span class='sm'>1295 paired queries</span></td><td>54.0 → 50.5 <b>(-3.5)</b></td><td>57.9 → 53.6 <b>(-4.2)</b></td><td>74.7 → 57.8 <b>(-16.9)</b></td></tr><tr><td>FiQA2018<br><span class='sm'>384 paired queries</span></td><td>42.4 → 34.1 <b>(-8.4)</b></td><td>32.5 → 28.1 <b>(-4.4)</b></td><td>62.2 → 41.8 <b>(-20.5)</b></td></tr><tr><td>TRECCOVID<br><span class='sm'>44 paired queries</span></td><td>55.5 → 66.9 <b>(+11.3)</b></td><td>78.3 → 68.2 <b>(-10.1)</b></td><td>94.0 → 80.7 <b>(-13.2)</b></td></tr></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><h2>3 · BGE-M3: dense vs sparse vs multi-vector vs hybrid</h2><div class="card"><div class="legend"><span><i class="dot" style="background:var(--bge)"></i>dense</span><span><i class="dot" style="background:var(--muted2)"></i>sparse</span><span><i class="dot" style="background:var(--bge2)"></i>multivector</span><span><i class="dot" style="background:var(--accent2)"></i>dense+sparse</span><span><i class="dot" style="background:var(--accent)"></i>all</span><span><i class="dot" style="background:var(--accent2l)"></i>dense+sparse(long)</span><span><i class="dot" style="background:var(--accentl)"></i>all(long)</span></div><svg viewBox="0 0 760 280" class="chart" role="img"><line x1="40" x2="750" y1="222.0" y2="222.0" class="grid"/><text x="34" y="226.0" class="ax" text-anchor="end">0</text><line x1="40" x2="750" y1="169.0" y2="169.0" class="grid"/><text x="34" y="173.0" class="ax" text-anchor="end">25</text><line x1="40" x2="750" y1="116.0" y2="116.0" class="grid"/><text x="34" y="120.0" class="ax" text-anchor="end">50</text><line x1="40" x2="750" y1="63.0" y2="63.0" class="grid"/><text x="34" y="67.0" class="ax" text-anchor="end">75</text><line x1="40" x2="750" y1="10.0" y2="10.0" class="grid"/><text x="34" y="14.0" class="ax" text-anchor="end">100</text><rect x="45.0" y="86.1" width="5.8" height="135.9" rx="2" fill="var(--bge)"><title>dense · SciFact: 64.1</title></rect><rect x="52.8" y="87.5" width="5.8" height="134.5" rx="2" fill="var(--muted2)"><title>sparse · SciFact: 63.4</title></rect><rect x="60.6" y="74.4" width="5.8" height="147.6" rx="2" fill="var(--bge2)"><title>multivector · SciFact: 69.6</title></rect><rect x="68.4" y="77.9" width="5.8" height="144.1" rx="2" fill="var(--accent2)"><title>dense+sparse · SciFact: 68.0</title></rect><rect x="76.2" y="73.2" width="5.8" height="148.8" rx="2" fill="var(--accent)"><title>all · SciFact: 70.2</title></rect><rect x="84.0" y="79.6" width="5.8" height="142.4" rx="2" fill="var(--accent2l)"><title>dense+sparse(long) · SciFact: 67.2</title></rect><rect x="91.8" y="70.3" width="5.8" height="151.7" rx="2" fill="var(--accentl)"><title>all(long) · SciFact: 71.5</title></rect><text x="72.3" y="238" class="ax" text-anchor="middle">SciFact</text><rect x="109.5" y="154.9" width="5.8" height="67.1" rx="2" fill="var(--bge)"><title>dense · NFCorpus: 31.7</title></rect><rect x="117.3" y="161.8" width="5.8" height="60.2" rx="2" fill="var(--muted2)"><title>sparse · NFCorpus: 28.4</title></rect><rect x="125.1" y="149.2" width="5.8" height="72.8" rx="2" fill="var(--bge2)"><title>multivector · NFCorpus: 34.3</title></rect><rect x="132.9" y="151.8" width="5.8" height="70.2" rx="2" fill="var(--accent2)"><title>dense+sparse · NFCorpus: 33.1</title></rect><rect x="140.7" y="148.7" width="5.8" height="73.3" rx="2" fill="var(--accent)"><title>all · NFCorpus: 34.6</title></rect><rect x="148.5" y="154.8" width="5.8" height="67.2" rx="2" fill="var(--accent2l)"><title>dense+sparse(long) · NFCorpus: 31.7</title></rect><rect x="156.3" y="149.8" width="5.8" height="72.2" rx="2" fill="var(--accentl)"><title>all(long) · NFCorpus: 34.1</title></rect><text x="136.8" y="238" class="ax" text-anchor="middle">NFCorpus</text><rect x="174.1" y="107.4" width="5.8" height="114.6" rx="2" fill="var(--bge)"><title>dense · ArguAna: 54.1</title></rect><rect x="181.9" y="146.1" width="5.8" height="75.9" rx="2" fill="var(--muted2)"><title>sparse · ArguAna: 35.8</title></rect><rect x="189.7" y="115.6" width="5.8" height="106.4" rx="2" fill="var(--bge2)"><title>multivector · ArguAna: 50.2</title></rect><rect x="197.5" y="113.4" width="5.8" height="108.6" rx="2" fill="var(--accent2)"><title>dense+sparse · ArguAna: 51.2</title></rect><rect x="205.3" y="112.6" width="5.8" height="109.4" rx="2" fill="var(--accent)"><title>all · ArguAna: 51.6</title></rect><rect x="213.1" y="139.2" width="5.8" height="82.8" rx="2" fill="var(--accent2l)"><title>dense+sparse(long) · ArguAna: 39.0</title></rect><rect x="220.8" y="129.0" width="5.8" height="93.0" rx="2" fill="var(--accentl)"><title>all(long) · ArguAna: 43.9</title></rect><text x="201.4" y="238" class="ax" text-anchor="middle">ArguAna</text><rect x="238.6" y="135.0" width="5.8" height="87.0" rx="2" fill="var(--bge)"><title>dense · FiQA2018: 41.1</title></rect><rect x="246.4" y="164.9" width="5.8" height="57.1" rx="2" fill="var(--muted2)"><title>sparse · FiQA2018: 26.9</title></rect><rect x="254.2" y="133.2" width="5.8" height="88.8" rx="2" fill="var(--bge2)"><title>multivector · FiQA2018: 41.9</title></rect><rect x="262.0" y="132.6" width="5.8" height="89.4" rx="2" fill="var(--accent2)"><title>dense+sparse · FiQA2018: 42.2</title></rect><rect x="269.8" y="130.7" width="5.8" height="91.3" rx="2" fill="var(--accent)"><title>all · FiQA2018: 43.1</title></rect><rect x="277.6" y="150.1" width="5.8" height="71.9" rx="2" fill="var(--accent2l)"><title>dense+sparse(long) · FiQA2018: 33.9</title></rect><rect x="285.4" y="135.3" width="5.8" height="86.7" rx="2" fill="var(--accentl)"><title>all(long) · FiQA2018: 40.9</title></rect><text x="265.9" y="238" class="ax" text-anchor="middle">FiQA</text><rect x="303.2" y="105.3" width="5.8" height="116.7" rx="2" fill="var(--bge)"><title>dense · TRECCOVID: 55.1</title></rect><rect x="311.0" y="109.5" width="5.8" height="112.5" rx="2" fill="var(--muted2)"><title>sparse · TRECCOVID: 53.1</title></rect><rect x="318.8" y="115.6" width="5.8" height="106.4" rx="2" fill="var(--bge2)"><title>multivector · TRECCOVID: 50.2</title></rect><rect x="326.6" y="86.7" width="5.8" height="135.3" rx="2" fill="var(--accent2)"><title>dense+sparse · TRECCOVID: 63.8</title></rect><rect x="334.4" y="96.1" width="5.8" height="125.9" rx="2" fill="var(--accent)"><title>all · TRECCOVID: 59.4</title></rect><rect x="342.1" y="83.7" width="5.8" height="138.3" rx="2" fill="var(--accent2l)"><title>dense+sparse(long) · TRECCOVID: 65.2</title></rect><rect x="349.9" y="71.3" width="5.8" height="150.7" rx="2" fill="var(--accentl)"><title>all(long) · TRECCOVID: 71.1</title></rect><text x="330.5" y="238" class="ax" text-anchor="middle">TRECCOVID</text><rect x="367.7" y="70.1" width="5.8" height="151.9" rx="2" fill="var(--bge)"><title>dense · ZacLegalTextRetrieval: 71.7</title></rect><rect x="375.5" y="83.4" width="5.8" height="138.6" rx="2" fill="var(--muted2)"><title>sparse · ZacLegalTextRetrieval: 65.4</title></rect><rect x="383.3" y="66.6" width="5.8" height="155.4" rx="2" fill="var(--bge2)"><title>multivector · ZacLegalTextRetrieval: 73.3</title></rect><rect x="391.1" y="65.2" width="5.8" height="156.8" rx="2" fill="var(--accent2)"><title>dense+sparse · ZacLegalTextRetrieval: 74.0</title></rect><rect x="398.9" y="63.7" width="5.8" height="158.3" rx="2" fill="var(--accent)"><title>all · ZacLegalTextRetrieval: 74.7</title></rect><rect x="406.7" y="74.9" width="5.8" height="147.1" rx="2" fill="var(--accent2l)"><title>dense+sparse(long) · ZacLegalTextRetrieval: 69.4</title></rect><rect x="414.5" y="65.4" width="5.8" height="156.6" rx="2" fill="var(--accentl)"><title>all(long) · ZacLegalTextRetrieval: 73.9</title></rect><text x="395.0" y="238" class="ax" text-anchor="middle">ZacLegal</text><rect x="432.3" y="90.0" width="5.8" height="132.0" rx="2" fill="var(--bge)"><title>dense · SciFact-VN: 62.3</title></rect><rect x="440.1" y="94.2" width="5.8" height="127.8" rx="2" fill="var(--muted2)"><title>sparse · SciFact-VN: 60.3</title></rect><rect x="447.9" y="80.5" width="5.8" height="141.5" rx="2" fill="var(--bge2)"><title>multivector · SciFact-VN: 66.7</title></rect><rect x="455.6" y="88.4" width="5.8" height="133.6" rx="2" fill="var(--accent2)"><title>dense+sparse · SciFact-VN: 63.0</title></rect><rect x="463.4" y="83.9" width="5.8" height="138.1" rx="2" fill="var(--accent)"><title>all · SciFact-VN: 65.1</title></rect><rect x="471.2" y="86.2" width="5.8" height="135.8" rx="2" fill="var(--accent2l)"><title>dense+sparse(long) · SciFact-VN: 64.1</title></rect><rect x="479.0" y="81.2" width="5.8" height="140.8" rx="2" fill="var(--accentl)"><title>all(long) · SciFact-VN: 66.4</title></rect><text x="459.5" y="238" class="ax" text-anchor="middle">SciFact-VN</text><rect x="496.8" y="156.4" width="5.8" height="65.6" rx="2" fill="var(--bge)"><title>dense · NFCorpus-VN: 31.0</title></rect><rect x="504.6" y="162.3" width="5.8" height="59.7" rx="2" fill="var(--muted2)"><title>sparse · NFCorpus-VN: 28.2</title></rect><rect x="512.4" y="151.7" width="5.8" height="70.3" rx="2" fill="var(--bge2)"><title>multivector · NFCorpus-VN: 33.2</title></rect><rect x="520.2" y="154.5" width="5.8" height="67.5" rx="2" fill="var(--accent2)"><title>dense+sparse · NFCorpus-VN: 31.9</title></rect><rect x="528.0" y="151.4" width="5.8" height="70.6" rx="2" fill="var(--accent)"><title>all · NFCorpus-VN: 33.3</title></rect><rect x="535.8" y="156.3" width="5.8" height="65.7" rx="2" fill="var(--accent2l)"><title>dense+sparse(long) · NFCorpus-VN: 31.0</title></rect><rect x="543.6" y="150.4" width="5.8" height="71.6" rx="2" fill="var(--accentl)"><title>all(long) · NFCorpus-VN: 33.8</title></rect><text x="524.1" y="238" class="ax" text-anchor="middle">NFCorpus-VN</text><rect x="561.4" y="115.0" width="5.8" height="107.0" rx="2" fill="var(--bge)"><title>dense · ArguAna-VN: 50.5</title></rect><rect x="569.2" y="170.3" width="5.8" height="51.7" rx="2" fill="var(--muted2)"><title>sparse · ArguAna-VN: 24.4</title></rect><rect x="576.9" y="124.6" width="5.8" height="97.4" rx="2" fill="var(--bge2)"><title>multivector · ArguAna-VN: 46.0</title></rect><rect x="584.7" y="125.0" width="5.8" height="97.0" rx="2" fill="var(--accent2)"><title>dense+sparse · ArguAna-VN: 45.7</title></rect><rect x="592.5" y="122.5" width="5.8" height="99.5" rx="2" fill="var(--accent)"><title>all · ArguAna-VN: 46.9</title></rect><rect x="600.3" y="161.4" width="5.8" height="60.6" rx="2" fill="var(--accent2l)"><title>dense+sparse(long) · ArguAna-VN: 28.6</title></rect><rect x="608.1" y="147.8" width="5.8" height="74.2" rx="2" fill="var(--accentl)"><title>all(long) · ArguAna-VN: 35.0</title></rect><text x="588.6" y="238" class="ax" text-anchor="middle">ArguAna-VN</text><rect x="625.9" y="149.7" width="5.8" height="72.3" rx="2" fill="var(--bge)"><title>dense · FiQA2018-VN: 34.1</title></rect><rect x="633.7" y="179.2" width="5.8" height="42.8" rx="2" fill="var(--muted2)"><title>sparse · FiQA2018-VN: 20.2</title></rect><rect x="641.5" y="150.3" width="5.8" height="71.7" rx="2" fill="var(--bge2)"><title>multivector · FiQA2018-VN: 33.8</title></rect><rect x="649.3" y="147.2" width="5.8" height="74.8" rx="2" fill="var(--accent2)"><title>dense+sparse · FiQA2018-VN: 35.3</title></rect><rect x="657.1" y="146.4" width="5.8" height="75.6" rx="2" fill="var(--accent)"><title>all · FiQA2018-VN: 35.7</title></rect><rect x="664.9" y="165.9" width="5.8" height="56.1" rx="2" fill="var(--accent2l)"><title>dense+sparse(long) · FiQA2018-VN: 26.4</title></rect><rect x="672.7" y="153.2" width="5.8" height="68.8" rx="2" fill="var(--accentl)"><title>all(long) · FiQA2018-VN: 32.5</title></rect><text x="653.2" y="238" class="ax" text-anchor="middle">FiQA-VN</text><rect x="690.5" y="80.3" width="5.8" height="141.7" rx="2" fill="var(--bge)"><title>dense · TRECCOVID-VN: 66.9</title></rect><rect x="698.2" y="121.1" width="5.8" height="100.9" rx="2" fill="var(--muted2)"><title>sparse · TRECCOVID-VN: 47.6</title></rect><rect x="706.0" y="91.1" width="5.8" height="130.9" rx="2" fill="var(--bge2)"><title>multivector · TRECCOVID-VN: 61.7</title></rect><rect x="713.8" y="75.3" width="5.8" height="146.7" rx="2" fill="var(--accent2)"><title>dense+sparse · TRECCOVID-VN: 69.2</title></rect><rect x="721.6" y="80.5" width="5.8" height="141.5" rx="2" fill="var(--accent)"><title>all · TRECCOVID-VN: 66.7</title></rect><rect x="729.4" y="97.8" width="5.8" height="124.2" rx="2" fill="var(--accent2l)"><title>dense+sparse(long) · TRECCOVID-VN: 58.6</title></rect><rect x="737.2" y="81.3" width="5.8" height="140.7" rx="2" fill="var(--accentl)"><title>all(long) · TRECCOVID-VN: 66.4</title></rect><text x="717.7" y="238" class="ax" text-anchor="middle">TRECCOVID-VN</text></svg><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><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><tr><td>dense only</td><td>(1,0,0)</td><td>71.7</td><td>65.4</td><td>97.8</td></tr><tr><td>all w2=0.1</td><td>[1, 0.1, 1]</td><td>74.1</td><td>68.8</td><td>98.2</td></tr><tr><td>all w2=0.2</td><td>[1, 0.2, 1]</td><td>74.5</td><td>69.2</td><td>98.4</td></tr><tr><td>all w2=0.5</td><td>[1, 0.5, 1]</td><td>74.7</td><td>69.4</td><td>98.2</td></tr><tr><td>all w2=0.8</td><td>[1, 0.8, 1]</td><td>74.7</td><td>69.3</td><td>98.1</td></tr><tr><td>all w2=1.0</td><td>[1, 1.0, 1]</td><td>74.8</td><td>69.4</td><td>98.0</td></tr><tr><td>all w2=1.5</td><td>[1, 1.5, 1]</td><td>74.2</td><td>68.7</td><td>98.0</td></tr><tr><td>d+s w2=0.1</td><td>[1, 0.1, 0]</td><td>73.3</td><td>67.7</td><td>98.2</td></tr><tr><td>d+s w2=0.2</td><td>[1, 0.2, 0]</td><td>73.9</td><td>68.5</td><td>98.5</td></tr><tr><td>d+s w2=0.5</td><td>[1, 0.5, 0]</td><td>73.8</td><td>68.3</td><td>98.5</td></tr><tr><td>d+s w2=0.8</td><td>[1, 0.8, 0]</td><td>73.8</td><td>68.2</td><td>98.1</td></tr><tr><td>d+s w2=1.0</td><td>[1, 1.0, 0]</td><td>73.5</td><td>67.9</td><td>98.1</td></tr><tr><td>d+s w2=1.5</td><td>[1, 1.5, 0]</td><td>72.4</td><td>66.4</td><td>97.6</td></tr></table></div><h2>4 · Matryoshka truncation</h2><div class="grid g2"><div class='card'><h3>Qwen3-4B: Matryoshka truncation, nDCG@10</h3><div class='tbl'><table><tr><th>Task</th><th>2560d</th><th>1024d</th><th>512d</th><th>256d</th></tr><tr><td>SciFact</td><td>78.3</td><td>78.0</td><td>76.7</td><td>74.1</td></tr><tr><td>NFCorpus</td><td>41.0</td><td>40.2</td><td>38.7</td><td>35.8</td></tr><tr><td>ArguAna</td><td>74.9</td><td>75.1</td><td>73.4</td><td>71.6</td></tr><tr><td>FiQA2018</td><td>61.7</td><td>62.3</td><td>60.8</td><td>58.2</td></tr><tr><td>TRECCOVID</td><td>93.5</td><td>94.1</td><td>94.0</td><td>92.3</td></tr><tr><td>ZacLegalTextRetrieval</td><td>76.6</td><td>76.3</td><td>74.7</td><td>72.4</td></tr><tr><td>SciFact-VN</td><td>72.6</td><td>72.0</td><td>70.4</td><td>69.0</td></tr><tr><td>NFCorpus-VN</td><td>38.8</td><td>38.3</td><td>36.6</td><td>34.4</td></tr><tr><td>ArguAna-VN</td><td>57.8</td><td>57.8</td><td>56.7</td><td>54.6</td></tr><tr><td>FiQA2018-VN</td><td>41.8</td><td>40.3</td><td>39.8</td><td>36.8</td></tr><tr><td>TRECCOVID-VN</td><td>80.7</td><td>80.5</td><td>80.5</td><td>79.5</td></tr></table></div></div><div class='card'><h3>EmbeddingGemma 2: Matryoshka truncation, nDCG@10</h3><div class='tbl'><table><tr><th>Task</th><th>768d</th><th>512d</th><th>256d</th><th>128d</th></tr><tr><td>SciFact</td><td>85.2</td><td>84.1</td><td>82.2</td><td>80.7</td></tr><tr><td>NFCorpus</td><td>36.9</td><td>36.7</td><td>35.1</td><td>30.6</td></tr><tr><td>ArguAna</td><td>58.6</td><td>58.2</td><td>57.1</td><td>52.4</td></tr><tr><td>FiQA2018</td><td>31.7</td><td>31.7</td><td>29.4</td><td>23.7</td></tr><tr><td>TRECCOVID</td><td>79.5</td><td>79.3</td><td>77.8</td><td>70.3</td></tr><tr><td>ZacLegalTextRetrieval</td><td>69.5</td><td>69.0</td><td>64.8</td><td>54.8</td></tr><tr><td>SciFact-VN</td><td>68.4</td><td>68.2</td><td>67.1</td><td>57.4</td></tr><tr><td>NFCorpus-VN</td><td>33.0</td><td>32.8</td><td>31.6</td><td>26.3</td></tr><tr><td>ArguAna-VN</td><td>53.6</td><td>53.5</td><td>51.9</td><td>45.7</td></tr><tr><td>FiQA2018-VN</td><td>28.1</td><td>28.1</td><td>26.2</td><td>19.1</td></tr><tr><td>TRECCOVID-VN</td><td>68.2</td><td>67.9</td><td>66.4</td><td>59.6</td></tr></table></div></div></div><h2>5 · EmbeddingGemma 2: fp16 vs fp32 in run 1</h2><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><tr><td>SciFact</td><td>0</td><td>min 0.9996 · mean 1.00010</td><td>85.21</td><td>85.21</td><td>+0.01</td><td>22 → 53</td></tr><tr><td>ZacLegalTextRetrieval</td><td>0</td><td>min 0.9995 · mean 1.00010</td><td>69.55</td><td>69.60</td><td>+0.05</td><td>26 → 61</td></tr><tr><td>FiQA2018-VN</td><td>0</td><td>min 0.9995 · mean 1.00010</td><td>28.08</td><td>27.97</td><td>-0.11</td><td>35 → 83</td></tr></table></div><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><p>Zalo Legal, Qwen3-4B: max_len 512 → nDCG@10 <b>76.6</b>, MRR@10 71.1, encode 143.5 min · max_len 2048 → nDCG@10 <b>78.8</b>, MRR@10 73.3, encode 195.0 min. 21.3% of documents exceed 512 tokens (mean 389, p95 1068).</p><h2>7 · Speed</h2><div class="grid g2"><div class="card"><h3>Throughput vs sequence length (tokens/s)</h3><svg viewBox="0 0 760 280" class="chart" role="img"><line x1="58" x2="748" y1="240.0" y2="240.0" class="grid"/><text x="52" y="244.0" class="ax" text-anchor="end">0</text><line x1="58" x2="748" y1="183.0" y2="183.0" class="grid"/><text x="52" y="187.0" class="ax" text-anchor="end">8,936</text><line x1="58" x2="748" y1="126.0" y2="126.0" class="grid"/><text x="52" y="130.0" class="ax" text-anchor="end">17,872</text><line x1="58" x2="748" y1="69.0" y2="69.0" class="grid"/><text x="52" y="73.0" class="ax" text-anchor="end">26,808</text><line x1="58" x2="748" y1="12.0" y2="12.0" class="grid"/><text x="52" y="16.0" class="ax" text-anchor="end">35,744</text><text x="58.0" y="256" class="ax" text-anchor="middle">64</text><text x="196.0" y="256" class="ax" text-anchor="middle">128</text><text x="334.0" y="256" class="ax" text-anchor="middle">256</text><text x="472.0" y="256" class="ax" text-anchor="middle">512</text><text x="610.0" y="256" class="ax" text-anchor="middle">1024</text><text x="748.0" y="256" class="ax" text-anchor="middle">2048</text><text x="403.0" y="276" class="ax" text-anchor="middle">sequence length (tokens)</text><text x="12" y="126.0" class="ax" text-anchor="middle" transform="rotate(-90 12 126.0)">tokens / s (best batch)</text><polyline points="58.0,37.5 196.0,36.4 334.0,44.3 472.0,56.5 610.0,79.2 748.0,108.8" fill="none" stroke="var(--bge)" stroke-width="2.2" /><circle cx="58.0" cy="37.5" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 31,742.6</title></circle><circle cx="196.0" cy="36.4" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 31,914.0</title></circle><circle cx="334.0" cy="44.3" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 30,687.7</title></circle><circle cx="472.0" cy="56.5" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 28,773.9</title></circle><circle cx="610.0" cy="79.2" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 25,207.8</title></circle><circle cx="748.0" cy="108.8" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 20,560.7</title></circle><polyline points="58.0,173.6 196.0,175.4 334.0,179.7 472.0,187.3 610.0,195.9 748.0,206.5" fill="none" stroke="var(--gemma)" stroke-width="2.2" /><circle cx="58.0" cy="173.6" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 10,415.8</title></circle><circle cx="196.0" cy="175.4" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 10,133.9</title></circle><circle cx="334.0" cy="179.7" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 9,452.8</title></circle><circle cx="472.0" cy="187.3" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 8,268.5</title></circle><circle cx="610.0" cy="195.9" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 6,920.8</title></circle><circle cx="748.0" cy="206.5" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 5,255.7</title></circle><polyline points="58.0,95.1 196.0,89.1 334.0,93.5 472.0,109.1 610.0,128.1 748.0,151.8" fill="none" stroke="var(--gemma2)" stroke-width="2.2" stroke-dasharray="5 4"/><circle cx="58.0" cy="95.1" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 22,718.9</title></circle><circle cx="196.0" cy="89.1" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 23,660.7</title></circle><circle cx="334.0" cy="93.5" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 22,970.7</title></circle><circle cx="472.0" cy="109.1" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 20,517.4</title></circle><circle cx="610.0" cy="128.1" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 17,546.7</title></circle><circle cx="748.0" cy="151.8" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 13,831.7</title></circle><polyline points="58.0,224.0 196.0,224.8 334.0,225.2 472.0,225.6 610.0,225.6 748.0,226.2" fill="none" stroke="var(--qwen)" stroke-width="2.2" /><circle cx="58.0" cy="224.0" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 2,514.7</title></circle><circle cx="196.0" cy="224.8" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 2,380.9</title></circle><circle cx="334.0" cy="225.2" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 2,325.9</title></circle><circle cx="472.0" cy="225.6" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 2,258.6</title></circle><circle cx="610.0" cy="225.6" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 2,256.5</title></circle><circle cx="748.0" cy="226.2" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 2,163.2</title></circle></svg></div><div class="card"><h3>Docs/s vs sequence length</h3><svg viewBox="0 0 760 280" class="chart" role="img"><line x1="58" x2="748" y1="228.5" y2="228.5" class="grid"/><text x="52" y="232.5" class="ax" text-anchor="end">1</text><line x1="58" x2="748" y1="192.6" y2="192.6" class="grid"/><text x="52" y="196.6" class="ax" text-anchor="end">3</text><line x1="58" x2="748" y1="153.1" y2="153.1" class="grid"/><text x="52" y="157.1" class="ax" text-anchor="end">10</text><line x1="58" x2="748" y1="117.1" y2="117.1" class="grid"/><text x="52" y="121.1" class="ax" text-anchor="end">30</text><line x1="58" x2="748" y1="77.7" y2="77.7" class="grid"/><text x="52" y="81.7" class="ax" text-anchor="end">100</text><line x1="58" x2="748" y1="41.7" y2="41.7" class="grid"/><text x="52" y="45.7" class="ax" text-anchor="end">300</text><text x="58.0" y="256" class="ax" text-anchor="middle">64</text><text x="196.0" y="256" class="ax" text-anchor="middle">128</text><text x="334.0" y="256" class="ax" text-anchor="middle">256</text><text x="472.0" y="256" class="ax" text-anchor="middle">512</text><text x="610.0" y="256" class="ax" text-anchor="middle">1024</text><text x="748.0" y="256" class="ax" text-anchor="middle">2048</text><text x="403.0" y="276" class="ax" text-anchor="middle">sequence length (tokens)</text><text x="12" y="126.0" class="ax" text-anchor="middle" transform="rotate(-90 12 126.0)">docs / s (log)</text><polyline points="58.0,25.3 196.0,47.8 334.0,71.8 472.0,96.6 610.0,123.6 748.0,153.0" fill="none" stroke="var(--bge)" stroke-width="2.2" /><circle cx="58.0" cy="25.3" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 496.0</title></circle><circle cx="196.0" cy="47.8" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 249.3</title></circle><circle cx="334.0" cy="71.8" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 119.9</title></circle><circle cx="472.0" cy="96.6" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 56.2</title></circle><circle cx="610.0" cy="123.6" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 24.6</title></circle><circle cx="748.0" cy="153.0" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 10.0</title></circle><polyline points="58.0,61.8 196.0,85.4 334.0,110.3 472.0,137.4 610.0,166.0 748.0,197.7" fill="none" stroke="var(--gemma)" stroke-width="2.2" /><circle cx="58.0" cy="61.8" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 162.7</title></circle><circle cx="196.0" cy="85.4" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 79.2</title></circle><circle cx="334.0" cy="110.3" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 36.9</title></circle><circle cx="472.0" cy="137.4" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 16.1</title></circle><circle cx="610.0" cy="166.0" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 6.8</title></circle><circle cx="748.0" cy="197.7" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 2.6</title></circle><polyline points="58.0,36.2 196.0,57.6 334.0,81.3 472.0,107.7 610.0,135.5 748.0,166.0" fill="none" stroke="var(--gemma2)" stroke-width="2.2" stroke-dasharray="5 4"/><circle cx="58.0" cy="36.2" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 355.0</title></circle><circle cx="196.0" cy="57.6" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 184.8</title></circle><circle cx="334.0" cy="81.3" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 89.7</title></circle><circle cx="472.0" cy="107.7" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 40.1</title></circle><circle cx="610.0" cy="135.5" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 17.1</title></circle><circle cx="748.0" cy="166.0" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 6.8</title></circle><polyline points="58.0,107.8 196.0,132.5 334.0,156.1 472.0,179.9 610.0,202.6 748.0,226.7" fill="none" stroke="var(--qwen)" stroke-width="2.2" /><circle cx="58.0" cy="107.8" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 39.9</title></circle><circle cx="196.0" cy="132.5" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 18.7</title></circle><circle cx="334.0" cy="156.1" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 9.1</title></circle><circle cx="472.0" cy="179.9" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 4.4</title></circle><circle cx="610.0" cy="202.6" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 2.2</title></circle><circle cx="748.0" cy="226.7" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 1.1</title></circle></svg></div><div class="card"><h3>Batch-size scaling @ 512 tokens</h3><svg viewBox="0 0 760 280" class="chart" role="img"><line x1="58" x2="748" y1="231.5" y2="231.5" class="grid"/><text x="52" y="235.5" class="ax" text-anchor="end">3</text><line x1="58" x2="748" y1="152.3" y2="152.3" class="grid"/><text x="52" y="156.3" class="ax" text-anchor="end">10</text><line x1="58" x2="748" y1="80.0" y2="80.0" class="grid"/><text x="52" y="84.0" class="ax" text-anchor="end">30</text><text x="58.0" y="256" class="ax" text-anchor="middle">1</text><text x="196.0" y="256" class="ax" text-anchor="middle">8</text><text x="334.0" y="256" class="ax" text-anchor="middle">16</text><text x="472.0" y="256" class="ax" text-anchor="middle">32</text><text x="610.0" y="256" class="ax" text-anchor="middle">64</text><text x="748.0" y="256" class="ax" text-anchor="middle">128</text><text x="403.0" y="276" class="ax" text-anchor="middle">batch size</text><text x="12" y="126.0" class="ax" text-anchor="middle" transform="rotate(-90 12 126.0)">docs / s @ 512 tok</text><polyline points="58.0,49.8 196.0,41.9 334.0,41.7 472.0,39.3 610.0,38.7 748.0,44.3" fill="none" stroke="var(--bge)" stroke-width="2.2" /><circle cx="58.0" cy="49.8" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 47.4</title></circle><circle cx="196.0" cy="41.9" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 53.5</title></circle><circle cx="334.0" cy="41.7" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 53.7</title></circle><circle cx="472.0" cy="39.3" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 55.7</title></circle><circle cx="610.0" cy="38.7" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 56.2</title></circle><circle cx="748.0" cy="44.3" r="3.2" fill="var(--bge)"><title>BGE-M3 fp16: 51.6</title></circle><polyline points="58.0,128.7 196.0,123.9 334.0,121.3 472.0,120.7 610.0,121.2 748.0,120.8" fill="none" stroke="var(--gemma)" stroke-width="2.2" /><circle cx="58.0" cy="128.7" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 14.3</title></circle><circle cx="196.0" cy="123.9" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 15.4</title></circle><circle cx="334.0" cy="121.3" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 16.0</title></circle><circle cx="472.0" cy="120.7" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 16.1</title></circle><circle cx="610.0" cy="121.2" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 16.0</title></circle><circle cx="748.0" cy="120.8" r="3.2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32: 16.1</title></circle><polyline points="58.0,124.5 196.0,65.2 334.0,63.5 472.0,61.5 610.0,60.9 748.0,61.4" fill="none" stroke="var(--gemma2)" stroke-width="2.2" stroke-dasharray="5 4"/><circle cx="58.0" cy="124.5" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 15.2</title></circle><circle cx="196.0" cy="65.2" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 37.6</title></circle><circle cx="334.0" cy="63.5" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 38.5</title></circle><circle cx="472.0" cy="61.5" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 39.7</title></circle><circle cx="610.0" cy="60.9" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 40.1</title></circle><circle cx="748.0" cy="61.4" r="3.2" fill="var(--gemma2)"><title>EmbeddingGemma 2 fp16: 39.8</title></circle><polyline points="58.0,207.1 196.0,206.0 334.0,206.7 472.0,207.5 610.0,211.0 748.0,213.3" fill="none" stroke="var(--qwen)" stroke-width="2.2" /><circle cx="58.0" cy="207.1" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 4.3</title></circle><circle cx="196.0" cy="206.0" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 4.4</title></circle><circle cx="334.0" cy="206.7" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 4.4</title></circle><circle cx="472.0" cy="207.5" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 4.3</title></circle><circle cx="610.0" cy="211.0" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 4.1</title></circle><circle cx="748.0" cy="213.3" r="3.2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16: 4.0</title></circle></svg></div><div class="card"><h3>Real corpus encode rate (docs/s, quality runs)</h3><svg viewBox="0 0 760 280" class="chart" role="img"><line x1="40" x2="750" y1="222.0" y2="222.0" class="grid"/><text x="34" y="226.0" class="ax" text-anchor="end">0</text><line x1="40" x2="750" y1="169.0" y2="169.0" class="grid"/><text x="34" y="173.0" class="ax" text-anchor="end">33</text><line x1="40" x2="750" y1="116.0" y2="116.0" class="grid"/><text x="34" y="120.0" class="ax" text-anchor="end">66</text><line x1="40" x2="750" y1="63.0" y2="63.0" class="grid"/><text x="34" y="67.0" class="ax" text-anchor="end">99</text><line x1="40" x2="750" y1="10.0" y2="10.0" class="grid"/><text x="34" y="14.0" class="ax" text-anchor="end">132</text><rect x="45.0" y="117.6" width="16.2" height="104.4" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · SciFact: 65</title></rect><text x="53.1" y="114.6" class="bv" text-anchor="middle">65</text><rect x="63.2" y="186.2" width="16.2" height="35.8" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · SciFact: 22</title></rect><text x="71.3" y="183.2" class="bv" text-anchor="middle">22</text><rect x="81.4" y="212.3" width="16.2" height="9.7" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · SciFact: 6</title></rect><text x="89.5" y="209.3" class="bv" text-anchor="middle">6</text><text x="72.3" y="238" class="ax" text-anchor="middle">SciFact</text><rect x="109.5" y="124.2" width="16.2" height="97.8" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · NFCorpus: 61</title></rect><text x="117.6" y="121.2" class="bv" text-anchor="middle">61</text><rect x="127.7" y="190.5" width="16.2" height="31.5" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · NFCorpus: 20</title></rect><text x="135.8" y="187.5" class="bv" text-anchor="middle">20</text><rect x="145.9" y="213.3" width="16.2" height="8.7" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · NFCorpus: 5</title></rect><text x="154.0" y="210.3" class="bv" text-anchor="middle">5</text><text x="136.8" y="238" class="ax" text-anchor="middle">NFCorpus</text><rect x="174.1" y="53.2" width="16.2" height="168.8" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · ArguAna: 105</title></rect><text x="182.2" y="50.2" class="bv" text-anchor="middle">105</text><rect x="192.3" y="168.3" width="16.2" height="53.7" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · ArguAna: 33</title></rect><text x="200.4" y="165.3" class="bv" text-anchor="middle">33</text><rect x="210.5" y="207.2" width="16.2" height="14.8" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · ArguAna: 9</title></rect><text x="218.5" y="204.2" class="bv" text-anchor="middle">9</text><text x="201.4" y="238" class="ax" text-anchor="middle">ArguAna</text><rect x="238.6" y="32.7" width="16.2" height="189.3" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · FiQA2018: 117</title></rect><text x="246.7" y="29.7" class="bv" text-anchor="middle">117</text><rect x="256.8" y="160.2" width="16.2" height="61.8" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · FiQA2018: 38</title></rect><text x="264.9" y="157.2" class="bv" text-anchor="middle">38</text><rect x="275.0" y="203.7" width="16.2" height="18.3" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · FiQA2018: 11</title></rect><text x="283.1" y="200.7" class="bv" text-anchor="middle">11</text><text x="265.9" y="238" class="ax" text-anchor="middle">FiQA</text><rect x="303.2" y="81.4" width="16.2" height="140.6" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · TRECCOVID: 87</title></rect><text x="311.3" y="78.4" class="bv" text-anchor="middle">87</text><rect x="321.4" y="174.9" width="16.2" height="47.1" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · TRECCOVID: 29</title></rect><text x="329.5" y="171.9" class="bv" text-anchor="middle">29</text><rect x="339.5" y="209.5" width="16.2" height="12.5" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · TRECCOVID: 8</title></rect><text x="347.6" y="206.5" class="bv" text-anchor="middle">8</text><text x="330.5" y="238" class="ax" text-anchor="middle">TRECCOVID</text><rect x="367.7" y="78.1" width="16.2" height="143.9" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · ZacLegalTextRetrieval: 89</title></rect><text x="375.8" y="75.1" class="bv" text-anchor="middle">89</text><rect x="385.9" y="180.4" width="16.2" height="41.6" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · ZacLegalTextRetrieval: 26</title></rect><text x="394.0" y="177.4" class="bv" text-anchor="middle">26</text><rect x="404.1" y="210.5" width="16.2" height="11.5" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · ZacLegalTextRetrieval: 7</title></rect><text x="412.2" y="207.5" class="bv" text-anchor="middle">7</text><text x="395.0" y="238" class="ax" text-anchor="middle">ZacLegal</text><rect x="432.3" y="123.6" width="16.2" height="98.4" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · SciFact-VN: 61</title></rect><text x="440.4" y="120.6" class="bv" text-anchor="middle">61</text><rect x="450.5" y="191.1" width="16.2" height="30.9" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · SciFact-VN: 19</title></rect><text x="458.5" y="188.1" class="bv" text-anchor="middle">19</text><rect x="468.6" y="213.6" width="16.2" height="8.4" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · SciFact-VN: 5</title></rect><text x="476.7" y="210.6" class="bv" text-anchor="middle">5</text><text x="459.5" y="238" class="ax" text-anchor="middle">SciFact-VN</text><rect x="496.8" y="127.9" width="16.2" height="94.1" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · NFCorpus-VN: 58</title></rect><text x="504.9" y="124.9" class="bv" text-anchor="middle">58</text><rect x="515.0" y="192.7" width="16.2" height="29.3" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · NFCorpus-VN: 18</title></rect><text x="523.1" y="189.7" class="bv" text-anchor="middle">18</text><rect x="533.2" y="214.1" width="16.2" height="7.9" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · NFCorpus-VN: 5</title></rect><text x="541.3" y="211.1" class="bv" text-anchor="middle">5</text><text x="524.1" y="238" class="ax" text-anchor="middle">NFCorpus-VN</text><rect x="561.4" y="74.3" width="16.2" height="147.7" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · ArguAna-VN: 92</title></rect><text x="569.5" y="71.3" class="bv" text-anchor="middle">92</text><rect x="579.5" y="177.7" width="16.2" height="44.3" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · ArguAna-VN: 28</title></rect><text x="587.6" y="174.7" class="bv" text-anchor="middle">28</text><rect x="597.7" y="210.1" width="16.2" height="11.9" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · ArguAna-VN: 7</title></rect><text x="605.8" y="207.1" class="bv" text-anchor="middle">7</text><text x="588.6" y="238" class="ax" text-anchor="middle">ArguAna-VN</text><rect x="625.9" y="42.6" width="16.2" height="179.4" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · FiQA2018-VN: 111</title></rect><text x="634.0" y="39.6" class="bv" text-anchor="middle">111</text><rect x="644.1" y="165.0" width="16.2" height="57.0" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · FiQA2018-VN: 35</title></rect><text x="652.2" y="162.0" class="bv" text-anchor="middle">35</text><rect x="662.3" y="206.1" width="16.2" height="15.9" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · FiQA2018-VN: 10</title></rect><text x="670.4" y="203.1" class="bv" text-anchor="middle">10</text><text x="653.2" y="238" class="ax" text-anchor="middle">FiQA-VN</text><rect x="690.5" y="88.6" width="16.2" height="133.4" rx="2" fill="var(--bge)"><title>BGE-M3 fp16 · TRECCOVID-VN: 83</title></rect><text x="698.5" y="85.6" class="bv" text-anchor="middle">83</text><rect x="708.6" y="180.9" width="16.2" height="41.1" rx="2" fill="var(--gemma)"><title>EmbeddingGemma 2 fp32 · TRECCOVID-VN: 25</title></rect><text x="716.7" y="177.9" class="bv" text-anchor="middle">25</text><rect x="726.8" y="211.0" width="16.2" height="11.0" rx="2" fill="var(--qwen)"><title>Qwen3-Emb-4B fp16 · TRECCOVID-VN: 7</title></rect><text x="734.9" y="208.0" class="bv" text-anchor="middle">7</text><text x="717.7" y="238" class="ax" text-anchor="middle">TRECCOVID-VN</text></svg></div></div><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><tr><td><i class='dot' style='background:var(--bge)'></i>BGE-M3 fp16</td><td>56.2</td><td>28.8k</td><td>18.0 / 22.6</td><td>2.6</td><td>20.1</td><td>1.47 / 1.03</td><td>none</td><td>867</td></tr><tr><td><i class='dot' style='background:var(--gemma)'></i>EmbeddingGemma 2 fp32</td><td>16.1</td><td>8.3k</td><td>52.7 / 68.8</td><td>10.3</td><td>23.8</td><td>1.14 / 1.08</td><td>L1024·bs128, L2048·bs64</td><td>999</td></tr><tr><td><i class='dot' style='background:var(--gemma2)'></i>EmbeddingGemma 2 fp16</td><td>40.1</td><td>20.5k</td><td>59.4 / 73.1</td><td>8.2</td><td>26.4</td><td>1.14 / 1.08</td><td>L1024·bs128, L2048·bs64</td><td>1174</td></tr><tr><td><i class='dot' style='background:var(--qwen)'></i>Qwen3-Emb-4B fp16</td><td>4.4</td><td>2.3k</td><td>59.4 / 71.8</td><td>12.7</td><td>27.0</td><td>1.16 / 1.08</td><td>L1024·bs128, L2048·bs64</td><td>717</td></tr></table></div><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>1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677<!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>:root{--bg:#f7f7f5;--panel:#fff;--ink:#1d1d1f;--muted:#5f6368;--muted2:#b9bcc2;--line:#e3e3e0;--track:#eeeeeb;--accent:#c2410c;--accentl:#f4a77c;--accent2:#d97706;--accent2l:#f5cf8a;--gemma:#2563eb;--gemma2:#93c5fd;--qwen:#7c3aed;--qwen2:#c4b5fd;--bge:#0f8a6a;--bge2:#5cc4a5;--best:#ecfdf5}@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#121214;--panel:#1b1b1f;--ink:#ececef;--muted:#a0a3aa;--muted2:#55585f;--line:#2c2c31;--track:#26262b;--accent:#fb923c;--accentl:#9a4a1c;--accent2:#fbbf24;--accent2l:#8a6a1c;--gemma:#60a5fa;--gemma2:#1e4f8f;--qwen:#a78bfa;--qwen2:#4c3a85;--bge:#34d399;--bge2:#1d7a5e;--best:#0d2a20}}:root[data-theme="dark"]{--bg:#121214;--panel:#1b1b1f;--ink:#ececef;--muted:#a0a3aa;--muted2:#55585f;--line:#2c2c31;--track:#26262b;--accent:#fb923c;--accentl:#9a4a1c;--accent2:#fbbf24;--accent2l:#8a6a1c;--gemma:#60a5fa;--gemma2:#1e4f8f;--qwen:#a78bfa;--qwen2:#4c3a85;--bge:#34d399;--bge2:#1d7a5e;--best:#0d2a20}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif}main{max-width:1100px;margin:0 auto;padding:28px 16px 64px}h1{font-size:28px;margin:0 0 6px}h2{font-size:20px;margin:38px 0 12px;padding-bottom:6px;border-bottom:1px solid var(--line)}h3{font-size:15px;margin:4px 0 8px}.sub{color:var(--muted);margin:0 0 14px}.grid{display:grid;gap:14px;margin:12px 0}.g4{grid-template-columns:repeat(auto-fit,minmax(200px,1fr))}.g2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}.card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px 16px;min-width:0;margin-bottom:12px}.kpi .n{font-size:24px;font-weight:700}.kpi .l{color:var(--muted);font-size:13px}.kpi .w{font-size:13px;font-weight:600;margin-top:2px}.dot{display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:6px;vertical-align:middle}.legend span{margin-right:14px;font-size:13px;white-space:nowrap}.tbl{width:100%;overflow-x:auto}table{border-collapse:collapse;width:100%;font-size:13.5px}th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:top}th{color:var(--muted);font-weight:600;font-size:12px;text-transform:uppercase;letter-spacing:.03em}td.best{background:var(--best);font-weight:700}tr.avg td{border-top:2px solid var(--line)}.sm{font-size:11.5px;color:var(--muted);font-weight:400}.note{font-size:12.5px;color:var(--muted)}code{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;background:var(--track);padding:1px 5px;border-radius:4px}.chart{width:100%;height:auto;display:block}.chart .grid{stroke:var(--line);stroke-width:1}.chart .ax{fill:var(--muted);font-size:11px}.chart .bv{fill:var(--ink);font-size:9.5px}.callout{border-radius:8px;padding:10px 14px;margin:10px 0;font-size:14px;background:var(--track)}.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}</style></head><body><main><h1>Vietnamese Embedding Benchmark</h1><p class="sub">21 embedding models (bf16) incl. Qwen3-Embedding-8B and the re-run run-1 models · 9 native Vietnamese + 4 machine-translated retrieval sets · 274/326 jobs (0 failed) · stage: final · compared with the run-1 Qwen3-Embedding-4B, BGE-M3 and EmbeddingGemma 2 where the tasks overlap · built 2026-12-03 23:26 GMT+7</p><div class="grid g4"><div class="card kpi"><div class="n">gemini-embedding-2</div><div class="l">best native Vietnamese accuracy (avg nDCG@10 over the 4 large native sets: 75.9)</div></div><div class="card kpi"><div class="n">gemini-embedding-2</div><div class="l">best P@1 on native Vietnamese (first result correct: 66.0%)</div></div><div class="card kpi"><div class="n">embeddinggemma-300m</div><div class="l">best model under 350M params (66.8 nDCG@10)</div></div><div class="card kpi"><div class="n">274/326</div><div class="l">jobs completed</div></div></div><h2>Conclusions</h2><div class="callout"><b>Verdict for Vietnamese retrieval.</b> None of the 14 new models beats the run-1 <b>Qwen3-Embedding-4B</b> (Zalo Legal nDCG@10 76.7, translated-4 avg 52.8). It is still the most accurate on every overlapping set. Among the new models, <b>OpenEmbed-2B</b> is the most accurate (native-4 69.7, P@1 57.8). The best quality for its size is <b>embeddinggemma-300m</b>, which reaches 72.2 on Zalo Legal with a 2,048-token window. That beats BGE-M3 dense (71.6) at about half its size. Models without Vietnamese support were removed after testing.</div>
<div class="tbl"><table><tr><th>Use case</th><th>Pick</th><th>Why (measured)</th></tr><tr><td>Highest Vietnamese accuracy</td><td><b>Qwen3-Embedding-4B</b> (run 1), or BGE-M3 with all three modes (74.7 on Zalo)</td><td>Still ahead of every new model: Zalo 76.7 vs 71.8 for the best new one. Note: only Zalo + translated sets overlap.</td></tr><tr><td>Best new model, any size</td><td><b>OpenEmbed-2B</b></td><td>#1 on native-4 (69.7 nDCG, 57.8 P@1) and translated-4 (47.3). Caveats: CC-BY-NC (non-commercial only), and its text instruction was assumed.</td></tr><tr><td>Small and accurate (≤ 0.6B, commercial licence)</td><td><b>embeddinggemma-300m</b> @ 2048 tokens, or <b>Skill-Venus-0.6B</b></td><td>EG-300m: native-4 66.8 at 512, and Zalo 72.2 at 2048. Skill-Venus: native-4 68.2, 2nd overall.</td></tr><tr><td>Tiny / CPU-friendly</td><td><b>granite-97m-multilingual-r2</b></td><td>61.9 native-4 at 97M params, more than 2× any other model under 120M</td></tr><tr><td>Weak for Vietnamese search</td><td>Mistral-Multimodal-Embed-1B, paraphrase-multilingual-MiniLM-L12</td><td>Native-4 nDCG ≈ 40: an image–text model and a similarity (not search) model with a 128-token window</td></tr></table></div>
<h3>Key findings</h3><ol><li><b>Vietnamese support is a hard requirement.</b> Models without Vietnamese in training (English-only sentence-transformers models and EmbeddingNandi) were tested and scored far below every multilingual model, so they were removed from this benchmark (listed in docs/models.md).</li><li><b>The skill-search fine-tune beat its own base model.</b> Skill-Venus-0.6B is ahead of Qwen3-0.6B by 5.3 nDCG on native-4, mostly on Tables (43.3 vs 29.5). I had expected the opposite. Both used the same instructions.</li><li><b>Tables are the hardest native set</b> (best 45.0), followed by Zalo Legal. TVPL and WebFAQ are easier (≈ 80 for the top models). The small Wikipedia QA sets (XQuAD, MLQA, Belebele) are near the ceiling for every multilingual model, so they separate models less.</li><li><b>A longer window helps on legal articles.</b> At 2,048 tokens, Zalo Legal improves by +4.3 for embeddinggemma-300m (→ 72.2), +3.0 for Qwen3-0.6B and +7.5 for Mistral, where 19–21% of documents exceed 512 tokens. Tables gain only about +1, and TVPL (8–9% of documents long) doesn't change. For Vietnamese legal search, use a 2,048-token window or chunk around 512 tokens.</li><li><b>Matryoshka truncation:</b> going from 768 to 512 dims costs about 1.5 points for embeddinggemma-300m. Qwen3-0.6B's 1024→512 costs 0.8. 256 dims costs 2.7–4 points, and 128 costs 5–8.</li><li><b>bf16 vs fp16 makes no difference</b> (Qwen3-0.6B: Zalo 67.08 vs 67.10; SciFact-VN 68.33 vs 68.13; no NaN).</li></ol>
<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><tr class=''><td>1</td><td><b>gemini-embedding-2</b><br><span class='sm'>google/gemini-embedding-2 (OpenRouter)</span></td><td>API</td><td>API</td><td><span class='bar' style='width:120px'></span><b>75.9</b></td><td>66.0</td><td>72.9</td><td>85.7</td><td>93.3</td><td>80.2</td><td>67.0</td><td>83.1</td><td>59.2</td></tr><tr class='t4m'><td>2</td><td><b>bge-m3-all</b><br><span class='sm'>BAAI/bge-m3 (dense+sparse+ColBERT) · run-1 model: Zalo + translated from run 1, other sets re-run on GPU</span></td><td>0.57B</td><td>yes</td><td><span class='bar' style='width:115px'></span><b>72.4</b></td><td>—</td><td>69.0</td><td>—</td><td>92.5</td><td>74.7</td><td>—</td><td>79.0</td><td>45.2</td></tr><tr class=''><td>3</td><td><b>octen-8b</b><br><span class='sm'>Octen/Octen-Embedding-8B</span></td><td>7.57B</td><td>multilingual</td><td><span class='bar' style='width:113px'></span><b>71.2</b></td><td>60.2</td><td>67.8</td><td>82.2</td><td>92.1</td><td>73.8</td><td>58.5</td><td>79.3</td><td>56.8</td></tr><tr class=''><td>4</td><td><b>qwen3-8b</b><br><span class='sm'>Qwen/Qwen3-Embedding-8B</span></td><td>7.57B</td><td>yes</td><td><span class='bar' style='width:112px'></span><b>70.7</b></td><td>59.5</td><td>67.3</td><td>81.9</td><td>91.2</td><td>75.1</td><td>59.5</td><td>69.9</td><td>54.2</td></tr><tr class=''><td>5</td><td><b>octen-4b</b><br><span class='sm'>Octen/Octen-Embedding-4B</span></td><td>4.02B</td><td>multilingual</td><td><span class='bar' style='width:111px'></span><b>70.1</b></td><td>58.9</td><td>66.8</td><td>81.5</td><td>91.7</td><td>73.6</td><td>58.5</td><td>77.3</td><td>54.2</td></tr><tr class=''><td>6</td><td><b>pplx-embed-v1-0.6b</b><br><span class='sm'>perplexity/pplx-embed-v1-0.6b (OpenRouter)</span></td><td>0.60B</td><td>API</td><td><span class='bar' style='width:111px'></span><b>70.0</b></td><td>58.7</td><td>66.5</td><td>81.4</td><td>91.6</td><td>70.1</td><td>53.9</td><td>77.2</td><td>47.5</td></tr><tr class=''><td>7</td><td><b>openembed-2b</b><br><span class='sm'>UCSC-VLAA/OpenEmbed-2B</span></td><td>2.21B</td><td>EN card</td><td><span class='bar' style='width:110px'></span><b>69.7</b></td><td>57.8</td><td>66.2</td><td>81.9</td><td>92.3</td><td>71.8</td><td>54.9</td><td>76.7</td><td>47.3</td></tr><tr class='t4m'><td>8</td><td><b>bge-m3</b><br><span class='sm'>BAAI/bge-m3 · run-1 model: Zalo + translated from run 1, other sets re-run on GPU</span></td><td>0.57B</td><td>yes</td><td><span class='bar' style='width:110px'></span><b>69.3</b></td><td>57.6</td><td>65.6</td><td>81.3</td><td>90.9</td><td>71.6</td><td>54.6</td><td>76.1</td><td>44.4</td></tr><tr class=''><td>9</td><td><b>voyage-4-lite</b><br><span class='sm'>mongodb/voyage-4-lite (OpenRouter)</span></td><td>API</td><td>API</td><td><span class='bar' style='width:109px'></span><b>69.1</b></td><td>57.5</td><td>65.6</td><td>80.8</td><td>92.0</td><td>68.2</td><td>52.5</td><td>77.7</td><td>50.8</td></tr><tr class='t4m'><td>10</td><td><b>qwen3-4b</b><br><span class='sm'>Qwen/Qwen3-Embedding-4B · run-1 model: Zalo + translated from run 1, other sets re-run on GPU</span></td><td>4.02B</td><td>yes</td><td><span class='bar' style='width:108px'></span><b>68.4</b></td><td>57.3</td><td>65.1</td><td>79.4</td><td>89.1</td><td>76.7</td><td>61.4</td><td>69.7</td><td>52.8</td></tr><tr class=''><td>11</td><td><b>skill-venus-0.6b</b><br><span class='sm'>inclusionAI/Skill-Venus-Embedding-0.6B</span></td><td>0.60B</td><td>via Qwen3</td><td><span class='bar' style='width:108px'></span><b>68.2</b></td><td>56.3</td><td>64.5</td><td>80.5</td><td>91.7</td><td>70.5</td><td>53.9</td><td>74.0</td><td>44.8</td></tr><tr class=''><td>12</td><td><b>embeddinggemma-300m</b><br><span class='sm'>google/embeddinggemma-300m</span></td><td>0.30B</td><td>yes</td><td><span class='bar' style='width:106px'></span><b>66.8</b></td><td>54.1</td><td>63.1</td><td>79.6</td><td>90.9</td><td>67.9</td><td>47.8</td><td>74.3</td><td>47.1</td></tr><tr class=''><td>13</td><td><b>openembed-0.8b</b><br><span class='sm'>UCSC-VLAA/OpenEmbed-0.8B</span></td><td>0.85B</td><td>EN card</td><td><span class='bar' style='width:105px'></span><b>66.6</b></td><td>54.5</td><td>62.9</td><td>79.0</td><td>90.5</td><td>69.6</td><td>52.7</td><td>73.2</td><td>43.3</td></tr><tr class=''><td>14</td><td><b>text-embedding-3-large</b><br><span class='sm'>OpenAI text-embedding-3-large (API)</span></td><td>API</td><td>API</td><td><span class='bar' style='width:105px'></span><b>66.5</b></td><td>53.7</td><td>62.6</td><td>79.5</td><td>90.8</td><td>65.3</td><td>45.4</td><td>74.2</td><td>46.4</td></tr><tr class=''><td>15</td><td><b>octen-0.6b</b><br><span class='sm'>Octen/Octen-Embedding-0.6B</span></td><td>0.60B</td><td>multilingual</td><td><span class='bar' style='width:103px'></span><b>65.1</b></td><td>53.4</td><td>61.5</td><td>77.4</td><td>89.2</td><td>66.3</td><td>49.5</td><td>71.2</td><td>48.0</td></tr><tr class='t4m'><td>16</td><td><b>embeddinggemma-2</b><br><span class='sm'>google/embeddinggemma-2 · run-1 model: Zalo + translated from run 1, other sets re-run on GPU</span></td><td>0.27B</td><td>yes</td><td><span class='bar' style='width:103px'></span><b>65.1</b></td><td>53.2</td><td>61.5</td><td>77.4</td><td>90.3</td><td>69.6</td><td>54.8</td><td>72.7</td><td>45.9</td></tr><tr class=''><td>17</td><td><b>qwen3-0.6b</b><br><span class='sm'>Qwen/Qwen3-Embedding-0.6B</span></td><td>0.60B</td><td>yes</td><td><span class='bar' style='width:100px'></span><b>62.9</b></td><td>51.3</td><td>59.3</td><td>75.1</td><td>87.2</td><td>67.1</td><td>50.9</td><td>65.6</td><td>46.9</td></tr><tr class=''><td>18</td><td><b>granite-97m-multi-r2</b><br><span class='sm'>ibm-granite/granite-embedding-97m-multilingual-r2</span></td><td>0.10B</td><td>yes</td><td><span class='bar' style='width:98px'></span><b>61.9</b></td><td>50.4</td><td>58.3</td><td>73.7</td><td>86.4</td><td>62.8</td><td>46.4</td><td>68.7</td><td>37.7</td></tr><tr class=''><td>19</td><td><b>text-embedding-3-small</b><br><span class='sm'>OpenAI text-embedding-3-small (API)</span></td><td>API</td><td>API</td><td><span class='bar' style='width:92px'></span><b>58.4</b></td><td>46.2</td><td>54.4</td><td>71.5</td><td>86.1</td><td>56.5</td><td>39.2</td><td>66.0</td><td>35.8</td></tr><tr class=''><td>20</td><td><b>mistral-embed-1b</b><br><span class='sm'>mistralai/Mistral-Multimodal-Embed-1B</span></td><td>1.24B</td><td>yes</td><td><span class='bar' style='width:63px'></span><b>39.9</b></td><td>27.6</td><td>35.8</td><td>53.5</td><td>73.5</td><td>35.2</td><td>20.1</td><td>47.6</td><td>28.2</td></tr><tr class=''><td>21</td><td><b>para-multi-minilm-l12</b><br><span class='sm'>sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2</span></td><td>0.12B</td><td>yes</td><td><span class='bar' style='width:62px'></span><b>39.4</b></td><td>28.6</td><td>35.7</td><td>51.9</td><td>70.9</td><td>41.3</td><td>26.0</td><td>53.3</td><td>28.1</td></tr></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"><tr><th>Model</th><th>Zalo Legal</th><th>TVPL legal</th><th>Tables</th><th>WebFAQ</th><th>ViQuAD</th><th>MLQA</th><th>XQuAD</th><th>Belebele</th><th>PublicHealth</th><th class='sep'></th><th>SciFact-VN</th><th>NFCorpus-VN</th><th>ArguAna-VN</th><th>FiQA-VN</th></tr><tr><td><b>gemini-embedding-2</b></td><td style='background:rgba(37,99,235,0.60);color:#fff'>80.2</td><td style='background:rgba(37,99,235,0.66);color:#fff'>87.4</td><td style='background:rgba(37,99,235,0.34);color:inherit'>45.4</td><td style='background:rgba(37,99,235,0.68);color:#fff'>90.7</td><td style='background:rgba(37,99,235,0.54);color:#fff'>71.5</td><td style='background:rgba(37,99,235,0.65);color:#fff'>86.3</td><td style='background:rgba(37,99,235,0.73);color:#fff'>97.4</td><td style='background:rgba(37,99,235,0.72);color:#fff'>96.6</td><td style='background:rgba(37,99,235,0.69);color:#fff'>92.6</td><td class='sep'></td><td style='background:rgba(37,99,235,0.62);color:#fff'>82.6</td><td style='background:rgba(37,99,235,0.31);color:inherit'>40.8</td><td style='background:rgba(37,99,235,0.49);color:#fff'>65.0</td><td style='background:rgba(37,99,235,0.36);color:inherit'>48.5</td></tr><tr><td><b>bge-m3-all</b></td><td style='background:rgba(37,99,235,0.56);color:#fff'>74.7</td><td style='background:rgba(37,99,235,0.62);color:#fff'>82.4</td><td style='background:rgba(37,99,235,0.35);color:inherit'>47.3</td><td style='background:rgba(37,99,235,0.64);color:#fff'>85.4</td><td style='background:rgba(37,99,235,0.46);color:#fff'>61.8</td><td style='background:rgba(37,99,235,0.65);color:#fff'>86.4</td><td style='background:rgba(37,99,235,0.73);color:#fff'>97.5</td><td style='background:rgba(37,99,235,0.72);color:#fff'>96.0</td><td style='background:rgba(37,99,235,0.60);color:#fff'>79.8</td><td class='sep'></td><td style='background:rgba(37,99,235,0.49);color:#fff'>65.1</td><td style='background:rgba(37,99,235,0.25);color:inherit'>33.3</td><td style='background:rgba(37,99,235,0.35);color:inherit'>46.9</td><td style='background:rgba(37,99,235,0.27);color:inherit'>35.7</td></tr><tr><td><b>octen-8b</b></td><td style='background:rgba(37,99,235,0.55);color:#fff'>73.8</td><td style='background:rgba(37,99,235,0.63);color:#fff'>84.2</td><td style='background:rgba(37,99,235,0.30);color:inherit'>40.0</td><td style='background:rgba(37,99,235,0.65);color:#fff'>86.8</td><td style='background:rgba(37,99,235,0.46);color:#fff'>61.5</td><td style='background:rgba(37,99,235,0.63);color:#fff'>83.6</td><td style='background:rgba(37,99,235,0.72);color:#fff'>95.5</td><td style='background:rgba(37,99,235,0.74);color:#fff'>98.3</td><td style='background:rgba(37,99,235,0.68);color:#fff'>90.1</td><td class='sep'></td><td style='background:rgba(37,99,235,0.57);color:#fff'>76.1</td><td style='background:rgba(37,99,235,0.29);color:inherit'>38.2</td><td style='background:rgba(37,99,235,0.48);color:#fff'>64.2</td><td style='background:rgba(37,99,235,0.36);color:inherit'>48.5</td></tr><tr><td><b>qwen3-8b</b></td><td style='background:rgba(37,99,235,0.56);color:#fff'>75.1</td><td style='background:rgba(37,99,235,0.63);color:#fff'>84.1</td><td style='background:rgba(37,99,235,0.28);color:inherit'>37.6</td><td style='background:rgba(37,99,235,0.65);color:#fff'>86.0</td><td style='background:rgba(37,99,235,0.09);color:inherit'>11.9</td><td style='background:rgba(37,99,235,0.50);color:#fff'>67.3</td><td style='background:rgba(37,99,235,0.69);color:#fff'>92.2</td><td style='background:rgba(37,99,235,0.73);color:#fff'>96.8</td><td style='background:rgba(37,99,235,0.59);color:#fff'>78.4</td><td class='sep'></td><td style='background:rgba(37,99,235,0.55);color:#fff'>73.9</td><td style='background:rgba(37,99,235,0.28);color:inherit'>37.2</td><td style='background:rgba(37,99,235,0.45);color:#fff'>60.5</td><td style='background:rgba(37,99,235,0.34);color:inherit'>45.1</td></tr><tr><td><b>octen-4b</b></td><td style='background:rgba(37,99,235,0.55);color:#fff'>73.6</td><td style='background:rgba(37,99,235,0.63);color:#fff'>84.2</td><td style='background:rgba(37,99,235,0.29);color:inherit'>38.3</td><td style='background:rgba(37,99,235,0.63);color:#fff'>84.4</td><td style='background:rgba(37,99,235,0.43);color:#fff'>57.4</td><td style='background:rgba(37,99,235,0.61);color:#fff'>81.2</td><td style='background:rgba(37,99,235,0.71);color:#fff'>94.5</td><td style='background:rgba(37,99,235,0.71);color:#fff'>94.6</td><td style='background:rgba(37,99,235,0.65);color:#fff'>87.1</td><td class='sep'></td><td style='background:rgba(37,99,235,0.54);color:#fff'>72.4</td><td style='background:rgba(37,99,235,0.30);color:inherit'>39.7</td><td style='background:rgba(37,99,235,0.46);color:#fff'>61.6</td><td style='background:rgba(37,99,235,0.32);color:inherit'>42.9</td></tr><tr><td><b>pplx-embed-v1-0.6b</b></td><td style='background:rgba(37,99,235,0.53);color:#fff'>70.1</td><td style='background:rgba(37,99,235,0.61);color:#fff'>81.6</td><td style='background:rgba(37,99,235,0.31);color:inherit'>41.2</td><td style='background:rgba(37,99,235,0.65);color:#fff'>87.1</td><td style='background:rgba(37,99,235,0.45);color:#fff'>59.7</td><td style='background:rgba(37,99,235,0.63);color:#fff'>83.4</td><td style='background:rgba(37,99,235,0.73);color:#fff'>97.1</td><td style='background:rgba(37,99,235,0.71);color:#fff'>95.3</td><td style='background:rgba(37,99,235,0.59);color:#fff'>79.2</td><td class='sep'></td><td style='background:rgba(37,99,235,0.48);color:#fff'>63.8</td><td style='background:rgba(37,99,235,0.25);color:inherit'>34.0</td><td style='background:rgba(37,99,235,0.41);color:inherit'>54.9</td><td style='background:rgba(37,99,235,0.28);color:inherit'>37.6</td></tr><tr><td><b>openembed-2b</b></td><td style='background:rgba(37,99,235,0.54);color:#fff'>71.8</td><td style='background:rgba(37,99,235,0.61);color:#fff'>81.0</td><td style='background:rgba(37,99,235,0.34);color:inherit'>45.0</td><td style='background:rgba(37,99,235,0.61);color:#fff'>80.9</td><td style='background:rgba(37,99,235,0.44);color:#fff'>58.1</td><td style='background:rgba(37,99,235,0.60);color:#fff'>80.4</td><td style='background:rgba(37,99,235,0.71);color:#fff'>94.9</td><td style='background:rgba(37,99,235,0.70);color:#fff'>93.4</td><td style='background:rgba(37,99,235,0.63);color:#fff'>84.5</td><td class='sep'></td><td style='background:rgba(37,99,235,0.55);color:#fff'>73.5</td><td style='background:rgba(37,99,235,0.25);color:inherit'>33.6</td><td style='background:rgba(37,99,235,0.38);color:inherit'>50.5</td><td style='background:rgba(37,99,235,0.24);color:inherit'>31.4</td></tr><tr><td><b>bge-m3</b></td><td style='background:rgba(37,99,235,0.54);color:#fff'>71.6</td><td style='background:rgba(37,99,235,0.61);color:#fff'>81.3</td><td style='background:rgba(37,99,235,0.30);color:inherit'>40.0</td><td style='background:rgba(37,99,235,0.63);color:#fff'>84.4</td><td style='background:rgba(37,99,235,0.43);color:#fff'>56.9</td><td style='background:rgba(37,99,235,0.62);color:#fff'>82.9</td><td style='background:rgba(37,99,235,0.72);color:#fff'>95.9</td><td style='background:rgba(37,99,235,0.70);color:#fff'>93.2</td><td style='background:rgba(37,99,235,0.59);color:#fff'>78.4</td><td class='sep'></td><td style='background:rgba(37,99,235,0.46);color:#fff'>62.0</td><td style='background:rgba(37,99,235,0.23);color:inherit'>31.0</td><td style='background:rgba(37,99,235,0.38);color:inherit'>50.5</td><td style='background:rgba(37,99,235,0.26);color:inherit'>34.1</td></tr><tr><td><b>voyage-4-lite</b></td><td style='background:rgba(37,99,235,0.51);color:#fff'>68.2</td><td style='background:rgba(37,99,235,0.62);color:#fff'>82.1</td><td style='background:rgba(37,99,235,0.33);color:inherit'>43.7</td><td style='background:rgba(37,99,235,0.62);color:#fff'>82.3</td><td style='background:rgba(37,99,235,0.48);color:#fff'>63.5</td><td style='background:rgba(37,99,235,0.62);color:#fff'>83.0</td><td style='background:rgba(37,99,235,0.72);color:#fff'>96.6</td><td style='background:rgba(37,99,235,0.71);color:#fff'>94.9</td><td style='background:rgba(37,99,235,0.63);color:#fff'>84.7</td><td class='sep'></td><td style='background:rgba(37,99,235,0.53);color:#fff'>70.5</td><td style='background:rgba(37,99,235,0.26);color:inherit'>34.6</td><td style='background:rgba(37,99,235,0.43);color:#fff'>56.8</td><td style='background:rgba(37,99,235,0.31);color:inherit'>41.5</td></tr><tr><td><b>qwen3-4b</b></td><td style='background:rgba(37,99,235,0.58);color:#fff'>76.7</td><td style='background:rgba(37,99,235,0.63);color:#fff'>83.8</td><td style='background:rgba(37,99,235,0.23);color:inherit'>30.1</td><td style='background:rgba(37,99,235,0.62);color:#fff'>83.0</td><td style='background:rgba(37,99,235,0.12);color:inherit'>16.5</td><td style='background:rgba(37,99,235,0.53);color:#fff'>70.5</td><td style='background:rgba(37,99,235,0.70);color:#fff'>92.7</td><td style='background:rgba(37,99,235,0.70);color:#fff'>93.3</td><td style='background:rgba(37,99,235,0.61);color:#fff'>81.1</td><td class='sep'></td><td style='background:rgba(37,99,235,0.54);color:#fff'>72.6</td><td style='background:rgba(37,99,235,0.29);color:inherit'>38.8</td><td style='background:rgba(37,99,235,0.43);color:#fff'>57.9</td><td style='background:rgba(37,99,235,0.31);color:inherit'>41.8</td></tr><tr><td><b>skill-venus-0.6b</b></td><td style='background:rgba(37,99,235,0.53);color:#fff'>70.5</td><td style='background:rgba(37,99,235,0.60);color:#fff'>80.0</td><td style='background:rgba(37,99,235,0.32);color:inherit'>43.3</td><td style='background:rgba(37,99,235,0.59);color:#fff'>79.0</td><td style='background:rgba(37,99,235,0.36);color:inherit'>47.8</td><td style='background:rgba(37,99,235,0.60);color:#fff'>79.7</td><td style='background:rgba(37,99,235,0.70);color:#fff'>93.4</td><td style='background:rgba(37,99,235,0.69);color:#fff'>92.4</td><td style='background:rgba(37,99,235,0.60);color:#fff'>79.6</td><td class='sep'></td><td style='background:rgba(37,99,235,0.50);color:#fff'>66.5</td><td style='background:rgba(37,99,235,0.23);color:inherit'>30.8</td><td style='background:rgba(37,99,235,0.40);color:inherit'>52.7</td><td style='background:rgba(37,99,235,0.22);color:inherit'>29.1</td></tr><tr><td><b>embeddinggemma-300m</b></td><td style='background:rgba(37,99,235,0.51);color:#fff'>67.9</td><td style='background:rgba(37,99,235,0.60);color:#fff'>79.5</td><td style='background:rgba(37,99,235,0.30);color:inherit'>40.4</td><td style='background:rgba(37,99,235,0.59);color:#fff'>79.3</td><td style='background:rgba(37,99,235,0.44);color:#fff'>58.8</td><td style='background:rgba(37,99,235,0.59);color:#fff'>78.2</td><td style='background:rgba(37,99,235,0.71);color:#fff'>95.3</td><td style='background:rgba(37,99,235,0.70);color:#fff'>93.0</td><td style='background:rgba(37,99,235,0.58);color:#fff'>76.8</td><td class='sep'></td><td style='background:rgba(37,99,235,0.53);color:#fff'>70.5</td><td style='background:rgba(37,99,235,0.26);color:inherit'>34.1</td><td style='background:rgba(37,99,235,0.41);color:#fff'>55.0</td><td style='background:rgba(37,99,235,0.22);color:inherit'>28.9</td></tr><tr><td><b>openembed-0.8b</b></td><td style='background:rgba(37,99,235,0.52);color:#fff'>69.6</td><td style='background:rgba(37,99,235,0.58);color:#fff'>78.0</td><td style='background:rgba(37,99,235,0.31);color:inherit'>41.6</td><td style='background:rgba(37,99,235,0.58);color:#fff'>77.2</td><td style='background:rgba(37,99,235,0.39);color:inherit'>52.5</td><td style='background:rgba(37,99,235,0.58);color:#fff'>77.9</td><td style='background:rgba(37,99,235,0.70);color:#fff'>92.8</td><td style='background:rgba(37,99,235,0.68);color:#fff'>90.7</td><td style='background:rgba(37,99,235,0.59);color:#fff'>78.7</td><td class='sep'></td><td style='background:rgba(37,99,235,0.51);color:#fff'>68.6</td><td style='background:rgba(37,99,235,0.24);color:inherit'>31.4</td><td style='background:rgba(37,99,235,0.35);color:inherit'>46.8</td><td style='background:rgba(37,99,235,0.20);color:inherit'>26.4</td></tr><tr><td><b>text-embedding-3-large</b></td><td style='background:rgba(37,99,235,0.49);color:#fff'>65.3</td><td style='background:rgba(37,99,235,0.59);color:#fff'>79.1</td><td style='background:rgba(37,99,235,0.28);color:inherit'>37.4</td><td style='background:rgba(37,99,235,0.63);color:#fff'>84.2</td><td style='background:rgba(37,99,235,0.41);color:inherit'>54.6</td><td style='background:rgba(37,99,235,0.59);color:#fff'>78.7</td><td style='background:rgba(37,99,235,0.70);color:#fff'>92.9</td><td style='background:rgba(37,99,235,0.69);color:#fff'>91.9</td><td style='background:rgba(37,99,235,0.63);color:#fff'>84.0</td><td class='sep'></td><td style='background:rgba(37,99,235,0.49);color:#fff'>64.9</td><td style='background:rgba(37,99,235,0.27);color:inherit'>36.0</td><td style='background:rgba(37,99,235,0.38);color:inherit'>51.0</td><td style='background:rgba(37,99,235,0.25);color:inherit'>33.8</td></tr><tr><td><b>octen-0.6b</b></td><td style='background:rgba(37,99,235,0.50);color:#fff'>66.3</td><td style='background:rgba(37,99,235,0.58);color:#fff'>77.9</td><td style='background:rgba(37,99,235,0.27);color:inherit'>35.4</td><td style='background:rgba(37,99,235,0.61);color:#fff'>80.9</td><td style='background:rgba(37,99,235,0.29);color:inherit'>38.3</td><td style='background:rgba(37,99,235,0.58);color:#fff'>77.0</td><td style='background:rgba(37,99,235,0.69);color:#fff'>92.3</td><td style='background:rgba(37,99,235,0.69);color:#fff'>92.0</td><td style='background:rgba(37,99,235,0.61);color:#fff'>81.0</td><td class='sep'></td><td style='background:rgba(37,99,235,0.52);color:#fff'>69.6</td><td style='background:rgba(37,99,235,0.25);color:inherit'>32.8</td><td style='background:rgba(37,99,235,0.42);color:#fff'>56.0</td><td style='background:rgba(37,99,235,0.25);color:inherit'>33.4</td></tr><tr><td><b>embeddinggemma-2</b></td><td style='background:rgba(37,99,235,0.52);color:#fff'>69.6</td><td style='background:rgba(37,99,235,0.58);color:#fff'>76.7</td><td style='background:rgba(37,99,235,0.31);color:inherit'>41.1</td><td style='background:rgba(37,99,235,0.55);color:#fff'>73.1</td><td style='background:rgba(37,99,235,0.42);color:#fff'>56.7</td><td style='background:rgba(37,99,235,0.61);color:#fff'>81.3</td><td style='background:rgba(37,99,235,0.71);color:#fff'>95.1</td><td style='background:rgba(37,99,235,0.71);color:#fff'>94.1</td><td style='background:rgba(37,99,235,0.50);color:#fff'>66.4</td><td class='sep'></td><td style='background:rgba(37,99,235,0.51);color:#fff'>68.4</td><td style='background:rgba(37,99,235,0.25);color:inherit'>33.0</td><td style='background:rgba(37,99,235,0.40);color:inherit'>53.9</td><td style='background:rgba(37,99,235,0.21);color:inherit'>28.2</td></tr><tr><td><b>qwen3-0.6b</b></td><td style='background:rgba(37,99,235,0.50);color:#fff'>67.1</td><td style='background:rgba(37,99,235,0.57);color:#fff'>76.4</td><td style='background:rgba(37,99,235,0.22);color:inherit'>29.5</td><td style='background:rgba(37,99,235,0.59);color:#fff'>78.8</td><td style='background:rgba(37,99,235,0.09);color:inherit'>11.5</td><td style='background:rgba(37,99,235,0.54);color:#fff'>71.9</td><td style='background:rgba(37,99,235,0.67);color:#fff'>90.0</td><td style='background:rgba(37,99,235,0.68);color:#fff'>90.5</td><td style='background:rgba(37,99,235,0.56);color:#fff'>74.6</td><td class='sep'></td><td style='background:rgba(37,99,235,0.51);color:#fff'>68.3</td><td style='background:rgba(37,99,235,0.24);color:inherit'>32.2</td><td style='background:rgba(37,99,235,0.41);color:inherit'>55.0</td><td style='background:rgba(37,99,235,0.24);color:inherit'>32.3</td></tr><tr><td><b>granite-97m-multi-r2</b></td><td style='background:rgba(37,99,235,0.47);color:#fff'>62.8</td><td style='background:rgba(37,99,235,0.55);color:#fff'>73.7</td><td style='background:rgba(37,99,235,0.23);color:inherit'>30.7</td><td style='background:rgba(37,99,235,0.60);color:#fff'>80.4</td><td style='background:rgba(37,99,235,0.34);color:inherit'>45.9</td><td style='background:rgba(37,99,235,0.54);color:#fff'>71.8</td><td style='background:rgba(37,99,235,0.66);color:#fff'>88.0</td><td style='background:rgba(37,99,235,0.64);color:#fff'>85.9</td><td style='background:rgba(37,99,235,0.59);color:#fff'>78.7</td><td class='sep'></td><td style='background:rgba(37,99,235,0.43);color:#fff'>57.4</td><td style='background:rgba(37,99,235,0.19);color:inherit'>25.6</td><td style='background:rgba(37,99,235,0.32);color:inherit'>43.0</td><td style='background:rgba(37,99,235,0.19);color:inherit'>24.9</td></tr><tr><td><b>text-embedding-3-small</b></td><td style='background:rgba(37,99,235,0.42);color:#fff'>56.5</td><td style='background:rgba(37,99,235,0.53);color:#fff'>70.1</td><td style='background:rgba(37,99,235,0.25);color:inherit'>33.2</td><td style='background:rgba(37,99,235,0.55);color:#fff'>73.7</td><td style='background:rgba(37,99,235,0.33);color:inherit'>44.1</td><td style='background:rgba(37,99,235,0.53);color:#fff'>71.3</td><td style='background:rgba(37,99,235,0.67);color:#fff'>89.4</td><td style='background:rgba(37,99,235,0.62);color:#fff'>83.1</td><td style='background:rgba(37,99,235,0.54);color:#fff'>72.2</td><td class='sep'></td><td style='background:rgba(37,99,235,0.41);color:#fff'>55.3</td><td style='background:rgba(37,99,235,0.20);color:inherit'>27.2</td><td style='background:rgba(37,99,235,0.30);color:inherit'>40.3</td><td style='background:rgba(37,99,235,0.15);color:inherit'>20.6</td></tr><tr><td><b>mistral-embed-1b</b></td><td style='background:rgba(37,99,235,0.26);color:inherit'>35.2</td><td style='background:rgba(37,99,235,0.38);color:inherit'>50.5</td><td style='background:rgba(37,99,235,0.14);color:inherit'>18.3</td><td style='background:rgba(37,99,235,0.42);color:#fff'>55.5</td><td style='background:rgba(37,99,235,0.16);color:inherit'>21.0</td><td style='background:rgba(37,99,235,0.40);color:inherit'>53.1</td><td style='background:rgba(37,99,235,0.53);color:#fff'>71.1</td><td style='background:rgba(37,99,235,0.47);color:#fff'>62.4</td><td style='background:rgba(37,99,235,0.46);color:#fff'>61.1</td><td class='sep'></td><td style='background:rgba(37,99,235,0.37);color:inherit'>49.3</td><td style='background:rgba(37,99,235,0.15);color:inherit'>20.3</td><td style='background:rgba(37,99,235,0.23);color:inherit'>31.3</td><td style='background:rgba(37,99,235,0.09);color:inherit'>11.8</td></tr><tr><td><b>para-multi-minilm-l12</b></td><td style='background:rgba(37,99,235,0.31);color:inherit'>41.3</td><td style='background:rgba(37,99,235,0.39);color:inherit'>52.6</td><td style='background:rgba(37,99,235,0.09);color:inherit'>12.2</td><td style='background:rgba(37,99,235,0.39);color:inherit'>51.4</td><td style='background:rgba(37,99,235,0.25);color:inherit'>34.0</td><td style='background:rgba(37,99,235,0.49);color:#fff'>64.9</td><td style='background:rgba(37,99,235,0.63);color:#fff'>84.1</td><td style='background:rgba(37,99,235,0.62);color:#fff'>82.7</td><td style='background:rgba(37,99,235,0.42);color:#fff'>56.5</td><td class='sep'></td><td style='background:rgba(37,99,235,0.32);color:inherit'>42.9</td><td style='background:rgba(37,99,235,0.15);color:inherit'>19.6</td><td style='background:rgba(37,99,235,0.28);color:inherit'>37.2</td><td style='background:rgba(37,99,235,0.10);color:inherit'>12.8</td></tr></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><tr class=''><td><b>gemini-embedding-2</b></td><td>63.4</td><td>54.6</td><td>80.2</td><td>67.0</td><td>75.6</td></tr><tr class=''><td><b>octen-8b</b></td><td>60.2</td><td>50.8</td><td>73.8</td><td>58.5</td><td>68.4</td></tr><tr class=''><td><b>qwen3-8b</b></td><td>58.4</td><td>48.3</td><td>75.1</td><td>59.5</td><td>69.9</td></tr><tr class=''><td><b>octen-4b</b></td><td>58.0</td><td>48.7</td><td>73.6</td><td>58.5</td><td>68.6</td></tr><tr class=''><td><b>qwen3-4b</b></td><td>57.6</td><td>48.7</td><td>76.7</td><td>61.4</td><td>71.8</td></tr><tr class='run1'><td><i>Qwen3-Embedding-4B (run 1)</i></td><td>57.6</td><td>48.7</td><td>76.7</td><td>61.4</td><td>71.8</td></tr><tr class=''><td><b>voyage-4-lite</b></td><td>54.3</td><td>45.5</td><td>68.2</td><td>52.5</td><td>63.2</td></tr><tr class=''><td><b>openembed-2b</b></td><td>52.2</td><td>40.9</td><td>71.8</td><td>54.9</td><td>66.9</td></tr><tr class=''><td><b>pplx-embed-v1-0.6b</b></td><td>52.1</td><td>43.5</td><td>70.1</td><td>53.9</td><td>64.5</td></tr><tr class=''><td><b>octen-0.6b</b></td><td>51.6</td><td>42.3</td><td>66.3</td><td>49.5</td><td>60.6</td></tr><tr class=''><td><b>embeddinggemma-300m</b></td><td>51.3</td><td>40.5</td><td>67.9</td><td>47.8</td><td>62.1</td></tr><tr class=''><td><b>bge-m3-all</b></td><td>51.1</td><td>—</td><td>74.7</td><td>—</td><td>69.4</td></tr><tr class='run1'><td><i>BGE-M3 all three modes (run 1)</i></td><td>51.1</td><td>—</td><td>74.7</td><td>—</td><td>69.4</td></tr><tr class=''><td><b>qwen3-0.6b</b></td><td>51.0</td><td>42.3</td><td>67.1</td><td>50.9</td><td>61.1</td></tr><tr class=''><td><b>embeddinggemma-2</b></td><td>50.6</td><td>41.4</td><td>69.6</td><td>54.8</td><td>64.7</td></tr><tr class='run1'><td><i>EmbeddingGemma 2 (run 1)</i></td><td>50.6</td><td>41.4</td><td>69.6</td><td>54.8</td><td>64.7</td></tr><tr class=''><td><b>text-embedding-3-large</b></td><td>50.2</td><td>39.5</td><td>65.3</td><td>45.4</td><td>58.9</td></tr><tr class=''><td><b>skill-venus-0.6b</b></td><td>49.9</td><td>41.1</td><td>70.5</td><td>53.9</td><td>64.6</td></tr><tr class=''><td><b>bge-m3</b></td><td>49.8</td><td>40.7</td><td>71.6</td><td>54.6</td><td>65.5</td></tr><tr class='run1'><td><i>BGE-M3 (run 1)</i></td><td>49.8</td><td>40.7</td><td>71.6</td><td>54.6</td><td>65.5</td></tr><tr class=''><td><b>openembed-0.8b</b></td><td>48.6</td><td>39.2</td><td>69.6</td><td>52.7</td><td>64.0</td></tr><tr class=''><td><b>granite-97m-multi-r2</b></td><td>42.7</td><td>34.1</td><td>62.8</td><td>46.4</td><td>57.2</td></tr><tr class=''><td><b>text-embedding-3-small</b></td><td>40.0</td><td>31.9</td><td>56.5</td><td>39.2</td><td>50.2</td></tr><tr class=''><td><b>para-multi-minilm-l12</b></td><td>30.8</td><td>21.0</td><td>41.3</td><td>26.0</td><td>35.3</td></tr><tr class=''><td><b>mistral-embed-1b</b></td><td>29.6</td><td>22.5</td><td>35.2</td><td>20.1</td><td>29.6</td></tr></table></div><h2>4 · Size vs Vietnamese legal accuracy (Zalo Legal nDCG@10)</h2><div class="card"><svg viewBox="0 0 760 380" class="chart"><line x1="50" x2="610" y1="340" y2="340" class="grid"/><text x="44" y="344" class="ax" text-anchor="end">0</text><line x1="50" x2="610" y1="274" y2="274" class="grid"/><text x="44" y="278" class="ax" text-anchor="end">20</text><line x1="50" x2="610" y1="209" y2="209" class="grid"/><text x="44" y="213" class="ax" text-anchor="end">40</text><line x1="50" x2="610" y1="143" y2="143" class="grid"/><text x="44" y="147" class="ax" text-anchor="end">60</text><line x1="50" x2="610" y1="78" y2="78" class="grid"/><text x="44" y="82" class="ax" text-anchor="end">80</text><line x1="50" x2="610" y1="12" y2="12" class="grid"/><text x="44" y="16" class="ax" text-anchor="end">100</text><text x="90" y="356" class="ax" text-anchor="middle">0.03B</text><text x="208" y="356" class="ax" text-anchor="middle">0.1B</text><text x="316" y="356" class="ax" text-anchor="middle">0.3B</text><text x="434" y="356" class="ax" text-anchor="middle">1B</text><text x="542" y="356" class="ax" text-anchor="middle">3B</text><text x="330.0" y="376" class="ax" text-anchor="middle">parameters (log scale)</text><circle cx="455.2" cy="224.6" r="5" fill="var(--c1)"><title>mistral-embed-1b: 35.2</title></circle><text x="463.2" y="228.6" class="pl">mistral-embed-1b 35.2</text><circle cx="224.3" cy="204.5" r="5" fill="var(--c1)"><title>para-multi-minilm-l12: 41.3</title></circle><text x="232.3" y="208.5" class="pl">para-multi-minilm-l12 41.3</text><circle cx="205.0" cy="134.1" r="5" fill="var(--c1)"><title>granite-97m-multi-r2: 62.8</title></circle><text x="213.0" y="138.1" class="pl">granite-97m-multi-r2 62.8</text><circle cx="383.9" cy="122.5" r="5" fill="var(--c1)"><title>octen-0.6b: 66.3</title></circle><text x="391.9" y="126.5" class="pl">octen-0.6b 66.3</text><circle cx="383.9" cy="120.0" r="5" fill="var(--c1)"><title>qwen3-0.6b: 67.1</title></circle><text x="391.9" y="124.0" class="pl">qwen3-0.6b 67.1</text><circle cx="315.9" cy="117.4" r="5" fill="var(--c1)"><title>embeddinggemma-300m: 67.9</title></circle><text x="323.9" y="121.4" class="pl">embeddinggemma-300m 67.9</text><circle cx="418.1" cy="111.8" r="5" fill="var(--c1)"><title>openembed-0.8b: 69.6</title></circle><text x="426.1" y="115.8" class="pl">openembed-0.8b 69.6</text><circle cx="305.9" cy="111.7" r="5" fill="var(--c1)"><title>embeddinggemma-2: 69.6</title></circle><text x="313.9" y="115.7" class="pl">embeddinggemma-2 69.6</text><circle cx="305.9" cy="111.7" r="5" fill="var(--accent)"><title>EmbeddingGemma 2 (run 1): 69.6</title></circle><text x="313.9" y="115.7" class="pl">EmbeddingGemma 2 (run 1) 69.6</text><circle cx="383.9" cy="110.0" r="5" fill="var(--c1)"><title>pplx-embed-v1-0.6b: 70.1</title></circle><text x="391.9" y="114.0" class="pl">pplx-embed-v1-0.6b 70.1</text><circle cx="383.9" cy="108.7" r="5" fill="var(--c1)"><title>skill-venus-0.6b: 70.5</title></circle><text x="391.9" y="112.7" class="pl">skill-venus-0.6b 70.5</text><circle cx="378.6" cy="105.1" r="5" fill="var(--c1)"><title>bge-m3: 71.6</title></circle><text x="386.6" y="109.1" class="pl">bge-m3 71.6</text><circle cx="378.6" cy="105.1" r="5" fill="var(--accent)"><title>BGE-M3 (run 1): 71.6</title></circle><text x="386.6" y="109.1" class="pl">BGE-M3 (run 1) 71.6</text><circle cx="511.9" cy="104.4" r="5" fill="var(--c1)"><title>openembed-2b: 71.8</title></circle><text x="519.9" y="108.4" class="pl">openembed-2b 71.8</text><circle cx="570.7" cy="98.7" r="5" fill="var(--c1)"><title>octen-4b: 73.6</title></circle><text x="578.7" y="102.7" class="pl">octen-4b 73.6</text><circle cx="632.8" cy="98.0" r="5" fill="var(--c1)"><title>octen-8b: 73.8</title></circle><text x="640.8" y="102.0" class="pl">octen-8b 73.8</text><circle cx="378.6" cy="95.0" r="5" fill="var(--c1)"><title>bge-m3-all: 74.7</title></circle><text x="386.6" y="99.0" class="pl">bge-m3-all 74.7</text><circle cx="632.8" cy="93.7" r="5" fill="var(--c1)"><title>qwen3-8b: 75.1</title></circle><text x="640.8" y="97.7" class="pl">qwen3-8b 75.1</text><circle cx="570.7" cy="88.5" r="5" fill="var(--c1)"><title>qwen3-4b: 76.7</title></circle><text x="578.7" y="92.5" class="pl">qwen3-4b 76.7</text><circle cx="570.7" cy="88.5" r="5" fill="var(--accent)"><title>Qwen3-4B (run 1): 76.7</title></circle><text x="578.7" y="92.5" class="pl">Qwen3-4B (run 1) 76.7</text></svg></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><tr><td>gemini-embedding-2</td><td>512</td><td>—</td><td>—%</td><td>nan</td><td>0.0</td><td>0.0</td></tr><tr><td>bge-m3-all</td><td>512</td><td>—</td><td>—%</td><td>nan</td><td>11.6</td><td>0.0</td></tr><tr><td>octen-8b</td><td>512</td><td>1.41</td><td>13.6%</td><td>nan</td><td>17.6</td><td>265.4</td></tr><tr><td>qwen3-8b</td><td>512</td><td>—</td><td>—%</td><td>54</td><td>17.6</td><td>289.7</td></tr><tr><td>octen-4b</td><td>512</td><td>1.41</td><td>13.6%</td><td>nan</td><td>10.1</td><td>153.9</td></tr><tr><td>pplx-embed-v1-0.6b</td><td>512</td><td>—</td><td>—%</td><td>nan</td><td>0.0</td><td>0.0</td></tr><tr><td>openembed-2b</td><td>512</td><td>1.33</td><td>11.8%</td><td>108</td><td>8.2</td><td>76.8</td></tr><tr><td>bge-m3</td><td>512</td><td>—</td><td>—%</td><td>nan</td><td>11.6</td><td>0.0</td></tr><tr><td>voyage-4-lite</td><td>512</td><td>—</td><td>—%</td><td>nan</td><td>0.0</td><td>0.0</td></tr><tr><td>qwen3-4b</td><td>512</td><td>1.50</td><td>14.1%</td><td>nan</td><td>10.1</td><td>113.0</td></tr><tr><td>skill-venus-0.6b</td><td>512</td><td>1.42</td><td>13.7%</td><td>293</td><td>3.0</td><td>27.4</td></tr><tr><td>embeddinggemma-300m</td><td>512</td><td>1.39</td><td>13.7%</td><td>573</td><td>2.5</td><td>16.8</td></tr><tr><td>openembed-0.8b</td><td>512</td><td>1.33</td><td>11.8%</td><td>130</td><td>9.2</td><td>95.5</td></tr><tr><td>text-embedding-3-large</td><td>512</td><td>—</td><td>—%</td><td>nan</td><td>0.0</td><td>0.0</td></tr><tr><td>octen-0.6b</td><td>512</td><td>1.41</td><td>13.6%</td><td>nan</td><td>3.0</td><td>29.9</td></tr><tr><td>embeddinggemma-2</td><td>512</td><td>1.48</td><td>14.3%</td><td>nan</td><td>8.2</td><td>18.8</td></tr><tr><td>qwen3-0.6b</td><td>512</td><td>1.42</td><td>13.7%</td><td>293</td><td>3.0</td><td>27.4</td></tr><tr><td>granite-97m-multi-r2</td><td>512</td><td>1.39</td><td>11.8%</td><td>2,181</td><td>4.6</td><td>4.2</td></tr><tr><td>text-embedding-3-small</td><td>512</td><td>—</td><td>—%</td><td>nan</td><td>0.0</td><td>0.0</td></tr><tr><td>mistral-embed-1b</td><td>512</td><td>1.46</td><td>14.6%</td><td>465</td><td>4.7</td><td>24.3</td></tr><tr><td>para-multi-minilm-l12</td><td>128</td><td>1.26</td><td>62.8%</td><td>7,320</td><td>0.8</td><td>1.8</td></tr></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><tr><td>gemini-embedding-2</td><td>3072d: <b>75.9</b></td><td>1536d: <b>75.8</b></td><td>768d: <b>75.6</b></td></tr><tr><td>qwen3-8b</td><td>4096d: <b>70.7</b></td><td>1024d: <b>70.3</b></td><td>512d: <b>69.5</b></td><td>256d: <b>68.2</b></td></tr><tr><td>voyage-4-lite</td><td>1024d: <b>69.1</b></td><td>512d: <b>68.1</b></td><td>256d: <b>65.0</b></td></tr><tr><td>qwen3-4b</td><td>2560d: <b>—</b></td><td>512d: <b>—</b></td><td>256d: <b>—</b></td><td>128d: <b>—</b></td></tr><tr><td>embeddinggemma-300m</td><td>768d: <b>66.8</b></td><td>512d: <b>65.3</b></td><td>256d: <b>62.8</b></td><td>128d: <b>58.6</b></td></tr><tr><td>text-embedding-3-large</td><td>3072d: <b>66.5</b></td><td>1024d: <b>65.5</b></td><td>512d: <b>64.4</b></td><td>256d: <b>61.8</b></td></tr><tr><td>embeddinggemma-2</td><td>768d: <b>—</b></td><td>512d: <b>—</b></td><td>256d: <b>—</b></td><td>128d: <b>—</b></td></tr><tr><td>qwen3-0.6b</td><td>1024d: <b>62.9</b></td><td>512d: <b>62.1</b></td><td>256d: <b>60.2</b></td><td>128d: <b>58.1</b></td></tr><tr><td>text-embedding-3-small</td><td>1536d: <b>58.4</b></td><td>1024d: <b>57.8</b></td><td>512d: <b>56.1</b></td><td>256d: <b>51.9</b></td></tr></table></div>
<h2>7 · Long documents: 512 → 2,048 tokens (nDCG@10)</h2><div class="tbl"><table><tr><th>Model</th><th>Tables</th><th>Zalo Legal</th><th>TVPL legal</th></tr><tr><td>bge-m3</td><td>40.0 → <b>40.4</b> (+0.4)<br><span class='sm'></span></td><td>71.6 → <b>74.3</b> (+2.7)<br><span class='sm'></span></td><td>81.3 → <b>81.3</b> (-0.0)<br><span class='sm'></span></td></tr><tr><td>bge-m3-all</td><td>47.3 → <b>47.9</b> (+0.6)<br><span class='sm'></span></td><td>74.7 → <b>77.5</b> (+2.8)<br><span class='sm'></span></td><td>82.4 → <b>82.4</b> (+0.0)<br><span class='sm'></span></td></tr><tr><td>embeddinggemma-300m</td><td>40.4 → <b>41.4</b> (+0.9)<br><span class='sm'>34% of docs cut at 512</span></td><td>67.9 → <b>72.2</b> (+4.4)<br><span class='sm'>19% of docs cut at 512</span></td><td>79.5 → <b>79.2</b> (-0.2)<br><span class='sm'>8% of docs cut at 512</span></td></tr><tr><td>granite-97m-multi-r2</td><td>30.7 → <b>31.2</b> (+0.5)<br><span class='sm'>23% of docs cut at 512</span></td><td>62.8 → <b>63.0</b> (+0.3)<br><span class='sm'>21% of docs cut at 512</span></td><td>73.7 → <b>73.7</b> (-0.0)<br><span class='sm'>9% of docs cut at 512</span></td></tr><tr><td>mistral-embed-1b</td><td>18.3 → <b>18.5</b> (+0.3)<br><span class='sm'>36% of docs cut at 512</span></td><td>35.2 → <b>42.7</b> (+7.5)<br><span class='sm'>20% of docs cut at 512</span></td><td>50.5 → <b>50.4</b> (-0.1)<br><span class='sm'>9% of docs cut at 512</span></td></tr><tr><td>octen-4b</td><td>38.3 → <b>38.5</b> (+0.2)<br><span class='sm'>33% of docs cut at 512</span></td><td>73.6 → <b>76.3</b> (+2.7)<br><span class='sm'>20% of docs cut at 512</span></td><td>84.2 → <b>84.3</b> (+0.1)<br><span class='sm'>8% of docs cut at 512</span></td></tr><tr><td>octen-8b</td><td>40.0 → <b>40.3</b> (+0.3)<br><span class='sm'>33% of docs cut at 512</span></td><td>73.8 → <b>77.1</b> (+3.3)<br><span class='sm'>20% of docs cut at 512</span></td><td>84.2 → <b>84.3</b> (+0.1)<br><span class='sm'>8% of docs cut at 512</span></td></tr><tr><td>openembed-0.8b</td><td>41.6 → <b>42.5</b> (+0.9)<br><span class='sm'>28% of docs cut at 512</span></td><td>69.6 → <b>—</b> (—)<br><span class='sm'>18% of docs cut at 512</span></td><td>78.0 → <b>—</b> (—)<br><span class='sm'>7% of docs cut at 512</span></td></tr><tr><td>openembed-2b</td><td>45.0 → <b>46.3</b> (+1.3)<br><span class='sm'>28% of docs cut at 512</span></td><td>71.8 → <b>70.0</b> (-1.8)<br><span class='sm'>18% of docs cut at 512</span></td><td>81.0 → <b>—</b> (—)<br><span class='sm'>7% of docs cut at 512</span></td></tr><tr><td>qwen3-0.6b</td><td>29.5 → <b>30.7</b> (+1.2)<br><span class='sm'>33% of docs cut at 512</span></td><td>67.1 → <b>70.1</b> (+3.0)<br><span class='sm'>20% of docs cut at 512</span></td><td>76.4 → <b>76.5</b> (+0.0)<br><span class='sm'>8% of docs cut at 512</span></td></tr><tr><td>qwen3-4b</td><td>30.1 → <b>31.6</b> (+1.6)<br><span class='sm'>33% of docs cut at 512</span></td><td>76.7 → <b>78.4</b> (+1.8)<br><span class='sm'></span></td><td>83.8 → <b>83.9</b> (+0.1)<br><span class='sm'>8% of docs cut at 512</span></td></tr><tr><td>qwen3-8b</td><td>37.6 → <b>38.6</b> (+1.0)<br><span class='sm'></span></td><td>75.1 → <b>78.3</b> (+3.2)<br><span class='sm'></span></td><td>84.1 → <b>84.3</b> (+0.2)<br><span class='sm'></span></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><tr><td>Zalo Legal</td><td>67.08</td><td>67.10</td><td>+0.02</td><td>50.89 → 50.89</td><td>0</td></tr><tr><td>SciFact-VN</td><td>68.33</td><td>68.13</td><td>-0.20</td><td>55.22 → 53.73</td><td>0</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>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# Raw benchmark data
Raw results for the Vietnamese embedding benchmark: **828 score rows**, **21 models**, **305 per-query files**. Both runs are merged into one schema (the `run` column records the source). Full column reference: [../docs/results.md](../docs/results.md).
| Path | What | Use it for ||---|---|---|| `scores.csv` / `scores.jsonl` | one row per model × dataset × configuration (window, precision, embedding size, BGE-M3 mode): nDCG@10, P@1, MRR@10, Recall@10/100, corpus size, tokens per word, share of truncated documents | leaderboards, plots, filtering by dataset group || `per_query/<model>/<dataset>__L<max_len>[-<precision>].csv.gz` | per-query nDCG@10, P@1, RR@10, Recall@10 | significance tests, paired wins/losses, error analysis || `top10/<model>/<dataset>__L<max_len>[-<precision>].jsonl.gz` | ranked top-10 document ids + cosine scores per query | inspecting failures, building rerank / fusion experiments || `speed/` | encode throughput on real Vietnamese text, sequence-length × batch sweep, query latency | relative speed between models (same file = same setup) |
## Quick start
```pythonimport pandas as pd
s = pd.read_csv("results/scores.csv")
# leaderboard: native Vietnamese sets, default 512-token window, full-size dense embeddingsmain = s[(s.dataset_group == "vi-native") & (s["mode"] == "dense") & (s.max_len <= 512) & ~s.matryoshka_truncated]core4 = ["zalo-legal", "tvpl", "table-markdown", "webfaq-vie"]print(main[main.dataset.isin(core4)].groupby("model")[["ndcg10", "p1"]].mean().sort_values("ndcg10", ascending=False))
# long input window gain (512 -> 2048)lw = s[(s["mode"] == "dense") & ~s.matryoshka_truncated & s.dataset.isin(["zalo-legal", "table-markdown", "tvpl"])]print(lw.pivot_table(index=["model", "dataset"], columns="max_len", values="ndcg10"))```
```python# paired per-query comparison of two models on one dataseta = pd.read_csv("results/per_query/qwen3-8b/zalo-legal__L512.csv.gz")b = pd.read_csv("results/per_query/openembed-2b/zalo-legal__L512.csv.gz")m = a.merge(b, on="qid", suffixes=("_qwen8b", "_openembed2b"))print("Qwen3-8B better on", (m.ndcg10_qwen8b > m.ndcg10_openembed2b).mean(), "of queries, worse on", (m.ndcg10_qwen8b < m.ndcg10_openembed2b).mean())```
```python# look at what a model retrieved (join ids with the original texts via the mteb / HF datasets in docs/datasets.md)import gzip, jsonfor line in gzip.open("results/top10/text-embedding-3-small/zalo-legal__L512-api.jsonl.gz", "rt"): print(json.loads(line)); break```
## Notes
- `dataset_group`: `vi-native` (human-written Vietnamese), `vi-translated` (VN-MTEB machine translation), `en` (run 1 only).- `precision`: `bf16` for run 2, `fp16` / `fp32` for run 1, `api` for the OpenAI model.- `matryoshka_truncated = true` rows use the first `dim` dimensions, re-normalised.- BGE-M3 hybrid rows (`mode` ≠ `dense`) have no per-query / top-10 files, and neither do BGE-M3's run-2 sets (its embeddings were not kept); BGE-M3 per-query data exists for the run-1 sets (`…__L512-fp16`).- `ndcg10_per_query_check` recomputes nDCG@10 from the per-query files; small gaps come from score ties (see docs/results.md).- Models without Vietnamese support were tested but are not included here (listed in ../docs/models.md).123version https://git-lfs.github.com/spec/v1oid sha256:b064d9f2bdd46f5447bebf0371b748e4d6f0d08d1461fad3039561bf6acf97cbsize 8121123version https://git-lfs.github.com/spec/v1oid sha256:bbb1539ee16dac9c45fa4c93d368a4ac9fa2ee4046ee5e1421b9029c442ea02csize 8716123version https://git-lfs.github.com/spec/v1oid sha256:a739521d0e6ba94ec85d639486b76dc4325e3dadf433f3907eae2821f7e7f36bsize 2380123version https://git-lfs.github.com/spec/v1oid sha256:75e936f79c1d85e3f14177fbf054217a9c4b43355a36ffd4ec9c7a03c079328csize 3734123version https://git-lfs.github.com/spec/v1oid sha256:da88335f38995268d59ce203e093c1b6dc6e0be6d8a142540c9f996bbdce5a03size 1703123version https://git-lfs.github.com/spec/v1oid sha256:6b6ca4efbac40bc323db2599101d878e29ec5ae580d808552d4db1ced9f2f0cbsize 3139123version https://git-lfs.github.com/spec/v1oid sha256:6f976a54f11582b348ba2546877f159931b420fce9d65d2a521f9224e9fa4279size 679123version https://git-lfs.github.com/spec/v1oid sha256:24711c9040ff354bfecd123fc68f3f5869d00d5fc33fa460a40742c2d578a7d2size 1233123version https://git-lfs.github.com/spec/v1oid sha256:9a5d46202aab279a4af3f1d9ff8bba4411547d8c47a537c51750ed349bb263a7size 617123version https://git-lfs.github.com/spec/v1oid sha256:eef0f506013d385e41061585978487ddc9cb11f6e92d062a802ae8f44413d2edsize 695123version https://git-lfs.github.com/spec/v1oid sha256:4473bfd080e88ef825a03354fa9c5ff6ed1c5badc9f44bfd4161a93641c6a70bsize 16866123version https://git-lfs.github.com/spec/v1oid sha256:62df6d7a275ffbc4c1c3e579f073ee3765a095ca7b5fe5ffbb545a04409a7fc7size 8136123version https://git-lfs.github.com/spec/v1oid sha256:a91b76b34cd6070ee0d4a3deb72343dbe26ad876ad562a64da38365d53d0e23asize 8634123version https://git-lfs.github.com/spec/v1oid sha256:8a2ebaa5855ae70caefa597454e588a87d4d5a074b67f3a7f0289e909bcdb88bsize 2461123version https://git-lfs.github.com/spec/v1oid sha256:e8c43b81391f35f4e43ca352a571e60bd088caf58fb30927166620a3e61a8d56size 2337123version https://git-lfs.github.com/spec/v1oid sha256:7af38d9d9053dd21142b826c1dec8e302c8686e0e0ac8e64c3dd82feba49937fsize 2332123version https://git-lfs.github.com/spec/v1oid sha256:d78907da7813ea00908fc93b55a2d6711a3ba71583b079cc6e9e1ab3492f7dc5size 3717123version https://git-lfs.github.com/spec/v1oid sha256:f9a61bc67291e2ce2f2a83ded801b7f24ba4a418ab0335598a5a13c24556522esize 1527.gitattributesAdded+41
README.mdAdded+94
assets/bge_m3_modes.pngAdded

Large File Pointer Details
- SHA256: 4cfc1800477970643a21b21b383b074b33a9efe1ae04443cd2f9be3601fd3c98
- Pointer size: 131 Bytes
- Size of remote file: 159 kB
assets/heatmap.pngAdded

Large File Pointer Details
- SHA256: 89419b1eda4a9260ee02a634308807121ca5bb8069ca2c11542c87c314a350d2
- Pointer size: 131 Bytes
- Size of remote file: 285 kB
assets/leaderboard.pngAdded

Large File Pointer Details
- SHA256: 0c880226c09e7b9d12343d08bbb53c259d5621cbd3fcdfb8850d96808607f5c5
- Pointer size: 131 Bytes
- Size of remote file: 183 kB
assets/long_context.pngAdded

Large File Pointer Details
- SHA256: 4534d9fcd2586e820bc96240041723cfe32d7c307a5ea9cde89f46c4b3a73735
- Pointer size: 131 Bytes
- Size of remote file: 200 kB
assets/mrl.pngAdded

Large File Pointer Details
- SHA256: 8c66010876170ecedf635dc92ca0c94fd7001fd986984baa5c72cdd549b941e2
- Pointer size: 131 Bytes
- Size of remote file: 266 kB
assets/size_vs_accuracy.pngAdded

Large File Pointer Details
- SHA256: 22f2e0f8e3b3dfba9d9eda8f564e0789f341cc5e487708dec1d4112d693a500c
- Pointer size: 131 Bytes
- Size of remote file: 140 kB
code/run1/data.pyAdded+15
code/run1/gate.pyAdded+57
code/run1/models.pyAdded+153
code/run1/quality.pyAdded+180
code/run1/report.cssAdded+16
code/run1/report.pyAdded+360
code/run1/speed.pyAdded+115
code/run2/build8b.pyAdded+32
code/run2/data.pyAdded+66
code/run2/m3.pyAdded+120
code/run2/plan_jobs.pyAdded+23
code/run2/report_pro.pyAdded+242
code/run2/score8b.pyAdded+108
code/run2/shard8b.pyAdded+98
code/run2/smoke.pyAdded+95
code/run2/worker.pyAdded+241
code/run2/zoo.pyAdded+148
docs/datasets.mdAdded+43
docs/methodology.mdAdded+57
docs/models.mdAdded+34
docs/results.mdAdded+38
reports/run1-benchmark-report.htmlAdded+76
reports/run2-vietnamese-benchmark-report.htmlAdded+77
results/README.mdAdded+51
results/per_query/bge-m3/arguana-vn__L512-fp16.csv.gzAdded+3
results/per_query/bge-m3/arguana__L512-fp16.csv.gzAdded+3
results/per_query/bge-m3/fiqa-vn__L512-fp16.csv.gzAdded+3
results/per_query/bge-m3/fiqa__L512-fp16.csv.gzAdded+3
results/per_query/bge-m3/nfcorpus-vn__L512-fp16.csv.gzAdded+3
results/per_query/bge-m3/nfcorpus__L512-fp16.csv.gzAdded+3
results/per_query/bge-m3/scifact-vn__L512-fp16.csv.gzAdded+3
results/per_query/bge-m3/scifact__L512-fp16.csv.gzAdded+3
results/per_query/bge-m3/trec-covid-vn__L512-fp16.csv.gzAdded+3
results/per_query/bge-m3/trec-covid__L512-fp16.csv.gzAdded+3
results/per_query/bge-m3/zalo-legal__L512-fp16.csv.gzAdded+3
results/per_query/embeddinggemma-2/arguana-vn__L512-fp32.csv.gzAdded+3
results/per_query/embeddinggemma-2/arguana__L512-fp32.csv.gzAdded+3
results/per_query/embeddinggemma-2/belebele-vie__L512.csv.gzAdded+3
results/per_query/embeddinggemma-2/fiqa-vn__L512-fp16.csv.gzAdded+3
results/per_query/embeddinggemma-2/fiqa-vn__L512-fp32.csv.gzAdded+3
results/per_query/embeddinggemma-2/fiqa__L512-fp32.csv.gzAdded+3
results/per_query/embeddinggemma-2/mlqa-vie__L512.csv.gzAdded+3