File size: 25,525 Bytes
b6e07f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Fit and evaluate the preregistered CPU contextual wording experiment."""
from __future__ import annotations

from argparse import ArgumentParser
import hashlib
import json
from pathlib import Path
import random
import shutil
import sys
import time

import joblib
import numpy as np
import onnxruntime as ort
from onnxruntime.quantization import QuantType, quantize_dynamic
from scipy.sparse import hstack
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, brier_score_loss, f1_score, log_loss
from threadpoolctl import threadpool_limits
import torch
from torch.utils.data import DataLoader
from transformers import AutoModel, AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup
from huggingface_hub import snapshot_download

ROOT = Path(__file__).resolve().parent
PROJECT = ROOT.parents[1]
BENCHMARK = PROJECT / "improvement_release/benchmark/local/frozen"
BASE_ID = "sentence-transformers/all-MiniLM-L6-v2"
BASE_REVISION = "1110a243fdf4706b3f48f1d95db1a4f5529b4d41"
SEED = 1729
MAX_LENGTH = 256
BATCH_SIZE = 16
THREADS = 3
WORK = ROOT / "work"
STAGE = ROOT / "stage"
CLASSES = {0: "no_biased_wording", 1: "biased_wording"}


def write_json(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")


def fingerprint(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def seed_all():
    random.seed(SEED)
    np.random.seed(SEED)
    torch.manual_seed(SEED)


def rows(split):
    return [json.loads(line) for line in (BENCHMARK / f"{split}.jsonl").read_text().splitlines() if line]


def labels(data):
    return np.array([int(row["label"]) for row in data], dtype=np.int64)


def scores(y, prediction, probability=None):
    result = {
        "rows": len(y), "macro_f1": float(f1_score(y, prediction, average="macro", labels=[0, 1], zero_division=0)),
        "accuracy": float(accuracy_score(y, prediction)),
        "per_class_f1": {CLASSES[i]: float(value) for i, value in enumerate(f1_score(y, prediction, average=None, labels=[0, 1], zero_division=0))},
    }
    if probability is not None:
        probability = np.clip(probability, 1e-7, 1 - 1e-7)
        result["brier"] = float(brier_score_loss(y, probability))
        result["negative_log_likelihood"] = float(log_loss(y, probability, labels=[0, 1]))
        confidence = np.maximum(probability, 1 - probability)
        correct = prediction == y
        ece = 0.0
        for lo in np.linspace(0, .9, 10):
            mask = (confidence >= lo) & (confidence < lo + .1 + 1e-8)
            if mask.any():
                ece += mask.mean() * abs(correct[mask].mean() - confidence[mask].mean())
        result["ece_10_bins"] = float(ece)
    return result


def probability(logits, temperature=1.0):
    values = logits / temperature
    values = np.exp(values - values.max(axis=1, keepdims=True))
    return (values / values.sum(axis=1, keepdims=True))[:, 1]


def token_batches(data, tokenizer, batch=32):
    for start in range(0, len(data), batch):
        selected = data[start:start + batch]
        tokens = tokenizer([row["text"] for row in selected], padding=True, truncation=True,
                           max_length=MAX_LENGTH, return_tensors="pt")
        yield selected, tokens


def embeddings(data, tokenizer, model):
    model.eval()
    output = []
    with torch.inference_mode():
        for _, tokens in token_batches(data, tokenizer):
            hidden = model(**tokens).last_hidden_state
            mask = tokens["attention_mask"].unsqueeze(-1)
            pooled = (hidden * mask).sum(1) / mask.sum(1).clamp(min=1)
            pooled = torch.nn.functional.normalize(pooled, dim=1)
            output.append(pooled.numpy())
    return np.concatenate(output)


def native_logits(data, tokenizer, model):
    model.eval()
    output = []
    with torch.inference_mode():
        for _, tokens in token_batches(data, tokenizer):
            value = model(**tokens)
            output.append((value if isinstance(value, torch.Tensor) else value.logits).numpy())
    return np.concatenate(output)


def logistic(train_x, y_train, validation_x, y_validation):
    best = None
    for c in (.1, 1., 10.):
        fit = LogisticRegression(C=c, max_iter=2000, class_weight="balanced", solver="liblinear", random_state=SEED)
        with threadpool_limits(limits=1):
            fit.fit(train_x, y_train)
        metric = scores(y_validation, fit.predict(validation_x))["macro_f1"]
        if best is None or metric > best["validation_macro_f1"]:
            best = {"fit": fit, "C": c, "validation_macro_f1": metric}
    return best


def fit_controls(train, validation, tokenizer, base_path):
    cached = WORK / "controls.joblib"
    expected = {split: fingerprint(BENCHMARK / f"{split}.jsonl") for split in ("train", "validation")}
    if cached.exists():
        value = joblib.load(cached)
        if value.get("data_fingerprints") == expected:
            return value["word"], value["char"], value["controls"]
    y_train, y_validation = labels(train), labels(validation)
    train_text, validation_text = [row["text"] for row in train], [row["text"] for row in validation]
    word = TfidfVectorizer(ngram_range=(1, 2), min_df=2, max_df=.98, max_features=50000, sublinear_tf=True)
    char = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5), min_df=3, max_features=80000, sublinear_tf=True)
    word_train, word_validation = word.fit_transform(train_text), word.transform(validation_text)
    char_train, char_validation = char.fit_transform(train_text), char.transform(validation_text)
    controls = {
        "word_tfidf": logistic(word_train, y_train, word_validation, y_validation),
        "character_tfidf": logistic(char_train, y_train, char_validation, y_validation),
        "word_character_tfidf": logistic(hstack([word_train, char_train]), y_train,
                                            hstack([word_validation, char_validation]), y_validation),
    }
    print("Encoding frozen MiniLM controls", flush=True)
    encoder = AutoModel.from_pretrained(base_path, local_files_only=True, attn_implementation="eager")
    train_embeddings = embeddings(train, tokenizer, encoder)
    validation_embeddings = embeddings(validation, tokenizer, encoder)
    controls["frozen_encoder_logistic"] = logistic(train_embeddings, y_train, validation_embeddings, y_validation)
    del encoder
    joblib.dump({"word": word, "char": char, "controls": controls, "data_fingerprints": expected}, cached)
    write_json(WORK / "validation_controls.json", {key: {k: v for k, v in row.items() if k != "fit"} for key, row in controls.items()})
    return word, char, controls


def fit_candidate(train, validation, tokenizer, base_path):
    best = -1.0
    history = []
    best_dir = WORK / "selected-native"
    y_validation = labels(validation)
    counts = np.bincount(labels(train), minlength=2)
    class_weights = torch.tensor(len(train) / (2 * counts), dtype=torch.float32)

    def collate(batch):
        tokens = tokenizer([row["text"] for row in batch], padding=True, truncation=True,
                           max_length=MAX_LENGTH, return_tensors="pt")
        tokens["labels"] = torch.tensor([row["label"] for row in batch], dtype=torch.long)
        return tokens

    for learning_rate in (2e-5, 5e-5):
        seed_all()
        model = AutoModelForSequenceClassification.from_pretrained(base_path, num_labels=2, id2label=CLASSES,
            label2id={value: key for key, value in CLASSES.items()}, local_files_only=True, attn_implementation="eager")
        generator = torch.Generator().manual_seed(SEED)
        loader = DataLoader(train, batch_size=BATCH_SIZE, shuffle=True, collate_fn=collate, generator=generator)
        optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=.01)
        steps = 3 * len(loader)
        scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=int(.1 * steps), num_training_steps=steps)
        for epoch in range(1, 4):
            started = time.perf_counter()
            model.train()
            loss_sum = 0.0
            for tokens in loader:
                y = tokens.pop("labels")
                optimizer.zero_grad(set_to_none=True)
                logits = model(**tokens).logits
                loss = torch.nn.functional.cross_entropy(logits, y, weight=class_weights)
                loss.backward()
                torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
                optimizer.step()
                scheduler.step()
                loss_sum += float(loss.detach())
            logits = native_logits(validation, tokenizer, model)
            metric = scores(y_validation, logits.argmax(1))
            row = {"learning_rate": learning_rate, "epoch": epoch, "training_loss": loss_sum / len(loader),
                   "validation": metric, "seconds": time.perf_counter() - started}
            history.append(row)
            print(json.dumps(row), flush=True)
            write_json(WORK / "training_history.json", history)
            if metric["macro_f1"] > best:
                best = metric["macro_f1"]
                model.save_pretrained(best_dir, safe_serialization=True)
                tokenizer.save_pretrained(best_dir)
                write_json(best_dir / "selection.json", row)
        del model, optimizer, scheduler
    return best_dir


def calibrate(validation_logits, y):
    choices = []
    for temperature in (.5, .75, 1., 1.5, 2., 3., 4.):
        p = probability(validation_logits, temperature)
        choices.append((float(log_loss(y, p, labels=[0, 1])), temperature))
    _, temperature = min(choices)
    p = probability(validation_logits, temperature)
    prediction = (p >= .5).astype(np.int64)
    full_f1 = scores(y, prediction)["macro_f1"]
    choices = []
    tradeoffs = []
    for threshold in (.55, .60, .65, .70, .75, .80, .85):
        mask = np.maximum(p, 1 - p) >= threshold
        metric = scores(y[mask], prediction[mask]) if mask.any() else {"macro_f1": 0.0}
        tradeoffs.append({"threshold": threshold, "coverage": float(mask.mean()), "resolved_macro_f1": metric["macro_f1"]})
        if mask.mean() >= .60 and metric["macro_f1"] >= full_f1 + .03:
            choices.append((float(mask.mean()), -threshold, threshold))
    threshold = max(choices)[2] if choices else .65
    return {"temperature": temperature, "threshold": threshold, "validation": scores(y, prediction, p),
            "validation_tradeoffs": tradeoffs, "method": "temperature_scaled_on_validation"}


def bootstrap(y, candidate, control, groups):
    unique = sorted(set(groups))
    indices = {group: np.flatnonzero(np.array(groups) == group) for group in unique}
    matrices = []
    for predictions in (candidate, control):
        matrices.append(np.array([np.bincount(2 * y[indices[group]] + predictions[indices[group]], minlength=4)
                                  for group in unique]))

    def macro(matrix):
        tn, fp, fn, tp = matrix
        positive = 2 * tp / max(1, 2 * tp + fp + fn)
        negative = 2 * tn / max(1, 2 * tn + fp + fn)
        return (positive + negative) / 2

    rng = np.random.default_rng(SEED)
    gains = []
    for _ in range(2000):
        weights = np.bincount(rng.integers(0, len(unique), len(unique)), minlength=len(unique))
        gains.append(macro(weights @ matrices[0]) - macro(weights @ matrices[1]))
    return {"unit": "article_group", "groups": len(unique), "draws": 2000,
            "gain_interval_95": [float(value) for value in np.quantile(gains, [.025, .975])]}


def old_control(data):
    sys.path.insert(0, str(PROJECT / "src"))
    from doxa.models import PortableModel
    model = PortableModel(PROJECT / "release_staging/model")
    predictions, probabilities, states = [], [], []
    for row in data:
        result = model.predict(row["text"], criterion_ids=["evaluative_framing"])["criteria"][0]
        state = result["suggested_decision"] or result["prediction_status"]
        states.append(state)
        values = result["scores"]
        p = values["present"] / (values["present"] + values["absent"]) if values else .5
        probabilities.append(p)
        predictions.append(int(p >= .5))
    return np.array(predictions), np.array(probabilities), states


class FrozenClassifier(torch.nn.Module):
    def __init__(self, base_path, fit):
        super().__init__()
        self.encoder = AutoModel.from_pretrained(base_path, local_files_only=True, attn_implementation="eager")
        self.register_buffer("coefficient", torch.tensor(fit.coef_[0], dtype=torch.float32))
        self.register_buffer("intercept", torch.tensor(fit.intercept_[0], dtype=torch.float32))

    def forward(self, input_ids, attention_mask, token_type_ids):
        hidden = self.encoder(input_ids=input_ids, attention_mask=attention_mask,
                              token_type_ids=token_type_ids).last_hidden_state
        mask = attention_mask.unsqueeze(-1)
        pooled = (hidden * mask).sum(1) / mask.sum(1).clamp(min=1)
        normalized = torch.nn.functional.normalize(pooled, dim=1)
        positive = normalized @ self.coefficient + self.intercept
        return torch.stack([torch.zeros_like(positive), positive], dim=1)


def export_onnx(model, tokenizer):
    folder = STAGE / "onnx"
    folder.mkdir(parents=True, exist_ok=True)

    class Logits(torch.nn.Module):
        def __init__(self, classifier):
            super().__init__()
            self.classifier = classifier

        def forward(self, input_ids, attention_mask, token_type_ids):
            value = self.classifier(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)
            return value if isinstance(value, torch.Tensor) else value.logits

    tokens = tokenizer("This policy was introduced after the committee voted.", return_tensors="pt")
    floating = WORK / "model.onnx"
    torch.onnx.export(Logits(model).eval(), (tokens["input_ids"], tokens["attention_mask"], tokens["token_type_ids"]), floating,
        input_names=["input_ids", "attention_mask", "token_type_ids"], output_names=["logits"],
        dynamic_axes={name: {0: "batch", 1: "sequence"} for name in tokens} | {"logits": {0: "batch"}},
        opset_version=17, dynamo=False)
    quantized = folder / "model_quantized.onnx"
    quantize_dynamic(str(floating), str(quantized), op_types_to_quantize=["MatMul", "Gemm", "Gather"], weight_type=QuantType.QInt8)
    return quantized


def onnx_logits(data, tokenizer, path):
    options = ort.SessionOptions()
    options.intra_op_num_threads = THREADS
    options.inter_op_num_threads = 1
    session = ort.InferenceSession(str(path), sess_options=options, providers=["CPUExecutionProvider"])
    output = []
    for _, tokens in token_batches(data, tokenizer):
        inputs = {item.name: tokens[item.name].numpy() for item in session.get_inputs()}
        output.append(session.run(None, inputs)[0])
    return np.concatenate(output)


def main():
    parser = ArgumentParser(description=__doc__)
    parser.add_argument("--evaluate-only", action="store_true", help="Reproduce export checks from the locked selected checkpoints")
    args = parser.parse_args()
    WORK.mkdir(parents=True, exist_ok=True)
    STAGE.mkdir(parents=True, exist_ok=True)
    torch.set_num_threads(THREADS)
    torch.set_num_interop_threads(1)
    seed_all()
    lock = {split: {"sha256": fingerprint(BENCHMARK / f"{split}.jsonl"),
                    "rows": sum(bool(line.strip()) for line in (BENCHMARK / f"{split}.jsonl").read_text().splitlines())}
            for split in ("train", "validation", "test")}
    lock["registration_sha256"] = fingerprint(ROOT / "EVALUATION_REGISTRATION.md")
    lock["amendment_1_sha256"] = fingerprint(ROOT / "EVALUATION_AMENDMENT_1.md")
    lock["export_plan_sha256"] = fingerprint(ROOT / "EXPORT_PLAN.md")
    write_json(WORK / "data_lock.json", lock)
    print(json.dumps({"data_lock": lock}), flush=True)
    base_path = snapshot_download(BASE_ID, revision=BASE_REVISION, token=False,
        allow_patterns=["config.json", "model.safetensors", "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "vocab.txt", "README.md"])
    tokenizer = AutoTokenizer.from_pretrained(base_path, local_files_only=True)
    train, validation = rows("train"), rows("validation")
    word, char, controls = fit_controls(train, validation, tokenizer, base_path)
    best_dir = WORK / "selected-native" if args.evaluate_only else fit_candidate(train, validation, tokenizer, base_path)
    fine_tuned = AutoModelForSequenceClassification.from_pretrained(best_dir, local_files_only=True, attn_implementation="eager")
    frozen = FrozenClassifier(base_path, controls["frozen_encoder_logistic"]["fit"])
    validation_logits = {"fine_tuned_encoder": native_logits(validation, tokenizer, fine_tuned),
                         "frozen_encoder_logistic": native_logits(validation, tokenizer, frozen)}
    validation_metrics = {name: scores(labels(validation), value.argmax(1)) for name, value in validation_logits.items()}
    selected_pipeline = max(validation_metrics, key=lambda name: validation_metrics[name]["macro_f1"])
    if args.evaluate_only:
        locked = json.loads((WORK / "pipeline_selection.json").read_text())
        if locked["selected"] != selected_pipeline:
            raise RuntimeError("The validation-selected pipeline changed")
        for name in validation_metrics:
            if abs(locked["validation"][name]["macro_f1"] - validation_metrics[name]["macro_f1"]) > 1e-8:
                raise RuntimeError("Locked validation metrics changed")
    model = fine_tuned if selected_pipeline == "fine_tuned_encoder" else frozen
    write_json(WORK / "pipeline_selection.json", {"selected": selected_pipeline, "validation": validation_metrics})
    calibration = calibrate(validation_logits[selected_pipeline], labels(validation))
    write_json(STAGE / "calibration.json", calibration)
    # Test labels and model outputs enter the experiment only after selection.
    test = rows("test")
    y_test = labels(test)
    test_logits = native_logits(test, tokenizer, model)
    candidate_prediction = test_logits.argmax(1)
    candidate_probability = probability(test_logits, calibration["temperature"])
    word_test, char_test = word.transform([row["text"] for row in test]), char.transform([row["text"] for row in test])
    encoder = AutoModel.from_pretrained(base_path, local_files_only=True, attn_implementation="eager")
    test_embeddings = embeddings(test, tokenizer, encoder)
    del encoder
    inputs = {"word_tfidf": word_test, "character_tfidf": char_test,
              "word_character_tfidf": hstack([word_test, char_test]), "frozen_encoder_logistic": test_embeddings}
    predictions = {name: row["fit"].predict(inputs[name]) for name, row in controls.items()}
    results = {name: scores(y_test, predictions[name], row["fit"].predict_proba(inputs[name])[:, 1]) for name, row in controls.items()}
    old_prediction, old_probability, old_states = old_control(test)
    predictions["doxa_framing_control"] = old_prediction
    results["doxa_framing_control"] = scores(y_test, old_prediction, old_probability)
    results["doxa_framing_control"]["original_decisions"] = {state: old_states.count(state) for state in sorted(set(old_states))}
    noncontextual_controls = [name for name in results if name != "frozen_encoder_logistic"]
    best_control = max(noncontextual_controls, key=lambda name: results[name]["macro_f1"])
    candidate = scores(y_test, candidate_prediction, candidate_probability)
    interval = bootstrap(y_test, candidate_prediction, predictions[best_control], [row["group_id"] for row in test])
    gain = candidate["macro_f1"] - results[best_control]["macro_f1"]
    native_pass = gain >= .02 and interval["gain_interval_95"][0] > 0
    if selected_pipeline == "fine_tuned_encoder":
        model.config._name_or_path = "Giuliocc/doxa-wording-encoder"
        model.save_pretrained(STAGE, safe_serialization=True)
    else:
        model.encoder.save_pretrained(STAGE / "encoder", safe_serialization=True)
        write_json(STAGE / "linear_head.json", {"coefficient": model.coefficient.tolist(), "intercept": float(model.intercept),
                    "pooling": "attention-masked mean, then L2 normalization", "logits": "[0, coefficient @ embedding + intercept]"})
    tokenizer.backend_tokenizer.no_truncation()
    tokenizer.backend_tokenizer.no_padding()
    tokenizer.save_pretrained(STAGE)
    if args.evaluate_only and (STAGE / "EVALUATION.json").exists():
        shutil.copy2(STAGE / "EVALUATION.json", WORK / "initial_export_results.json")
    if args.evaluate_only and (STAGE / "onnx/model_quantized.onnx").exists():
        shutil.copy2(STAGE / "onnx/model_quantized.onnx", WORK / "initial_matrix_quantized.onnx")
    quantized_path = export_onnx(model, tokenizer)
    quantized_logits = onnx_logits(test, tokenizer, quantized_path)
    quantized_prediction = quantized_logits.argmax(1)
    quantized = scores(y_test, quantized_prediction, probability(quantized_logits, calibration["temperature"]))
    agreement = float((quantized_prediction == candidate_prediction).mean())
    quantized_pass = abs(quantized["macro_f1"] - candidate["macro_f1"]) <= .01 and agreement >= .98
    token_counts = np.array([len(tokenizer.encode(row["text"], truncation=False)) for row in test])
    within_limit = token_counts <= MAX_LENGTH
    mask = (np.maximum(candidate_probability, 1 - candidate_probability) >= calibration["threshold"]) & within_limit
    candidate["resolved_coverage"] = float(mask.mean())
    candidate["resolved_macro_f1"] = scores(y_test[mask], candidate_prediction[mask])["macro_f1"] if mask.any() else None
    result = {"method": "doxa-wording-minilm-v1", "base_model": BASE_ID, "base_revision": BASE_REVISION,
        "data_lock": lock, "selected": json.loads((best_dir / "selection.json").read_text()),
        "task": "BABE expert-majority biased wording", "controls": results, "candidate": candidate,
        "selected_pipeline": selected_pipeline, "contextual_validation": validation_metrics,
        "test_input_limits": {"maximum_tokens": MAX_LENGTH, "within_limit": int(within_limit.sum()),
                              "exceeds_limit": int((~within_limit).sum()), "maximum_observed_tokens": int(token_counts.max())},
        "strongest_control": best_control, "macro_f1_gain": gain, "bootstrap": interval,
        "quantized": quantized, "native_quantized_agreement": agreement, "quantized_bytes": quantized_path.stat().st_size,
        "release_gate": {"native": native_pass, "quantized": quantized_pass, "size": quantized_path.stat().st_size < 40_000_000,
                         "passed": native_pass and quantized_pass and quantized_path.stat().st_size < 40_000_000},
        "new_spend_usd": 0}
    other_model = frozen if selected_pipeline == "fine_tuned_encoder" else fine_tuned
    other_name = "frozen_encoder_logistic" if selected_pipeline == "fine_tuned_encoder" else "fine_tuned_encoder"
    other_logits = native_logits(test, tokenizer, other_model)
    result["contextual_test"] = {selected_pipeline: candidate,
        other_name: scores(y_test, other_logits.argmax(1), probability(other_logits))}
    result["fine_tuning_gain_over_frozen"] = result["contextual_test"]["fine_tuned_encoder"]["macro_f1"] - result["contextual_test"]["frozen_encoder_logistic"]["macro_f1"]
    write_json(STAGE / "EVALUATION.json", result)
    write_json(WORK / "results.json", result)
    case_predictions = []
    for i, row in enumerate(test):
        case_predictions.append({"id": row["id"], "group_id": row["group_id"], "reference_label": int(y_test[i]),
            "candidate_label": int(candidate_prediction[i]), "quantized_label": int(quantized_prediction[i]),
            "model_score": float(candidate_probability[i]), "resolved": bool(mask[i]),
            "quantized_model_score": float(probability(quantized_logits[i:i+1], calibration["temperature"])[0]),
            "token_count": int(token_counts[i]), "within_deployment_limit": bool(within_limit[i]),
            "contextual_labels": {selected_pipeline: int(candidate_prediction[i]), other_name: int(other_logits[i].argmax())},
            "controls": {name: int(values[i]) for name, values in predictions.items()}})
    (STAGE / "test_predictions.jsonl").write_text("".join(json.dumps(row) + "\n" for row in case_predictions))
    write_json(STAGE / "runtime_manifest.json", {"method": "doxa-wording-minilm-v1", "task": "biased_wording",
        "model_id": "Giuliocc/doxa-wording-encoder", "revision": "v0.1.0", "maximum_tokens": MAX_LENGTH,
        "selected_pipeline": selected_pipeline,
        "temperature": calibration["temperature"], "threshold": calibration["threshold"],
        "score_calibration": calibration["method"], "files": {
            "tokenizer": {"path": "tokenizer.json", "sha256": fingerprint(STAGE / "tokenizer.json")},
            "weights": {"path": "onnx/model_quantized.onnx", "sha256": fingerprint(quantized_path), "bytes": quantized_path.stat().st_size}},
        "scope": "A provisional screen trained on English news sentences labeled for wording bias. Academic and other genres require separate validation. Read the surrounding context."})
    print(json.dumps(result, indent=2), flush=True)


if __name__ == "__main__":
    main()