File size: 9,019 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
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
"""Fix 2: name-only retrieval over address-less pool records, by character TF-IDF.



Reproduced exactly from MODEL5_FALSE_NEGATIVE_FIXES.md s4.2, which is the version that was

measured. Of 16,332 true copies model-4 never retrieved, 7,628 have an empty address, and

this channel recovers them:



    k = 5    3,386 of 7,628 (44%)    2.6% of the channel's candidates are true copies

    k = 10   4,259 (56%)             1.4%

    k = 20   4,906 (64%)             -



k = 5 is the recommendation and the default here: 5 extra candidates per S1, about 8.7M test

pairs, and the precision of the channel falls off fast beyond it.



WHY CHARACTER TF-IDF AND NOT THE DENSE ENCODER. I first built this channel with e5-small

embeddings, which was a guess. This recipe is the one with a measured recovery rate attached,

it needs no GPU at all, and character 3-grams are the right tool for the failure being

targeted: typos and spacing damage on a short name with no address to fall back on.



THE TRAP THIS CHANNEL WALKS INTO (s4.4). These candidates are address-less records that the

other retrievers rank low. Under reciprocal-rank fusion with one channel voting they land

below rank 64 and get cut - so fusing them normally throws away the entire point. They must

enter the candidate set as a GUARANTEED UNION after the cut. 12_new_pairs.py gives this

channel priority 0 for exactly that reason.



Address-only retrieval is deliberately NOT implemented: measured at 6-12% recovery, about

+0.0002 val, for 10-50 candidates per S1. It was rejected on the evidence.

"""
from __future__ import annotations

import argparse
import os
import sys
import time

import numpy as np
import pandas as pd

# Pin BLAS before numpy/scipy import, so each forked worker stays single-threaded.
for _v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS",
           "NUMEXPR_NUM_THREADS"):
    os.environ.setdefault(_v, "1")

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


_G: dict = {}          # set in the parent, inherited by forked workers


def _block(args):
    """One query chunk, run in a forked worker.



    Q and D are inherited through fork rather than pickled. A country's TF-IDF matrices are

    hundreds of MB and pickling them per task would cost more than the multiply.

    """
    s, e, k = args
    Q, DT = _G["Q"], _G["DT"]
    sim = (Q[s:e] @ DT).toarray()
    kk = min(k, sim.shape[1])
    part = np.argpartition(-sim, kk - 1, axis=1)[:, :kk]
    rows = np.arange(e - s)[:, None]
    sv = sim[rows, part]
    order = np.argsort(-sv, axis=1)
    return s, e, part[rows, order].astype(np.int32), sv[rows, order].astype(np.float32)


def topk_sparse(Q, D, k: int, chunk: int = 4096, workers: int = 0):
    """Top-k cosine per query row, over a pool of processes.



    Both matrices are L2-normalised TF-IDF, so the inner product IS the cosine.



    WHY PARALLEL. Serially this is one core of the 96 on the box: France measured at about

    4 minutes, and the work scales with queries x documents, so India is 8.5x France and the

    whole channel projects to roughly an hour - on the critical path to the Colab lanes, for

    a step that is embarrassingly parallel over query chunks.



    Each worker is pinned to a single BLAS thread. Without that, N workers each spawn their

    own thread pool on a 96-core box and spend their time fighting each other for cache.

    """
    import multiprocessing as mp

    n = Q.shape[0]
    idx = np.zeros((n, k), dtype=np.int32)
    val = np.zeros((n, k), dtype=np.float32)
    _G["Q"], _G["DT"] = Q, D.T.tocsc()
    tasks = [(s, min(s + chunk, n), k) for s in range(0, n, chunk)]

    if workers <= 0:
        # Leave headroom: this box is shared and has been made unusable before by a job that
        # took every core.
        workers = max(1, min(16, (os.cpu_count() or 8) // 4, len(tasks)))
    t0 = time.time()
    pool = None
    if workers == 1:
        results = map(_block, tasks)
    else:
        # fork, so Q and DT are inherited rather than pickled per task. Windows has no fork;
        # this runs on Linux, but falling back keeps the file testable anywhere.
        try:
            ctx = mp.get_context("fork")
        except ValueError:
            print("      no fork on this platform; running serially", flush=True)
            ctx = None
        if ctx is None:
            workers = 1
            results = map(_block, tasks)
            pool = None
        else:
            pool = ctx.Pool(workers)
            results = pool.imap_unordered(_block, tasks, chunksize=1)

    done = 0
    for s, e, bi, bv in results:
        kk = bi.shape[1]
        idx[s:e, :kk] = bi
        val[s:e, :kk] = bv
        done += e - s
        if done % (chunk * 20) < chunk:
            el = time.time() - t0
            f = done / n
            print(f"      {done:>9,}/{n:,} ({f:5.1%})  {workers}w  "
                  f"eta {el/max(f,1e-9)-el:6.0f}s", flush=True)
    if pool is not None:
        pool.close()
        pool.join()
    _G.clear()
    return idx, val


def _self_test():
    """Prove the parallel path returns exactly what the serial path returns.



    Run through the real entry point, not an imported copy: multiprocessing resolves the

    worker function by module name, so a module loaded under a synthetic name fails to

    pickle even though production is fine.

    """
    from scipy import sparse
    D = sparse.random(3000, 150, density=0.1, format="csr", random_state=1, dtype=np.float32)
    Q = sparse.random(2000, 150, density=0.1, format="csr", random_state=2, dtype=np.float32)
    i1, v1 = topk_sparse(Q, D, 5, chunk=128, workers=1)
    i8, v8 = topk_sparse(Q, D, 5, chunk=128, workers=8)
    assert np.allclose(v1, v8), "parallel scores differ from serial"
    assert (i1 == i8).all(), "parallel indices differ from serial"
    print(f"self-test PASS: 8 workers match serial exactly on {Q.shape[0]:,} queries")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--split", default="test")
    ap.add_argument("--k", type=int, default=5)
    ap.add_argument("--chunk", type=int, default=4096)
    ap.add_argument("--workers", type=int, default=0, help="0 = auto (capped, shared box)")
    ap.add_argument("--self-test", action="store_true",
                    help="check the parallel path against the serial one, then exit")
    a = ap.parse_args()

    if a.self_test:
        _self_test()
        return

    from sklearn.feature_extraction.text import TfidfVectorizer

    d = os.path.dirname(P.work("prep", a.split, "_"))
    s1 = pd.read_parquet(os.path.join(d, "source1.parquet"))
    pool = pd.read_parquet(os.path.join(d, "pool.parquet"))
    empty = (pool["business_address"].astype(str).str.strip() == "").to_numpy()
    print(f"{a.split}: {len(s1):,} S1, {len(pool):,} pool, "
          f"{int(empty.sum()):,} address-less ({empty.mean():.2%})")

    qs, cs, ss, rs = [], [], [], []
    for country in sorted(set(s1["country"])):
        qrows = np.flatnonzero((s1["country"] == country).to_numpy())
        drows = np.flatnonzero(empty & (pool["country"] == country).to_numpy())
        if len(qrows) == 0 or len(drows) == 0:
            print(f"  {country}: nothing to do")
            continue
        print(f"  {country}: {len(qrows):,} queries x {len(drows):,} address-less docs",
              flush=True)
        docs = pool["business_name"].astype(str).to_numpy()[drows]
        qtxt = s1["business_name"].astype(str).to_numpy()[qrows]
        # Fitted on the DOCUMENTS, as measured - the idf weighting should describe the
        # address-less pool, not the S1 table.
        vec = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 3), sublinear_tf=True)
        t0 = time.time()
        D = vec.fit_transform(docs)
        Q = vec.transform(qtxt)
        print(f"    tfidf {D.shape[1]:,} features in {time.time()-t0:.0f}s", flush=True)
        idx, val = topk_sparse(Q, D, a.k, a.chunk, a.workers)
        kk = idx.shape[1]
        qs.append(np.repeat(qrows, kk))
        cs.append(drows[idx.ravel()])
        ss.append(val.ravel())
        rs.append(np.tile(np.arange(kk, dtype=np.int16), len(qrows)))

    assert qs, "no country produced candidates"
    out = pd.DataFrame({
        "q": np.concatenate(qs).astype(np.int32),
        "c": np.concatenate(cs).astype(np.int32),
        "s": np.concatenate(ss).astype(np.float32),
        "r": np.concatenate(rs).astype(np.int16),
    })
    out = out[out["s"] > 0]                       # a zero score means no shared 3-gram at all
    p = P.work("retr", f"{a.split}_ename_s0of1.parquet")
    out.to_parquet(p, index=False)
    print(f"\nwrote {p}  {len(out):,} pairs  "
          f"({len(out)/len(s1):.2f} per S1)")


if __name__ == "__main__":
    main()