Download code/harness-v1/speed.py from quocbao747/embedding-model-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 5.47 kB
-
https://huggingface.co/quocbao747/embedding-model-benchmark/resolve/main/code/harness-v1/speed.py
- Command line
-
hf download hf://quocbao747/embedding-model-benchmark/code/harness-v1/speed.py
-
curl -L -o speed.py https://huggingface.co/quocbao747/embedding-model-benchmark/resolve/main/code/harness-v1/speed.py
5.47 kB
| """Speed sweep: seq-length bucket x batch size, query latency, VRAM, cold load, clocks.""" | |
| import sys, time, json, statistics, gc | |
| T_START = time.time() | |
| import numpy as np, torch | |
| from common import RES, GpuMonitor, append_jsonl, tg | |
| import 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_START | |
| append_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 EN | |
| en_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%}") | |