File size: 7,763 Bytes
d231962
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Embed a SINGLE-FIELD text view with e5-small, for the F4 and F5 rescue channels.



WHY SINGLE-FIELD. From the false-negative audit: of the copies that are never retrieved,

78% are outside the fused top-100 of every retriever, worth 0.416 val points. The reason is

structural, not a tuning problem - all three retrievers embed name AND address together, so a

copy whose name was scrambled or whose address was deleted is far away in the joint space

however good the encoder is. The losses line up exactly with that:



    by address: empty 0.172, Indian addresses with no parsable house number 0.138

    by name:    scrambled 0.127, partial 0.108, typo 0.073, native script 0.069



A channel that reads only the surviving field is the only thing that can reach them.



  --view name --side pool --only-empty-address   F4: name-only over the ~265k address-less

                                                 records. Their address is gone, so including

                                                 it is not merely useless, it is noise that

                                                 dominates a short name.

  --view addr                                    F5: address-only over the whole pool, which

                                                 reaches scrambled and partial names sitting

                                                 at a correct address.



The model is the same multilingual-e5-small already used for the main channel, with the same

"query: " prefix, so the output is directly comparable and needs no new download.

"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time

import numpy as np
import pandas as pd

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from berx import paths as P  # noqa: E402

MODEL = "intfloat/multilingual-e5-small"
PREFIX = "query: "


def build_texts(df: pd.DataFrame, view: str) -> list[str]:
    if view == "name":
        src = df["business_name"].astype(str)
    elif view == "addr":
        src = df["business_address"].astype(str)
    else:
        raise ValueError(view)
    # An empty field would embed to whatever the prefix alone embeds to, which is the same
    # point for every such row - a dense cluster of mutually "identical" records. The country
    # keeps them apart and costs nothing.
    cc = df["country"].astype(str)
    return [PREFIX + (s.strip() or "?") + " | " + c for s, c in zip(src, cc)]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--split", default="test")
    ap.add_argument("--view", required=True, choices=["name", "addr"])
    ap.add_argument("--side", required=True, choices=["s1", "pool"])
    ap.add_argument("--out-channel", required=True)
    ap.add_argument("--only-empty-address", action="store_true",
                    help="pool side only: restrict to records with no address (F4)")
    ap.add_argument("--batch", type=int, default=1024)
    ap.add_argument("--max-len", type=int, default=64)
    ap.add_argument("--device", default="cuda")
    a = ap.parse_args()

    import torch
    from transformers import AutoModel, AutoTokenizer

    d = os.path.dirname(P.work("prep", a.split, "_"))
    src = "source1.parquet" if a.side == "s1" else "pool.parquet"
    df = pd.read_parquet(os.path.join(d, src))

    keep = np.arange(len(df))
    if a.only_empty_address:
        assert a.side == "pool", "--only-empty-address applies to the pool side"
        keep = np.flatnonzero((df["business_address"].astype(str).str.strip() == "").to_numpy())
        df = df.iloc[keep].reset_index(drop=True)
        print(f"  restricted to {len(df):,} address-less records "
              f"({len(df)/len(keep) if len(keep) else 0:.0%} of the filter set)")

    texts = build_texts(df, a.view)
    print(f"{a.out_channel}/{a.split}_{a.side}: {len(texts):,} texts, view={a.view}")
    print(f"  e.g. {texts[0][:90]!r}")

    tok = AutoTokenizer.from_pretrained(MODEL)
    model = AutoModel.from_pretrained(MODEL, dtype=torch.float16).eval().to(a.device)

    # Length-sort so a batch pads to its own longest member. On single-field text most rows
    # are very short and the corpus maximum is not representative of anything.
    order = np.argsort([len(t) for t in texts], kind="stable")
    out = np.empty((len(texts), 384), dtype=np.float16)

    # Checkpointing. This is a ~30 minute pass on a card shared with 25 other users, so it
    # will occasionally be killed. The counter is a position in the LENGTH-SORTED order,
    # which is the only order in which completed work forms a contiguous prefix.
    dest_early = os.path.join(P.EMB, a.out_channel, f"{a.split}_{a.side}")
    os.makedirs(dest_early, exist_ok=True)
    ck = os.path.join(dest_early, "partial")
    start = 0
    if os.path.exists(ck + ".json"):
        meta_ck = json.load(open(ck + ".json"))
        if meta_ck.get("n") == len(texts) and meta_ck.get("view") == a.view:
            start = int(meta_ck["done"])
            out = np.load(ck + ".npy")
            print(f"  resuming at {start:,}/{len(texts):,}")
        else:
            print("  checkpoint is for a different input; ignoring")
    t0 = time.time()
    with torch.inference_mode():
        for s in range(start, len(order), a.batch):
            idx = order[s:s + a.batch]
            enc = tok([texts[i] for i in idx], padding=True, truncation=True,
                      max_length=a.max_len, return_tensors="pt").to(a.device)
            h = model(**enc).last_hidden_state
            m = enc["attention_mask"].unsqueeze(-1).to(h.dtype)
            v = (h * m).sum(1) / m.sum(1).clamp(min=1e-6)          # mean pool, as e5 expects
            v = torch.nn.functional.normalize(v.float(), dim=1)
            out[idx] = v.half().cpu().numpy()
            if (s // a.batch) % 200 == 0 and s > start:
                np.save(ck + ".npy", out)
                json.dump({"done": int(s), "n": len(texts), "view": a.view},
                          open(ck + ".json", "w"))
            if (s // a.batch) % 200 == 0:
                done = (s + len(idx)) / len(order)
                el = time.time() - t0
                print(f"    {s+len(idx):>10,}/{len(order):,} ({done:6.1%})  "
                      f"{(s+len(idx))/max(el,1e-9):,.0f} rows/s  "
                      f"eta {el/max(done,1e-9)-el:6.0f}s", flush=True)

    dest = P.emb_dir(a.out_channel, a.split, a.side) \
        if a.out_channel in P.CHANNELS else \
        os.path.join(P.EMB, a.out_channel, f"{a.split}_{a.side}")
    os.makedirs(dest, exist_ok=True)
    np.save(os.path.join(dest, "matrix.npy"), out)
    for ext in (".npy", ".json"):                       # the run finished; drop the partial
        if os.path.exists(ck + ext):
            os.remove(ck + ext)
    with open(os.path.join(dest, "ids.txt"), "w") as fh:
        fh.write("\n".join(df["entity_id"].astype(str)) + "\n")
    # The row->original-index map. F4's pool matrix covers only address-less records, so its
    # row i is NOT pool row i; anything consuming it must remap or every candidate index is
    # wrong. Saving it here is what makes that remap possible at all.
    np.save(os.path.join(dest, "rows.npy"), keep.astype(np.int64))
    json.dump({"model": MODEL, "prefix": PREFIX, "view": a.view, "side": a.side,
               "n": len(df), "dim": 384, "subset": bool(a.only_empty_address),
               "seconds": round(time.time() - t0, 1)},
              open(os.path.join(dest, "meta.json"), "w"), indent=1)
    print(f"  wrote {dest}  {out.shape}  {time.time()-t0:.0f}s")


if __name__ == "__main__":
    main()