File size: 10,871 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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())),
    }