"""Pinned Hugging Face materialization for untouched retention benchmarks. The legacy freeze path consumed hand-exported ``native rows`` whose fixture shape did not match the real repositories (MMMU-Pro has ``image_1..image_7`` and stringified options; MathVista uses ``pid``; MMLU-Pro uses ``question_id``). This module loads the exact revisions in resources.yaml and normalizes the real schemas directly into the common evaluation manifest. """ from __future__ import annotations import ast import io from collections import Counter from collections.abc import Callable, Mapping, Sequence from pathlib import Path from typing import Any, cast from ..atomic_io import atomic_write_bytes, atomic_write_jsonl from ..config import ResourcesManifest from ..hashing import canonical_json_hash from ..ingest.base import canonicalize_mc_answer, infer_open_answer_type, mc_choices from .core import ( EvaluationError, flatten_retention_items, load_evaluation_manifest, ) RETENTION_SOURCES: tuple[str, ...] = ( "mmmu_pro", "mathvision", "mathvista", "mmlu_pro_text", ) _SOURCE_SPECS: dict[str, tuple[str, str, int]] = { "mmmu_pro": ("standard (10 options)", "test", 1_730), "mathvision": ("default", "testmini", 304), "mathvista": ("default", "testmini", 1_000), "mmlu_pro_text": ("default", "test", 12_032), } DatasetLoader = Callable[..., Sequence[Mapping[str, Any]]] def _load_dataset( repo_id: str, config: str, *, split: str, revision: str, cache_dir: str | None, ) -> Sequence[Mapping[str, Any]]: try: from datasets import load_dataset except ImportError as exc: raise EvaluationError(f"datasets is required for retention download: {exc}") from exc return cast( Sequence[Mapping[str, Any]], load_dataset( repo_id, config, split=split, revision=revision, cache_dir=cache_dir, ), ) def _options(value: Any, *, source: str, native_id: str) -> list[str]: if value in (None, ""): return [] parsed = value if isinstance(value, str): try: parsed = ast.literal_eval(value) except (SyntaxError, ValueError) as exc: raise EvaluationError( f"{source}/{native_id}: options string is not a Python list literal" ) from exc if not isinstance(parsed, Sequence) or isinstance(parsed, str | bytes | bytearray): raise EvaluationError(f"{source}/{native_id}: options must be a sequence") result = [str(option) for option in parsed] if any(not option for option in result): raise EvaluationError(f"{source}/{native_id}: options contain an empty value") return result def _native_id(source: str, row: Mapping[str, Any]) -> str: field = { "mmmu_pro": "id", "mathvision": "id", "mathvista": "pid", "mmlu_pro_text": "question_id", }[source] value = row.get(field) if value is None or not str(value): raise EvaluationError(f"{source}: row has no {field}") return str(value) def _image_values(source: str, row: Mapping[str, Any]) -> list[Any]: if source == "mmmu_pro": return [row.get(f"image_{index}") for index in range(1, 8) if row.get(f"image_{index}")] if source in {"mathvision", "mathvista"}: value = row.get("decoded_image") return [value] if value is not None else [] return [] def _png_bytes(value: Any, *, label: str) -> bytes: try: from PIL import Image, ImageOps except ImportError as exc: raise EvaluationError(f"Pillow is required for retention images: {exc}") from exc image: Any try: if isinstance(value, Image.Image): image = value.copy() elif isinstance(value, Mapping) and isinstance(value.get("bytes"), bytes): image = Image.open(io.BytesIO(value["bytes"])).copy() elif isinstance(value, Mapping) and isinstance(value.get("path"), str): image = Image.open(str(value["path"])).copy() elif isinstance(value, str | Path): image = Image.open(str(value)).copy() else: raise EvaluationError(f"{label}: unsupported decoded image value") image = ImageOps.exif_transpose(image).convert("RGB") buffer = io.BytesIO() image.save(buffer, format="PNG", optimize=False) return buffer.getvalue() except (OSError, ValueError) as exc: raise EvaluationError(f"{label}: cannot decode image: {exc}") from exc def _store_images( source: str, row_index: int, native_id: str, values: Sequence[Any], asset_root: Path, ) -> list[str]: if source != "mmlu_pro_text" and not values: raise EvaluationError(f"{source}/{native_id}: visual retention row has no image") paths: list[str] = [] for image_index, value in enumerate(values): relative = Path(source) / f"{row_index:06d}" / f"image-{image_index}.png" atomic_write_bytes( asset_root / relative, _png_bytes(value, label=f"{source}/{native_id} image {image_index}"), fsync_dir=False, ) paths.append(relative.as_posix()) return paths def _item( source: str, row: Mapping[str, Any], *, row_index: int, revision: str, config: str, split: str, asset_root: Path, ) -> dict[str, Any]: native_id = _native_id(source, row) question = row.get("question") answer = row.get("answer") if not isinstance(question, str) or not question.strip(): raise EvaluationError(f"{source}/{native_id}: question is empty") if answer is None or not str(answer).strip(): raise EvaluationError(f"{source}/{native_id}: answer is empty") raw_options = _options( row.get("options") if source != "mathvista" else row.get("choices"), source=source, native_id=native_id, ) choices = [choice.to_dict() for choice in mc_choices(raw_options)] if choices: answer_type = "multiple_choice" canonical_answer = canonicalize_mc_answer(str(answer), mc_choices(raw_options)) else: answer_type = infer_open_answer_type(str(answer)) canonical_answer = str(answer) image_paths = _store_images( source, row_index, native_id, _image_values(source, row), asset_root, ) return { "base_id": canonical_json_hash( { "source": source, "revision": revision, "config": config, "split": split, "native_id": native_id, } ), "source": source, "source_revision": revision, "source_config": config, "source_split": split, "question": question, "choices": choices, "image_paths": image_paths, "answer_type": answer_type, "answer_canonical": canonical_answer, "subject": str(row.get("subject") or row.get("category") or "unknown"), } def _existing_summary( output_path: Path, asset_root: Path, *, expected_sources: Sequence[str], ) -> dict[str, Any]: rows = load_evaluation_manifest(output_path) for row in rows: images = row.get("images") if not isinstance(images, list): raise EvaluationError("existing retention row images are malformed") for image in images: if not isinstance(image, Mapping) or not isinstance(image.get("path"), str): raise EvaluationError("existing retention image record is malformed") if not (asset_root / str(image["path"])).is_file(): raise EvaluationError(f"existing retention image is missing: {image['path']}") source_counts = Counter(str(row["source"]) for row in rows) if set(source_counts) != set(expected_sources): raise EvaluationError( "existing retention manifest sources differ from the requested source set" ) return { "schema_version": 1, "kind": "pinned_hf_retention_evaluation_manifest", "status": "reused", "path": str(output_path.resolve()), "item_count": len(rows), "source_counts": dict(sorted(source_counts.items())), } def materialize_hf_retention( resources: ResourcesManifest, output_path: Path, asset_root: Path, *, cache_dir: Path | None = None, sources: Sequence[str] = RETENTION_SOURCES, dataset_loader: DatasetLoader = _load_dataset, expected_counts: Mapping[str, int] | None = None, ) -> dict[str, Any]: """Download pinned untouched sources and freeze the common eval manifest.""" selected = tuple(dict.fromkeys(sources)) if not selected or any(source not in RETENTION_SOURCES for source in selected): raise EvaluationError(f"retention sources must come from {RETENTION_SOURCES}") if output_path.exists(): return _existing_summary(output_path, asset_root, expected_sources=selected) asset_root.mkdir(parents=True, exist_ok=True) items: list[dict[str, Any]] = [] counts: dict[str, int] = {} for source in selected: config, split, registered_count = _SOURCE_SPECS[source] resource = resources.dataset(source) if resource.role not in {"untouched_eval_only", "untouched_text_reasoning_retention_eval"}: raise EvaluationError(f"{source} is not registered as untouched evaluation") rows = dataset_loader( resource.repo_id, config, split=split, revision=resource.revision, cache_dir=str(cache_dir) if cache_dir is not None else None, ) count = len(rows) wanted = ( expected_counts[source] if expected_counts is not None and source in expected_counts else registered_count ) if count != wanted: raise EvaluationError(f"{source}: pinned split has {count} rows, expected {wanted}") counts[source] = count items.extend( _item( source, row, row_index=index, revision=resource.revision, config=config, split=split, asset_root=asset_root, ) for index, row in enumerate(rows) ) evaluation_rows = flatten_retention_items(items) atomic_write_jsonl(output_path, evaluation_rows) return { "schema_version": 1, "kind": "pinned_hf_retention_evaluation_manifest", "status": "completed", "path": str(output_path.resolve()), "asset_root": str(asset_root.resolve()), "item_count": len(evaluation_rows), "source_counts": dict(sorted(counts.items())), }