| """CPU-only contracts for the certified intervention evaluation. |
| |
| The release already contains executor-certified gold. Evaluation therefore |
| does not need an annotation workflow: it flattens the frozen group rows, joins |
| one prediction per view, and computes the registered group-aware metrics. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import copy |
| import json |
| from collections import Counter, defaultdict |
| from collections.abc import Iterable, Mapping, Sequence |
| from pathlib import Path |
| from typing import Any |
|
|
| from ..atomic_io import atomic_write_json, atomic_write_jsonl, read_jsonl |
| from ..hashing import canonical_json_hash |
| from ..training.answers import ( |
| UNANSWERABLE_TOKEN, |
| NormalizationError, |
| answers_equal, |
| normalize_answer, |
| parse_answer, |
| ) |
| from ..training.targets import ANSWERABLE_STATES, UNANSWERABLE_STATES, ours_target |
|
|
|
|
| class EvaluationError(ValueError): |
| """Raised when frozen gold, predictions, or a score join is incomplete.""" |
|
|
|
|
| _REQUIRED_GROUP_FIELDS = ( |
| "group_id", |
| "base_id", |
| "source", |
| "split", |
| "question", |
| "choices", |
| "full_answer_canonical", |
| "answer_type", |
| "views", |
| ) |
|
|
|
|
| def _object(value: Any, label: str) -> Mapping[str, Any]: |
| if not isinstance(value, Mapping): |
| raise EvaluationError(f"{label} must be an object") |
| return value |
|
|
|
|
| def _nonempty_string(value: Any, label: str) -> str: |
| if not isinstance(value, str) or not value: |
| raise EvaluationError(f"{label} must be a non-empty string") |
| return value |
|
|
|
|
| def _safe_images( |
| value: Any, |
| *, |
| eval_id: str, |
| allow_empty: bool = False, |
| ) -> list[dict[str, Any]]: |
| if not isinstance(value, list) or (not value and not allow_empty): |
| raise EvaluationError(f"{eval_id}: evaluation view has no image") |
| images: list[dict[str, Any]] = [] |
| for index, raw in enumerate(value): |
| image = dict(_object(raw, f"{eval_id} image")) |
| path = _nonempty_string(image.get("path"), f"{eval_id} image path") |
| relative = Path(path) |
| if relative.is_absolute() or ".." in relative.parts or "\\" in path: |
| raise EvaluationError(f"{eval_id}: unsafe image path {path!r}") |
| if image.get("image_index") != index: |
| raise EvaluationError(f"{eval_id}: image indices must be contiguous") |
| images.append(image) |
| return images |
|
|
|
|
| def _slice_values(group: Mapping[str, Any], view: Mapping[str, Any]) -> dict[str, str]: |
| values = { |
| "source": str(group.get("source", "unknown")), |
| "split": str(group.get("split", "unknown")), |
| "state": str(view.get("state", "unknown")), |
| "intervention_operator": str(view.get("operator", "unknown")), |
| "source_role": str(view.get("role", "unknown")), |
| "answer_type": str(group.get("answer_type", "unknown")), |
| "certificate_tier": str(view.get("certification_tier", "unknown")), |
| "subject": str(group.get("subject") or "unknown"), |
| "dependency_depth": str( |
| group.get("dependency_depth") |
| if group.get("dependency_depth") is not None |
| else "unknown" |
| ), |
| "renderer_family": str( |
| view.get("renderer_family") |
| or view.get("renderer") |
| or group.get("renderer_family") |
| or "unknown" |
| ), |
| } |
| values["intervention_family"] = ( |
| "original" |
| if values["state"] == "FULL" |
| else ("substitution" if values["source_role"] == "SUBSTITUTE" else "removal_or_control") |
| ) |
| return values |
|
|
|
|
| def flatten_certified_groups(groups: Iterable[Mapping[str, Any]]) -> tuple[dict[str, Any], ...]: |
| """Flatten certified group rows into one immutable evaluation row per view.""" |
|
|
| rows: list[dict[str, Any]] = [] |
| seen_groups: set[str] = set() |
| seen_base_ids: set[str] = set() |
| seen_eval_ids: set[str] = set() |
| for group_index, raw_group in enumerate(groups): |
| group = dict(_object(raw_group, f"group[{group_index}]")) |
| missing = [field for field in _REQUIRED_GROUP_FIELDS if field not in group] |
| if missing: |
| raise EvaluationError(f"group[{group_index}] missing fields: {missing}") |
| group_id = _nonempty_string(group["group_id"], "group_id") |
| base_id = _nonempty_string(group["base_id"], "base_id") |
| if group_id in seen_groups or base_id in seen_base_ids: |
| raise EvaluationError(f"duplicate evaluation group/base identity: {group_id}/{base_id}") |
| seen_groups.add(group_id) |
| seen_base_ids.add(base_id) |
| question = _nonempty_string(group["question"], f"{group_id} question") |
| choices = group["choices"] |
| if not isinstance(choices, list) or any(not isinstance(item, Mapping) for item in choices): |
| raise EvaluationError(f"{group_id}: choices must be a list of objects") |
| answer_type = _nonempty_string(group["answer_type"], f"{group_id} answer_type") |
| views = group["views"] |
| if not isinstance(views, list) or not views: |
| raise EvaluationError(f"{group_id}: views must be a non-empty list") |
| states = Counter(str(_object(view, "view").get("state", "")) for view in views) |
| if states["FULL"] != 1: |
| raise EvaluationError(f"{group_id}: exactly one FULL view is required") |
| for raw_view in views: |
| view = dict(_object(raw_view, f"{group_id} view")) |
| view_id = _nonempty_string(view.get("view_id"), f"{group_id} view_id") |
| state = _nonempty_string(view.get("state"), f"{view_id} state") |
| if state not in ANSWERABLE_STATES | UNANSWERABLE_STATES: |
| raise EvaluationError(f"{view_id}: unsupported state {state!r}") |
| eval_id = canonical_json_hash({"group_id": group_id, "view_id": view_id}) |
| if eval_id in seen_eval_ids: |
| raise EvaluationError(f"duplicate evaluation view: {view_id}") |
| seen_eval_ids.add(eval_id) |
| try: |
| gold = ours_target(view, group["full_answer_canonical"]) |
| normalize_answer(gold, answer_type, choices=choices) |
| except (ValueError, NormalizationError) as exc: |
| raise EvaluationError(f"{view_id}: invalid certified target: {exc}") from exc |
| rows.append( |
| { |
| "schema_version": 1, |
| "eval_id": eval_id, |
| "benchmark": ( |
| "certified_intervention_primary" |
| if group["split"] == "certified_eval" |
| else "certified_intervention_secondary" |
| ), |
| "group_id": group_id, |
| "base_id": base_id, |
| "source": str(group["source"]), |
| "split": str(group["split"]), |
| "view_id": view_id, |
| "state": state, |
| "role": str(view.get("role", "")), |
| "operator": str(view.get("operator", "")), |
| "question": question, |
| "choices": [copy.deepcopy(dict(choice)) for choice in choices], |
| "images": _safe_images(view.get("images"), eval_id=eval_id), |
| "gold_target": str(gold), |
| "answer_type": answer_type, |
| "slices": _slice_values(group, view), |
| } |
| ) |
| if not rows: |
| raise EvaluationError("evaluation group input is empty") |
| rows.sort(key=lambda row: (str(row["group_id"]), str(row["view_id"]))) |
| return tuple(rows) |
|
|
|
|
| def freeze_certified_groups( |
| group_paths: Sequence[Path], |
| output_path: Path, |
| *, |
| expected_groups: int | None = None, |
| ) -> dict[str, Any]: |
| """Flatten one or more release split files and write a write-once manifest.""" |
|
|
| if not group_paths: |
| raise EvaluationError("at least one --groups file is required") |
| groups: list[Mapping[str, Any]] = [] |
| try: |
| for path in group_paths: |
| groups.extend(_object(row, f"row in {path}") for row in read_jsonl(path)) |
| except (OSError, json.JSONDecodeError) as exc: |
| raise EvaluationError(f"cannot read evaluation groups: {exc}") from exc |
| rows = flatten_certified_groups(groups) |
| group_count = len({str(row["group_id"]) for row in rows}) |
| if expected_groups is not None and group_count != expected_groups: |
| raise EvaluationError( |
| f"evaluation group count {group_count} differs from expected {expected_groups}" |
| ) |
| if output_path.exists(): |
| existing = tuple(read_jsonl(output_path)) |
| if existing != rows: |
| raise EvaluationError( |
| f"refusing to overwrite drifted evaluation manifest: {output_path}" |
| ) |
| else: |
| atomic_write_jsonl(output_path, rows) |
| return { |
| "schema_version": 1, |
| "kind": "certified_intervention_evaluation_manifest", |
| "path": str(output_path.resolve()), |
| "group_count": group_count, |
| "view_count": len(rows), |
| "source_counts": dict(sorted(Counter(str(row["source"]) for row in rows).items())), |
| "split_counts": dict(sorted(Counter(str(row["split"]) for row in rows).items())), |
| "state_counts": dict(sorted(Counter(str(row["state"]) for row in rows).items())), |
| } |
|
|
|
|
| def flatten_retention_items(items: Iterable[Mapping[str, Any]]) -> tuple[dict[str, Any], ...]: |
| """Convert untouched normalized eval items to the common prediction schema.""" |
|
|
| rows: list[dict[str, Any]] = [] |
| seen: set[str] = set() |
| for index, raw_item in enumerate(items): |
| item = dict(_object(raw_item, f"retention item[{index}]")) |
| base_id = _nonempty_string(item.get("base_id"), f"retention item[{index}] base_id") |
| if base_id in seen: |
| raise EvaluationError(f"duplicate retention base_id: {base_id}") |
| seen.add(base_id) |
| question = _nonempty_string(item.get("question"), f"{base_id} question") |
| source = _nonempty_string(item.get("source"), f"{base_id} source") |
| split = _nonempty_string(item.get("source_split"), f"{base_id} source_split") |
| source_revision = str(item.get("source_revision") or "unknown") |
| source_config = str(item.get("source_config") or "default") |
| choices = item.get("choices") |
| image_paths = item.get("image_paths") |
| answer_type = _nonempty_string(item.get("answer_type"), f"{base_id} answer_type") |
| if not isinstance(choices, list) or any( |
| not isinstance(choice, Mapping) for choice in choices |
| ): |
| raise EvaluationError(f"{base_id}: retention choices are malformed") |
| if not isinstance(image_paths, list) or any( |
| not isinstance(path, str) for path in image_paths |
| ): |
| raise EvaluationError(f"{base_id}: retention image paths are malformed") |
| gold = item.get("answer_canonical") |
| if not isinstance(gold, str | int | float | bool): |
| raise EvaluationError(f"{base_id}: retention gold answer is missing") |
| try: |
| normalized_gold = normalize_answer(str(gold), answer_type, choices=choices) |
| except NormalizationError as exc: |
| raise EvaluationError(f"{base_id}: invalid retention gold: {exc}") from exc |
| eval_id = canonical_json_hash({"benchmark": "untouched_retention", "base_id": base_id}) |
| images = [ |
| {"image_index": image_index, "path": path} |
| for image_index, path in enumerate(image_paths) |
| ] |
| rows.append( |
| { |
| "schema_version": 1, |
| "eval_id": eval_id, |
| "benchmark": "untouched_retention", |
| "group_id": base_id, |
| "base_id": base_id, |
| "source": source, |
| "source_revision": source_revision, |
| "source_config": source_config, |
| "split": split, |
| "view_id": base_id, |
| "state": "ORIGINAL", |
| "role": "ORIGINAL", |
| "operator": "identity", |
| "question": question, |
| "choices": [copy.deepcopy(dict(choice)) for choice in choices], |
| "images": _safe_images(images, eval_id=eval_id, allow_empty=True), |
| "gold_target": normalized_gold, |
| "answer_type": answer_type, |
| "slices": { |
| "source": source, |
| "source_revision": source_revision, |
| "source_config": source_config, |
| "split": split, |
| "state": "ORIGINAL", |
| "answer_type": answer_type, |
| "subject": str(item.get("subject") or "unknown"), |
| }, |
| } |
| ) |
| if not rows: |
| raise EvaluationError("retention item input is empty") |
| rows.sort(key=lambda row: (str(row["source"]), str(row["base_id"]))) |
| return tuple(rows) |
|
|
|
|
| def freeze_retention_items( |
| item_paths: Sequence[Path], |
| output_path: Path, |
| *, |
| expected_items: int | None = None, |
| ) -> dict[str, Any]: |
| """Write a common, write-once manifest for untouched capability probes.""" |
|
|
| if not item_paths: |
| raise EvaluationError("at least one --items file is required") |
| items: list[Mapping[str, Any]] = [] |
| try: |
| for path in item_paths: |
| items.extend(_object(row, f"row in {path}") for row in read_jsonl(path)) |
| except (OSError, json.JSONDecodeError) as exc: |
| raise EvaluationError(f"cannot read retention items: {exc}") from exc |
| rows = flatten_retention_items(items) |
| if expected_items is not None and len(rows) != expected_items: |
| raise EvaluationError( |
| f"retention item count {len(rows)} differs from expected {expected_items}" |
| ) |
| if output_path.exists(): |
| existing = tuple(read_jsonl(output_path)) |
| if existing != rows: |
| raise EvaluationError( |
| f"refusing to overwrite drifted retention manifest: {output_path}" |
| ) |
| else: |
| atomic_write_jsonl(output_path, rows) |
| return { |
| "schema_version": 1, |
| "kind": "untouched_retention_evaluation_manifest", |
| "path": str(output_path.resolve()), |
| "item_count": len(rows), |
| "source_counts": dict(sorted(Counter(str(row["source"]) for row in rows).items())), |
| } |
|
|
|
|
| def load_evaluation_manifest(path: Path) -> tuple[dict[str, Any], ...]: |
| try: |
| rows = tuple(dict(_object(row, f"row in {path}")) for row in read_jsonl(path)) |
| except (OSError, json.JSONDecodeError) as exc: |
| raise EvaluationError(f"cannot read evaluation manifest: {exc}") from exc |
| if not rows: |
| raise EvaluationError("evaluation manifest is empty") |
| ids = [row.get("eval_id") for row in rows] |
| if any(not isinstance(value, str) or not value for value in ids) or len(ids) != len(set(ids)): |
| raise EvaluationError("evaluation manifest has empty or duplicate eval_id values") |
| return rows |
|
|
|
|
| def _rate(numerator: int, denominator: int) -> dict[str, int | float | None]: |
| return { |
| "numerator": numerator, |
| "denominator": denominator, |
| "value": (numerator / denominator if denominator else None), |
| } |
|
|
|
|
| def _accuracy(rows: Sequence[Mapping[str, Any]]) -> dict[str, int | float | None]: |
| return _rate(sum(bool(row["correct"]) for row in rows), len(rows)) |
|
|
|
|
| def _slice_metrics(scored: Sequence[Mapping[str, Any]]) -> dict[str, dict[str, Any]]: |
| buckets: dict[str, dict[str, list[Mapping[str, Any]]]] = defaultdict(lambda: defaultdict(list)) |
| for row in scored: |
| raw_slices = row.get("slices") |
| if not isinstance(raw_slices, Mapping): |
| continue |
| for name, value in raw_slices.items(): |
| buckets[str(name)][str(value)].append(row) |
| return { |
| name: {value: _accuracy(bucket) for value, bucket in sorted(values.items())} |
| for name, values in sorted(buckets.items()) |
| } |
|
|
|
|
| def _aggregate_score_metrics(scored: Sequence[Mapping[str, Any]]) -> dict[str, Any]: |
| by_state: dict[str, list[Mapping[str, Any]]] = defaultdict(list) |
| by_group: dict[str, list[Mapping[str, Any]]] = defaultdict(list) |
| for row in scored: |
| by_state[str(row["state"])].append(row) |
| by_group[str(row["group_id"])].append(row) |
| full_correct_groups = { |
| group_id |
| for group_id, rows in by_group.items() |
| if len(full := [row for row in rows if row["state"] == "FULL"]) == 1 |
| and bool(full[0]["correct"]) |
| } |
| transformed = [row for row in scored if row["state"] not in {"FULL", "ORIGINAL"}] |
| transformed_conditioned = [row for row in transformed if row["group_id"] in full_correct_groups] |
| unanswerable = [row for row in scored if bool(row["gold_unanswerable"])] |
| answerable = [row for row in scored if not bool(row["gold_unanswerable"])] |
| strict_correct = sum(all(bool(row["correct"]) for row in rows) for rows in by_group.values()) |
| result: dict[str, Any] = { |
| "group_count": len(by_group), |
| "view_count": len(scored), |
| "accuracy": _accuracy(scored), |
| "strict_group_accuracy": _rate(strict_correct, len(by_group)), |
| "unsupported_answer_rate": _rate( |
| sum(bool(row["unsupported_answer"]) for row in unanswerable), len(unanswerable) |
| ), |
| "false_abstention_rate": _rate( |
| sum(bool(row["false_abstention"]) for row in answerable), len(answerable) |
| ), |
| "transformed_accuracy": _accuracy(transformed), |
| "transformed_accuracy_conditioned_on_full_correct": _accuracy(transformed_conditioned), |
| "full_correct_group_count": len(full_correct_groups), |
| "slices": _slice_metrics(scored), |
| } |
| for state, name in { |
| "FULL": "full_accuracy", |
| "A_SAME": "a_same_accuracy", |
| "A_CHANGED": "a_changed_accuracy", |
| "U_MISSING": "u_missing_abstention_accuracy", |
| "U_INVALID": "u_invalid_abstention_accuracy", |
| "ORIGINAL": "retention_accuracy", |
| }.items(): |
| result[name] = _accuracy(by_state.get(state, [])) |
| return result |
|
|
|
|
| def score_predictions( |
| gold_rows: Sequence[Mapping[str, Any]], |
| prediction_rows: Sequence[Mapping[str, Any]], |
| ) -> tuple[dict[str, Any], tuple[dict[str, Any], ...]]: |
| """Join exact prediction coverage and compute the registered primary metrics.""" |
|
|
| if not gold_rows: |
| raise EvaluationError("gold evaluation rows are empty") |
| predictions: dict[str, Mapping[str, Any]] = {} |
| run_ids: set[str] = set() |
| for index, raw in enumerate(prediction_rows): |
| row = _object(raw, f"prediction[{index}]") |
| eval_id = _nonempty_string(row.get("eval_id"), f"prediction[{index}] eval_id") |
| if eval_id in predictions: |
| raise EvaluationError(f"duplicate prediction eval_id: {eval_id}") |
| predictions[eval_id] = row |
| run_ids.add(_nonempty_string(row.get("run_id"), f"prediction[{index}] run_id")) |
| if len(run_ids) != 1: |
| raise EvaluationError("prediction file must contain exactly one run_id") |
| gold_ids = {_nonempty_string(row.get("eval_id"), "gold eval_id") for row in gold_rows} |
| missing = sorted(gold_ids - predictions.keys()) |
| extra = sorted(predictions.keys() - gold_ids) |
| if missing or extra: |
| raise EvaluationError( |
| f"prediction coverage mismatch: missing={missing[:5]}, extra={extra[:5]}" |
| ) |
| scored: list[dict[str, Any]] = [] |
| for raw_gold in gold_rows: |
| gold = _object(raw_gold, "gold row") |
| eval_id = str(gold["eval_id"]) |
| prediction = predictions[eval_id] |
| if prediction.get("prompt_truncated") is True: |
| raise EvaluationError(f"{eval_id}: prompt truncation is an integrity failure") |
| if prediction.get("completion_truncated") is True: |
| raise EvaluationError(f"{eval_id}: completion truncation is an integrity failure") |
| response = prediction.get("response") |
| if not isinstance(response, str): |
| raise EvaluationError(f"{eval_id}: prediction response must be a string") |
| parsed = parse_answer(response) |
| normalized_prediction: str | None = None |
| if parsed.valid: |
| try: |
| normalized_prediction = normalize_answer( |
| parsed.require_content(), |
| str(gold["answer_type"]), |
| choices=gold.get("choices") if isinstance(gold.get("choices"), list) else [], |
| ) |
| except NormalizationError: |
| normalized_prediction = None |
| correct = parsed.valid and answers_equal( |
| parsed.require_content(), |
| gold["gold_target"], |
| str(gold["answer_type"]), |
| choices=gold.get("choices") if isinstance(gold.get("choices"), list) else [], |
| ) |
| gold_unanswerable = str(gold["gold_target"]) == UNANSWERABLE_TOKEN |
| predicted_unanswerable = normalized_prediction == UNANSWERABLE_TOKEN |
| scored.append( |
| { |
| "schema_version": 1, |
| "run_id": next(iter(run_ids)), |
| "eval_id": eval_id, |
| "group_id": str(gold["group_id"]), |
| "base_id": str(gold["base_id"]), |
| "benchmark": str(gold.get("benchmark", "certified_intervention_primary")), |
| "source": str(gold["source"]), |
| "split": str(gold["split"]), |
| "state": str(gold["state"]), |
| "gold_target": str(gold["gold_target"]), |
| "response": response, |
| "parser_valid": parsed.valid, |
| "parser_error": parsed.error, |
| "normalized_prediction": normalized_prediction, |
| "correct": bool(correct), |
| "gold_unanswerable": gold_unanswerable, |
| "predicted_unanswerable": predicted_unanswerable, |
| "unsupported_answer": bool( |
| gold_unanswerable and parsed.valid and not predicted_unanswerable |
| ), |
| "false_abstention": bool( |
| not gold_unanswerable and parsed.valid and predicted_unanswerable |
| ), |
| "slices": copy.deepcopy(dict(_object(gold.get("slices", {}), "slices"))), |
| } |
| ) |
| by_benchmark: dict[str, list[Mapping[str, Any]]] = defaultdict(list) |
| for row in scored: |
| by_benchmark[str(row["benchmark"])].append(row) |
| benchmark_metrics = { |
| benchmark: _aggregate_score_metrics(rows) |
| for benchmark, rows in sorted(by_benchmark.items()) |
| } |
| selected_benchmark = ( |
| "certified_intervention_primary" |
| if "certified_intervention_primary" in benchmark_metrics |
| else next(iter(benchmark_metrics)) |
| ) |
| metrics: dict[str, Any] = { |
| "schema_version": 1, |
| "kind": "evaluation_score", |
| "run_id": next(iter(run_ids)), |
| "selected_benchmark": selected_benchmark, |
| "benchmark_metrics": benchmark_metrics, |
| **benchmark_metrics[selected_benchmark], |
| } |
| return metrics, tuple(scored) |
|
|
|
|
| def write_score_outputs( |
| output_dir: Path, |
| metrics: Mapping[str, Any], |
| scored_rows: Sequence[Mapping[str, Any]], |
| ) -> None: |
| if output_dir.exists() and any(output_dir.iterdir()): |
| raise EvaluationError(f"score output directory is not empty: {output_dir}") |
| output_dir.mkdir(parents=True, exist_ok=True) |
| atomic_write_json(output_dir / "metrics.json", dict(metrics)) |
| atomic_write_jsonl(output_dir / "scored.jsonl", scored_rows) |
|
|