File size: 12,687 Bytes
36d9039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281aff2
36d9039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe20926
 
 
36d9039
 
fe20926
 
 
 
 
 
36d9039
fe20926
 
 
36d9039
fe20926
 
 
 
 
 
 
 
 
 
 
 
 
 
36d9039
 
 
 
 
 
 
 
 
 
 
 
 
 
281aff2
 
 
 
 
 
 
 
 
 
 
 
 
 
36d9039
281aff2
 
36d9039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4342a6b
 
36d9039
 
 
 
4342a6b
 
 
 
36d9039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4342a6b
36d9039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281aff2
 
 
 
36d9039
281aff2
 
 
 
 
36d9039
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
"""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, traceback
from pathlib import Path
import numpy as np, torch, pytrec_eval
import 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 = 100
LOG = 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 j.get("id") or 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, budget=1.5 * 2**30):
    """Exact MaxSim over the whole corpus. Docs are streamed to the GPU in length-sorted chunks of 256 (each moved once);
    queries stay on the GPU in length-sorted blocks of 64; the [bq, Lq, nd, Ld] score tensor is split to stay under budget."""
    dev = "cuda"
    nq = len(Qv)
    qord = np.argsort([v.shape[0] for v in Qv])
    qblocks = []
    for c in range(0, nq, 64):
        ids = qord[c:c + 64]
        Xq, Mq = _pad([Qv[i] for i in ids], dev)
        qblocks.append((torch.as_tensor(ids, device=dev), Xq, Mq))
    best_s = torch.full((nq, K + 1), -1e9, device=dev); best_i = torch.zeros((nq, K + 1), dtype=torch.long, device=dev)
    dord = np.argsort([v.shape[0] for v in Dv])
    for c in range(0, len(dord), 256):
        ids = dord[c:c + 256]
        X, M = _pad([Dv[i] for i in ids], dev)
        dids = torch.as_tensor(ids, device=dev)
        for qids, Xq, Mq in qblocks:
            bq, Lq = Xq.shape[:2]
            step = max(1, int(budget // (bq * Lq * X.shape[1] * 6)))  # bf16 einsum out + fp32 copy
            parts = []
            for s0 in range(0, X.shape[0], step):
                s = torch.einsum("qid,njd->qinj", Xq, X[s0:s0 + step]).float()  # [bq, Lq, n, Ld]
                s = s.masked_fill(~M[s0:s0 + step][None, None], -1e4).amax(-1)  # [bq, Lq, n]
                parts.append((s * Mq[:, :, None]).sum(1))  # [bq, n]
            S = torch.cat([best_s[qids]] + parts, 1)
            I = torch.cat([best_i[qids], dids[None].expand(bq, -1)], 1)
            v, ix = S.topk(K + 1, dim=1)
            best_s[qids] = v; best_i[qids] = torch.gather(I, 1, ix)
        del X, M
    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_shard(enc, j):
    """Document-chunk job (option A): encode corpus[start:end] (or all queries) and save fp16 embeddings for a later merge."""
    corpus, queries, _ = data.load_task(j["task"])
    d = R / "shards" / j["model"] / j["task"].replace(":", "_"); d.mkdir(parents=True, exist_ok=True)
    t = time.time()
    if j["shard"] == "q":
        E = enc.encode_queries([q["text"] for q in queries], j["task"]); f = d / "queries.npy"
    else:
        E = enc.encode_docs(corpus[j["start"]:j["end"]]); f = d / f"docs_{j['start']:07d}.npy"
    tmp = f.with_suffix(".tmp.npy"); np.save(tmp, np.asarray(E, dtype=np.float32).astype(np.float16)); tmp.rename(f)
    log(f"SHARD {jid(j)} n={len(E)} {time.time()-t:.0f}s nan={int(np.isnan(E).any(1).sum())}")
    return []


def run_job(enc, j):
    if j.get("shard") is not None:
        return run_shard(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 in ("multivec", "vintern"):
        variants = [(128, norm_slice(Qe, 128), norm_slice(De, 128))] if enc.kind == "multivec" else [(Qe[0].shape[1], Qe, De)]
        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
            r_ = to_run(S, I, qids, dids)
            if dim == variants[0][0]:
                run = r_  # main variant: its top-10 is saved below
            results.append({**base, "dim": dim, "score_s": ts, **evaluate(qrels, r_)})
            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" or enc.key.startswith("vintern")) 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)
            if res:
                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()))
            if res:
                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)")
            else:
                log(f"DONE {name} (shard) ({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()