| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import math |
| from collections import Counter, defaultdict |
| from pathlib import Path |
| from statistics import median |
| from typing import Any, Iterable |
|
|
| from src.data.io_utils import read_jsonl, write_csv |
| from src.models.encoder_verifier import load_tokenizer |
|
|
| LABEL_ORDER = ["SUPPORTS", "REFUTES", "NEI", "CONFLICTING"] |
| DEFAULT_CLAIMS = [ |
| Path("data_processed/averitec/claims_train_inner.jsonl"), |
| Path("data_processed/averitec/claims_dev_inner.jsonl"), |
| Path("data_processed/averitec/claims_local_test.jsonl"), |
| ] |
| DEFAULT_CANDIDATE_POOLS = [ |
| Path("outputs/retrieval/averitec/candidate_pool_train_inner.jsonl"), |
| Path("outputs/retrieval/averitec/candidate_pool_dev_inner.jsonl"), |
| Path("outputs/retrieval/averitec/candidate_pool_local_test.jsonl"), |
| ] |
| DEFAULT_VERIFIER_INPUTS = [ |
| Path("outputs/verifier_inputs/averitec/train_inner_top10_qa.jsonl"), |
| Path("outputs/verifier_inputs/averitec/dev_inner_top10_qa.jsonl"), |
| Path("outputs/verifier_inputs/averitec/local_test_top10_qa.jsonl"), |
| ] |
| DEFAULT_PREDICTIONS = Path( |
| "outputs/baselines/averitec/encoder_verifier/" |
| "answerdotai__ModernBERT-large_top10_qa_weighted_sampler/seed_13/predictions_test.jsonl" |
| ) |
| DEFAULT_METRICS = Path( |
| "outputs/baselines/averitec/encoder_verifier/" |
| "answerdotai__ModernBERT-large_top10_qa_weighted_sampler/seed_13/metrics.json" |
| ) |
|
|
|
|
| def existing(paths: Iterable[Path]) -> list[Path]: |
| return [path for path in paths if path.exists()] |
|
|
|
|
| def infer_split(path: Path, row: dict[str, Any] | None = None) -> str: |
| if row and row.get("split"): |
| return str(row["split"]) |
| stem = path.stem |
| if stem.startswith("claims_"): |
| return stem.removeprefix("claims_") |
| if stem.startswith("candidate_pool_"): |
| return stem.removeprefix("candidate_pool_") |
| for split in ["train_inner", "dev_inner", "local_test", "hidden_test", "train", "dev", "test"]: |
| if split in stem: |
| return split |
| return stem |
|
|
|
|
| def pct(numerator: int | float, denominator: int | float) -> float: |
| if not denominator: |
| return 0.0 |
| return round(float(numerator) / float(denominator) * 100.0, 6) |
|
|
|
|
| def as_bool(value: Any) -> bool: |
| return bool(value) if value is not None else False |
|
|
|
|
| def safe_float(value: Any) -> float: |
| try: |
| if value is None: |
| return 0.0 |
| numeric = float(value) |
| if math.isnan(numeric) or math.isinf(numeric): |
| return 0.0 |
| return numeric |
| except (TypeError, ValueError): |
| return 0.0 |
|
|
|
|
| def percentile(values: list[int], q: float) -> float: |
| if not values: |
| return 0.0 |
| ordered = sorted(values) |
| if len(ordered) == 1: |
| return float(ordered[0]) |
| position = (len(ordered) - 1) * q |
| lower = math.floor(position) |
| upper = math.ceil(position) |
| if lower == upper: |
| return float(ordered[int(position)]) |
| fraction = position - lower |
| return float(ordered[lower] * (1 - fraction) + ordered[upper] * fraction) |
|
|
|
|
| def load_claims(paths: list[Path]) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]]]: |
| claims_by_id: dict[str, dict[str, Any]] = {} |
| rows: list[dict[str, Any]] = [] |
| for path in paths: |
| for row in read_jsonl(path): |
| claim_id = str(row.get("claim_id") or row.get("id") or "") |
| if not claim_id: |
| continue |
| row = dict(row) |
| row.setdefault("split", infer_split(path, row)) |
| claims_by_id[claim_id] = row |
| rows.append(row) |
| return claims_by_id, rows |
|
|
|
|
| def label_distribution_rows(claim_rows: list[dict[str, Any]]) -> list[dict[str, Any]]: |
| grouped: dict[str, list[dict[str, Any]]] = defaultdict(list) |
| for row in claim_rows: |
| grouped[str(row.get("split") or "unknown")].append(row) |
|
|
| output: list[dict[str, Any]] = [] |
| for split in sorted(grouped): |
| rows = grouped[split] |
| counts = Counter(str(row.get("label") or "UNLABELED") for row in rows) |
| labels = list(LABEL_ORDER) |
| labels.extend(label for label in sorted(counts) if label not in labels) |
| total = len(rows) |
| out: dict[str, Any] = {"Split": split, "Total": total} |
| for label in labels: |
| out[label] = counts.get(label, 0) |
| for label in labels: |
| out[f"{label}_pct"] = pct(counts.get(label, 0), total) |
| output.append(out) |
| return output |
|
|
|
|
| def retrieval_by_label_rows( |
| candidate_paths: list[Path], |
| claims_by_id: dict[str, dict[str, Any]], |
| ) -> list[dict[str, Any]]: |
| grouped: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list) |
| for path in candidate_paths: |
| fallback_split = infer_split(path) |
| for row in read_jsonl(path): |
| query_id = str(row.get("query_id") or row.get("id") or "") |
| claim = claims_by_id.get(query_id, {}) |
| label = str(claim.get("label") or row.get("label") or "UNLABELED") |
| split = str(row.get("split") or claim.get("split") or fallback_split) |
| grouped[(split, label)].append(row) |
|
|
| output: list[dict[str, Any]] = [] |
| for split, label in sorted(grouped, key=lambda key: (key[0], LABEL_ORDER.index(key[1]) if key[1] in LABEL_ORDER else 99, key[1])): |
| rows = grouped[(split, label)] |
| count = len(rows) |
| r5 = sum(1 for row in rows if as_bool(row.get("metrics", {}).get("gold_at_5"))) |
| r10 = sum(1 for row in rows if as_bool(row.get("metrics", {}).get("gold_at_10"))) |
| r30 = sum(1 for row in rows if as_bool(row.get("metrics", {}).get("gold_at_30"))) |
| has_gold = sum(1 for row in rows if row.get("metrics", {}).get("has_gold") is not False) |
| mrr_values = [safe_float(row.get("metrics", {}).get("mrr")) for row in rows] |
| ndcg_values = [safe_float(row.get("metrics", {}).get("ndcg_at_10")) for row in rows] |
| output.append( |
| { |
| "Split": split, |
| "Label": label, |
| "Count": count, |
| "Has_gold_count": has_gold, |
| "R@5": round(r5 / max(1, count), 6), |
| "R@10": round(r10 / max(1, count), 6), |
| "R@30": round(r30 / max(1, count), 6), |
| "MRR": round(sum(mrr_values) / max(1, count), 6), |
| "nDCG@10": round(sum(ndcg_values) / max(1, count), 6), |
| } |
| ) |
| return output |
|
|
|
|
| def parse_top_k(path: Path, rows: list[dict[str, Any]]) -> str: |
| for row in rows: |
| if row.get("top_k") is not None: |
| return str(row["top_k"]) |
| stem = path.stem |
| for part in stem.split("_"): |
| if part.startswith("top") and part[3:].isdigit(): |
| return part[3:] |
| return "" |
|
|
|
|
| def tokenize_lengths(tokenizer: Any, texts: list[str]) -> list[int]: |
| lengths: list[int] = [] |
| for text in texts: |
| lengths.append(len(tokenizer(str(text), add_special_tokens=True, truncation=False)["input_ids"])) |
| return lengths |
|
|
|
|
| def truncation_report_rows( |
| verifier_paths: list[Path], |
| max_lengths: list[int], |
| tokenizer_model: str, |
| ) -> list[dict[str, Any]]: |
| try: |
| tokenizer = load_tokenizer(tokenizer_model) |
| tokenizer_status = "ok" |
| except Exception as exc: |
| tokenizer = None |
| tokenizer_status = f"fallback_whitespace:{type(exc).__name__}" |
|
|
| grouped: dict[tuple[str, str, str, str], list[int]] = defaultdict(list) |
| for path in verifier_paths: |
| rows = read_jsonl(path) |
| fallback_split = infer_split(path) |
| top_k = parse_top_k(path, rows) |
| for row in rows: |
| split = str(row.get("split") or fallback_split) |
| label = str(row.get("label") or "UNLABELED") |
| input_format = str(row.get("input_format") or ("qa" if "_qa" in path.stem else "flat")) |
| text = str(row.get("input_text") or "") |
| if tokenizer is None: |
| length = len(text.split()) |
| else: |
| length = tokenize_lengths(tokenizer, [text])[0] |
| grouped[(split, label, input_format, top_k)].append(length) |
|
|
| output: list[dict[str, Any]] = [] |
| for split, label, input_format, top_k in sorted( |
| grouped, |
| key=lambda key: (key[0], LABEL_ORDER.index(key[1]) if key[1] in LABEL_ORDER else 99, key[1], key[2], key[3]), |
| ): |
| values = grouped[(split, label, input_format, top_k)] |
| for max_length in max_lengths: |
| truncated = sum(1 for value in values if value > max_length) |
| output.append( |
| { |
| "Split": split, |
| "Label": label, |
| "Format": input_format, |
| "Top-k": top_k, |
| "Max length": max_length, |
| "Count": len(values), |
| "p50 tokens": round(float(median(values)), 3) if values else 0.0, |
| "p90": round(percentile(values, 0.90), 3), |
| "p95": round(percentile(values, 0.95), 3), |
| "max_tokens": max(values) if values else 0, |
| "% truncated": pct(truncated, len(values)), |
| "tokenizer": tokenizer_model, |
| "tokenizer_status": tokenizer_status, |
| } |
| ) |
| return output |
|
|
|
|
| def prediction_distribution_rows(prediction_path: Path) -> list[dict[str, Any]]: |
| predictions = read_jsonl(prediction_path) |
| matrix: Counter[tuple[str, str]] = Counter() |
| gold_counts: Counter[str] = Counter() |
| pred_counts: Counter[str] = Counter() |
| correct_by_gold: Counter[str] = Counter() |
| split_counts: Counter[str] = Counter() |
|
|
| for row in predictions: |
| split = str(row.get("split") or "unknown") |
| gold = str(row.get("gold") or row.get("label") or "UNLABELED") |
| pred = str(row.get("prediction") or "UNPREDICTED") |
| key_gold = f"{split}:{gold}" |
| key_pred = f"{split}:{pred}" |
| matrix[(split, gold, pred)] += 1 |
| gold_counts[key_gold] += 1 |
| pred_counts[key_pred] += 1 |
| split_counts[split] += 1 |
| if gold == pred: |
| correct_by_gold[key_gold] += 1 |
|
|
| output: list[dict[str, Any]] = [] |
| labels = list(LABEL_ORDER) |
| seen_labels = sorted({gold for _, gold, _ in matrix} | {pred for _, _, pred in matrix}) |
| labels.extend(label for label in seen_labels if label not in labels) |
| for split in sorted(split_counts): |
| for gold in labels: |
| total_gold = gold_counts.get(f"{split}:{gold}", 0) |
| if not total_gold: |
| continue |
| for pred in labels: |
| count = matrix.get((split, gold, pred), 0) |
| output.append( |
| { |
| "Split": split, |
| "Gold": gold, |
| "Prediction": pred, |
| "Count": count, |
| "Pct_of_gold": pct(count, total_gold), |
| "Gold_count": total_gold, |
| "Predicted_label_count": pred_counts.get(f"{split}:{pred}", 0), |
| "Gold_recall_pct": pct(correct_by_gold.get(f"{split}:{gold}", 0), total_gold), |
| } |
| ) |
| return output |
|
|
|
|
| def compact_text(value: Any, limit: int = 360) -> str: |
| text = " ".join(str(value or "").split()) |
| if len(text) <= limit: |
| return text |
| return text[: limit - 3].rstrip() + "..." |
|
|
|
|
| def error_case_rows( |
| prediction_path: Path, |
| claims_by_id: dict[str, dict[str, Any]], |
| verifier_paths: list[Path], |
| candidate_paths: list[Path], |
| max_cases: int, |
| ) -> list[dict[str, Any]]: |
| verifier_by_id: dict[str, dict[str, Any]] = {} |
| for path in verifier_paths: |
| for row in read_jsonl(path): |
| verifier_by_id[str(row.get("id") or "")] = row |
|
|
| candidates_by_id: dict[str, dict[str, Any]] = {} |
| for path in candidate_paths: |
| for row in read_jsonl(path): |
| candidates_by_id[str(row.get("query_id") or "")] = row |
|
|
| errors: list[dict[str, Any]] = [] |
| for row in read_jsonl(prediction_path): |
| gold = str(row.get("gold") or row.get("label") or "") |
| pred = str(row.get("prediction") or "") |
| if gold == pred: |
| continue |
| claim_id = str(row.get("id") or "") |
| claim = claims_by_id.get(claim_id, {}) |
| verifier = verifier_by_id.get(claim_id, {}) |
| candidate_row = candidates_by_id.get(claim_id, {}) |
| evidence = verifier.get("evidence") or [] |
| top_evidence = evidence[0] if evidence else {} |
| metrics = candidate_row.get("metrics") if isinstance(candidate_row.get("metrics"), dict) else {} |
| probabilities = row.get("probabilities") if isinstance(row.get("probabilities"), dict) else {} |
| errors.append( |
| { |
| "id": claim_id, |
| "split": row.get("split") or claim.get("split") or verifier.get("split"), |
| "gold": gold, |
| "prediction": pred, |
| "confidence": row.get("confidence"), |
| "gold_probability": probabilities.get(gold), |
| "pred_probability": probabilities.get(pred), |
| "claim": compact_text(row.get("claim") or claim.get("claim")), |
| "gold_at_5": metrics.get("gold_at_5"), |
| "gold_at_10": metrics.get("gold_at_10"), |
| "gold_at_30": metrics.get("gold_at_30"), |
| "mrr": metrics.get("mrr"), |
| "ndcg_at_10": metrics.get("ndcg_at_10"), |
| "top_evidence_id": top_evidence.get("candidate_id"), |
| "top_evidence_is_gold": top_evidence.get("is_gold"), |
| "top_question": compact_text(top_evidence.get("question"), limit=220), |
| "top_answer": compact_text(top_evidence.get("answer"), limit=220), |
| "top_evidence": compact_text(top_evidence.get("text"), limit=360), |
| "evidence_ids": "|".join(str(item) for item in row.get("evidence_ids", [])), |
| } |
| ) |
|
|
| errors.sort(key=lambda item: (item.get("gold") != "CONFLICTING", item.get("gold") != "NEI", -safe_float(item.get("confidence")))) |
| return errors[:max_cases] |
|
|
|
|
| def load_metrics(path: Path) -> dict[str, Any]: |
| if not path.exists(): |
| return {} |
| return json.loads(path.read_text(encoding="utf-8")) |
|
|
|
|
| def gold_qa_upper_bound_rows(metrics_path: Path) -> list[dict[str, Any]]: |
| metrics = load_metrics(metrics_path) |
| test = metrics.get("test") if isinstance(metrics.get("test"), dict) else {} |
| per_class = test.get("per_class") if isinstance(test.get("per_class"), dict) else {} |
| return [ |
| { |
| "Method": "ModernBERT top10 retrieved QA", |
| "Evidence input": "retrieved QA", |
| "Status": "DONE", |
| "Acc": test.get("accuracy", ""), |
| "Macro-F1": test.get("macro_f1", ""), |
| "NEI F1": per_class.get("NEI", {}).get("f1", ""), |
| "CONFLICTING F1": per_class.get("CONFLICTING", {}).get("f1", ""), |
| "Metrics file": str(metrics_path), |
| "Next action": "", |
| }, |
| { |
| "Method": "ModernBERT gold QA upper-bound", |
| "Evidence input": "gold QA", |
| "Status": "PENDING_NEEDS_RUN", |
| "Acc": "", |
| "Macro-F1": "", |
| "NEI F1": "", |
| "CONFLICTING F1": "", |
| "Metrics file": "", |
| "Next action": "build_gold_qa_verifier_inputs_then_train_or_evaluate_as_diagnostic", |
| }, |
| ] |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--claims", type=Path, nargs="*", default=existing(DEFAULT_CLAIMS)) |
| parser.add_argument("--candidate-pool", type=Path, nargs="*", default=existing(DEFAULT_CANDIDATE_POOLS)) |
| parser.add_argument("--predictions", type=Path, default=DEFAULT_PREDICTIONS) |
| parser.add_argument("--verifier-input", type=Path, nargs="*", default=existing(DEFAULT_VERIFIER_INPUTS)) |
| parser.add_argument("--metrics", type=Path, default=DEFAULT_METRICS) |
| parser.add_argument("--output-dir", type=Path, default=Path("outputs/analysis")) |
| parser.add_argument("--tokenizer-model", default="answerdotai/ModernBERT-large") |
| parser.add_argument("--max-lengths", type=int, nargs="*", default=[1024, 2048]) |
| parser.add_argument("--max-error-cases", type=int, default=200) |
| args = parser.parse_args() |
|
|
| claims_by_id, claim_rows = load_claims(args.claims) |
| label_rows = label_distribution_rows(claim_rows) |
| retrieval_rows = retrieval_by_label_rows(args.candidate_pool, claims_by_id) |
| truncation_rows = truncation_report_rows(args.verifier_input, args.max_lengths, args.tokenizer_model) |
| prediction_rows = prediction_distribution_rows(args.predictions) |
| error_rows = error_case_rows( |
| args.predictions, |
| claims_by_id, |
| args.verifier_input, |
| args.candidate_pool, |
| args.max_error_cases, |
| ) |
| upper_bound_rows = gold_qa_upper_bound_rows(args.metrics) |
|
|
| output_dir = args.output_dir |
| outputs = { |
| "label_distribution": output_dir / "averitec_label_distribution.csv", |
| "retrieval_by_label": output_dir / "averitec_retrieval_by_label.csv", |
| "input_truncation_report": output_dir / "averitec_input_truncation_report.csv", |
| "prediction_distribution": output_dir / "averitec_prediction_distribution.csv", |
| "error_cases": output_dir / "averitec_error_cases.csv", |
| "gold_qa_upper_bound": output_dir / "averitec_gold_qa_upper_bound.csv", |
| } |
| write_csv(outputs["label_distribution"], label_rows) |
| write_csv(outputs["retrieval_by_label"], retrieval_rows) |
| write_csv(outputs["input_truncation_report"], truncation_rows) |
| write_csv(outputs["prediction_distribution"], prediction_rows) |
| write_csv(outputs["error_cases"], error_rows) |
| write_csv(outputs["gold_qa_upper_bound"], upper_bound_rows) |
|
|
| print("Wrote AVeriTeC diagnostic outputs:") |
| for name, path in outputs.items(): |
| print(f"- {name}: {path}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|