File size: 8,279 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
"""D. Cross-encoder scoring, shardable across machines, and the dual-CE blend.



WHY BOTH ENCODERS. Averaging mDeBERTa-v3 with bge-reranker-v2-m3 measured +0.0011 CE-only val

F0.5, against +0.0023 for doubling the training data of one of them. The average costs no

training at all, only a second forward pass, so it is the better trade whenever a GPU-hour is

the scarce resource. Note the two numbers are not directly comparable to the final metric: a

separate end-to-end test put the post-stacker gain at +0.00032, because the stacker already

recovers most of what the blend adds. Budget for the smaller number.



A CAVEAT THAT MATTERS FOR WHICH CHECKPOINT YOU BLEND. Model-3's reranker saw 4,581 of

model-4's val records and 8,977 of its stack records during training. Any dual-CE gain

measured on model-4's val with THAT checkpoint is partly leakage, not signal. Blend

checkpoints trained on the same split as the run you are evaluating, or accept that the val

number is optimistic and judge on the leaderboard.



THROUGHPUT. Pairs are sorted by tokenised length before batching, so a batch is padded to its

own longest member rather than to the corpus maximum. That alone is most of the difference

between ~150 pairs/s and ~2,400 pairs/s on a shared card.



RESUMPTION. The checkpoint stores a count of completed rows in LENGTH-SORTED order, and the

scores are written back through the sort permutation only at the end. Do not "simplify" this

to input order: the resume prefix would no longer be contiguous and a restart would silently

score the wrong rows.

"""
from __future__ import annotations

import json
import os
import time

import numpy as np

os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")


def pair_text(name, addr, country) -> str:
    """The exact string format the shipped cross-encoders were fine-tuned on.



    Changing the separators or the field order here silently degrades a fine-tuned model,

    because the tokeniser sees a format it never saw in training. It is also what made a

    cross-model ensemble possible at all: both encoders were trained on this same rendering.

    """
    return f"name: {name} | addr: {addr} | country: {country}"


def load_model(path_or_id: str, device: str = "cuda", compile_model: bool = False):
    """Load a sequence-classification cross-encoder for scoring.



    fp32 weights are requested even though inference runs under autocast. Loading fp16 master

    weights is how a previous run produced NaNs on optimiser step 1; for pure inference it is

    merely wasteful, but keeping one loading path for both avoids reintroducing that.

    """
    import torch
    from transformers import AutoModelForSequenceClassification, AutoTokenizer

    tok = AutoTokenizer.from_pretrained(path_or_id)
    model = AutoModelForSequenceClassification.from_pretrained(path_or_id, dtype=torch.float32)
    model.eval().to(device)
    if compile_model:
        try:
            model = torch.compile(model, mode="max-autotune")
        except Exception as e:                                  # not fatal, just slower
            print(f"  torch.compile unavailable: {e}")
    return tok, model


@np.errstate(over="ignore")
def _sigmoid(x):
    return 1.0 / (1.0 + np.exp(-x))


def score_pairs(texts_a, texts_b, tok, model, device: str = "cuda", batch: int = 128,

                max_len: int = 160, ckpt: str | None = None, ckpt_every: int = 200_000,

                log_every: int = 50, output: str = "logit"):
    """Score a list of (a, b) text pairs. Returns float32 scores in INPUT order.



    `output` MUST match the scale the consuming model was trained on:

      "logit" (default) - the raw head output

      "prob"            - sigmoid / softmax of it



    THIS DEFAULT IS NOT COSMETIC. model-4's stored `ce` column is a RAW LOGIT: range

    -11.06 to 9.63, mean 3.46, 98% of values outside [0, 1] (y=1 mean 8.66, y=0 mean -6.35).

    Scoring new candidate pairs as probabilities and appending them to that column would give

    the stacker a feature on two scales - old rows in [-11, 10], new rows in [0, 1] - so every

    new pair would land where the model reads "strong negative". It would validate, score

    plausibly, and be wrong exactly on the pairs the rescue channels exist to recover.



    `ckpt_every` defaults to 200,000 rather than the 2,000,000 used on the college box.

    A Colab session can disappear without warning, and 2M rows is roughly 15 minutes of work

    to redo; 200k is under two. Write the checkpoint to Drive, never to the VM disk.

    """
    import torch

    n = len(texts_a)
    assert len(texts_b) == n, "pair arrays differ in length"
    lens = np.fromiter((len(a) + len(b) for a, b in zip(texts_a, texts_b)), np.int32, n)
    order = np.argsort(lens, kind="stable")                     # short batches first

    scores_sorted = np.zeros(n, dtype=np.float32)
    start = 0
    if ckpt and os.path.exists(ckpt + ".json"):
        meta = json.load(open(ckpt + ".json"))
        if meta.get("n") == n:
            start = int(meta["done"])
            scores_sorted[:start] = np.load(ckpt + ".npy")[:start]
            print(f"  resuming at {start:,}/{n:,}")
        else:
            print(f"  checkpoint is for n={meta.get('n')}, this run has n={n}; ignoring")

    t0 = time.time()
    last_ck = start
    with torch.inference_mode():
        for bi, s in enumerate(range(start, n, batch)):
            e = min(s + batch, n)
            idx = order[s:e]
            enc = tok([texts_a[i] for i in idx], [texts_b[i] for i in idx],
                      padding=True, truncation=True, max_length=max_len,
                      return_tensors="pt").to(device)
            with torch.autocast("cuda", dtype=torch.float16, enabled=device.startswith("cuda")):
                logits = model(**enc).logits
            lg = logits.float().cpu().numpy()
            if output == "logit":
                # one column -> that logit; two -> the positive-class margin
                scores_sorted[s:e] = lg[:, 0] if lg.shape[1] == 1 else lg[:, -1] - lg[:, 0]
            else:
                scores_sorted[s:e] = _sigmoid(lg[:, 0]) if lg.shape[1] == 1 \
                    else _softmax_pos(lg)
            if ckpt and e - last_ck >= ckpt_every:
                _save_ckpt(ckpt, scores_sorted, e, n)
                last_ck = e
            if log_every and bi % log_every == 0:
                done = e / n
                el = time.time() - t0
                rate = (e - start) / max(el, 1e-9)
                print(f"  {e:>10,}/{n:,} ({done:6.1%})  {rate:7.0f} pairs/s  "
                      f"eta {(n - e) / max(rate, 1e-9):6.0f}s", flush=True)

    if ckpt:
        _save_ckpt(ckpt, scores_sorted, n, n)
    out = np.empty(n, dtype=np.float32)
    out[order] = scores_sorted                                  # undo the length sort
    return out


def _softmax_pos(lg):
    m = lg.max(axis=1, keepdims=True)
    ex = np.exp(lg - m)
    return (ex[:, -1] / ex.sum(axis=1)).astype(np.float32)


def _save_ckpt(ckpt: str, scores, done: int, n: int):
    np.save(ckpt + ".npy", scores)
    with open(ckpt + ".json", "w") as fh:
        json.dump({"done": int(done), "n": int(n)}, fh)


def blend(score_a: np.ndarray, score_b: np.ndarray, w: float = 0.5,

          mode: str = "rank") -> np.ndarray:
    """Combine two cross-encoder score vectors.



    `mode="rank"` averages normalised ranks rather than probabilities. Two encoders fine-tuned

    separately are not calibrated to each other, so averaging raw probabilities lets whichever

    one happens to be more confident dominate; rank averaging is invariant to that. `mode="p"`

    is the plain probability average, kept because it is what the +0.0011 measurement used.

    """
    if mode == "p":
        return (w * score_a + (1 - w) * score_b).astype(np.float32)
    ra = _rank01(score_a)
    rb = _rank01(score_b)
    return (w * ra + (1 - w) * rb).astype(np.float32)


def _rank01(x):
    o = np.argsort(x, kind="stable")
    r = np.empty(len(x), dtype=np.float32)
    r[o] = np.arange(len(x), dtype=np.float32)
    return r / max(len(x) - 1, 1)