File size: 27,446 Bytes
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
"""
SemIf (open Jev-pattern reproduction) zero-shot benchmark on the ECBS5200 canonical val split
==========================================================================================
SemIf (github.com/TheoLeeCJ/SemIf, MIT) reproduces Jev's *interface* — runtime-defined
criteria + typed options, probabilities read from one forward pass — with an open model
(pinned Qwen3.5-4B, BF16). This script runs it on the same 6,430 canonical val complaints
we gave Jev (verification/jev_benchmark.py) and scores it with the same metrics, so every
comparison is a paired bootstrap on the same examples.

SemIf's decision contract allows 2-16 options (single-letter answer slots A-P), so the flat
113-way Choice we gave Jev does not fit. Two decompositions, both zero-shot:

  bracket  (primary)  Two rounds of SemIf Choice decisions. Round 1: the 113 labels are split
                      into 8 fixed groups (seeded permutation, 14-15 labels each), one Choice
                      per group with the complaint as state and the same question Jev got;
                      all 8 share one prefill ("shared" mode). Round 2: the 8 group winners in
                      one Choice. Prediction = round-2 winner. Composed probability
                      p(label) = p1(label | its group) * p2(its group's winner), which sums to 1.
  ovr                 One binary criterion per label ("is the issue category X?", yes/no), all
                      113 sharing one prefill (SemIf's own systems-benchmark shape). The 113
                      yes/no log-odds are softmaxed into a distribution (SemIf's reranker
                      composition rule, docs/METHOD.md); prediction = argmax. The model never
                      sees the alternatives, which is why this is the secondary variant.

  *_v1 variants add the same 34 label definitions Jev got (verification/jev_criteria/v1.json).

Backend: MLX on Apple Silicon (SemIf's supported Mac path), source precision, no
quantization. Run from the SemIf venv (editable install + datasets + scikit-learn):

    SEMIF=/path/to/SemIf
    caffeinate -i $SEMIF/.venv/bin/python verification/semif_benchmark.py --variant bracket --dev --n 100
    caffeinate -i $SEMIF/.venv/bin/python verification/semif_benchmark.py --variant bracket --n 200   # val pilot
    caffeinate -i $SEMIF/.venv/bin/python verification/semif_benchmark.py --variant bracket          # full val
    $SEMIF/.venv/bin/python verification/semif_benchmark.py --variant bracket --eval-only

Every complaint's raw option logits are appended to a JSONL cache keyed by row index,
so an interrupted run resumes where it stopped and a pilot's rows are reused by the full run.
"""

import argparse
import datetime
import json
import os
import subprocess
import sys
import time
from functools import partial
from pathlib import Path

print = partial(print, flush=True)

import numpy as np

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "verification"))
from utils.data_utils import load_course_data, LABEL_LIST, NUM_LABELS
from jev_benchmark import (OUT_DIR as JEV_OUT_DIR, SEED, N_BOOT, load_comparators, pick_subset,
                           macro_f1, tier_f1, zero_f1_count, ece, paired_bootstrap)

# =========================================================================
# CONFIG
# =========================================================================
MODEL = "Qwen/Qwen3.5-4B"
REVISION = "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a"   # SemIf's pinned direct-logit baseline
TAG = "semif-qwen3.5-4b"
MAX_TOKENS = 4096
OUT_DIR = ROOT / "verification" / "semif_benchmark_artifacts"
CRITERIA_DIR = ROOT / "verification" / "jev_criteria"
PROMPT_VERSION = "semif-113way-v1"
N_GROUPS = 8
VARIANTS = ("bracket", "bracket_v1", "ovr", "ovr_v1")

# Bracket: the question Jev got, options = label names (or name + definition in _v1).
CHOICE_QUESTION = "Which issue category best describes the consumer financial complaint in `complaint`?"
CHOICE_QUESTION_V1 = json.loads((ROOT / "verification" / "jev_criteria" / "v1.json").read_text())["instructions"]

# One-vs-rest: one binary criterion per label. Wording fixed before any val example was scored;
# the only check was the train dev slice (--dev) to confirm the format is not degenerate.
QUESTION = 'Does the issue category "{label}" best describe this consumer financial complaint?'
OPTIONS = [
    {"id": "yes", "description": "Yes, it does."},
    {"id": "no", "description": "No, it does not."},
]
# v1 variant: the same 34 label definitions Jev got (verification/jev_criteria/v1.json), appended
# to the criterion for the labels that have one. Everything else identical.
QUESTION_V1 = ('Does the issue category "{label}" best describe this consumer financial complaint? '
               'Definition: {what}{not_for}')


def load_definitions():
    d = json.loads((CRITERIA_DIR / "v1.json").read_text())["criteria"]
    assert set(d) <= set(LABEL_LIST)
    return d


def label_groups(seed=SEED):
    """Fixed partition of the 113 label indices into N_GROUPS groups (seeded, label-only)."""
    perm = np.random.default_rng(seed).permutation(NUM_LABELS)
    return [sorted(g.tolist()) for g in np.array_split(perm, N_GROUPS)]


GROUPS = label_groups()   # replaced in place by --group-seed (robustness replicates)


def describe(label, definitions):
    if definitions and label in definitions:
        nf = definitions[label].get("not_for")
        return f"{label}: {definitions[label]['what']}" + (f" Not for: {nf}" if nf else "")
    return label


def choice_row(idx, text, rid, label_ids, definitions):
    return {"id": f"{idx}-{rid}", "state": {"complaint": text},
            "question": CHOICE_QUESTION_V1 if definitions else CHOICE_QUESTION,
            "options": [{"id": str(k), "description": describe(LABEL_LIST[k], definitions)}
                        for k in label_ids]}


def build_rows(idx, text, variant, definitions=None):
    """Round-1 rows: 8 group Choices (bracket) or 113 binary criteria (ovr). Same state."""
    if variant.startswith("bracket"):
        return [choice_row(idx, text, f"g{g}", ids, definitions) for g, ids in enumerate(GROUPS)]
    rows = []
    for k, label in enumerate(LABEL_LIST):
        if definitions and label in definitions:
            nf = definitions[label].get("not_for")
            q = QUESTION_V1.format(label=label, what=definitions[label]["what"],
                                   not_for=f" Not for: {nf}" if nf else "")
        else:
            q = QUESTION.format(label=label)
        rows.append({"id": f"{idx}-{k}", "state": {"complaint": text}, "question": q,
                     "options": OPTIONS})
    return rows


def cache_path(split, variant):
    return OUT_DIR / f"{TAG}_{variant}_{split}_responses.jsonl"


def load_cache(path):
    cache = {}
    if path.exists():
        for line in path.read_text().splitlines():
            rec = json.loads(line)
            cache[rec["row_idx"]] = rec
    return cache


# =========================================================================
# SemIf calls (MLX shared mode)
# =========================================================================
def load_semif():
    from semif_phase1 import mlx_backend
    t0 = time.time()
    model, tokenizer, metadata = mlx_backend.load_model(MODEL, REVISION, None)
    print(f"  loaded {MODEL}@{REVISION[:8]} on MLX in {time.time() - t0:.0f}s; "
          f"dtypes {metadata['dtype']}, mlx {metadata['mlx_version']}, mlx-lm {metadata['mlx_lm_version']}")
    return model, tokenizer, metadata


def score_one(mlx_backend, model, tokenizer, metadata, i, text, variant, definitions):
    rows = build_rows(i, text, variant, definitions)
    try:
        results, timing = mlx_backend.score_shared(model, tokenizer, rows, metadata, MAX_TOKENS)
        shared = True
    except ValueError as e:
        # 30/6,430 val complaints end with a masked amount like "{$140.00}": the closing "}" merges
        # with the JSON quote, so SemIf's prefix-cache check rejects them. Score the same prompts
        # in SemIf's direct mode (no cache reuse); prompt hashes are identical either way.
        if "state prefix does not match" not in str(e):
            raise
        results = [mlx_backend.score(model, tokenizer, row, metadata, MAX_TOKENS) for row in rows]
        timing = {"total_seconds": sum(r["total_seconds"] for r in results), "encode_seconds": 0.0,
                  "prefix_tokens": 0, "prefill_seconds": 0.0, "replicate_seconds": 0.0,
                  "suffix_forward_seconds": sum(r["forward_seconds"] for r in results),
                  "batch_size": 1, "true_suffix_tokens": sum(r["input_tokens"] for r in results),
                  "padded_suffix_tokens": sum(r["input_tokens"] for r in results)}
        shared = False
    assert [r["id"] for r in results] == [r["id"] for r in rows]
    rec = {"row_idx": int(i), "variant": variant, "shared_prefill": shared,
           "option_logits": [r["option_logits"] for r in results],
           "input_tokens": [r["input_tokens"] for r in results],
           "prompt_sha256": [r["prompt_sha256"] for r in results], "timing": timing}
    if variant.startswith("bracket"):
        assert all(r["option_ids"] == [str(k) for k in g] for r, g in zip(results, GROUPS))
        winners = [g[int(np.argmax(r["option_logits"]))] for r, g in zip(results, GROUPS)]
        final = choice_row(i, text, "final", winners, definitions)
        r2 = mlx_backend.score(model, tokenizer, final, metadata, MAX_TOKENS)
        assert r2["option_ids"] == [str(k) for k in winners]
        rec.update(winners=winners, final_logits=r2["option_logits"], final_input_tokens=r2["input_tokens"],
                   final_prompt_sha256=r2["prompt_sha256"], final_seconds=r2["total_seconds"])
        rec["timing"] = {**timing, "final_seconds": r2["total_seconds"],
                         "total_seconds": timing["total_seconds"] + r2["total_seconds"]}
    else:
        assert all(r["option_ids"] == ["yes", "no"] for r in results)
    return rec


def run_semif(texts, todo, path, variant, progress_every=25):
    from semif_phase1 import mlx_backend
    definitions = load_definitions() if variant.endswith("_v1") else None
    model, tokenizer, metadata = load_semif()
    OUT_DIR.mkdir(exist_ok=True)
    # warm-up (shader compilation) outside any recorded timing
    score_one(mlx_backend, model, tokenizer, metadata, -1, texts[todo[0]], variant, definitions)
    done, t_start = 0, time.time()
    with open(path, "a") as f:
        for i in todo:
            rec = score_one(mlx_backend, model, tokenizer, metadata, i, texts[i], variant, definitions)
            f.write(json.dumps(rec) + "\n")
            f.flush()
            done += 1
            if done == 1 or done % progress_every == 0 or done == len(todo):
                el, t = time.time() - t_start, rec["timing"]
                n_dec = len(GROUPS) + 1 if variant.startswith("bracket") else NUM_LABELS
                print(f"  {done}/{len(todo)} | {el:.0f}s | {el / done:.2f} s/complaint | "
                      f"{n_dec * done / el:.1f} decisions/s | last: prefix {t['prefix_tokens']} tok, "
                      f"prefill {t['prefill_seconds'] * 1e3:.0f} ms, suffixes {t['suffix_forward_seconds'] * 1e3:.0f} ms"
                      + (f", final {t['final_seconds'] * 1e3:.0f} ms" if "final_seconds" in t else ""))
    return metadata


# =========================================================================
# Composition + metrics
# =========================================================================
def _softmax(z):
    z = np.asarray(z, dtype=np.float64)
    e = np.exp(z - z.max(-1, keepdims=True))
    return e / e.sum(-1, keepdims=True)


def compose(cache, have):
    """113-way distribution + prediction + a per-label score used for rank diagnostics."""
    variant = cache[have[0]].get("variant", "ovr")
    n = len(have)
    if variant.startswith("bracket"):
        probs = np.zeros((n, NUM_LABELS))
        preds = np.empty(n, dtype=int)
        for r, i in enumerate(have):
            rec = cache[i]
            p2 = _softmax(rec["final_logits"])                       # over the 8 group winners
            for g, (ids, logits) in enumerate(zip(GROUPS, rec["option_logits"])):
                probs[r, ids] = _softmax(logits) * p2[g]              # p1(l|g) * p2(winner of g)
            preds[r] = rec["winners"][int(np.argmax(rec["final_logits"]))]
        assert np.allclose(probs.sum(-1), 1)
        return probs, preds, np.log(probs + 1e-300), None
    logits = np.array([cache[i]["option_logits"] for i in have], dtype=np.float64)  # n x 113 x 2
    logodds = logits[:, :, 0] - logits[:, :, 1]
    probs = _softmax(logodds)
    p_yes = 1 / (1 + np.exp(-logodds))
    return probs, probs.argmax(-1), logodds, p_yes


def load_jev_rows(have):
    """Jev's bare-label and v1 (form instruction + definitions) val answers, if present."""
    rows = []
    npz = JEV_OUT_DIR / "jev-1.13.0_val_probs.npz"
    if npz.exists():
        d = np.load(npz)
        rows.append(("Jev 1.13 zero-shot (label names only)", d["preds"][have], d["probs"][have]))
    v1 = JEV_OUT_DIR / "jev-1.13.0_v1_val_responses.jsonl"
    if v1.exists():
        c = {}
        for line in v1.read_text().splitlines():
            r = json.loads(line)
            c[r["idx"]] = r
        if all(i in c for i in have):
            rows.append(("Jev 1.13 + form instruction + definitions",
                         np.array([LABEL_LIST.index(c[i]["choice"]) for i in have]),
                         np.array([c[i]["probs"] for i in have])))
    return rows


def evaluate(sub, y_all, tiers_all, comparators, cache, label, n_requested):
    have = np.array([i for i in sub if i in cache])
    if len(have) < len(sub):
        print(f"\n  NOTE: {len(sub) - len(have)} of {len(sub)} subset rows not scored yet; "
              f"scoring the {len(have)} that are.")
    if len(have) == 0:
        return None
    y = y_all[have]
    probs, preds, logodds, p_yes = compose(cache, have)

    rows = [(label, preds, probs)]
    if comparators is not None:
        rows += load_jev_rows(have)
        rows += [(c["name"], c["preds"][have], c["probs"][have]) for c in comparators]

    print("\n" + "=" * 100)
    print(f"  RESULTS — {len(have)} examples" + ("" if n_requested is None else f" (requested n={n_requested})"))
    print("=" * 100)
    results = {"n": int(len(have)), "models": {}}
    if tiers_all is not None:
        tiers = tiers_all[have]
        tier_labels = {t: sorted(set(y_all[tiers_all == t].tolist())) for t in ("head", "mid", "tail")}
        print(f"  {'Model':<44} {'Acc':>6} {'MacroF1':>8} {'Head':>6} {'Mid':>6} {'Tail':>6} "
              f"{'Zero-F1':>9} {'ECE':>6}")
    else:
        print(f"  {'Model':<44} {'Acc':>6} {'MacroF1':>8} {'Zero-F1':>9} {'ECE':>6}")
    for name, p, pr in rows:
        z, k = zero_f1_count(y, p)
        r = {"accuracy": float((p == y).mean()), "macro_f1": float(macro_f1(y, p)),
             "zero_f1": z, "classes_present": k, "ece": float(ece(y, pr))}
        if tiers_all is not None:
            for t in ("head", "mid", "tail"):
                r[f"{t}_f1"] = float(tier_f1(y, p, tiers, t, tier_labels))
            print(f"  {name:<44} {r['accuracy']:>6.3f} {r['macro_f1']:>8.3f} {r['head_f1']:>6.3f} "
                  f"{r['mid_f1']:>6.3f} {r['tail_f1']:>6.3f} {z:>4}/{k:<4} {r['ece']:>6.3f}")
        else:
            print(f"  {name:<44} {r['accuracy']:>6.3f} {r['macro_f1']:>8.3f} {z:>4}/{k:<4} {r['ece']:>6.3f}")
        results["models"][name] = r

    if len(rows) > 1:
        print(f"\n  Paired bootstrap, Δ macro F1 = SemIf − model ({N_BOOT} resamples, seed {SEED}):")
        results["paired"] = {}
        for name, p, _ in rows[1:]:
            d, (lo, hi) = paired_bootstrap(y, preds, p)
            sig = "significant" if (lo > 0 or hi < 0) else "CI includes 0"
            results["paired"][name] = {"delta": float(d), "ci95": [float(lo), float(hi)]}
            print(f"    vs {name:<44} Δ={d:+.3f}  95% CI [{lo:+.3f}, {hi:+.3f}]  {sig}")

    # Diagnostics: where the true label ranks under the composed score; variant-specific extras
    rank_true = (logodds > logodds[np.arange(len(have)), y][:, None]).sum(-1) + 1
    top = probs.max(-1)
    correct = preds == y
    results["semif_diag"] = {
        "true_label_rank_median": float(np.median(rank_true)),
        "true_in_top5": float((rank_true <= 5).mean()),
        "true_in_top10": float((rank_true <= 10).mean()),
        "distinct_labels_predicted": int(len(set(preds.tolist()))),
    }
    extra = ""
    if p_yes is not None:
        n_yes = (p_yes > 0.5).sum(-1)
        results["semif_diag"].update({"labels_with_p_yes_gt_0.5_mean": float(n_yes.mean()),
                                      "labels_with_p_yes_gt_0.5_median": float(np.median(n_yes))})
        extra = f"; labels with p(yes)>0.5 per complaint mean {n_yes.mean():.1f}, median {np.median(n_yes):.0f}"
    else:
        # bracket: did the round-1 groups even contain the truth's winner? (truth reached the final)
        in_final = np.array([y[r] in cache[i]["winners"] for r, i in enumerate(have)])
        argmax_is_winner = (probs.argmax(-1) == preds).mean()
        results["semif_diag"].update(true_label_reached_final=float(in_final.mean()),
                                     final_accuracy_given_reached=float(correct[in_final].mean()) if in_final.any() else None,
                                     composed_argmax_equals_winner=float(argmax_is_winner))
        extra = (f"; true label reached the final {in_final.mean():.3f}, final picked it when there "
                 f"{correct[in_final].mean() if in_final.any() else float('nan'):.3f}; composed argmax = "
                 f"winner {argmax_is_winner:.3f}")
    print(f"\n  SemIf diagnostics: true label rank median {np.median(rank_true):.0f}; true in top-5 "
          f"{(rank_true <= 5).mean():.3f}, top-10 {(rank_true <= 10).mean():.3f}; distinct labels "
          f"predicted {len(set(preds.tolist()))}{extra}")
    results["semif_by_confidence"] = {}
    print("  SemIf accuracy by composed top probability:")
    for lo, hi in [(0.9, 1.01), (0.5, 0.9), (0.0, 0.5)]:
        m = (top >= lo) & (top < hi)
        if m.any():
            results["semif_by_confidence"][f"[{lo},{min(hi, 1.0)}]"] = {
                "share": float(m.mean()), "accuracy": float(correct[m].mean())}
            print(f"    p_top in [{lo:.1f}, {min(hi, 1.0):.1f}]: {m.mean():>5.1%} of examples, "
                  f"accuracy {correct[m].mean():.3f}")

    tm = [cache[i]["timing"] for i in have]
    tot = np.array([t["total_seconds"] for t in tm])
    n_dec = len(GROUPS) + 1 if p_yes is None else NUM_LABELS
    n_fallback = sum(not cache[i].get("shared_prefill", True) for i in have)
    results["semif_ops"] = {
        "decisions_per_complaint": n_dec, "rows_scored_without_shared_prefill": int(n_fallback),
        "s_per_complaint_p50": float(np.percentile(tot, 50)),
        "s_per_complaint_p95": float(np.percentile(tot, 95)),
        "decisions_per_s_mean": float(n_dec / tot.mean()),
        "prefill_ms_p50": float(np.percentile([t["prefill_seconds"] for t in tm], 50) * 1e3),
        "suffix_forward_ms_p50": float(np.percentile([t["suffix_forward_seconds"] for t in tm], 50) * 1e3),
        "prefix_tokens_mean": float(np.mean([t["prefix_tokens"] for t in tm])),
        "suffix_tokens_true_mean": float(np.mean([t["true_suffix_tokens"] for t in tm])),
        "input_tokens_per_decision_mean": float(np.mean([np.mean(cache[i]["input_tokens"]) for i in have])),
    }
    o = results["semif_ops"]
    print(f"\n  SemIf ops (MLX, this laptop): {o['s_per_complaint_p50']:.2f} s/complaint p50 "
          f"({o['s_per_complaint_p95']:.2f} p95) = {o['decisions_per_s_mean']:.1f} decisions/s ({n_dec}/complaint); "
          f"prefill {o['prefill_ms_p50']:.0f} ms, suffixes {o['suffix_forward_ms_p50']:.0f} ms; "
          f"prefix {o['prefix_tokens_mean']:.0f} tok, {o['input_tokens_per_decision_mean']:.0f} tok/decision; "
          f"{n_fallback} rows scored in direct mode (prefix-check fallback)")
    return results


def export_full(y_all, tiers_all, cache, results, variant, metadata):
    n = len(y_all)
    probs, preds, logodds, _ = compose(cache, np.arange(n))
    npz_path = OUT_DIR / f"{TAG}_{variant}_val_probs.npz"
    np.savez_compressed(npz_path, probs=probs, preds=preds, labels=y_all, tiers=tiers_all, logodds=logodds)
    try:
        commit = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True,
                                cwd=ROOT).stdout.strip()
    except OSError:
        commit = None
    semif_commit = None
    try:
        import semif_phase1
        semif_repo = Path(semif_phase1.__file__).resolve().parents[2]
        semif_commit = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True,
                                      cwd=semif_repo).stdout.strip()
    except Exception:
        pass
    import platform
    manifest = {
        "exported_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"),
        "system": "SemIf (github.com/TheoLeeCJ/SemIf), MLX backend, shared mode",
        "semif_commit": semif_commit, "build_repo_commit": commit,
        "model": {"source": MODEL, "revision": REVISION, **({k: v for k, v in metadata.items()
                  if k != "source_artifact_sha256"} if metadata else {})},
        "source_artifact_sha256": metadata.get("source_artifact_sha256") if metadata else None,
        "hardware": {"machine": platform.machine(), "platform": platform.platform(),
                     "chip": "Apple M4 Max, 128 GB unified memory"},
        "eval_set": "canonical val (utils/data_utils.py), 6,430 examples, 113 classes",
        "prompt_version": PROMPT_VERSION, "variant": variant,
        "prompt": ({"state": {"complaint": "<val complaint text, untruncated>"},
                    "question": CHOICE_QUESTION_V1 if variant.endswith("_v1") else CHOICE_QUESTION,
                    "options": "label name (+ ': definition' for the 34 v1 labels), one Choice per group, then the 8 winners",
                    "groups": GROUPS, "semif_system_prompt": "SemIf DIRECT_SYSTEM (core.py), direct-options-v1"}
                   if variant.startswith("bracket") else
                   {"state": {"complaint": "<val complaint text, untruncated>"},
                    "question": QUESTION_V1 if variant.endswith("_v1") else QUESTION, "options": OPTIONS,
                    "semif_system_prompt": "SemIf DIRECT_SYSTEM (core.py), direct-options-v1"}),
        "composition": ("p(label) = softmax_within_group(round-1 logits) * softmax(round-2 logits)[group]; "
                        "prediction = round-2 winner" if variant.startswith("bracket") else
                        "softmax over per-label (logit_yes - logit_no); prediction = argmax"),
        "files": {"responses_jsonl": cache_path("val", variant).name, "probs_npz": npz_path.name,
                  "results_json": f"{TAG}_{variant}_results_full.json"},
        "results": results,
    }
    (OUT_DIR / f"{TAG}_{variant}_manifest_full.json").write_text(json.dumps(manifest, indent=2))
    print(f"  Exported {npz_path.name} and manifest")


# =========================================================================
# Main
# =========================================================================
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--n", type=int, default=None, help="pilot size (stratified on val; first-n on dev)")
    ap.add_argument("--variant", choices=VARIANTS, default="bracket")
    ap.add_argument("--dev", action="store_true", help="train dev slice (prompt sanity), not val")
    ap.add_argument("--eval-only", action="store_true")
    ap.add_argument("--group-seed", type=int, default=SEED,
                    help="bracket grouping seed (robustness replicates; results tagged _g<seed>)")
    ap.add_argument("--fit-subset", type=int, default=None, metavar="N",
                    help="score a seeded random N-complaint subset of the fit set (train+test) for the features "
                         "experiment; no evaluation, exports probabilities only")
    args = ap.parse_args()
    if args.group_seed != SEED:
        GROUPS[:] = label_groups(args.group_seed)
        args.variant = f"{args.variant}_g{args.group_seed}"
        print(f"Bracket grouping seed {args.group_seed}: variant tag {args.variant}")

    print("Loading canonical splits...")
    train_ds, val_ds, test_ds = load_course_data()
    if args.fit_subset:
        texts = list(train_ds["text"]) + list(test_ds["text"])
        sub = np.sort(np.random.default_rng(SEED).permutation(len(texts))[: args.fit_subset])
        path = cache_path("fit", args.variant)
        cache = load_cache(path)
        todo = [int(i) for i in sub if int(i) not in cache]
        print(f"fit subset: {len(sub)} | cached: {len(sub) - len(todo)} | to score: {len(todo)} | variant {args.variant}")
        if todo:
            run_semif(texts, todo, path, args.variant, progress_every=500)
            cache = load_cache(path)
        have = np.array([i for i in sub if i in cache])
        probs, preds, _, _ = compose(cache, have)
        np.savez_compressed(OUT_DIR / f"{TAG}_{args.variant}_fit{args.fit_subset}_probs.npz",
                            fit_idx=have, probs=probs, preds=preds)
        print(f"  Exported {TAG}_{args.variant}_fit{args.fit_subset}_probs.npz ({len(have)} rows)")
        return
    if args.dev:
        dev_idx = json.loads((CRITERIA_DIR / "train_dev_idx.json").read_text())
        texts, y_all = list(train_ds["text"]), np.array(train_ds["label"])
        sub = np.array(dev_idx[: args.n] if args.n else dev_idx)
        comparators, tiers_all, split = None, None, "traindev"
    else:
        texts, y_all = list(val_ds["text"]), np.array(val_ds["label"])
        assert len(y_all) == 6430 and NUM_LABELS == 113
        print("Loading comparator val predictions from HF Hub...")
        comparators, tiers_all = load_comparators(y_all)
        sub, split = pick_subset(y_all, args.n), "val"

    path = cache_path(split, args.variant)
    cache = load_cache(path)
    todo = [int(i) for i in sub if int(i) not in cache]
    print(f"\n{split} subset: {len(sub)} | cached: {len(sub) - len(todo)} | to score: {len(todo)} "
          f"| variant {args.variant}")

    metadata = None
    if todo and not args.eval_only:
        metadata = run_semif(texts, todo, path, args.variant)
        cache = load_cache(path)

    label = f"SemIf Qwen3.5-4B {args.variant}"
    results = evaluate(sub, y_all, tiers_all, comparators, cache, label, args.n)
    if results:
        tag = "full" if (args.n is None and not args.dev) else f"{split}{args.n or len(sub)}"
        out = OUT_DIR / f"{TAG}_{args.variant}_results_{tag}.json"
        OUT_DIR.mkdir(exist_ok=True)
        out.write_text(json.dumps(results, indent=2))
        print(f"\n  Saved {out.relative_to(ROOT)}")
        if not args.dev and args.n is None and results["n"] == len(y_all):
            if metadata is None:
                from semif_phase1 import mlx_backend
                _, _, metadata = mlx_backend.load_model(MODEL, REVISION, None)
            export_full(y_all, tiers_all, cache, results, args.variant, metadata)


if __name__ == "__main__":
    main()