File size: 23,313 Bytes
3ef3d94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
"""Phase 5: does a calibrator with linguistic features choose draft-tree nodes better than confidence alone?

The draft tree of phase5_tree_draft.py keeps the N nodes with the highest
path score. Here the per-node factor of that score is the output of a small
model that predicts whether the node is accepted given that its parent was,
so the path score is the predicted chance that the node and all its
ancestors are accepted. Four selection rules are compared at exactly the
same number of verified nodes:

  confidence   the draft head's own probability (the existing confidence tree)
  conf         calibrator on confidence features only: log-probability, rank
               among siblings, the top sibling's log-probability and margin,
               spread over the K siblings, the ancestors' log-probability and
               ranks; one model per depth
  shuf         calibrator on the same confidence features plus the linguistic
               features permuted across nodes (same input size, no signal)
  ling         calibrator on confidence plus linguistic features, all of
               which are known when the tree is drafted: the candidate starts
               a word or continues one; its word-group class guessed from the
               token (inside a word, function word, group start); the class of
               the word in progress and of the word before it in the prefix;
               tokens since the last word start; script of the candidate and
               of the prefix, and whether they differ; token length in
               characters

A fifth model, "only", sees the linguistic features without any confidence
feature. It is not part of the comparison; it shows how much of the
acceptance signal the linguistic features carry on their own. The output also
has the log-loss and expected calibration error of each model on the test
documents, per depth.

Each calibrator is fitted as a logistic regression and as a small MLP.
Calibration documents never include a test document: they are the
even-indexed documents of the first --spec-docs held-out documents plus the
next --extra-fit-docs documents; every fifth one is held back to stop MLP
training and to choose between the two model families. Tokens per pass is
reported on the odd-indexed documents of the first --spec-docs, the same test
documents as phase5_tree_draft.py.
"""

import argparse
import json
import os
import sys
import time
from pathlib import Path

os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID")
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO))
sys.path.insert(0, str(REPO / "scripts"))

import numpy as np
import torch

from phase5_tree_draft import DEPTH, DEVICE, K, accepted_depth, bootstrap_gain, expand_tree, labelled_nodes, path_scores, replay, true_ranks

BUDGETS = (8, 16, 24)
SETS = ("conf", "shuf", "ling")
ALL_SETS = SETS + ("only",)  # "only": linguistic features alone, as a measure of what they carry by themselves
FAMILIES = ("lr", "mlp")
OTHER, DEVANAGARI, LATIN = 0, 1, 2


def vocab_tables(tokenizer, vocab: int) -> tuple:
    """Per vocabulary id: script of the decoded piece and its length in characters."""
    script = np.zeros(vocab, dtype=np.int64)
    length = np.zeros(vocab, dtype=np.int64)
    for tid in range(len(tokenizer)):
        piece = tokenizer.decode([tid]).strip()
        length[tid] = len(piece)
        if any("ऀ" <= ch <= "ॿ" for ch in piece):
            script[tid] = DEVANAGARI
        elif any(ch.isalpha() and (ch < "ɐ" or "Ḁ" <= ch <= "ỿ") for ch in piece):
            script[tid] = LATIN
    return script, length


def prefix_states(seq: list, is_start: np.ndarray, gclass: np.ndarray, script: np.ndarray, true_classes: np.ndarray) -> dict:
    """State of the text after each token of seq: word in progress, word before it, script."""
    n = len(seq)
    out = {k: np.zeros(n, dtype=np.int64) for k in ("word_cls", "prev_cls", "tiw", "last_script")}
    word_cls = prev_cls = last_script = 0
    tiw = 0
    cur_true = 0  # class of the word in progress computed from the full word; usable once that word is over
    for i, t in enumerate(seq):
        if is_start[t]:
            prev_cls = cur_true if cur_true else word_cls
            word_cls, tiw, cur_true = int(gclass[t]), 0, int(true_classes[i])
        else:
            tiw += 1
        if script[t]:
            last_script = int(script[t])
        out["word_cls"][i], out["prev_cls"][i], out["tiw"][i], out["last_script"][i] = word_cls, prev_cls, tiw, last_script
    return out


def onehot(x: np.ndarray, n: int) -> np.ndarray:
    """(..., n) one-hot of x clipped to n - 1; negative values give all zeros."""
    return (np.minimum(x, n - 1)[..., None] == np.arange(n)).astype(np.float32)


def node_features(toks: list, lps: list, state0: dict, is_start: np.ndarray, gclass: np.ndarray, script: np.ndarray, length: np.ndarray) -> tuple:
    """Confidence and linguistic features of every node, per depth; arrays shaped like toks[d] plus a feature axis."""
    conf, ling = [], []
    h = toks[0].shape[0]
    st = {k: v.copy() for k, v in state0.items()}
    st.update(anc_lp=np.zeros(h, dtype=np.float32), parent_rank=np.full(h, -1), grand_rank=np.full(h, -1))
    for d in range(DEPTH):
        tok, lp = toks[d], lps[d].astype(np.float32)
        shape = tok.shape
        b = {k: np.broadcast_to(v[..., None], shape) for k, v in st.items()}
        rank = np.broadcast_to(np.arange(K), shape)
        top_lp = np.broadcast_to(lp[..., :1], shape)
        margin = np.broadcast_to(lp[..., :1] - lp[..., 1:2], shape)
        p = np.exp(lp)
        pn = p / p.sum(-1, keepdims=True)
        spread = np.broadcast_to(-(pn * np.log(pn + 1e-9)).sum(-1, keepdims=True), shape)
        conf.append(np.concatenate([
            np.stack([lp, lp * lp, p, top_lp, margin, spread, b["anc_lp"]], -1),
            onehot(rank, K), onehot(b["parent_rank"], K), onehot(b["grand_rank"], K)], -1).astype(np.float32))

        own_start = is_start[tok]
        own_cls = gclass[tok]
        own_script = script[tok]
        switch = ((own_script > 0) & (b["last_script"] > 0) & (own_script != b["last_script"])).astype(np.float32)
        ln = length[tok]
        cls1h, word1h = onehot(own_cls, 3), onehot(b["word_cls"], 3)
        ling.append(np.concatenate([
            np.stack([own_start.astype(np.float32), np.broadcast_to(own_start[..., :1], shape).astype(np.float32),
                      switch, np.minimum(ln, 8) / 8.0, lp * switch], -1),
            cls1h, np.broadcast_to(cls1h[..., :1, :], shape + (3,)), word1h, onehot(b["prev_cls"], 3),
            onehot(b["tiw"], 4), onehot(own_script, 3), onehot(b["last_script"], 3), onehot(ln, 5),
            lp[..., None] * cls1h, lp[..., None] * word1h], -1).astype(np.float32))

        st = {
            "word_cls": np.where(own_start, own_cls, b["word_cls"]),
            "prev_cls": np.where(own_start, b["word_cls"], b["prev_cls"]),
            "tiw": np.where(own_start, 0, b["tiw"] + 1),
            "last_script": np.where(own_script > 0, own_script, b["last_script"]),
            "anc_lp": b["anc_lp"] + lp,
            "grand_rank": np.array(b["parent_rank"]),
            "parent_rank": np.array(rank),
        }
    return conf, ling


CONF_NAMES = (["lp", "lp_squared", "p", "top_sibling_lp", "margin", "sibling_spread", "ancestors_lp"]
              + [f"rank_{i}" for i in range(K)] + [f"parent_rank_{i}" for i in range(K)] + [f"grandparent_rank_{i}" for i in range(K)])
CLS = ("inside_word", "function_word", "group_start")
SCR = ("other", "devanagari", "latin")
LING_NAMES = (["starts_word", "top_sibling_starts_word", "script_switch", "length_chars", "lp_x_script_switch"]
              + [f"own_{c}" for c in CLS] + [f"top_sibling_{c}" for c in CLS]
              + [f"prefix_word_{c}" for c in ("none", "function_word", "group_start")]
              + [f"prefix_previous_word_{c}" for c in ("none", "function_word", "group_start")]
              + [f"tokens_since_word_start_{i}" for i in ("0", "1", "2", "3plus")]
              + [f"own_script_{s}" for s in SCR] + [f"prefix_script_{s}" for s in ("none", "devanagari", "latin")]
              + [f"length_{i}" for i in ("0", "1", "2", "3", "4plus")]
              + [f"lp_x_own_{c}" for c in CLS] + [f"lp_x_prefix_word_{c}" for c in ("none", "function_word", "group_start")])


def calibration_metrics(p: np.ndarray, y: np.ndarray, bins: int = 15) -> dict:
    """Log-loss and expected calibration error (equal-mass bins) of predicted acceptance p against labels y."""
    p = np.clip(p.astype(np.float64), 1e-6, 1 - 1e-6)
    order = np.argsort(p, kind="stable")
    ece = sum(len(idx) * abs(p[idx].mean() - y[idx].mean()) for idx in np.array_split(order, bins)) / len(p)
    return {"log_loss": float(-(y * np.log(p) + (1 - y) * np.log(1 - p)).mean()), "ece": float(ece)}


def fit_model(family: str, xt: torch.Tensor, yt: torch.Tensor, xv: torch.Tensor, yv: torch.Tensor, seed: int) -> tuple:
    """Fit on the calibration-train rows; returns (model, validation log-loss)."""
    torch.manual_seed(seed)
    f = xt.shape[1]
    bce = torch.nn.functional.binary_cross_entropy_with_logits
    with torch.enable_grad():
        if family == "lr":
            model = torch.nn.Linear(f, 1).to(xt.device)
            opt = torch.optim.LBFGS(model.parameters(), max_iter=200, line_search_fn="strong_wolfe")

            def closure():
                opt.zero_grad()
                loss = bce(model(xt).squeeze(-1), yt) + 1e-4 * (model.weight**2).sum()
                loss.backward()
                return loss

            opt.step(closure)
        else:
            model = torch.nn.Sequential(torch.nn.Linear(f, 64), torch.nn.ReLU(), torch.nn.Linear(64, 64), torch.nn.ReLU(), torch.nn.Linear(64, 1)).to(xt.device)
            opt = torch.optim.AdamW(model.parameters(), lr=2e-3, weight_decay=1e-4)
            best, best_state, bad = float("inf"), None, 0
            for _ in range(60):
                perm = torch.randperm(len(xt), device=xt.device)
                for s in range(0, len(xt), 4096):
                    idx = perm[s : s + 4096]
                    opt.zero_grad()
                    bce(model(xt[idx]).squeeze(-1), yt[idx]).backward()
                    opt.step()
                with torch.no_grad():
                    val = bce(model(xv).squeeze(-1), yv).item()
                if val < best - 1e-5:
                    best, bad = val, 0
                    best_state = {k: v.clone() for k, v in model.state_dict().items()}
                else:
                    bad += 1
                    if bad >= 6:
                        break
            model.load_state_dict(best_state)
    with torch.no_grad():
        return model, bce(model(xv).squeeze(-1), yv).item()


@torch.no_grad()
def main() -> None:
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--name", required=True)
    p.add_argument("--ckpt-dir", required=True)
    p.add_argument("--heldout", required=True)
    p.add_argument("--out", required=True)
    p.add_argument("--arm", default="dependent_teacher")
    p.add_argument("--spec-docs", type=int, default=256)
    p.add_argument("--extra-fit-docs", type=int, default=256)
    p.add_argument("--scheme", default="", help="Devanagari, ITRANS, IAST or ISO for the Hindi function-word list; empty for English")
    p.add_argument("--train-ids", default="", help="training token ids, needed with --scheme")
    p.add_argument("--words-per-token", type=float, default=0.0, help="words per token on the held-out text, to report words per pass")
    p.add_argument("--fit-seed", type=int, default=0)
    args = p.parse_args()
    t0 = time.perf_counter()

    from transformers import AutoModelForCausalLM, AutoTokenizer
    import phase4_boundary_decoding as pb
    import phase5_word_groups as wg
    from phase5_dependent_eval import BACKBONE, load_arm
    from src.train.data import load_heldout_texts

    tok = AutoTokenizer.from_pretrained(BACKBONE)
    backbone = AutoModelForCausalLM.from_pretrained(BACKBONE, dtype=torch.float32).to(DEVICE).eval()
    vocab = backbone.config.vocab_size
    starts = pb.word_start_table(tok)
    is_start = np.array(starts + [False] * (vocab - len(starts)))
    script, length = vocab_tables(tok, vocab)
    unembed = backbone.lm_head.weight
    fwords = set()
    gclass = np.where(is_start, wg.GROUP_START, wg.WITHIN_WORD).astype(np.int64)
    if args.scheme:
        fwords = wg.function_words(args.scheme)
        gclass, _ = wg.token_group_table(np.load(args.train_ids, mmap_mode="r"), is_start, tok, fwords)
    eos = backbone.generation_config.eos_token_id
    eos_ids = set(eos if isinstance(eos, list) else [eos])
    texts = load_heldout_texts(args.heldout)

    def continuations(chunk: list) -> list:
        pairs = pb.generate_continuations(backbone, tok, chunk, 256, 64 + pb.LOOKAHEAD, 16, eos_ids)
        return [(pr, c) for pr, c in pairs if min(64, len(c) - pb.LOOKAHEAD + 1) >= 1]

    first = continuations(texts[: args.spec_docs])
    extra = continuations(texts[args.spec_docs : args.spec_docs + args.extra_fit_docs]) if args.extra_fit_docs else []
    stack = load_arm(backbone, Path(args.ckpt_dir) / f"{args.arm}.pt", args.arm.startswith("dependent"))

    def build(prompt: list, cont: list) -> dict:
        horizon = min(64, len(cont) - pb.LOOKAHEAD + 1)
        seq = prompt + cont
        full = torch.tensor([seq], device=DEVICE)
        p0 = len(prompt) - 1
        trunk = stack.trunk_states(backbone.model(input_ids=full).last_hidden_state[0, p0 : p0 + horizon])
        continuation = [prompt[-1]] + cont
        exact_next = torch.tensor(continuation[1 : horizon + 1], device=DEVICE)
        truth = np.array([continuation[j + 2 : j + 2 + DEPTH] for j in range(horizon)])
        toks, lps = expand_tree(stack, unembed, trunk, exact_next)
        states = prefix_states(seq, is_start, gclass, script, wg.token_classes(seq, is_start, tok, fwords))
        state0 = {k: v[len(prompt) : len(prompt) + horizon] for k, v in states.items()}  # after the exact next token
        conf, ling = node_features(toks, lps, state0, is_start, gclass, script, length)
        return {"lps": lps, "ranks": true_ranks(toks, truth), "x": [np.concatenate([c, g], -1) for c, g in zip(conf, ling)]}

    docs_first = [build(pr, c) for pr, c in first]
    docs_extra = [build(pr, c) for pr, c in extra]
    test = docs_first[1::2]
    calib = docs_first[0::2] + docs_extra
    val = calib[4::5]
    train = [d for i, d in enumerate(calib) if i % 5 != 4]
    n_conf, n_ling = len(CONF_NAMES), len(LING_NAMES)
    assert docs_first[0]["x"][0].shape[-1] == n_conf + n_ling
    print(f"{args.name}: {len(test)} test docs, {len(train)} calibration docs, {len(val)} validation docs, features {n_conf}+{n_ling}, {time.perf_counter() - t0:.0f}s", flush=True)

    rng = np.random.default_rng(args.fit_seed)
    only_cols = np.array([n_conf + i for i, n in enumerate(LING_NAMES) if not n.startswith("lp_x")])

    def rows(docs: list, d: int) -> tuple:
        xs, ys = [], []
        for doc in docs:
            x, y = labelled_nodes(doc["x"], doc["ranks"])[d]
            xs.append(x.reshape(-1, x.shape[-1]))
            ys.append(y.reshape(-1))
        return np.concatenate(xs), np.concatenate(ys).astype(np.float32)

    def view(x: np.ndarray, which: str, perm=None) -> np.ndarray:
        if which == "conf":
            return x[:, :n_conf]
        if which == "shuf":
            return np.concatenate([x[:, :n_conf], x[perm, n_conf:]], 1)
        if which == "only":
            return x[:, only_cols]
        return x

    models, val_loss, norm, coef = {}, {}, {}, {}
    fit_rows = {}
    for d in range(DEPTH):
        xt, yt = rows(train, d)
        xv, yv = rows(val, d)
        fit_rows[str(d + 1)] = {"train": int(len(yt)), "validation": int(len(yv)), "accepted_share": float(yt.mean())}
        pt, pv = rng.permutation(len(xt)), rng.permutation(len(xv))
        for which in ALL_SETS:
            a, b = view(xt, which, pt), view(xv, which, pv)
            mu, sd = a.mean(0), a.std(0) + 1e-6
            norm[which, d] = (mu, sd)
            at = torch.tensor((a - mu) / sd, device=DEVICE)
            bt = torch.tensor((b - mu) / sd, device=DEVICE)
            ytt, yvt = torch.tensor(yt, device=DEVICE), torch.tensor(yv, device=DEVICE)
            for fam in FAMILIES:
                models[which, fam, d], val_loss[which, fam, d] = fit_model(fam, at, ytt, bt, yvt, args.fit_seed)
            if which == "ling":
                w = models[which, "lr", d].weight[0].cpu().numpy()
                coef[str(d + 1)] = {n: float(v) for n, v in zip(CONF_NAMES + LING_NAMES, w)}
    chosen = {which: min(FAMILIES, key=lambda fam: sum(val_loss[which, fam, d] for d in range(DEPTH))) for which in ALL_SETS}
    print(f"{args.name}: fitted, {time.perf_counter() - t0:.0f}s; validation log-loss by depth: "
          + "; ".join(f"{w}_{f} " + "/".join(f"{val_loss[w, f, d]:.4f}" for d in range(DEPTH)) for w in ALL_SETS for f in FAMILIES), flush=True)

    # calibration on the test documents: nodes whose parent is accepted, as in the fit
    test_calibration = {}
    for d in range(DEPTH):
        xs, ys = rows(test, d)
        entry = {"rows": int(len(ys)), "accepted_share": float(ys.mean()),
                 "base_rate": calibration_metrics(np.full(len(ys), ys.mean()), ys), "raw_confidence": calibration_metrics(xs[:, 2], ys)}
        for which in ("conf", "ling", "only"):
            mu, sd = norm[which, d]
            for fam in FAMILIES:
                prob = torch.sigmoid(models[which, fam, d](torch.tensor((view(xs, which) - mu) / sd, device=DEVICE)).squeeze(-1)).cpu().numpy()
                entry[f"{which}_{fam}"] = calibration_metrics(prob, ys)
        test_calibration[str(d + 1)] = entry

    # one permutation of the linguistic block over all test nodes of a depth, for the shuffled calibrator
    test_perm, offsets = [], []
    for d in range(DEPTH):
        sizes = [int(np.prod(doc["x"][d].shape[:-1])) for doc in test]
        offsets.append(np.concatenate([[0], np.cumsum(sizes)]))
        test_perm.append(rng.permutation(int(offsets[-1][-1])))
    test_ling = [np.concatenate([doc["x"][d].reshape(-1, n_conf + n_ling)[:, n_conf:] for doc in test]) for d in range(DEPTH)]

    policies = ["confidence"] + [f"{w}_{f}" for w in ALL_SETS for f in FAMILIES]
    per_doc = {pol: {n: [] for n in BUDGETS} for pol in policies}
    chain, full_tree = [], []
    for i, doc in enumerate(test):
        ranks = doc["ranks"]
        scores = {"confidence": path_scores(doc["lps"])}
        for which in ALL_SETS:
            for fam in FAMILIES:
                level = []
                for d in range(DEPTH):
                    x = doc["x"][d].reshape(-1, n_conf + n_ling)
                    if which == "conf":
                        x = x[:, :n_conf]
                    elif which == "shuf":
                        x = np.concatenate([x[:, :n_conf], test_ling[d][test_perm[d][offsets[d][i] : offsets[d][i + 1]]]], 1)
                    elif which == "only":
                        x = x[:, only_cols]
                    mu, sd = norm[which, d]
                    logit = models[which, fam, d](torch.tensor((x - mu) / sd, device=DEVICE)).squeeze(-1)
                    level.append(torch.nn.functional.logsigmoid(logit).cpu().numpy().reshape(doc["x"][d].shape[:-1]))
                scores[f"{which}_{fam}"] = path_scores(level)
        for pol in policies:
            for n in BUDGETS:
                per_doc[pol][n].append(replay(accepted_depth(scores[pol], ranks, n)))
        chain.append(replay(np.cumprod(ranks == 0, 1).sum(1)))
        full_tree.append(replay((ranks >= 0).sum(1)))

    def tpp(rws: list) -> float:
        a = np.array(rws)
        return float(a[:, 0].sum() / a[:, 1].sum())

    for which in ALL_SETS:  # the calibrator of each feature set is the family with the lower validation log-loss
        per_doc[which] = per_doc[f"{which}_{chosen[which]}"]
    names = policies + list(ALL_SETS)
    res = {
        "name": args.name, "ckpt_dir": args.ckpt_dir, "arm": args.arm, "gpu": torch.cuda.get_device_name(DEVICE), "scheme": args.scheme,
        "test_docs": len(test), "calibration_docs": len(train), "validation_docs": len(val), "candidates_per_node": K,
        "features": {"confidence": CONF_NAMES, "linguistic": LING_NAMES}, "fit_rows_by_depth": fit_rows,
        "validation_log_loss_by_depth": {f"{w}_{f}": [val_loss[w, f, d] for d in range(DEPTH)] for w in ALL_SETS for f in FAMILIES},
        "test_calibration_by_depth": test_calibration,
        "chosen_family": chosen, "chain": tpp(chain), "full_tree_84_nodes": tpp(full_tree),
        "tokens_per_pass": {pol: {str(n): tpp(per_doc[pol][n]) for n in BUDGETS} for pol in names},
        "words_per_token": args.words_per_token, "tests_percent_gain": {}, "ling_lr_coefficients_by_depth": coef,
    }
    # per test document (committed tokens, passes), so seeds can be pooled in one paired test
    res["per_document"] = {pol: {str(n): np.array(per_doc[pol][n]).tolist() for n in BUDGETS} for pol in names}
    if args.words_per_token:
        res["words_per_pass"] = {pol: {n: v * args.words_per_token for n, v in t.items()} for pol, t in res["tokens_per_pass"].items()}
    for n in BUDGETS:
        arr = {pol: np.array(per_doc[pol][n], dtype=float) for pol in names}
        t = {}
        for suffix in ("", "_lr", "_mlp"):
            t[f"ling{suffix}_vs_conf{suffix}"] = bootstrap_gain(arr[f"ling{suffix}"], arr[f"conf{suffix}"])
            t[f"shuf{suffix}_vs_conf{suffix}"] = bootstrap_gain(arr[f"shuf{suffix}"], arr[f"conf{suffix}"])
            t[f"ling{suffix}_vs_shuf{suffix}"] = bootstrap_gain(arr[f"ling{suffix}"], arr[f"shuf{suffix}"])
            t[f"conf{suffix}_vs_confidence"] = bootstrap_gain(arr[f"conf{suffix}"], arr["confidence"])
            t[f"ling{suffix}_vs_confidence"] = bootstrap_gain(arr[f"ling{suffix}"], arr["confidence"])
            t[f"only{suffix}_vs_confidence"] = bootstrap_gain(arr[f"only{suffix}"], arr["confidence"])
        res["tests_percent_gain"][str(n)] = t
    res["wall_seconds"] = time.perf_counter() - t0
    res["peak_gpu_mib"] = torch.cuda.max_memory_allocated(DEVICE) / 2**20
    Path(args.out).parent.mkdir(parents=True, exist_ok=True)
    Path(args.out).write_text(json.dumps(res, indent=1))
    print(f"{args.name}: chain {res['chain']:.3f}, full tree {res['full_tree_84_nodes']:.3f}, chosen {chosen}", flush=True)
    for pol in names:
        print(f"  {pol:12s} " + "  ".join(f"N={n}: {res['tokens_per_pass'][pol][str(n)]:.3f}" for n in BUDGETS), flush=True)
    for n in BUDGETS:
        t = res["tests_percent_gain"][str(n)]
        print(f"  N={n:2d}  " + "   ".join(f"{k} {t[k][0]:+.2f}% [{t[k][1]:+.2f}, {t[k][2]:+.2f}]" for k in ("ling_vs_conf", "shuf_vs_conf", "conf_vs_confidence", "ling_lr_vs_conf_lr", "ling_mlp_vs_conf_mlp")), flush=True)
    for d, e in test_calibration.items():
        print(f"  depth {d} test log-loss / ECE: " + "   ".join(f"{k} {e[k]['log_loss']:.4f} / {e[k]['ece']:.4f}" for k in e if isinstance(e[k], dict)), flush=True)
    print(f"{args.name}: {res['wall_seconds']:.0f}s, peak {res['peak_gpu_mib']:.0f} MiB", flush=True)


if __name__ == "__main__":
    main()