File size: 14,752 Bytes
2ea2835
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
"""Metadata-only matched-video dataset with explicitly lazy teacher I/O."""

from __future__ import annotations

from dataclasses import dataclass
import os
from pathlib import Path
import time
from typing import Any, Callable, Mapping, Sequence

import numpy as np
import torch
from torch.utils.data import Dataset

from utils.matched_video_feature_cache import (
    MATCHED_PYAV_LAST64_DECODER_CONTRACT,
    MATCHED_VJEPA2_L15_LAST64_FEATURE_CONTRACT,
    MatchedVideoFeatureCache,
)
from utils.matched_video_manifest import (
    MatchedVideoManifestEntry,
    load_matched_video_manifest,
)


@dataclass(frozen=True)
class DecodedMatchedVideo:
    """The final contiguous RGB frame window in V-JEPA2 input range."""

    video01: torch.Tensor
    frame_indices: torch.Tensor
    source_frame_count: int


def _frames_to_video01(frames: Sequence[Any]) -> torch.Tensor:
    tensors: list[torch.Tensor] = []
    shape: tuple[int, int, int] | None = None
    for frame in frames:
        array = frame.to_ndarray(format="rgb24")
        if not isinstance(array, np.ndarray):
            raise TypeError("PyAV frame.to_ndarray did not return ndarray")
        if array.ndim != 3 or int(array.shape[2]) != 3:
            raise ValueError(
                f"decoded RGB frame must be [H,W,3], got {array.shape}"
            )
        if array.dtype != np.uint8:
            raise ValueError(f"decoded RGB frame must be uint8, got {array.dtype}")
        current_shape = tuple(int(value) for value in array.shape)
        if shape is None:
            shape = current_shape
        elif current_shape != shape:
            raise ValueError(
                "video changes resolution inside selected frame window: "
                f"{current_shape} != {shape}"
            )
        tensors.append(
            torch.from_numpy(np.ascontiguousarray(array)).permute(2, 0, 1)
        )
    if not tensors:
        raise ValueError("decoded frame window is empty")
    return torch.stack(tensors).to(dtype=torch.float32).div_(255.0)


def decode_matched_video_last_contiguous_pyav(
    video_path: str | os.PathLike,
    *,
    decoder_contract: Mapping[str, Any] | None = None,
) -> DecodedMatchedVideo:
    """Decode exactly frames 17..80 from a contractually 81-frame MP4."""

    contract = dict(
        decoder_contract
        if decoder_contract is not None
        else MATCHED_PYAV_LAST64_DECODER_CONTRACT
    )
    if contract.get("backend") != "pyav":
        raise ValueError("decoder contract backend must be pyav")
    if contract.get("selection") != "last_contiguous":
        raise ValueError("decoder contract selection must be last_contiguous")
    num_frames = int(contract.get("num_frames", 0))
    expected_count = int(contract.get("expected_source_frame_count", 0))
    if num_frames <= 0 or expected_count < num_frames:
        raise ValueError("decoder contract frame geometry is invalid")
    expected_bounds = [expected_count - num_frames, expected_count - 1]
    if list(contract.get("expected_frame_indices", ())) != expected_bounds:
        raise ValueError(
            "decoder contract expected_frame_indices do not describe last64"
        )
    try:
        import av  # Imported only for cache misses.
    except ImportError as exc:  # pragma: no cover
        raise ImportError(
            "PyAV is required for a matched-video teacher cache miss; "
            "install the pinned av==13.1.0 dependency"
        ) from exc
    expected_version = str(contract.get("backend_version", ""))
    actual_version = str(getattr(av, "__version__", ""))
    if actual_version != expected_version:
        raise RuntimeError(
            "PyAV version differs from the cache decoder contract: "
            f"{actual_version!r} != {expected_version!r}"
        )

    path = Path(video_path).expanduser().resolve()
    if not path.is_file():
        raise FileNotFoundError(path)
    selected: list[Any] = []
    decoded_count = 0
    start = expected_count - num_frames
    with av.open(str(path), mode="r") as container:
        streams = container.streams.video
        if len(streams) != 1:
            raise ValueError(
                f"expected exactly one video stream in {path}, got {len(streams)}"
            )
        stream = streams[0]
        for frame_index, frame in enumerate(container.decode(stream)):
            decoded_count = frame_index + 1
            if start <= frame_index < expected_count:
                selected.append(frame)
    if decoded_count != expected_count:
        raise ValueError(
            "matched video source frame count violates the last64 contract: "
            f"sample={path.name}, actual={decoded_count}, "
            f"expected={expected_count}"
        )
    if len(selected) != num_frames:
        raise RuntimeError(
            f"failed to decode frames {start}..{expected_count - 1} from {path}"
        )
    video01 = _frames_to_video01(selected)
    if tuple(video01.shape[:2]) != (num_frames, 3):
        raise RuntimeError(f"decoded video has invalid shape {tuple(video01.shape)}")
    return DecodedMatchedVideo(
        video01=video01,
        frame_indices=torch.arange(start, expected_count, dtype=torch.long),
        source_frame_count=decoded_count,
    )


DecodeFunction = Callable[[Path, Mapping[str, Any]], DecodedMatchedVideo]


def _default_decode(
    path: Path,
    contract: Mapping[str, Any],
) -> DecodedMatchedVideo:
    return decode_matched_video_last_contiguous_pyav(
        path, decoder_contract=contract
    )


class MatchedManifestVideoDataset(Dataset):
    """Return metadata eagerly; teacher cache/decode only on explicit request."""

    def __init__(
        self,
        manifest_path: str | os.PathLike,
        video_root: str | os.PathLike,
        cache_root: str | os.PathLike,
        expected_model_sha256: str,
        expected_feature_contract_sha256: str,
        *,
        expected_source_csv_sha256: str | None = None,
        expected_count: int | None = None,
        feature_contract: Mapping[str, Any] | None = None,
        decoder_contract: Mapping[str, Any] | None = None,
        decode_fn: DecodeFunction | None = None,
    ) -> None:
        self.manifest_path = Path(manifest_path).expanduser().resolve()
        self.video_root = Path(video_root).expanduser().resolve()
        if not self.video_root.is_dir():
            raise NotADirectoryError(self.video_root)
        self.entries, self.manifest_metadata = load_matched_video_manifest(
            self.manifest_path,
            expected_source_csv_sha256=expected_source_csv_sha256,
            expected_count=expected_count,
        )
        if not self.entries:
            raise ValueError("matched-video manifest is empty")
        self.feature_cache = MatchedVideoFeatureCache(
            cache_root,
            expected_model_sha256=expected_model_sha256,
            expected_feature_contract_sha256=expected_feature_contract_sha256,
            feature_contract=(
                feature_contract
                if feature_contract is not None
                else MATCHED_VJEPA2_L15_LAST64_FEATURE_CONTRACT
            ),
            decoder_contract=(
                decoder_contract
                if decoder_contract is not None
                else MATCHED_PYAV_LAST64_DECODER_CONTRACT
            ),
        )
        self.decoder_contract = self.feature_cache.decoder_contract
        self.decode_fn = decode_fn if decode_fn is not None else _default_decode
        self._cache_key_to_index: dict[str, int] = {}
        self._sample_id_to_index: dict[str, int] = {}
        for index, entry in enumerate(self.entries):
            cache_key = self.feature_cache.key_for(entry)
            if cache_key in self._cache_key_to_index:
                raise ValueError(f"duplicate matched-video cache key: {cache_key}")
            if entry.sample_id in self._sample_id_to_index:
                raise ValueError(f"duplicate sample_id: {entry.sample_id}")
            self._cache_key_to_index[cache_key] = index
            self._sample_id_to_index[entry.sample_id] = index

    def __len__(self) -> int:
        return len(self.entries)

    def _entry_for_sample(self, sample_id: str) -> MatchedVideoManifestEntry:
        try:
            return self.entries[self._sample_id_to_index[str(sample_id)]]
        except KeyError as exc:
            raise KeyError(f"unknown matched-video sample_id: {sample_id!r}") from exc

    def _video_path_and_verify_stat(
        self,
        entry: MatchedVideoManifestEntry,
    ) -> Path:
        path = self.video_root / entry.video_name
        if not path.is_file():
            raise FileNotFoundError(path)
        stat = path.stat()
        actual = (int(stat.st_size), int(stat.st_mtime_ns))
        expected = (entry.video_size_bytes, entry.video_mtime_ns)
        if actual != expected:
            raise ValueError(
                "matched video is stale after manifest freeze for "
                f"sample_id={entry.sample_id}: actual={actual}, "
                f"expected={expected}"
            )
        return path

    def cache_key_for_sample(self, sample_id: str) -> str:
        return self.feature_cache.key_for(self._entry_for_sample(sample_id))

    def __getitem__(self, index: int) -> dict[str, Any]:
        """Return only prompt/sample/path metadata; never touch teacher data."""

        entry = self.entries[int(index)]
        video_path = self._video_path_and_verify_stat(entry)
        return {
            "idx": entry.manifest_index,
            "prompts": entry.caption,
            "sample_id": entry.sample_id,
            "teacher_cache_key": self.feature_cache.key_for(entry),
            "video_name": entry.video_name,
            "video_path": str(video_path),
        }

    def load_teacher_payload(self, sample_id: str) -> dict[str, Any]:
        """Load/decode teacher input only after suffix replay selects a sample."""

        entry = self._entry_for_sample(sample_id)
        video_path = self._video_path_and_verify_stat(entry)
        cache_key = self.feature_cache.key_for(entry)
        cached = self.feature_cache.load(entry, cache_key=cache_key)
        payload: dict[str, Any] = {
            "sample_id": entry.sample_id,
            "teacher_cache_key": cache_key,
            "video_name": entry.video_name,
            "video_path": str(video_path),
        }
        if cached is not None:
            payload.update({
                "current_teacher_cache_hit": True,
                "current_teacher_decode_seconds": 0.0,
                "current_teacher_features": cached,
            })
            return payload

        decode_started = time.perf_counter()
        decoded = self.decode_fn(video_path, self.decoder_contract)
        decode_seconds = time.perf_counter() - decode_started
        if not isinstance(decoded, DecodedMatchedVideo):
            raise TypeError("decode_fn must return DecodedMatchedVideo")
        expected_count = int(self.decoder_contract["expected_source_frame_count"])
        expected_frames = int(self.decoder_contract["num_frames"])
        expected_indices = torch.arange(
            expected_count - expected_frames,
            expected_count,
            dtype=torch.long,
        )
        if (
            int(decoded.source_frame_count) != expected_count
            or not isinstance(decoded.frame_indices, torch.Tensor)
            or decoded.frame_indices.dtype != torch.long
            or not torch.equal(
                decoded.frame_indices.detach().cpu(), expected_indices
            )
        ):
            raise ValueError(
                "decode_fn violated the strict last-contiguous 17..80 contract"
            )
        video = decoded.video01
        if (
            not isinstance(video, torch.Tensor)
            or video.dtype != torch.float32
            or video.ndim != 4
            or tuple(video.shape[:2]) != (expected_frames, 3)
            or not bool(torch.isfinite(video).all().item())
            or float(video.min()) < 0.0
            or float(video.max()) > 1.0
        ):
            raise ValueError(
                "decode_fn returned invalid video01; expected finite FP32 "
                f"[{expected_frames},3,H,W] in [0,1]"
            )
        payload.update({
            "current_teacher_cache_hit": False,
            "current_teacher_decode_seconds": decode_seconds,
            "current_teacher_frame_indices": decoded.frame_indices,
            "current_teacher_source_frame_count": expected_count,
            "current_teacher_video01": video.contiguous(),
        })
        return payload

    def write_feature_cache(
        self,
        cache_key: str,
        feature: torch.Tensor,
        *,
        sample_id: str,
    ) -> Path:
        try:
            index = self._cache_key_to_index[str(cache_key)]
        except KeyError as exc:
            raise KeyError(f"unknown teacher cache key: {cache_key!r}") from exc
        entry = self.entries[index]
        if entry.sample_id != str(sample_id):
            raise ValueError(
                "sample_id does not own teacher cache key: "
                f"{sample_id!r} != {entry.sample_id!r}"
            )
        self._video_path_and_verify_stat(entry)
        return self.feature_cache.write(
            entry, feature, cache_key=str(cache_key)
        )

    @staticmethod
    def collate_fn(batch: Sequence[Mapping[str, Any]]) -> dict[str, Any]:
        return collate_matched_video_metadata(batch)


def collate_matched_video_metadata(
    batch: Sequence[Mapping[str, Any]],
) -> dict[str, Any]:
    """Collate only metadata; teacher payloads intentionally have no collator."""

    if not batch:
        raise ValueError("cannot collate an empty matched-video batch")
    forbidden = {
        "current_teacher_features",
        "current_teacher_video01",
        "current_teacher_cache_hit",
    }
    for item in batch:
        present = forbidden.intersection(item)
        if present:
            raise ValueError(
                "metadata collator received eager teacher payload fields: "
                f"{sorted(present)}"
            )
    return {
        "idx": torch.tensor([int(item["idx"]) for item in batch]),
        "prompts": [str(item["prompts"]) for item in batch],
        "sample_ids": [str(item["sample_id"]) for item in batch],
        "teacher_cache_keys": [str(item["teacher_cache_key"]) for item in batch],
        "video_names": [str(item["video_name"]) for item in batch],
        "video_paths": [str(item["video_path"]) for item in batch],
    }


__all__ = [
    "DecodedMatchedVideo",
    "MatchedManifestVideoDataset",
    "collate_matched_video_metadata",
    "decode_matched_video_last_contiguous_pyav",
]