File size: 16,305 Bytes
0dd5490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Expected-F0.5 set decoding (Stage C).

For one S1 entity with m candidates and calibrated, independent match
probabilities p_1 >= ... >= p_m, predicting the top-k candidates gives, per the
challenge metric (see src/metric.py),

    F = 5 * tp / (4k + n)     (k >= 1, tp > 0; else 0)
    F = 1{n == 0}             (k == 0)

where tp ~ PoissonBinomial(p_1..p_k) is the number of true matches among the
chosen k and n = tp + u, u ~ PoissonBinomial(p_{k+1}..p_m). So

    E[F_0] = prod_i (1 - p_i)
    E[F_k] = 5 * sum_{a=1..k} Pr(tp=a) * a * H_k(4k + a),
    H_k(J) = E_u[ 1 / (J + u) ].

Pr(tp=a) for every prefix is the usual forward Poisson-binomial DP. H_k is
obtained by a backward recursion that adds one candidate at a time to the
unchosen set,

    H_m(J)     = 1 / J
    H_{k-1}(J) = (1 - p_k) H_k(J) + p_k H_k(J + 1),

on the integer grid J = 0..5m (only J <= 5k is ever needed for H_k). Because
beta^2 = 1/4 makes 4k + n an integer, this is exact and costs O(m^2) per
entity (about 3 m^2 flops) instead of the O(m^3) prefix x suffix double sum.
Every update is a convex combination, so it is numerically stable.

Public API
    expected_f05_topk(probs)                     -> E[F_k] for k = 0..m
    best_subset(probs, min_prob=0, max_k=None)   -> (k, E[F_k])
    threshold_decode(probs, t)                   -> boolean mask p > t
    decode_arrays(s1_ids, probs, ...)            -> DecodeResult (vectorised, multiprocess)
    decode_all(s1_ids, probs, ...)               -> {s1_id: [row indices selected]}
    decode_frame(df, ...)                        -> one row per S1 with selected candidate ids

Benchmark:
    python -m src.decode --bench 200000 --max-m 60 --n-jobs 8
"""
from __future__ import annotations

import os
import time
from dataclasses import dataclass
from typing import Iterator

import numpy as np
import pandas as pd

__all__ = [
    "expected_f05_topk",
    "best_subset",
    "threshold_decode",
    "decode_arrays",
    "decode_all",
    "decode_frame",
    "pred_dict_from_frame",
    "DecodeResult",
]

_TIE_TOL = 1e-12  # prefer the smaller k when expected values tie


# ---------------------------------------------------------------------------
# Core batched kernel
# ---------------------------------------------------------------------------
def _expected_f05_sorted(P: np.ndarray) -> np.ndarray:
    """Expected F0.5 of every top-k prediction, batched.

    P : (B, M) float64, each row sorted in DEcreasing order. Rows may be
        zero-padded on the right; values for k <= (true row length) are exact.
    Returns E : (B, M+1) with E[:, k] = E[F0.5 | predict first k columns].

    Internally the entity axis is kept innermost (arrays are (.., B)) so every
    update is a contiguous vector op; ~2-4x faster than the (B, ..) layout.
    """
    P = np.asarray(P, dtype=np.float64)
    B, M = P.shape
    PT = np.ascontiguousarray(P.T)              # (M, B)
    QT = 1.0 - PT
    E = np.empty((M + 1, B))
    E[0] = np.prod(QT, axis=0)                  # k = 0: correct iff no true match
    if M == 0:
        return E.T

    # Forward: prefix Poisson-binomial pmfs, pre[k, a, :] = Pr(tp among top-k = a).
    pre = np.zeros((M + 1, M + 1, B))
    pre[0, 0] = 1.0
    L = 5 * M + 1
    buf = np.empty((L, B))
    for k in range(1, M + 1):
        p, q = PT[k - 1], QT[k - 1]
        prev, cur = pre[k - 1], pre[k]
        np.multiply(prev[:k + 1], q, out=cur[:k + 1])
        np.multiply(prev[:k], p, out=buf[:k])
        cur[1:k + 1] += buf[:k]

    # Backward: H over J = 0..5M, starting from H_M(J) = 1/J (empty suffix).
    J = np.arange(L, dtype=np.float64)
    J[0] = 1.0  # J = 0 is never read for k >= 1; avoid division by zero
    H = np.repeat((1.0 / J)[:, None], B, axis=1)
    a = np.arange(1, M + 1, dtype=np.float64)[:, None]
    for k in range(M, 0, -1):
        # H currently holds H_k (suffix = candidates k+1..M).
        w = buf[:k]
        np.multiply(H[4 * k + 1:5 * k + 1], a[:k], out=w)   # a * H_k(4k + a), a = 1..k
        w *= pre[k][1:k + 1]
        E[k] = w.sum(axis=0)
        if k > 1:
            # H_{k-1}(J) = (1-p_k) H_k(J) + p_k H_k(J+1), needed for J <= 5(k-1)
            n = 5 * (k - 1) + 1
            t = buf[:n]
            np.multiply(H[1:n + 1], PT[k - 1], out=t)
            H[:n] *= QT[k - 1]
            H[:n] += t
    E[1:] *= 5.0
    return E.T


def _choose_k(E: np.ndarray, P: np.ndarray, m: np.ndarray | None = None,
              min_prob: float = 0.0, max_k: int | None = None) -> tuple[np.ndarray, np.ndarray]:
    """Argmax_k of E subject to k <= m, k <= max_k and p_k >= min_prob."""
    B, M1 = E.shape
    limit = np.full(B, M1 - 1, dtype=np.int64)
    if m is not None:
        limit = np.minimum(limit, m)
    if max_k is not None:
        limit = np.minimum(limit, int(max_k))
    if min_prob and min_prob > 0:
        limit = np.minimum(limit, (P >= min_prob).sum(axis=1))
    kk = np.arange(M1)
    Em = np.where(kk[None, :] <= limit[:, None], E, -np.inf)
    best = Em.max(axis=1)
    k = np.argmax(Em >= (best - _TIE_TOL)[:, None], axis=1)
    return k, E[np.arange(B), k]


# ---------------------------------------------------------------------------
# Single-entity API
# ---------------------------------------------------------------------------
def _clean_probs(probs) -> np.ndarray:
    p = np.asarray(probs, dtype=np.float64).ravel()
    p = np.nan_to_num(p, nan=0.0)
    return np.clip(p, 0.0, 1.0)


def expected_f05_topk(probs) -> np.ndarray:
    """E[F0.5] of predicting the top-k candidates (by probability), k = 0..m."""
    p = np.sort(_clean_probs(probs))[::-1]
    return _expected_f05_sorted(p[None, :])[0]


def best_subset(probs: np.ndarray, min_prob: float = 0.0,
                max_k: int | None = None) -> tuple[int, float]:
    """Return (k, E[F0.5]) for the best top-k prediction of one entity.

    The chosen set is the k highest-probability candidates. ``min_prob`` forbids
    predicting any candidate with p < min_prob (those candidates still count as
    possible true matches in the expectation); ``max_k`` caps k.
    """
    p = np.sort(_clean_probs(probs))[::-1][None, :]
    E = _expected_f05_sorted(p)
    k, v = _choose_k(E, p, None, min_prob, max_k)
    return int(k[0]), float(v[0])


def threshold_decode(probs, t: float) -> np.ndarray:
    """Plain global threshold: boolean mask of p > t (any shape)."""
    return np.nan_to_num(np.asarray(probs, dtype=np.float64), nan=0.0) > t


# ---------------------------------------------------------------------------
# Batched / multiprocess API
# ---------------------------------------------------------------------------
@dataclass
class DecodeResult:
    entity_ids: np.ndarray    # (E,) unique S1 ids, in order of first appearance
    k: np.ndarray             # (E,) number of candidates selected
    expected_f05: np.ndarray  # (E,) model-expected F0.5 of the chosen set
    n_candidates: np.ndarray  # (E,)
    selected: np.ndarray      # (N,) bool mask over input rows
    order: np.ndarray         # (N,) row indices sorted by (entity, prob desc)
    starts: np.ndarray        # (E,) offset of each entity's block in ``order``

    def rows_for(self, e: int) -> np.ndarray:
        s = self.starts[e]
        return self.order[s:s + self.k[e]]


_MIN_ROWS_FOR_POOL = 50_000


def _worker(task):
    """Sort each entity's candidates (prob desc, stable) and pick k.

    Returns (k, E[F_k], perm) where perm[i] is the within-row sort order."""
    P, method, threshold, min_prob, max_k = task
    perm = np.argsort(-P, axis=1, kind="stable")
    P = np.take_along_axis(P, perm, axis=1)
    E = _expected_f05_sorted(P)
    if method == "threshold":
        k = (P > threshold).sum(axis=1)
        if max_k is not None:
            k = np.minimum(k, int(max_k))
        v = E[np.arange(P.shape[0]), k]
    else:
        k, v = _choose_k(E, P, None, min_prob, max_k)
    small = np.int16 if P.shape[1] < 32767 else np.int32
    return k.astype(np.int32), v, perm.astype(small)


def _batch_size(m: int, mem_budget_mb: float) -> int:
    per_entity = 8.0 * ((m + 1) ** 2 + 13 * (m + 1))  # pre + H + buf + E/P/Q
    return int(max(32, min(16384, mem_budget_mb * 1e6 / per_entity)))


def _group_rows(codes: np.ndarray, n_groups: int) -> np.ndarray:
    """Row indices grouped by code (stable within a group), in O(N)."""
    try:  # pandas' counting sort; private, so fall back if it moves
        from pandas._libs.algos import groupsort_indexer
        ix, _ = groupsort_indexer(codes.astype(np.intp, copy=False), n_groups)
        return np.asarray(ix, dtype=np.int64)
    except Exception:  # noqa: BLE001
        counts = np.bincount(codes, minlength=n_groups)
        starts = np.zeros(n_groups, dtype=np.int64)
        np.cumsum(counts[:-1], out=starts[1:])
        within = pd.Series(codes).groupby(codes, sort=False).cumcount().to_numpy()
        out = np.empty(len(codes), dtype=np.int64)
        out[starts[codes] + within] = np.arange(len(codes))
        return out


def decode_arrays(s1_ids, probs, *, method: str = "expected_f", threshold: float = 0.5,
                  min_prob: float = 0.0, max_k: int | None = None, n_jobs: int | None = None,
                  mem_budget_mb: float = 32.0, verbose: bool = False) -> DecodeResult:
    """Decode every S1 entity from long-format arrays (one row per candidate pair).

    s1_ids : (N,) S1 id of each candidate row (any hashable dtype; rows need not
             be grouped or sorted)
    probs  : (N,) calibrated match probability of each row
    method : "expected_f" (default) or "threshold" (select p > threshold)
    min_prob, max_k : constraints for the expected-F decoder (see best_subset);
             max_k also caps the threshold decoder
    n_jobs : worker processes (default os.cpu_count(); 1 = in-process)

    Entities are bucketed by candidate count so no padding is needed; each
    bucket is split into chunks of about ``mem_budget_mb`` of kernel memory.
    """
    if method not in ("expected_f", "threshold"):
        raise ValueError(f"unknown method {method!r}")
    t0 = time.time()
    probs = _clean_probs(probs)
    s1_ids = np.asarray(s1_ids)
    if s1_ids.shape[0] != probs.shape[0]:
        raise ValueError("s1_ids and probs must have the same length")
    codes, uniques = pd.factorize(s1_ids, sort=False)
    if (codes < 0).any():
        raise ValueError("s1_ids contains missing values")
    n_ent = len(uniques)
    N = len(probs)
    counts = np.bincount(codes, minlength=n_ent)
    starts = np.zeros(n_ent, dtype=np.int64)
    np.cumsum(counts[:-1], out=starts[1:])
    grouped = _group_rows(codes, n_ent)        # rows grouped by entity
    del codes
    gp = probs[grouped]

    # Bucket entities by m, chunk each bucket.
    ent_by_m = np.argsort(counts, kind="stable")
    bounds = np.flatnonzero(np.diff(counts[ent_by_m])) + 1
    chunks: list[np.ndarray] = []
    for g in np.split(ent_by_m, bounds):
        if len(g):
            bs = _batch_size(int(counts[g[0]]), mem_budget_mb)
            chunks.extend(g[i:i + bs] for i in range(0, len(g), bs))

    def block(ents: np.ndarray) -> np.ndarray:
        return starts[ents][:, None] + np.arange(int(counts[ents[0]]))[None, :]

    def tasks() -> Iterator[tuple]:
        for ents in chunks:
            yield (gp[block(ents)], method, threshold, min_prob, max_k)

    best_k = np.zeros(n_ent, dtype=np.int32)
    exp_f = np.zeros(n_ent, dtype=np.float64)
    order = np.empty(N, dtype=np.int64)        # rows by entity, then prob desc

    def collect(results) -> None:
        for ents, (k, v, perm) in zip(chunks, results):
            best_k[ents] = k
            exp_f[ents] = v
            idx = block(ents)
            order[idx] = np.take_along_axis(grouped[idx], perm.astype(np.int64), axis=1)

    if n_jobs is None:
        n_jobs = os.cpu_count() or 1
    n_jobs = max(1, min(int(n_jobs), len(chunks)))
    if n_jobs == 1 or N < _MIN_ROWS_FOR_POOL:
        n_jobs = 1
        collect(map(_worker, tasks()))
    else:
        import multiprocessing as mp
        with mp.get_context().Pool(n_jobs) as pool:
            collect(pool.imap(_worker, tasks(), chunksize=1))
    del gp, grouped

    pos = np.arange(N, dtype=np.int64) - np.repeat(starts, counts)
    sel_sorted = pos < np.repeat(best_k, counts)
    selected = np.zeros(N, dtype=bool)
    selected[order[sel_sorted]] = True
    if verbose:
        print(f"[decode] {n_ent:,} entities, {N:,} rows, {len(chunks):,} chunks, "
              f"n_jobs={n_jobs}, {time.time() - t0:.1f}s, mean E[F]={exp_f.mean():.4f}, "
              f"mean k={best_k.mean():.3f}")
    return DecodeResult(np.asarray(uniques), best_k, exp_f, counts, selected, order, starts)


def _selected_blocks(r: DecodeResult) -> tuple[list, list]:
    """(selected row indices grouped by entity, prob desc; per-entity offsets into that list)."""
    counts = r.n_candidates
    pos = np.arange(len(r.order), dtype=np.int64) - np.repeat(r.starts, counts)
    rows = r.order[pos < np.repeat(r.k, counts)].tolist()
    offs = np.zeros(len(r.k) + 1, dtype=np.int64)
    np.cumsum(r.k, out=offs[1:])
    return rows, offs.tolist()


def decode_all(s1_ids, probs, **kwargs) -> dict:
    """{s1_id: [input row indices of the selected candidates, by prob desc]}.

    Every S1 id present in ``s1_ids`` gets a key (empty list = predict no match).
    Keyword arguments are passed to :func:`decode_arrays`.
    """
    r = decode_arrays(s1_ids, probs, **kwargs)
    rows, offs = _selected_blocks(r)
    return {sid: rows[offs[i]:offs[i + 1]] for i, sid in enumerate(r.entity_ids.tolist())}


def decode_frame(df: pd.DataFrame, s1_col: str = "source1_entity_id",
                 cand_col: str = "candidate_entity_id", prob_col: str = "prob",
                 **kwargs) -> pd.DataFrame:
    """DataFrame in (one row per candidate pair) -> DataFrame out (one row per S1).

    Output columns: s1_col, matched_entity_ids (list, prob desc), k,
    n_candidates, expected_f05. Keyword arguments go to :func:`decode_arrays`.
    """
    r = decode_arrays(df[s1_col].to_numpy(), df[prob_col].to_numpy(), **kwargs)
    rows, offs = _selected_blocks(r)
    cands = df[cand_col].to_numpy()[np.asarray(rows, dtype=np.int64)].tolist()
    matched = [cands[offs[i]:offs[i + 1]] for i in range(len(r.k))]
    return pd.DataFrame({
        s1_col: r.entity_ids,
        "matched_entity_ids": matched,
        "k": r.k,
        "n_candidates": r.n_candidates,
        "expected_f05": r.expected_f05,
    })


def pred_dict_from_frame(frame: pd.DataFrame, s1_col: str = "source1_entity_id") -> dict:
    """decode_frame output -> {s1_id: set(candidate ids)} for src.metric."""
    return {k: set(v) for k, v in zip(frame[s1_col].tolist(), frame["matched_entity_ids"])}


# ---------------------------------------------------------------------------
# Benchmark
# ---------------------------------------------------------------------------
def _bench(n_ent: int, max_m: int, n_jobs: int | None, seed: int = 0) -> None:
    rng = np.random.default_rng(seed)
    m = rng.integers(1, max_m + 1, size=n_ent)
    ids = np.array([f"S1-{i:08d}" for i in range(n_ent)], dtype=object)
    s1 = np.repeat(ids, m)
    # mostly low probabilities, a few confident ones
    p = np.where(rng.random(m.sum()) < 0.05, rng.beta(5, 1, m.sum()), rng.beta(0.3, 6, m.sum()))
    perm = rng.permutation(len(p))
    s1, p = s1[perm], p[perm]
    print(f"bench: {n_ent:,} entities, {len(p):,} rows, m ~ U[1,{max_m}]")
    t = time.time()
    out = decode_all(s1, p, n_jobs=n_jobs, verbose=True)
    print(f"decode_all total {time.time() - t:.1f}s  ({len(out):,} keys)")
    # pure kernel throughput, one core, m = max_m
    P = -np.sort(-rng.beta(0.3, 6, size=(_batch_size(max_m, 32.0), max_m)), axis=1)
    t = time.time()
    reps = 5
    for _ in range(reps):
        _expected_f05_sorted(P)
    dt = (time.time() - t) / reps
    print(f"kernel: {P.shape[0] / dt:,.0f} entities/s/core at m={max_m}")


if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser()
    ap.add_argument("--bench", type=int, default=200_000, help="number of synthetic entities")
    ap.add_argument("--max-m", type=int, default=60)
    ap.add_argument("--n-jobs", type=int, default=None)
    a = ap.parse_args()
    _bench(a.bench, a.max_m, a.n_jobs)