File size: 24,597 Bytes
715cc5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
from __future__ import annotations

import argparse
import json
import random
import re
from collections import Counter
from pathlib import Path
from typing import Any

import numpy as np
import torch
import yaml
from sklearn.utils.class_weight import compute_class_weight
from torch.utils.data import Dataset, WeightedRandomSampler
from transformers import EarlyStoppingCallback, Trainer, TrainingArguments, set_seed

from src.data.io_utils import read_csv_dicts, read_jsonl, write_csv, write_json, write_jsonl
from src.eval.calibration import expected_calibration_error
from src.eval.confusion_matrix import confusion_matrix_rows
from src.models.encoder_verifier import load_sequence_classifier, load_tokenizer, sanitize_model_name
from src.utils.metrics import classification_metrics, softmax


class VerifierDataset(Dataset):
    def __init__(self, rows: list[dict[str, Any]], tokenizer: Any, label2id: dict[str, int], max_length: int):
        self.rows = rows
        self.encodings = tokenizer(
            [row["input_text"] for row in rows],
            padding=True,
            truncation=True,
            max_length=max_length,
        )
        self.labels = [label2id[row["label"]] for row in rows]

    def __len__(self) -> int:
        return len(self.rows)

    def __getitem__(self, idx: int) -> dict[str, torch.Tensor]:
        item = {key: torch.tensor(value[idx]) for key, value in self.encodings.items()}
        item["labels"] = torch.tensor(self.labels[idx], dtype=torch.long)
        return item


class WeightedTrainer(Trainer):
    def __init__(
        self,
        class_weights: torch.Tensor | None = None,
        train_sampler: WeightedRandomSampler | None = None,
        loss_type: str = "cross_entropy",
        focal_gamma: float = 2.0,
        **kwargs: Any,
    ):
        super().__init__(**kwargs)
        self.class_weights = class_weights
        self.train_sampler = train_sampler
        self.loss_type = loss_type
        self.focal_gamma = focal_gamma

    def _get_train_sampler(self, train_dataset: Dataset | None = None) -> torch.utils.data.Sampler | None:
        if self.train_sampler is not None:
            return self.train_sampler
        return super()._get_train_sampler(train_dataset)

    def compute_loss(
        self,
        model: torch.nn.Module,
        inputs: dict[str, torch.Tensor | Any],
        return_outputs: bool = False,
        num_items_in_batch: torch.Tensor | int | None = None,
    ) -> torch.Tensor | tuple[torch.Tensor, Any]:
        labels = inputs.pop("labels")
        outputs = model(**inputs)
        logits = outputs.logits
        weights = self.class_weights.to(logits.device) if self.class_weights is not None else None
        logits = logits.view(-1, logits.shape[-1])
        labels = labels.view(-1)
        if self.loss_type == "focal_loss":
            log_probs = torch.nn.functional.log_softmax(logits, dim=-1)
            log_pt = log_probs.gather(1, labels.unsqueeze(1)).squeeze(1)
            pt = log_pt.exp()
            ce_loss = torch.nn.functional.nll_loss(log_probs, labels, weight=weights, reduction="none")
            loss = ((1 - pt) ** self.focal_gamma * ce_loss).mean()
        else:
            loss = torch.nn.functional.cross_entropy(logits, labels, weight=weights)
        return (loss, outputs) if return_outputs else loss


def effective_max_length(tokenizer: Any, requested: int) -> int:
    tokenizer_max = getattr(tokenizer, "model_max_length", None)
    if isinstance(tokenizer_max, int) and 0 < tokenizer_max < 100_000:
        return min(requested, tokenizer_max)
    return requested


def token_length_stats(rows: list[dict[str, Any]], tokenizer: Any, max_length: int) -> dict[str, Any]:
    lengths: list[int] = []
    for row in rows:
        ids = tokenizer(row["input_text"], truncation=False, add_special_tokens=True)["input_ids"]
        lengths.append(len(ids))
    if not lengths:
        return {"avg_tokens": 0.0, "max_tokens": 0, "pct_over_max_length": 0.0}
    over = sum(1 for length in lengths if length > max_length)
    return {
        "avg_tokens": round(float(np.mean(lengths)), 4),
        "max_tokens": int(max(lengths)),
        "pct_over_max_length": round(over / len(lengths), 6),
    }


def normalized_class_weights(counts: list[int], mode: str) -> np.ndarray:
    total = sum(counts)
    safe_counts = np.array([max(1, count) for count in counts], dtype=np.float64)
    if mode == "inverse_frequency":
        weights = total / safe_counts
    elif mode == "inverse_sqrt_frequency":
        weights = np.sqrt(total / safe_counts)
    else:
        raise ValueError(f"Unsupported class weight mode: {mode}")
    return weights / weights.mean()

def class_weights_for(rows: list[dict[str, Any]], label_set: list[str], label2id: dict[str, int], mode: str | None) -> torch.Tensor | None:
    if mode in (None, "", "none", "None"):
        return None
    mode = str(mode)
    labels = np.array([label2id[row["label"]] for row in rows])
    classes = np.arange(len(label_set))
    if mode == "balanced":
        weights = compute_class_weight(class_weight="balanced", classes=classes, y=labels)
    elif mode in {"inverse_frequency", "inverse_sqrt_frequency"}:
        counts_by_id = Counter(int(label_id) for label_id in labels)
        counts = [counts_by_id.get(class_id, 0) for class_id in classes]
        weights = normalized_class_weights(counts, mode)
    else:
        raise ValueError(f"Unsupported class weight mode: {mode}")
    return torch.tensor(weights, dtype=torch.float)

def sampler_for(rows: list[dict[str, Any]], label2id: dict[str, int], cfg: dict[str, Any] | None) -> WeightedRandomSampler | None:
    if not cfg or cfg.get("type") != "weighted_random_sampler":
        return None
    mode = str(cfg.get("weight_mode", "inverse_frequency"))
    cap = float(cfg.get("minority_sampling_cap", cfg.get("cap", 3.0)))
    labels = [label2id[row["label"]] for row in rows]
    counts_by_id = Counter(labels)
    counts = [counts_by_id.get(class_id, 0) for class_id in range(len(label2id))]
    class_weights = normalized_class_weights(counts, mode)
    if cap > 0:
        min_weight = float(class_weights.min())
        class_weights = np.minimum(class_weights, min_weight * cap)
    sample_weights = torch.tensor([float(class_weights[label_id]) for label_id in labels], dtype=torch.double)
    return WeightedRandomSampler(sample_weights, num_samples=len(sample_weights), replacement=True)


def write_predictions(
    path: Path,
    rows: list[dict[str, Any]],
    probs: np.ndarray,
    pred_ids: np.ndarray,
    id2label: dict[int, str],
    model_name: str,
    seed: int,
) -> None:
    out_rows: list[dict[str, Any]] = []
    for row, prob, pred_id in zip(rows, probs, pred_ids, strict=False):
        evidence = row.get("evidence", [])
        out_rows.append(
            {
                "id": row.get("id"),
                "dataset": row.get("dataset"),
                "split": row.get("split"),
                "gold": row.get("label"),
                "prediction": id2label[int(pred_id)],
                "confidence": round(float(prob.max()), 6),
                "probabilities": {id2label[idx]: round(float(value), 6) for idx, value in enumerate(prob)},
                "model_name": model_name,
                "seed": seed,
                "claim": row.get("claim"),
                "evidence_ids": [item.get("candidate_id") for item in evidence],
            }
        )
    write_jsonl(path, out_rows)


def evaluate_split(
    trainer: Trainer,
    rows: list[dict[str, Any]],
    dataset: VerifierDataset,
    split_key: str,
    output_dir: Path,
    label_set: list[str],
    id2label: dict[int, str],
    model_name: str,
    seed: int,
) -> dict[str, Any]:
    pred = trainer.predict(dataset)
    logits = np.asarray(pred.predictions)
    probs = softmax(logits)
    pred_ids = probs.argmax(axis=1)
    true_ids = np.asarray([label_set.index(row["label"]) for row in rows])
    y_true = [row["label"] for row in rows]
    y_pred = [id2label[int(idx)] for idx in pred_ids]
    metrics = classification_metrics(label_set, y_true, y_pred)
    metrics["ece"] = expected_calibration_error(probs, true_ids)
    metrics["split"] = split_key
    metrics["eval_size"] = len(rows)
    write_predictions(output_dir / f"predictions_{split_key}.jsonl", rows, probs, pred_ids, id2label, model_name, seed)
    write_csv(output_dir / f"confusion_matrix_{split_key}.csv", confusion_matrix_rows(label_set, y_true, y_pred))
    return metrics


def update_csv_by_key(path: Path, new_rows: list[dict[str, Any]], key_fields: list[str]) -> None:
    existing = read_csv_dicts(path) if path.exists() else []
    new_keys = {tuple(str(row.get(field, "")) for field in key_fields) for row in new_rows}
    kept = [row for row in existing if tuple(str(row.get(field, "")) for field in key_fields) not in new_keys]
    write_csv(path, kept + new_rows)


def aggregate_seed_metrics(seed_metrics: list[dict[str, Any]], key: str) -> tuple[float, float]:
    values = [float(row[key]) for row in seed_metrics]
    return round(float(np.mean(values)), 6), round(float(np.std(values, ddof=0)), 6)

def load_available_seed_results(base_dir: Path, in_memory_results: list[dict[str, Any]]) -> list[dict[str, Any]]:
    results_by_seed = {int(row["seed"]): row for row in in_memory_results}
    for metrics_path in base_dir.glob("seed_*/metrics.json"):
        try:
            metrics = json.loads(metrics_path.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError):
            continue
        if "seed" in metrics and "test" in metrics:
            results_by_seed[int(metrics["seed"])] = metrics
    return [results_by_seed[seed] for seed in sorted(results_by_seed)]


def loss_name(cfg: dict[str, Any]) -> str:
    loss_cfg = cfg.get("loss") or {}
    loss_type = str(loss_cfg.get("type", "cross_entropy"))
    class_weight_mode = loss_cfg.get("class_weight_mode")
    if class_weight_mode is None:
        class_weight_mode = (cfg.get("training") or {}).get("class_weight")
    if loss_type == "focal_loss":
        gamma = float(loss_cfg.get("gamma", 2.0))
        suffix = f":{class_weight_mode}" if class_weight_mode else ""
        return f"focal_loss:gamma={gamma:g}{suffix}"
    if class_weight_mode:
        return f"weighted_cross_entropy:{class_weight_mode}"
    return loss_type


def input_metadata(cfg: dict[str, Any]) -> dict[str, str]:
    train_path = Path(cfg["input"]["train"])
    top_match = re.search(r"_top(\d+)", train_path.stem)
    top_k = top_match.group(1) if top_match else ""
    input_format = str((cfg.get("input") or {}).get("format") or cfg.get("input_format") or "flat")
    if train_path.stem.endswith("_qa"):
        input_format = "qa"
    return {"top_k": top_k, "input_format": input_format}


def method_metadata(
    dataset: str,
    model_name: str,
    top_k: str,
    loss: str,
    sampler: dict[str, Any] | None,
    input_format: str,
) -> dict[str, str]:
    if dataset == "healthver":
        return {
            "Protocol": "P6",
            "Method": "PubMedBERT baseline",
            "Evidence source": "paired evidence + augmentation",
            "Notes": "pair-level anchored protocol",
        }
    if dataset == "vifactcheck":
        return {
            "Protocol": "P1",
            "Method": "XLM-R baseline",
            "Evidence source": "context chunks",
            "Notes": "gold Evidence excluded from main input",
        }
    model_family = "DeBERTa-v3-large" if "deberta" in model_name.lower() else "ModernBERT"
    sampler_suffix = " sampler" if sampler and sampler.get("type") == "weighted_random_sampler" else ""
    qa_suffix = " QA" if input_format == "qa" else ""
    if "deberta" in model_name.lower():
        loss_suffix = " focal" if loss.startswith("focal_loss") else ""
        return {
            "Protocol": "P4",
            "Method": f"{model_family} top{top_k}{qa_suffix}{loss_suffix} weighted{sampler_suffix} rescue",
            "Evidence source": "retrieved evidence",
            "Notes": "AVeriTeC rescue candidate; official dev used as local_test; hidden test excluded",
        }
    if sampler and sampler.get("type") == "weighted_random_sampler":
        loss_suffix = " focal" if loss.startswith("focal_loss") else ""
        return {
            "Protocol": "P4",
            "Method": f"{model_family} top{top_k}{qa_suffix}{loss_suffix} weighted sampler rescue",
            "Evidence source": "retrieved evidence",
            "Notes": "AVeriTeC rescue candidate with weighted sampler; official dev used as local_test; hidden test excluded",
        }
    if top_k == "10":
        loss_suffix = " focal" if loss.startswith("focal_loss") else ""
        return {
            "Protocol": "P4",
            "Method": f"{model_family} top{top_k}{qa_suffix}{loss_suffix} weighted rescue",
            "Evidence source": "retrieved evidence",
            "Notes": "AVeriTeC rescue candidate; official dev used as local_test; hidden test excluded",
        }
    return {
        "Protocol": "P4",
        "Method": "ModernBERT baseline",
        "Evidence source": "retrieved evidence",
        "Notes": "official dev used as local_test; hidden test excluded",
    }


def run_seed(cfg: dict[str, Any], seed: int, output_dir: Path) -> dict[str, Any]:
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    set_seed(seed)

    dataset_name = cfg["dataset"]
    model_name = cfg["model_name"]
    label_set = list(cfg["label_set"])
    label2id = {label: idx for idx, label in enumerate(label_set)}
    id2label = {idx: label for label, idx in label2id.items()}
    training_cfg = cfg["training"]

    train_rows = [row for row in read_jsonl(Path(cfg["input"]["train"])) if row.get("label") in label2id]
    dev_rows = [row for row in read_jsonl(Path(cfg["input"]["dev"])) if row.get("label") in label2id]
    test_rows = [row for row in read_jsonl(Path(cfg["input"]["test"])) if row.get("label") in label2id]

    tokenizer = load_tokenizer(model_name)
    requested_max_length = int(training_cfg.get("max_length", 512))
    max_length = effective_max_length(tokenizer, requested_max_length)
    model = load_sequence_classifier(model_name, len(label_set), label_set)

    train_dataset = VerifierDataset(train_rows, tokenizer, label2id, max_length=max_length)
    dev_dataset = VerifierDataset(dev_rows, tokenizer, label2id, max_length=max_length)
    test_dataset = VerifierDataset(test_rows, tokenizer, label2id, max_length=max_length)
    loss_cfg = cfg.get("loss") or {}
    loss_type = loss_cfg.get("type", "cross_entropy")
    focal_gamma = float(loss_cfg.get("gamma", 2.0))
    class_weight_mode = loss_cfg.get("class_weight_mode")
    if class_weight_mode is None:
        class_weight_mode = training_cfg.get("class_weight")
    if loss_type not in {"cross_entropy", "weighted_cross_entropy", "focal_loss"}:
        raise ValueError(f"Unsupported loss type: {loss_type}")
    if loss_type == "weighted_cross_entropy" and not class_weight_mode:
        raise ValueError("loss.type=weighted_cross_entropy requires loss.class_weight_mode")
    weights = class_weights_for(train_rows, label_set, label2id, class_weight_mode)
    train_sampler = sampler_for(train_rows, label2id, cfg.get("sampler"))

    args = TrainingArguments(
        output_dir=str(output_dir / "trainer"),
        num_train_epochs=float(training_cfg.get("epochs", 3)),
        per_device_train_batch_size=int(training_cfg.get("batch_size", 8)),
        per_device_eval_batch_size=int(training_cfg.get("eval_batch_size", training_cfg.get("batch_size", 8))),
        gradient_accumulation_steps=int(training_cfg.get("gradient_accumulation_steps", 1)),
        learning_rate=float(training_cfg.get("learning_rate", 2e-5)),
        weight_decay=float(training_cfg.get("weight_decay", 0.01)),
        warmup_ratio=float(training_cfg.get("warmup_ratio", 0.06)),
        eval_strategy="epoch",
        save_strategy="epoch",
        logging_strategy="steps",
        logging_steps=int(training_cfg.get("logging_steps", 25)),
        load_best_model_at_end=True,
        metric_for_best_model=str(training_cfg.get("metric_for_best_model", "macro_f1")),
        greater_is_better=True,
        save_total_limit=1,
        bf16=bool(training_cfg.get("precision") == "bf16" and torch.cuda.is_available()),
        fp16=bool(training_cfg.get("precision") == "fp16" and torch.cuda.is_available()),
        report_to=[],
        seed=seed,
        dataloader_num_workers=int(training_cfg.get("dataloader_num_workers", 0)),
    )

    def compute_metrics(eval_pred: Any) -> dict[str, float]:
        logits, labels = eval_pred
        pred_ids = np.asarray(logits).argmax(axis=1)
        y_true = [id2label[int(idx)] for idx in labels]
        y_pred = [id2label[int(idx)] for idx in pred_ids]
        metrics = classification_metrics(label_set, y_true, y_pred)
        return {
            "accuracy": metrics["accuracy"],
            "macro_f1": metrics["macro_f1"],
            "weighted_f1": metrics["weighted_f1"],
        }

    trainer = WeightedTrainer(
        model=model,
        args=args,
        train_dataset=train_dataset,
        eval_dataset=dev_dataset,
        processing_class=tokenizer,
        compute_metrics=compute_metrics,
        callbacks=[EarlyStoppingCallback(early_stopping_patience=int(training_cfg.get("early_stopping_patience", 2)))],
        class_weights=weights,
        train_sampler=train_sampler,
        loss_type=loss_type,
        focal_gamma=focal_gamma,
    )
    trainer.train()

    dev_metrics = evaluate_split(trainer, dev_rows, dev_dataset, "dev", output_dir, label_set, id2label, model_name, seed)
    test_metrics = evaluate_split(trainer, test_rows, test_dataset, "test", output_dir, label_set, id2label, model_name, seed)
    train_token_stats = token_length_stats(train_rows, tokenizer, max_length)
    dev_token_stats = token_length_stats(dev_rows, tokenizer, max_length)
    test_token_stats = token_length_stats(test_rows, tokenizer, max_length)

    training_log = trainer.state.log_history
    write_jsonl(output_dir / "training_log.jsonl", training_log)
    metrics = {
        "dataset": dataset_name,
        "model_name": model_name,
        "seed": seed,
        "label_set": label_set,
        "requested_max_length": requested_max_length,
        "effective_max_length": max_length,
        "train_size": len(train_rows),
        "loss": {
            "type": loss_type,
            "gamma": focal_gamma if loss_type == "focal_loss" else None,
            "class_weight_mode": class_weight_mode,
            "class_weights": [round(float(value), 6) for value in weights.tolist()] if weights is not None else None,
        },
        "sampler": cfg.get("sampler"),
        "dev": dev_metrics,
        "test": test_metrics,
        "token_stats": {
            "train": train_token_stats,
            "dev": dev_token_stats,
            "test": test_token_stats,
        },
    }
    write_json(output_dir / "metrics.json", metrics)
    return metrics


def update_summary_tables(cfg: dict[str, Any], model_dir_name: str, seed_results: list[dict[str, Any]], output_root: Path) -> None:
    dataset = cfg["dataset"]
    model_name = cfg["model_name"]
    test_seed_metrics = [row["test"] for row in seed_results]
    acc_mean, acc_std = aggregate_seed_metrics(test_seed_metrics, "accuracy")
    f1_mean, f1_std = aggregate_seed_metrics(test_seed_metrics, "macro_f1")
    per_class = test_seed_metrics[-1].get("per_class_f1", "{}")
    input_meta = input_metadata(cfg)
    top_k = input_meta["top_k"]
    input_format = input_meta["input_format"]
    loss = loss_name(cfg)
    meta = method_metadata(dataset, model_name, top_k, loss, cfg.get("sampler"), input_format)
    seed_count = len(seed_results)
    last_per_class = test_seed_metrics[-1].get("per_class", {})
    collapse_labels = [
        label
        for label, values in last_per_class.items()
        if float(values.get("f1", 0.0)) < 0.1 and (dataset == "averitec" or float(values.get("support", 0)) > 0)
    ]
    collapse_warning = "No" if not collapse_labels else f"YES: {'/'.join(collapse_labels)} collapse"
    averitec_rescue_minimum_pass = True
    if dataset == "averitec":
        nei_f1 = float(last_per_class.get("NEI", {}).get("f1", 0.0))
        conflicting_f1 = float(last_per_class.get("CONFLICTING", {}).get("f1", 0.0))
        averitec_rescue_minimum_pass = f1_mean >= 0.4 and nei_f1 > 0.1 and conflicting_f1 > 0.1

    if dataset == "averitec" and (collapse_labels or not averitec_rescue_minimum_pass):
        gate = "NEEDS_RESCUE"
        strong_gate_status = "PENDING_AVERITEC_RESCUE"
    elif dataset == "averitec" and seed_count < 3:
        gate = "RESCUE_MINIMUM_PASS"
        strong_gate_status = "PENDING_3_SEEDS"
    elif seed_count >= 3:
        gate = "STRONG_PASS_CANDIDATE"
        strong_gate_status = "READY_FOR_STRONG_GATE_REVIEW"
    else:
        gate = "MINIMUM_PASS"
        strong_gate_status = "PENDING_3_SEEDS"

    t11_row = {
        "Dataset": dataset,
        "Protocol": meta["Protocol"],
        "Method": meta["Method"],
        "Evidence source": meta["Evidence source"],
        "Verifier": model_name,
        "KG/path": "No",
        "Top-k": top_k,
        "input_top_k": top_k,
        "input_format": input_format,
        "loss_type": loss,
        "Acc": acc_mean,
        "Acc std": acc_std,
        "Macro-F1": f1_mean,
        "Macro-F1 std": f1_std,
        "Per-class F1": per_class,
        "Seeds": ",".join(str(row["seed"]) for row in seed_results),
        "seed_count": seed_count,
        "collapse_warning": collapse_warning,
        "strong_gate_status": strong_gate_status,
        "Gate": gate,
        "Notes": meta["Notes"],
    }
    update_csv_by_key(
        output_root / "tables" / "T11_main_verification.csv",
        [t11_row],
        key_fields=["Dataset", "Method", "Verifier", "Top-k", "loss_type", "input_format"],
    )

    training = cfg["training"]
    t5_row = {
        "Dataset": dataset,
        "Verifier": model_name,
        "Model dir": model_dir_name,
        "Top-k": top_k,
        "input_format": input_format,
        "max_length": training.get("max_length"),
        "batch_size": training.get("batch_size"),
        "gradient_accumulation_steps": training.get("gradient_accumulation_steps"),
        "learning_rate": training.get("learning_rate"),
        "epochs": training.get("epochs"),
        "precision": training.get("precision"),
        "loss_type": loss,
        "sampler": json.dumps(cfg.get("sampler"), sort_keys=True) if cfg.get("sampler") else "",
        "seeds": ",".join(str(seed) for seed in cfg["training"].get("seeds", [])),
    }
    update_csv_by_key(
        output_root / "tables" / "T5_training_config.csv",
        [t5_row],
        key_fields=["Dataset", "Verifier", "Model dir", "Top-k"],
    )


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", type=Path, required=True)
    parser.add_argument("--output-root", type=Path, default=Path("outputs"))
    parser.add_argument("--seeds", type=int, nargs="*", default=None)
    parser.add_argument("--refresh-summary-only", action="store_true")
    args = parser.parse_args()

    cfg = yaml.safe_load(args.config.read_text(encoding="utf-8"))
    seeds = args.seeds if args.seeds else list(cfg["training"].get("seeds", [13]))
    cfg["training"]["seeds"] = seeds
    model_dir_name = str(cfg.get("output_name") or sanitize_model_name(cfg["model_name"])).replace("/", "__")
    base_dir = args.output_root / "baselines" / cfg["dataset"] / "encoder_verifier" / model_dir_name
    base_dir.mkdir(parents=True, exist_ok=True)

    seed_results: list[dict[str, Any]] = []
    if not args.refresh_summary_only:
        for seed in seeds:
            seed_dir = base_dir / f"seed_{seed}"
            seed_dir.mkdir(parents=True, exist_ok=True)
            seed_results.append(run_seed(cfg, seed, seed_dir))

    all_seed_results = load_available_seed_results(base_dir, seed_results)
    if not all_seed_results:
        raise FileNotFoundError(f"No seed metrics found under {base_dir}")
    cfg["training"]["seeds"] = [int(row["seed"]) for row in all_seed_results]
    write_json(base_dir / "summary.json", {"config": cfg, "seeds": cfg["training"]["seeds"], "results": all_seed_results})
    update_summary_tables(cfg, model_dir_name, all_seed_results, args.output_root)
    print(f"Wrote encoder verifier outputs to {base_dir}")


if __name__ == "__main__":
    main()