File size: 10,331 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"""C. Multi-GPU top-K retrieval and the three-channel union.



WHY THIS IS WORTH GPU TIME. Measured ceilings on model-4's val, with a perfect decision layer:



    top-64 candidates (what ships)          0.9953

    top-100 candidates                      0.9964

    union of three retrievers' top-100      0.9976



The union is worth +0.0023 of headroom over what ships. That is larger than every decision-side

idea left on the list, and unlike them it cannot be had on CPU.



HOW THE GPUs ARE USED



  * Per country. Zero true pairs cross a country boundary in train, so a cross-country score

    is arithmetic that can only produce a false positive. Blocking by country cuts the work

    to sum(share^2) = 0.445 of the full matrix - a 2.2x saving before any other optimisation.

  * Resident pool. A 96 GB card holds an entire country's pool in fp16 (10.3M x 1024 x 2 =

    21 GB for the large channels, 7.9 GB for e5-small). When it fits, the pool is uploaded

    once and every query chunk reuses it, so the run is pure matmul with no PCIe traffic.

    `resident="auto"` measures free memory and decides.

  * Streaming fallback. When it does not fit, pool blocks are staged through a pinned host

    buffer on a second CUDA stream, double-buffered, so the copy for block i+1 overlaps the

    matmul for block i.

  * Query sharding. `--shard i --nshards n` splits the QUERY set, not the pool, so the two

    GPUs never need to exchange anything and a shard can be re-run alone after a failure.



SHARED-BOX MANNERS. This box has other users on it. Run it under `nice -n 19 ionice -c3` and

leave `--pblock` at the default; an earlier memmap-heavy job at load 37 made SSH unreachable

for everyone.

"""
from __future__ import annotations

import os
import time

import numpy as np


def _load(path: str) -> np.ndarray:
    """mmap a .npy. NOT np.memmap: a .npy carries a 128-byte header that np.memmap maps as

    data, which shifts every row and fails a reshape by exactly the header size in elements."""
    return np.load(path, mmap_mode="r")


def _free_bytes(dev: int) -> int:
    import torch
    free, _ = torch.cuda.mem_get_info(dev)
    return free


def topk_country(qmat: np.ndarray, pmat: np.ndarray, k: int, device: str,

                 qchunk: int = 4096, pblock: int = 262_144, resident: str = "auto",

                 log_every: int = 20):
    """Top-k over one country. Returns (idx[nq,k] int64, val[nq,k] float32).



    Embeddings are assumed L2-normalised, so the inner product is cosine. If they are not,

    normalise them before calling - silently normalising here would hide a mismatch between

    the matrix on disk and the model that produced it.

    """
    import torch

    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True
    dev = torch.device(device)
    nq, d = qmat.shape
    npool = pmat.shape[0]
    k = min(k, npool)

    want = npool * d * 2
    if resident == "auto":
        use_resident = want < _free_bytes(dev.index or 0) * 0.55
    else:
        use_resident = resident == "yes"

    # The pool is ALWAYS walked in blocks, whichever mode is chosen. `resident` decides only
    # where a block is read from - a GPU-resident copy of the pool, or the host mmap. It does
    # not mean "one matmul over the whole pool": the score matrix for a 4,096-query chunk
    # against a 6M-row country pool would be 49 GiB on its own, dwarfing the embeddings.
    P_gpu = None
    if use_resident:
        P_gpu = torch.empty((npool, d), dtype=torch.float16, device=dev)
        for ps in range(0, npool, pblock):                         # staged upload, once
            pe = min(ps + pblock, npool)
            P_gpu[ps:pe] = torch.from_numpy(np.ascontiguousarray(pmat[ps:pe])).to(dev, torch.float16)
        print(f"    pool resident on {device}: {want/2**30:.1f} GiB")
    else:
        print(f"    pool streamed on {device} ({want/2**30:.1f} GiB vs free "
              f"{_free_bytes(dev.index or 0)/2**30:.1f} GiB), pblock={pblock:,}")

    blocks = [(ps, min(ps + pblock, npool)) for ps in range(0, npool, pblock)]
    best_i = torch.empty((nq, k), dtype=torch.int64, device=dev)
    best_v = torch.full((nq, k), -1e4, dtype=torch.float16, device=dev)
    copy_stream = torch.cuda.Stream(device=dev) if not use_resident else None
    main = torch.cuda.current_stream(dev)
    t0 = time.time()

    for ci, qs in enumerate(range(0, nq, qchunk)):
        qe = min(qs + qchunk, nq)
        Q = torch.from_numpy(np.ascontiguousarray(qmat[qs:qe])).to(dev, torch.float16)
        bi = torch.zeros((qe - qs, k), dtype=torch.int64, device=dev)
        bv = torch.full((qe - qs, k), -1e4, dtype=torch.float16, device=dev)

        staged = staged_off = staged_evt = None
        for bidx in range(len(blocks) + 1):
            nxt = nxt_off = nxt_evt = None
            if bidx < len(blocks):
                ps, pe = blocks[bidx]
                if use_resident:
                    nxt, nxt_off = P_gpu[ps:pe], ps
                else:
                    # Prefetch block bidx while block bidx-1 is still being multiplied.
                    with torch.cuda.stream(copy_stream):
                        host = torch.from_numpy(np.ascontiguousarray(pmat[ps:pe])).pin_memory()
                        nxt = host.to(dev, torch.float16, non_blocking=True)
                        nxt_evt = torch.cuda.Event()
                        nxt_evt.record(copy_stream)
                    nxt_off = ps
            if staged is not None:
                if staged_evt is not None:
                    main.wait_event(staged_evt)
                s = Q @ staged.T                                   # [qc, block] fp16
                v, i = torch.topk(s, min(k, s.shape[1]), dim=1)
                bv, bi = _merge(bv, bi, v, i + staged_off, k)
                del s
                if not use_resident:
                    del staged
            staged, staged_off, staged_evt = nxt, nxt_off, nxt_evt

        best_v[qs:qe], best_i[qs:qe] = bv, bi
        if log_every and ci % log_every == 0:
            done = qe / nq
            el = time.time() - t0
            print(f"    {qe:>9,}/{nq:,} ({done:6.1%})  {el:6.0f}s  "
                  f"eta {el/max(done, 1e-9) - el:6.0f}s", flush=True)

    del P_gpu
    torch.cuda.empty_cache()
    return best_i.cpu().numpy(), best_v.float().cpu().numpy()


def _merge(bv, bi, v, i, k):
    import torch
    cv = torch.cat([bv, v], dim=1)
    ci = torch.cat([bi, i], dim=1)
    nv, pos = torch.topk(cv, k, dim=1)
    return nv, torch.gather(ci, 1, pos)


def run_channel(qmat_path: str, pmat_path: str, q_country: np.ndarray, p_country: np.ndarray,

                k: int, device: str, shard: int = 0, nshards: int = 1,

                max_queries: int | None = None, **kw):
    """Retrieve top-k for one channel, one query shard, blocking by country.



    Returns a dict with flat arrays: q (global query row), c (global pool row), s (score),

    r (rank within the channel). Global rows, not per-country rows - a per-country index that

    escapes into a later stage is the kind of bug that produces a plausible wrong answer.

    """
    Q = _load(qmat_path)
    P = _load(pmat_path)
    assert Q.shape[1] == P.shape[1], f"dim mismatch {Q.shape} vs {P.shape}"
    assert len(q_country) == Q.shape[0], "query country vector does not match the matrix"
    assert len(p_country) == P.shape[0], "pool country vector does not match the matrix"

    qs_all, cs_all, ss_all, rs_all = [], [], [], []
    for country in sorted(set(q_country.tolist())):
        qrows = np.flatnonzero(q_country == country)
        qrows = qrows[shard::nshards]
        if max_queries:
            qrows = qrows[:max_queries]           # debug path only
        prows = np.flatnonzero(p_country == country)
        if len(qrows) == 0 or len(prows) == 0:
            continue
        print(f"  {country}: {len(qrows):,} queries x {len(prows):,} pool", flush=True)
        qm = np.ascontiguousarray(Q[qrows])
        pm = P[prows]
        idx, val = topk_country(qm, pm, k, device, **kw)
        n, kk = idx.shape
        qs_all.append(np.repeat(qrows, kk))
        cs_all.append(prows[idx.ravel()])
        ss_all.append(val.ravel())
        rs_all.append(np.tile(np.arange(kk, dtype=np.int16), n))

    if not qs_all:
        return {k_: np.array([]) for k_ in ("q", "c", "s", "r")}
    return {
        "q": np.concatenate(qs_all).astype(np.int32),
        "c": np.concatenate(cs_all).astype(np.int32),
        "s": np.concatenate(ss_all).astype(np.float32),
        "r": np.concatenate(rs_all).astype(np.int16),
    }


def union(frames: dict, rrf_k: int = 60):
    """Union per-channel results into one candidate table with per-channel evidence.



    `frames` maps channel name -> the dict from run_channel. The output keeps each channel's

    score and rank as separate columns, plus Reciprocal Rank Fusion. Keeping the per-channel

    columns matters: a pair found by all three is different evidence from a pair found by one,

    and collapsing to a single fused score throws that distinction away before the stacker

    ever sees it.

    """
    import pandas as pd

    out = None
    for name, f in frames.items():
        if len(f["q"]) == 0:
            continue
        d = pd.DataFrame({"q": f["q"], "c": f["c"],
                          f"s_{name}": f["s"], f"r_{name}": f["r"]})
        d = d.sort_values(f"s_{name}", ascending=False).drop_duplicates(["q", "c"])
        out = d if out is None else out.merge(d, on=["q", "c"], how="outer")

    if out is None:
        return None
    rrf = np.zeros(len(out), dtype=np.float32)
    nfound = np.zeros(len(out), dtype=np.int8)
    for name in frames:
        col = f"r_{name}"
        if col not in out:
            continue
        r = out[col].to_numpy()
        ok = ~np.isnan(r)
        rrf[ok] += 1.0 / (rrf_k + r[ok])
        nfound[ok] += 1
        out[col] = np.where(ok, r, 9999).astype(np.int16)
        out[f"s_{name}"] = out[f"s_{name}"].fillna(0.0).astype(np.float32)
    out["rrf"] = rrf
    out["n_channels"] = nfound
    return out.reset_index(drop=True)