"""Lazy, prefetchable image dataset for the RL training path. Replaces the ~35-min upfront materialization of all 46K images (``Dataset.from_list(_materialize_images(rows))``, which serially PIL-loads every image and PNG-re-encodes them into an Arrow table on EVERY process launch) with a map-style :class:`LazyImageRLDataset` whose :py:meth:`__getitem__` decodes one row's images on demand. Fed through a TRL GRPO DataLoader with ``num_workers>0`` + ``prefetch_factor``, the GPU trains step ``X`` while background workers decode step ``X+1``'s batch. This is a plain map-style class (``__len__`` + ``__getitem__``), NOT a ``torch.utils.data.Dataset`` subclass. The pinned torch 2.11.0 ``DataLoader`` classifies a dataset as map-style whenever it is NOT an ``IterableDataset`` (``isinstance(dataset, IterableDataset)`` is the only check; there is no ``isinstance(dataset, Dataset)`` gate), and TRL/transformers likewise only special-case ``datasets.Dataset`` and ``IterableDataset``. Keeping torch out of this module means it imports cleanly in the torch-free test environment. Reproducibility (paper-grade): the stream of indices is produced by TRL's ``RepeatSampler`` in the MAIN process (seeded by ``args.seed``); workers only materialize items by index and perform no RNG. ``__getitem__`` is a pure function of ``index`` and applies the SAME image-key rule (``image`` vs ``images``) as ``_materialize_images``, so the row schema at every index is identical to the current materialized path. With no disk cache (``EXPLICIT_IMAGE_CACHE_DIR`` unset, the default) each image is decoded by the existing :func:`_load_pil`, so decoded PIL is byte-identical to the status quo. """ from __future__ import annotations import copy import hashlib import io import os from collections.abc import Mapping, Sequence from pathlib import Path from typing import Any from .backend import BackendContractError, _load_pil def _load_pil_cached(path: str, cache_dir: str | None) -> Any: """Decode ``path`` to an RGB PIL image, optionally backed by a disk cache. With ``cache_dir is None`` (the default) this delegates to the existing :func:`_load_pil`, so the decoded image is byte-identical to the current serial materialization path. With a cache dir, entries are keyed by the SOURCE content ``sha256`` (NOT ``path + mtime`` — mtime is unstable across Lustre mirror syncs) and stored as lossless PNG, so a cache hit returns an image identical to a cache miss for the same source bytes. Writes are atomic (``os.replace``), so concurrent workers cannot corrupt an entry. """ from PIL import Image if cache_dir is None: return _load_pil(path) raw = Path(path).read_bytes() key = hashlib.sha256(raw).hexdigest() entry = Path(cache_dir) / key[:2] / f"{key}.png" if entry.is_file(): with Image.open(entry) as cached: return cached.convert("RGB").copy() with Image.open(io.BytesIO(raw)) as image: decoded = image.convert("RGB") entry.parent.mkdir(parents=True, exist_ok=True) tmp = entry.with_suffix(".png.tmp") decoded.save(tmp, format="PNG") os.replace(tmp, entry) # atomic; concurrent workers safe with Image.open(entry) as cached: return cached.convert("RGB").copy() def _materialize_row(source: Mapping[str, Any], cache_dir: str | None) -> dict[str, Any]: """Build a single trainer-facing row, decoding its images lazily. Mirrors ``_materialize_images`` per-row: pop ``image_paths``, decode each path, set ``image`` for a single image or ``images`` for several, and drop ``assistant_response`` (a no-op for RL rows). Pure function of ``source`` plus the (deterministic) decode, so repeated calls are idempotent and never mutate ``source``. """ row = copy.deepcopy(dict(source)) paths = row.pop("image_paths", None) if not isinstance(paths, list) or not paths: raise BackendContractError("prepared row has no image paths") images = [_load_pil_cached(str(path), cache_dir) for path in paths] if len(images) == 1: row["image"] = images[0] else: row["images"] = images row.pop("assistant_response", None) return row class LazyImageRLDataset: """Map-style dataset that decodes row images lazily in DataLoader workers. Index order is identical to ``Dataset.from_list(_materialize_images(rows))``: ``self.rows[i]`` is the same source row, and :py:meth:`__getitem__` applies the same image-key rule, so the row schema at every index is byte-identical to the current materialized path. Stored rows are plain dicts (no PIL), so they pickle cheaply to workers. """ def __init__( self, rows: Sequence[Mapping[str, Any]], cache_dir: str | None = None, ) -> None: # Deepcopy once at construction so worker processes (which receive a # pickled copy) never share references with the main process's rows. self.rows: list[dict[str, Any]] = [copy.deepcopy(dict(r)) for r in rows] self.cache_dir = cache_dir # optional, env-gated; None => no disk cache. def __len__(self) -> int: return len(self.rows) def __getitem__(self, index: int) -> dict[str, Any]: return _materialize_row(self.rows[index], self.cache_dir)