Download code/harness/smoke.py from quocbao747/embedding-model-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 5.31 kB
-
https://huggingface.co/quocbao747/embedding-model-benchmark/resolve/main/code/harness/smoke.py
- Command line
-
hf download hf://quocbao747/embedding-model-benchmark/code/harness/smoke.py
-
curl -L -o smoke.py https://huggingface.co/quocbao747/embedding-model-benchmark/resolve/main/code/harness/smoke.py
5.31 kB
| """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, os | |
| T0 = time.time() | |
| import numpy as np, torch | |
| import zoo, data | |
| OUT = os.path.expanduser(os.environ.get("SMOKE_OUT", "~/embed/results/smoke.jsonl")) | |
| TASKS = data.TIER1 + data.TIER2 | |
| 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."), | |
| ] | |
| # 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) | |