File size: 5,469 Bytes
36d9039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
"""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%}")