File size: 29,151 Bytes
5f3280f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
#!/opt/pytorch/bin/python
"""Zero-shot embedding-model evaluation for AMLC 2026 business entity resolution.

Builds an S1 -> (S2 u S3) retrieval eval set per country from the labelled train
data, encodes it with candidate encoders on the GPU (no fine-tuning), and reports
recall@K / MRR / hard-negative AUC, recall@20 per pair category, a z-scored
cosine ensemble plus top-K union of two models, and name-only text variants.

Run on the GPU box:
    /opt/pytorch/bin/python embed_eval.py            # full run
    /opt/pytorch/bin/python embed_eval.py --smoke    # tiny eval set, no S3 upload
    /opt/pytorch/bin/python embed_eval.py --models bge-m3,qwen3-4b
Embeddings are cached per model/variant, so a rerun after a Spot interruption
only re-encodes what is missing.
"""
import os
import sys
import gc
import json
import time
import argparse
import datetime
import subprocess
import traceback

os.environ.setdefault("HF_HOME", "/opt/dlami/nvme/hf")
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")

import numpy as np
import pandas as pd
import duckdb
import torch
import torch.nn.functional as F
from sklearn.metrics import roc_auc_score

BASE = os.environ.get("AMLC_BASE", "/opt/dlami/nvme/amlc")
DB = f"{BASE}/amlc.duckdb"
AUDIT = f"{BASE}/parquet/pair_audit.parquet"
S3 = "s3://amlc-2026-478982785786/ckpt/embed_eval/"
COUNTRIES = ["US", "India"]
SEED = 42
KS = [1, 5, 20, 50]
MAX_SEQ = 64
CATS = ["indic_name", "domain_form", "former_form", "rename", "addr_empty", "other"]
CAT_DESC = {"rename": "rename (name_j=0)", "other": "other (none of the flags)"}
QWEN_INST = ("Instruct: Given a business name and address, retrieve records of the "
             "same business entity\nQuery:")

MODELS = {
    # key: hf id, dtype, batch, query prompt, document prompt, extra variants
    "bge-m3": dict(hf="BAAI/bge-m3", dtype="float16", bs=256,
                   q_prompt=None, d_prompt=None, name_variant=True),
    "e5-large": dict(hf="intfloat/multilingual-e5-large", dtype="float16", bs=256,
                     q_prompt="query: ", d_prompt="query: "),
    "qwen3-0.6b": dict(hf="Qwen/Qwen3-Embedding-0.6B", dtype="bfloat16", bs=128,
                       q_prompt_name="query", d_prompt=None, left_pad=True, inst_variant=True),
    # bs=64 measured faster than 128/256 on the power-capped (72 W) L4
    "qwen3-4b": dict(hf="Qwen/Qwen3-Embedding-4B", dtype="bfloat16", bs=64,
                     q_prompt_name="query", d_prompt=None, left_pad=True,
                     name_variant=True, inst_variant=True),
    # contrastively fine-tuned e5-large (hf_jobs/train_e5_ft.py; private repo, loaded with HF_TOKEN)
    "e5-ft": dict(hf=os.environ.get("FT_MODEL", "Arushhh/amlc-e5-ft"), dtype="float16", bs=256,
                  q_prompt="query: ", d_prompt="query: "),
}
ENS = ("bge-m3", "qwen3-4b")


def log(*a):
    print(f"[{datetime.datetime.now():%H:%M:%S}]", *a, flush=True)


class Cfg:
    n_q = 6000
    n_dist = 120000
    suffix = ""
    upload = True


def path(name):
    stem, ext = os.path.splitext(name)
    return f"{BASE}/{stem}{Cfg.suffix}{ext}"


def cache_path(key, variant):
    return f"{BASE}/embed_eval_cache{Cfg.suffix}/{key}__{variant}.npy"


def s3_put(p, sub="", wait=True):
    if not Cfg.upload:
        return None
    cmd = ["aws", "s3", "cp", p, S3 + sub + os.path.basename(p), "--only-show-errors"]
    if not wait:
        return subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
    try:
        r = subprocess.run(cmd, capture_output=True, text=True, timeout=900)
        if r.returncode != 0:
            log("S3 upload failed", p, r.stderr[-500:])
    except Exception as e:  # never let an upload kill the run
        log("S3 upload error", p, repr(e))
    return None


# --------------------------------------------------------------------------- eval set
def build_eval_set(rebuild=False):
    pq = path("parquet/embed_eval_set.parquet")
    if os.path.exists(pq) and not rebuild:
        log("loading eval set", pq)
        return pd.read_parquet(pq)
    t0 = time.time()
    con = duckdb.connect(DB, read_only=True)
    con.execute("SET memory_limit='16GB'")
    con.execute(f"SET temp_directory='{BASE}/duck_tmp'")
    parts = []
    for c in COUNTRIES:
        q = con.execute(
            """SELECT s1.entity_id, s1.business_name, s1.business_address, s1.country, 'S1' AS src
               FROM s1 SEMI JOIN pairs p ON p.a = s1.entity_id
               WHERE s1.country = ?
               ORDER BY hash(s1.entity_id || ?) LIMIT ?""",
            [c, f"q{SEED}", Cfg.n_q]).df()
        q["role"] = "query"
        q["match_of"] = None
        con.register("qids", q[["entity_id"]])
        m = con.execute(
            """SELECT s.entity_id, s.business_name, s.business_address, s.country, s.src,
                      p.a AS match_of
               FROM pairs p JOIN qids ON p.a = qids.entity_id
               JOIN s23 s ON s.entity_id = p.b""").df()
        m["role"] = "match"
        con.register("mids", m[["entity_id"]])
        d = con.execute(
            """SELECT s.entity_id, s.business_name, s.business_address, s.country, s.src
               FROM s23 s ANTI JOIN mids ON s.entity_id = mids.entity_id
               WHERE s.country = ?
               ORDER BY hash(s.entity_id || ?) LIMIT ?""",
            [c, f"d{SEED}", Cfg.n_dist]).df()
        d["role"] = "distractor"
        d["match_of"] = None
        con.unregister("qids")
        con.unregister("mids")
        part = pd.concat([q, m, d], ignore_index=True)
        part["eval_country"] = c
        parts.append(part)
        log(f"eval set {c}: {len(q)} queries, {len(m)} true matches, {len(d)} distractors")
    ev = pd.concat(parts, ignore_index=True)

    # pair categories from pair_audit (matches only; b is unique across pairs)
    mm = ev.loc[ev.role == "match", ["match_of", "entity_id"]]
    con.register("mm", mm)
    aud = con.execute(
        f"""SELECT a.a AS match_of, a.b AS entity_id, a.name_j, a.addr_j,
                   a.indic_name, a.domain_form, a.former_form, a.addr_empty
            FROM read_parquet('{AUDIT}') a
            JOIN mm ON a.a = mm.match_of AND a.b = mm.entity_id""").df()
    con.close()
    flags = ["indic_name", "domain_form", "former_form", "addr_empty"]
    is_m = (ev.role == "match").to_numpy()
    mdf = ev.loc[is_m, ["match_of", "entity_id"]].merge(aud, on=["match_of", "entity_id"], how="left")
    n_missing = int(mdf.name_j.isna().sum() + 0)
    if n_missing:
        log(f"WARNING: {n_missing} matches missing from pair_audit (treated as no flags)")
    ev["name_j"] = np.nan
    ev["addr_j"] = np.nan
    ev.loc[is_m, "name_j"] = mdf.name_j.to_numpy()
    ev.loc[is_m, "addr_j"] = mdf.addr_j.to_numpy()
    for f in flags:
        ev[f] = False
        ev.loc[is_m, f] = mdf[f].fillna(False).astype(bool).to_numpy()
    ev["rename"] = is_m & (ev.name_j == 0).to_numpy()
    anyflag = ev[flags + ["rename"]].any(axis=1).to_numpy()
    ev["other"] = is_m & ~anyflag

    name = ev.business_name.fillna("").astype(str).str.strip()
    addr = ev.business_address.fillna("").astype(str).str.strip()
    ev["text_name"] = name
    ev["text_full"] = np.where(addr.str.len() > 0, name + " | " + addr, name)
    pq_dir = os.path.dirname(pq)
    os.makedirs(pq_dir, exist_ok=True)
    ev.to_parquet(pq, index=False)
    log(f"eval set built in {time.time() - t0:.1f}s -> {pq} ({len(ev)} rows)")
    s3_put(pq)
    return ev


def country_index(ev):
    CI = {}
    role = ev.role.to_numpy()
    ctry = ev.eval_country.to_numpy()
    eid = ev.entity_id.to_numpy()
    for c in COUNTRIES:
        qrows = np.nonzero((ctry == c) & (role == "query"))[0]
        prows = np.nonzero((ctry == c) & (role != "query"))[0]
        qpos = {e: i for i, e in enumerate(eid[qrows])}
        pool = ev.iloc[prows]
        pair_p = np.nonzero((pool.role == "match").to_numpy())[0]
        pair_q = np.array([qpos[a] for a in pool.match_of.to_numpy()[pair_p]], dtype=np.int64)
        o = np.argsort(pair_q, kind="stable")
        pair_q, pair_p = pair_q[o], pair_p[o]
        cats = {k: pool[k].to_numpy()[pair_p].astype(bool) for k in CATS}
        CI[c] = dict(qrows=qrows, prows=prows, pair_q=pair_q, pair_p=pair_p, cats=cats)
        log(f"{c}: {len(qrows)} queries, pool {len(prows)}, {len(pair_p)} true pairs, "
            + ", ".join(f"{k}={int(v.sum())}" for k, v in cats.items()))
    return CI


# --------------------------------------------------------------------------- encoding
def load_model(cfg):
    from sentence_transformers import SentenceTransformer
    dt = getattr(torch, cfg["dtype"])
    kw = dict(device="cuda", model_kwargs={"dtype": dt})
    if cfg.get("left_pad"):
        kw["processor_kwargs"] = {"padding_side": "left"}
    t0 = time.time()
    try:
        m = SentenceTransformer(cfg["hf"], **kw)
    except TypeError:
        kw.pop("processor_kwargs", None)
        try:
            m = SentenceTransformer(cfg["hf"], **kw)
        except TypeError:  # older transformers only know torch_dtype
            kw["model_kwargs"] = {"torch_dtype": dt}
            m = SentenceTransformer(cfg["hf"], **kw)
    if next(m.parameters()).dtype != dt:
        m = m.to(dt)
    if cfg.get("left_pad"):
        try:
            m.tokenizer.padding_side = "left"
        except Exception as e:
            log("could not set padding_side on tokenizer:", repr(e))
    m.max_seq_length = MAX_SEQ
    m.eval()
    return m, time.time() - t0


def encode(m, texts, bs, prompt=None, prompt_name=None, tag=""):
    n = len(texts)
    order = np.argsort(-np.fromiter((len(t) for t in texts), dtype=np.int64, count=n), kind="stable")
    out = None
    CH = 16384
    torch.cuda.synchronize()
    t0 = time.time()
    for s in range(0, n, CH):
        idx = order[s:s + CH]
        with torch.inference_mode():
            e = m.encode([texts[i] for i in idx], batch_size=bs, prompt=prompt,
                         prompt_name=prompt_name, normalize_embeddings=True,
                         convert_to_tensor=True, show_progress_bar=False)
        e = e.float().cpu().numpy().astype(np.float16)
        if out is None:
            out = np.empty((n, e.shape[1]), dtype=np.float16)
        out[idx] = e
        el = time.time() - t0
        done = min(n, s + CH)
        log(f"  {tag}: {done}/{n} encoded, {el:.0f}s, {done / el:.0f} rec/s")
    torch.cuda.synchronize()
    return out, time.time() - t0


def trunc_rate(m, texts, prompt):
    tok = m.tokenizer
    pre = prompt or ""
    ids = tok([pre + t for t in texts], add_special_tokens=True, truncation=False)["input_ids"]
    lens = np.array([len(x) for x in ids])
    return float((lens > MAX_SEQ).mean()), float(np.median(lens)), float(np.percentile(lens, 95))


def encode_model(key, ev, R, prev):
    cfg = MODELS[key]
    variants = ["full"] + (["name"] if cfg.get("name_variant") else [])
    if cfg.get("inst_variant"):
        variants.append("qinst")
    todo = [v for v in variants if not os.path.exists(cache_path(key, v))]
    if not todo:
        log(f"{key}: all embeddings cached")
        if key in prev.get("throughput", {}):
            R["throughput"][key] = prev["throughput"][key]
        return
    os.makedirs(os.path.dirname(cache_path(key, "x")), exist_ok=True)
    log(f"{key}: loading {cfg['hf']} ({cfg['dtype']})")
    torch.cuda.reset_peak_memory_stats()
    m, load_s = load_model(cfg)
    q_prompt = cfg.get("q_prompt")
    if cfg.get("q_prompt_name"):
        q_prompt = m.prompts.get(cfg["q_prompt_name"])
        if q_prompt is None:
            raise RuntimeError(f"prompt '{cfg['q_prompt_name']}' missing in {cfg['hf']}")
    d_prompt = cfg.get("d_prompt")
    log(f"{key}: loaded in {load_s:.1f}s; q_prompt={q_prompt!r} d_prompt={d_prompt!r}; "
        f"param dtype={next(m.parameters()).dtype}; max_seq_length={m.max_seq_length}")
    tp = R["throughput"].setdefault(key, {})
    tp.update(hf=cfg["hf"], dtype=cfg["dtype"], batch=cfg["bs"], max_seq=MAX_SEQ,
              load_s=round(load_s, 1), q_prompt=q_prompt, d_prompt=d_prompt)
    is_q = (ev.role == "query").to_numpy()
    tf = ev.text_full.to_numpy()
    rng = np.random.default_rng(SEED)
    tr = {}
    for c in COUNTRIES:
        in_c = (ev.eval_country == c).to_numpy()
        prow = np.nonzero(in_c & ~is_q)[0]
        qrow = np.nonzero(in_c & is_q)[0]
        prow = rng.choice(prow, size=min(20000, len(prow)), replace=False)
        qrow = rng.choice(qrow, size=min(3000, len(qrow)), replace=False)
        dr = trunc_rate(m, tf[prow].tolist(), d_prompt)
        qr = trunc_rate(m, tf[qrow].tolist(), q_prompt)
        tr[c] = dict(pool_trunc=round(dr[0], 4), pool_med_tok=dr[1], pool_p95_tok=dr[2],
                     query_trunc=round(qr[0], 4), query_med_tok=qr[1], query_p95_tok=qr[2])
    tp["tokens"] = tr
    log(f"{key}: token stats {tr}")

    for v in todo:
        cp = cache_path(key, v)
        if v == "qinst":
            texts = ev.text_full.to_numpy()[is_q].tolist()
            emb, sec = encode(m, texts, cfg["bs"], prompt=QWEN_INST, tag=f"{key}/qinst")
        else:
            col = ev["text_" + v].to_numpy()
            if q_prompt == d_prompt:
                emb, sec = encode(m, col.tolist(), cfg["bs"], prompt=q_prompt, tag=f"{key}/{v}")
            else:
                eq, s1 = encode(m, col[is_q].tolist(), cfg["bs"], prompt=q_prompt, tag=f"{key}/{v}/query")
                ed, s2 = encode(m, col[~is_q].tolist(), cfg["bs"], prompt=d_prompt, tag=f"{key}/{v}/pool")
                emb = np.empty((len(col), eq.shape[1]), dtype=np.float16)
                emb[is_q] = eq
                emb[~is_q] = ed
                sec = s1 + s2
        n = emb.shape[0]
        tp[v] = dict(n=n, sec=round(sec, 1), rps=round(n / sec, 1))
        log(f"{key}/{v}: {n} texts in {sec:.1f}s = {n / sec:.0f} rec/s, dim={emb.shape[1]}")
        np.save(cp + ".tmp.npy", emb)
        os.replace(cp + ".tmp.npy", cp)
        s3_put(cp, sub="cache/", wait=False)
    tp["peak_mem_gb"] = round(torch.cuda.max_memory_allocated() / 1e9, 2)
    del m
    gc.collect()
    torch.cuda.empty_cache()


# --------------------------------------------------------------------------- evaluation
def to_gpu(a):
    return F.normalize(torch.from_numpy(np.ascontiguousarray(a)).cuda().float(), dim=1)


@torch.no_grad()
def rank_eval(score_fn, nq, ci, want_stats=False, chunk=512):
    pair_q, pair_p = ci["pair_q"], ci["pair_p"]
    npairs = len(pair_q)
    ranks = np.empty(npairs, dtype=np.float64)  # mid-rank on ties
    tsc = np.empty(npairs, dtype=np.float32)
    top = np.empty((nq, 50), dtype=np.int32)
    hard = np.empty((nq, 20), dtype=np.float32)
    pq_t = torch.from_numpy(pair_q).cuda()
    pp_t = torch.from_numpy(pair_p).cuda()
    s_sum = s_sq = 0.0
    n_el = 0
    for s in range(0, nq, chunk):
        e = min(nq, s + chunk)
        S = score_fn(s, e)
        if want_stats:
            s_sum += S.sum(dtype=torch.float64).item()
            s_sq += (S.double() ** 2).sum().item()
            n_el += S.numel()
        lo, hi = np.searchsorted(pair_q, [s, e])
        r = pq_t[lo:hi] - s
        cidx = pp_t[lo:hi]
        t = S[r, cidx]
        for b in range(0, hi - lo, 256):
            rb, tb = r[b:b + 256], t[b:b + 256]
            Sb = S[rb]
            gt = (Sb > tb[:, None]).sum(1).double()
            eq = (Sb == tb[:, None]).sum(1).double()  # includes the pair itself
            ranks[lo + b: lo + b + len(rb)] = (gt + 1 + (eq - 1) / 2).cpu().numpy()
            del Sb
        tsc[lo:hi] = t.cpu().numpy()
        top[s:e] = S.topk(50, dim=1).indices.cpu().numpy()
        S[r, cidx] = -float("inf")
        hard[s:e] = S.topk(20, dim=1).values.cpu().numpy()
        del S
    stats = None
    if want_stats:
        mu = s_sum / n_el
        stats = (mu, float(np.sqrt(max(s_sq / n_el - mu * mu, 1e-12))))
    return ranks, tsc, hard, top, stats


def summarize(ranks, tsc, hard, ci, nq):
    m = {f"R@{k}": float((ranks <= k).mean()) for k in KS}
    best = np.full(nq, np.inf)
    np.minimum.at(best, ci["pair_q"], ranks)
    m["Hit@1"] = float((best <= 1).mean())
    m["R@1_ceiling"] = float(nq / len(ranks))
    m["MRR"] = float((1.0 / best).mean())
    m["MRR_pair"] = float((1.0 / ranks).mean())
    y = np.r_[np.ones(len(tsc)), np.zeros(hard.size)]
    m["AUC_hard20"] = float(roc_auc_score(y, np.r_[tsc, hard.ravel()]))
    m["n_queries"] = int(nq)
    m["n_pairs"] = int(len(ranks))
    m["cat_R@20"] = {k: {"n": int(v.sum()), "R@20": (float((ranks[v] <= 20).mean()) if v.any() else None)}
                     for k, v in ci["cats"].items()}
    return m


STATE = {}  # (label, country) -> dict(top=..., stats=...)


def eval_single(label, key, variant, ev, CI, R):
    E = np.load(cache_path(key, "full" if variant == "qinst" else variant), mmap_mode="r")
    Eq_inst = None
    if variant == "qinst":
        Eq_inst = np.load(cache_path(key, "qinst"))
        qall = np.nonzero((ev.role == "query").to_numpy())[0]
    R["metrics"].setdefault(label, {})
    for c in COUNTRIES:
        ci = CI[c]
        if Eq_inst is not None:
            Q = to_gpu(Eq_inst[np.searchsorted(qall, ci["qrows"])])
        else:
            Q = to_gpu(E[ci["qrows"]])
        P = to_gpu(E[ci["prows"]])
        t0 = time.time()
        ranks, tsc, hard, top, stats = rank_eval(lambda s, e: Q[s:e] @ P.T, len(ci["qrows"]), ci, want_stats=True)
        m = summarize(ranks, tsc, hard, ci, len(ci["qrows"]))
        m["cos_mean"], m["cos_std"] = stats
        m["eval_s"] = round(time.time() - t0, 1)
        R["metrics"][label][c] = m
        STATE[(label, c)] = dict(top=top, stats=stats)
        log(f"{label} {c}: " + " ".join(f"{k}={m[k]:.4f}" for k in ["R@1", "R@5", "R@20", "R@50", "Hit@1", "MRR", "AUC_hard20"])
            + f" ({m['eval_s']}s)")
        del Q, P
        torch.cuda.empty_cache()


def eval_ensemble(variant, ev, CI, R):
    a, b = ENS
    la, lb = label_for(a, variant), label_for(b, variant)
    if any((l, c) not in STATE for l in (la, lb) for c in COUNTRIES):
        log(f"ensemble {variant}: missing inputs, skipped")
        return
    Ea = np.load(cache_path(a, variant), mmap_mode="r")
    Eb = np.load(cache_path(b, variant), mmap_mode="r")
    lz = f"ens-z({a}+{b})" + ("" if variant == "full" else f" [{variant}]")
    lu = f"union({a}|{b})" + ("" if variant == "full" else f" [{variant}]")
    R["metrics"].setdefault(lz, {})
    R["union"].setdefault(lu, {})
    for c in COUNTRIES:
        ci = CI[c]
        nq = len(ci["qrows"])
        Qa, Pa = to_gpu(Ea[ci["qrows"]]), to_gpu(Ea[ci["prows"]])
        Qb, Pb = to_gpu(Eb[ci["qrows"]]), to_gpu(Eb[ci["prows"]])
        ma, sa = STATE[(la, c)]["stats"]
        mb, sb = STATE[(lb, c)]["stats"]
        fn = lambda s, e: 0.5 * ((Qa[s:e] @ Pa.T - ma) / sa + (Qb[s:e] @ Pb.T - mb) / sb)
        ranks, tsc, hard, top, _ = rank_eval(fn, nq, ci)
        m = summarize(ranks, tsc, hard, ci, nq)
        R["metrics"][lz][c] = m
        log(f"{lz} {c}: " + " ".join(f"{k}={m[k]:.4f}" for k in ["R@1", "R@5", "R@20", "R@50", "Hit@1", "MRR", "AUC_hard20"]))
        del Qa, Pa, Qb, Pb
        torch.cuda.empty_cache()
        # union of each model's top-K
        ta, tb = STATE[(la, c)]["top"], STATE[(lb, c)]["top"]
        pq, pp = ci["pair_q"], ci["pair_p"]
        u = {}
        for K in KS:
            ina = (ta[pq, :K] == pp[:, None]).any(1)
            inb = (tb[pq, :K] == pp[:, None]).any(1)
            hit = ina | inb
            srt = np.sort(np.hstack([ta[:, :K], tb[:, :K]]), axis=1)
            size = 1 + (np.diff(srt, axis=1) != 0).sum(1)
            u[f"K={K}"] = dict(recall=float(hit.mean()), mean_cands=float(size.mean()),
                               only_a=float((ina & ~inb).mean()), only_b=float((inb & ~ina).mean()))
            if K == 20:
                u["cat_R@20"] = {k: {"n": int(v.sum()), "R@20": (float(hit[v].mean()) if v.any() else None)}
                                 for k, v in ci["cats"].items()}
        R["union"][lu][c] = u
        log(f"{lu} {c}: " + " ".join(f"{k}:{v['recall']:.4f}/{v['mean_cands']:.1f}c" for k, v in u.items() if k.startswith("K=")))


def label_for(key, variant):
    return key if variant == "full" else (f"{key} +inst" if variant == "qinst" else f"{key} [{variant}]")


# --------------------------------------------------------------------------- reporting
def fmt_tables(R):
    L = []
    add = L.append
    meta = R["meta"]
    add(f"AMLC 2026 zero-shot embedding eval — started {meta['started']}, "
        f"{'finished ' + meta['finished'] if meta.get('finished') else 'PARTIAL'}")
    add(f"GPU: {meta['gpu']} | torch {meta['torch']} | transformers {meta['transformers']} | "
        f"sentence-transformers {meta['st']} | max_seq_length={MAX_SEQ}")
    add("Eval set: per country, S1 queries with >=1 labelled match; pool = all their true S2/S3 matches "
        "+ random same-country S2/S3 distractors (seeded hash sample). Text = name | address.")
    for c, s in R.get("eval_set", {}).items():
        add(f"  {c}: {s['queries']} queries, {s['pairs']} true pairs, pool {s['pool']} "
            f"({s['distractors']} distractors)")
    add("Metrics: R@K = share of true pairs ranked in the top K of the pool for their S1 (pair-level; "
        "R@1 is capped at n_queries/n_pairs because an S1 has ~3.7 matches but one rank-1 slot); "
        "Hit@1 = share of S1 whose top-1 is a true match; MRR = mean over S1 of 1/rank of its best-ranked "
        "true match; MRRp = mean over pairs of 1/rank; AUC = ROC-AUC of cosine, true pairs vs each S1's "
        "top-20 non-matches (hard negatives). Ties get the mid-rank.")
    add("")

    add("== Throughput on L4 (full text; query side with prompt + pool side) ==")
    hdr = f"{'model':<12} {'dtype':<9} {'bs':>4} {'load s':>7} {'texts':>8} {'enc s':>8} {'rec/s':>8} " \
          f"{'name rec/s':>10} {'peak GB':>8}  {'trunc>64 pool/query US':>23}  {'trunc>64 pool/query IN':>23}"
    add(hdr)
    for k, t in R["throughput"].items():
        full = t.get("full", {})
        nm = t.get("name", {})
        tok = t.get("tokens", {})

        def tr(c):
            d = tok.get(c)
            return f"{d['pool_trunc']:.1%} / {d['query_trunc']:.1%}" if d else "-"

        add(f"{k:<12} {t.get('dtype', ''):<9} {t.get('batch', ''):>4} {t.get('load_s', ''):>7} "
            f"{full.get('n', ''):>8} {full.get('sec', ''):>8} {full.get('rps', ''):>8} {nm.get('rps', '-'):>10} "
            f"{t.get('peak_mem_gb', ''):>8}  {tr('US'):>23}  {tr('India'):>23}")
    add("")

    for c in COUNTRIES:
        add(f"== Retrieval metrics — {c} ==")
        cap = next((per[c]["R@1_ceiling"] for per in R["metrics"].values() if c in per), None)
        if cap is not None:
            add(f"(R@1 ceiling = {cap:.4f})")
        add(f"{'variant':<36} {'R@1':>7} {'R@5':>7} {'R@20':>7} {'R@50':>7} {'Hit@1':>7} {'MRR':>7} {'MRRp':>7} {'AUC':>7}")
        for lab, per in R["metrics"].items():
            if c not in per:
                continue
            m = per[c]
            add(f"{lab:<36} {m['R@1']:>7.4f} {m['R@5']:>7.4f} {m['R@20']:>7.4f} {m['R@50']:>7.4f} "
                f"{m['Hit@1']:>7.4f} {m['MRR']:>7.4f} {m['MRR_pair']:>7.4f} {m['AUC_hard20']:>7.4f}")
        add("")

    if R["union"]:
        add("== Union of each model's top-K (recall of true pairs / mean candidate count per S1) ==")
        for c in COUNTRIES:
            add(f"-- {c}")
            add(f"{'variant':<36} " + " ".join(f"{'K=' + str(k) + ' rec':>10} {'cands':>6}" for k in KS)
                + f" {'onlyA@20':>9} {'onlyB@20':>9}")
            for lab, per in R["union"].items():
                if c not in per:
                    continue
                u = per[c]
                add(f"{lab:<36} " + " ".join(f"{u[f'K={k}']['recall']:>10.4f} {u[f'K={k}']['mean_cands']:>6.1f}" for k in KS)
                    + f" {u['K=20']['only_a']:>9.4f} {u['K=20']['only_b']:>9.4f}")
        add("  (onlyA/onlyB = share of true pairs found in the top-20 of only the first / only the second model)")
        add("")

    for c in COUNTRIES:
        add(f"== Recall@20 by pair category — {c} (categories overlap; 'other' = none of the flags) ==")
        ns = None
        for per in R["metrics"].values():
            if c in per:
                ns = {k: v["n"] for k, v in per[c]["cat_R@20"].items()}
                break
        if ns is None:
            continue
        add(f"{'variant':<36} {'all':>7} " + " ".join(f"{k[:12]:>12}" for k in CATS))
        add(f"{'(n pairs)':<36} {'':>7} " + " ".join(f"{ns[k]:>12}" for k in CATS))
        rows = [(lab, per[c]["R@20"], per[c]["cat_R@20"]) for lab, per in R["metrics"].items() if c in per]
        rows += [(lab + " @20", per[c]["K=20"]["recall"], per[c]["cat_R@20"]) for lab, per in R["union"].items() if c in per]
        for lab, allr, cr in rows:
            add(f"{lab:<36} {allr:>7.4f} " + " ".join(
                (f"{cr[k]['R@20']:>12.4f}" if cr[k]["R@20"] is not None else f"{'-':>12}") for k in CATS))
        add("")

    add("== Name-only vs name|address text, Recall@20 ==")
    add(f"{'model':<36} {'US full':>8} {'US name':>8} {'IN full':>8} {'IN name':>8}")
    for base in list(ENS) + [f"ens-z({ENS[0]}+{ENS[1]})"]:
        full = R["metrics"].get(base, {})
        nm = R["metrics"].get(f"{base} [name]", {})
        if not full and not nm:
            continue
        g = lambda d, c: (f"{d[c]['R@20']:.4f}" if c in d else "-")
        add(f"{base:<36} {g(full,'US'):>8} {g(nm,'US'):>8} {g(full,'India'):>8} {g(nm,'India'):>8}")
    add("")
    if R["failures"]:
        add("== Failures ==")
        for k, v in R["failures"].items():
            add(f"{k}: {v}")
        add("")
    return "\n".join(L)


def save(R):
    jp, tp = path("embed_eval_results.json"), path("embed_eval_results.txt")
    with open(jp + ".tmp", "w") as f:
        json.dump(R, f, indent=1, default=float)
    os.replace(jp + ".tmp", jp)
    txt = fmt_tables(R)
    with open(tp, "w") as f:
        f.write(txt + "\n")
    s3_put(jp)
    s3_put(tp)
    return txt


# --------------------------------------------------------------------------- main
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--models", default=",".join(MODELS))
    ap.add_argument("--smoke", action="store_true")
    ap.add_argument("--rebuild", action="store_true")
    ap.add_argument("--no-upload", action="store_true")
    args = ap.parse_args()
    if args.smoke:
        Cfg.n_q, Cfg.n_dist, Cfg.suffix, Cfg.upload = 300, 4000, "_smoke", False
    if args.no_upload:
        Cfg.upload = False
    keys = [k for k in args.models.split(",") if k]
    import transformers
    import sentence_transformers
    prev = {}
    if os.path.exists(path("embed_eval_results.json")):
        try:
            prev = json.load(open(path("embed_eval_results.json")))
        except Exception:
            prev = {}
    R = dict(meta=dict(started=f"{datetime.datetime.now():%Y-%m-%d %H:%M:%S}", finished=None,
                       gpu=torch.cuda.get_device_name(0), torch=torch.__version__,
                       transformers=transformers.__version__, st=sentence_transformers.__version__,
                       n_q=Cfg.n_q, n_dist=Cfg.n_dist, seed=SEED, max_seq=MAX_SEQ, qwen_inst=QWEN_INST),
             eval_set={}, throughput={}, metrics={}, union={}, failures={})
    log("config", R["meta"])
    ev = build_eval_set(args.rebuild)
    CI = country_index(ev)
    for c in COUNTRIES:
        ci = CI[c]
        R["eval_set"][c] = dict(queries=len(ci["qrows"]), pairs=len(ci["pair_p"]), pool=len(ci["prows"]),
                                distractors=len(ci["prows"]) - len(ci["pair_p"]),
                                cats={k: int(v.sum()) for k, v in ci["cats"].items()})
    save(R)

    for key in keys:
        cfg = MODELS[key]
        try:
            encode_model(key, ev, R, prev)
        except Exception as e:
            log(f"{key}: ENCODE FAILED\n{traceback.format_exc()}")
            R["failures"][key] = f"encode/load: {type(e).__name__}: {str(e)[:1500]}"
            gc.collect()
            torch.cuda.empty_cache()
            save(R)
            continue
        variants = ["full"] + (["name"] if cfg.get("name_variant") else []) + (["qinst"] if cfg.get("inst_variant") else [])
        for v in variants:
            try:
                eval_single(label_for(key, v), key, v, ev, CI, R)
            except Exception as e:
                log(f"{key}/{v}: EVAL FAILED\n{traceback.format_exc()}")
                R["failures"][f"{key}/{v}"] = f"eval: {type(e).__name__}: {str(e)[:1500]}"
        txt = save(R)
        log("tables so far:\n" + txt)

    if all(k in keys for k in ENS):
        for v in ["full", "name"]:
            try:
                eval_ensemble(v, ev, CI, R)
            except Exception as e:
                log(f"ensemble/{v}: FAILED\n{traceback.format_exc()}")
                R["failures"][f"ensemble/{v}"] = f"{type(e).__name__}: {str(e)[:1500]}"
    R["meta"]["finished"] = f"{datetime.datetime.now():%Y-%m-%d %H:%M:%S}"
    txt = save(R)
    log("FINAL TABLES:\n" + txt)
    log("EMBED_EVAL_DONE")


if __name__ == "__main__":
    main()