Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/docs/pypaimon/video.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,10 @@ physical video range, so different frame descriptors reuse one decoder session
in each DataLoader worker. `decoder_factory(stream)` opens any codec library;
`decode_fn(decoder, frame_index, row)` receives the embedded frame ordinal.

Collators in one process can share parsed MP4 indexes when they use the same
FileIO and `metadata_cache` instance with a cache-aware decoder. The sequential
decoder below opens its own MP4 container.

```python
import av
import torch
Expand Down
3 changes: 2 additions & 1 deletion paimon-python/pypaimon/multimodal/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
join_asof,
join_window,
)
from pypaimon.multimodal.video import VideoFrameCollator
from pypaimon.multimodal.video import VideoFrameCollator, VideoMetadataCache
from pypaimon.table.row.blob import Blob, BlobDescriptor, VideoFrameDescriptor
from pypaimon.table.data_evolution_merge_into import (
lit,
Expand Down Expand Up @@ -83,6 +83,7 @@
"TemporalAlignment",
"VectorRoute",
"VideoFrameCollator",
"VideoMetadataCache",
"VideoFrameDescriptor",
"connect",
"interpolate",
Expand Down
27 changes: 17 additions & 10 deletions paimon-python/pypaimon/multimodal/lerobot/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -2269,8 +2269,8 @@ def _open_video_decoder(stream, backend=None, codec_threads=0):
if keyframe_index is None and isinstance(getattr(stream, "video_length", None), int):
cache = getattr(stream, "video_metadata_cache", None)
key = ("container", getattr(stream, "video_metadata_key", None))
keyframe_index = cache.get(key) if cache is not None else None
if keyframe_index is None:

def load_index():
try:
source = stream
hint = getattr(stream, "video_moov_range", (0, 0))
Expand All @@ -2285,16 +2285,23 @@ def _open_video_decoder(stream, backend=None, codec_threads=0):
head = min(256 * 1024, hint[0] + hint[1] + 128 * 1024)
source.prefetch([(0, min(head, stream.video_length)), hint])
stream.video_bootstrap = source
keyframe_index = ContainerFrameIndex(source, stream.video_length)
except (ValueError, OSError, RuntimeError, EOFError, OverflowError, IndexError, struct.error):
bootstrap = getattr(stream, "video_bootstrap", None)
if bootstrap is not None:
bootstrap.close()
stream.video_bootstrap = None
return ContainerFrameIndex(source, stream.video_length)
finally:
stream.seek(0)
if keyframe_index is not None and cache is not None:
cache[key] = keyframe_index
try:
if callable(getattr(cache, "get_or_load", None)):
keyframe_index = cache.get_or_load(key, load_index)
else:
keyframe_index = cache.get(key) if cache is not None else None
if keyframe_index is None:
keyframe_index = load_index()
if cache is not None:
cache[key] = keyframe_index
except (ValueError, OSError, RuntimeError, EOFError, OverflowError, IndexError, struct.error):
bootstrap = getattr(stream, "video_bootstrap", None)
if bootstrap is not None:
bootstrap.close()
stream.video_bootstrap = None
stream.video_keyframe_index = keyframe_index
if backend is None and keyframe_index is not None:
try:
Expand Down
16 changes: 11 additions & 5 deletions paimon-python/pypaimon/multimodal/lerobot/indexed_torchcodec.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,16 +77,22 @@ def __init__(self, stream, index, codec_threads=1):
+ list(index.metadata_ranges))
cache = getattr(stream, "video_metadata_cache", None)
cache_key = ("timeline", getattr(stream, "video_metadata_key", None))
timeline = cache.get(cache_key) if cache is not None else None
if timeline is None:
timeline = _SharedTimeline(source, self._length, index if hasattr(index, "pts") else None)

def load_timeline():
return _SharedTimeline(source, self._length, index if hasattr(index, "pts") else None)
if callable(getattr(cache, "get_or_load", None)):
timeline = cache.get_or_load(cache_key, load_timeline)
else:
timeline = cache.get(cache_key) if cache is not None else None
if timeline is None:
timeline = load_timeline()
if cache is not None:
cache[cache_key] = timeline
self._pts, self._durations, self._scale = timeline.pts, timeline.durations, timeline.scale
if index.keyframes[-1][0] >= len(self._pts):
raise ValueError("Keyframe ordinal exceeds the MP4 timeline.")
self._timeline = timeline
self._pts_tolerance = timeline.tolerance
if cache is not None:
cache[cache_key] = timeline
self._decoder = VideoDecoder(
source, stream_index=timeline.stream_index, device="cpu",
num_ffmpeg_threads=codec_threads, seek_mode="approximate")
Expand Down
113 changes: 87 additions & 26 deletions paimon-python/pypaimon/multimodal/video.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@
import weakref
from collections import OrderedDict, deque
from collections.abc import Mapping
from concurrent.futures import ThreadPoolExecutor, wait
from concurrent.futures import Future, ThreadPoolExecutor, wait
from contextlib import ExitStack, contextmanager
from fractions import Fraction
from itertools import chain
from threading import RLock

try:
from contextvars import copy_context
Expand Down Expand Up @@ -378,39 +379,89 @@ def close(self):
super().close()


class _VideoMetadataCache(weakref.WeakValueDictionary):
"""Retain bounded container mappings across decoder eviction."""
class VideoMetadataCache(weakref.WeakValueDictionary):
"""Process-local cache for parsed video metadata.

Values must support weak references. Strong retention requires ``nbytes``
and is bounded by bytes and entry count.
"""

def __init__(self, max_bytes=16 * 1024 * 1024, max_entries=64):
super().__init__()
self._retained = OrderedDict()
self._bytes = 0
self._max_bytes = max_bytes
self._max_entries = max_entries
self._lock = RLock()
self._pending = {}

def get(self, key, default=None):
if key in self._retained:
self._retained.move_to_end(key)
return super().get(key, default)
with self._lock:
if key in self._retained:
self._retained.move_to_end(key)
return super().get(key, default)

def __setitem__(self, key, value):
super().__setitem__(key, value)
previous = self._retained.pop(key, None)
if previous is not None:
self._bytes -= previous.nbytes
size = getattr(value, "nbytes", None)
if size is None or size > self._max_bytes:
return
self._retained[key] = value
self._bytes += size
while self._bytes > self._max_bytes or len(self._retained) > self._max_entries:
_, removed = self._retained.popitem(last=False)
self._bytes -= removed.nbytes
with self._lock:
super().__setitem__(key, value)
previous = self._retained.pop(key, None)
if previous is not None:
self._bytes -= previous.nbytes
size = getattr(value, "nbytes", None)
if size is None or size > self._max_bytes:
return
self._retained[key] = value
self._bytes += size
while self._bytes > self._max_bytes or len(self._retained) > self._max_entries:
_, removed = self._retained.popitem(last=False)
self._bytes -= removed.nbytes

def get_or_load(self, key, loader):
"""Return a cached value, sharing one in-flight load per key."""
with self._lock:
value = self.get(key)
if value is not None:
return value
pending = self._pending.get(key)
owner = pending is None
if owner:
pending = self._pending[key] = Future()
if not owner:
return pending.result()
try:
value = loader()
with self._lock:
self[key] = value
self._pending.pop(key)
pending.set_result(value)
return value
except BaseException as error:
with self._lock:
self._pending.pop(key)
pending.set_exception(error)
raise

def clear(self):
self._retained.clear()
self._bytes = 0
super().clear()
with self._lock:
self._retained.clear()
self._bytes = 0
super().clear()


_VideoMetadataCache = VideoMetadataCache


class _VideoStorageScope:
"""Hash a FileIO by identity and keep it alive while its keys are cached."""

def __init__(self, file_io):
self._file_io = file_io

def __hash__(self):
return id(self._file_io)

def __eq__(self, other):
return isinstance(other, _VideoStorageScope) and self._file_io is other._file_io


class VideoFrameCollator:
Expand Down Expand Up @@ -441,7 +492,8 @@ class VideoFrameCollator:
Larger videos or a full budget retain range reads. The budget is per collator
and worker; decoder buffers, RGB outputs and temporary copies are additional.

The cache is process-local and keyed by physical video payload identity.
Share a caller-owned ``metadata_cache`` to reuse parsed indexes across
collators using the same FileIO in one process.
``collate_fn`` defaults to PyTorch's ``default_collate`` and may be replaced
for decoders that already return batched objects.
"""
Expand All @@ -459,7 +511,8 @@ def __init__(
decode_batch_fn=None,
range_parallelism=4,
prefetch_max_bytes=0,
decode_parallelism=1):
decode_parallelism=1,
metadata_cache=None):
if not video_column:
raise ValueError("video_column is required.")
if not callable(decoder_factory):
Expand Down Expand Up @@ -493,6 +546,8 @@ def __init__(
or not isinstance(decode_parallelism, int)
or decode_parallelism <= 0):
raise ValueError("decode_parallelism must be a positive int.")
if metadata_cache is not None and not isinstance(metadata_cache, VideoMetadataCache):
raise TypeError("metadata_cache must be a VideoMetadataCache.")

raw_table = getattr(table, "raw_table", table)
file_io = getattr(raw_table, "file_io", None)
Expand All @@ -512,7 +567,9 @@ def __init__(
self.decode_parallelism = decode_parallelism
self._decode_pool = _VideoDecodePool()
self._decoders = OrderedDict()
self._video_metadata_cache = _VideoMetadataCache()
self._video_metadata_cache = (metadata_cache if metadata_cache is not None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Fix before merge

The shared cache uses the video descriptor as its key, while each collator resolves that descriptor through its own FileIO. Two S3-compatible endpoints can serve different MP4s for the same URI and byte range. In a local repro with two FileIO test doubles and real MP4s, the second PyAV collator returned frame ordinal 7 for a request for ordinal 5 after reusing the first video's index.

Please include the resolved storage namespace in the cache key. When a stable namespace is unavailable, scope entries to the FileIO instance. A regression test should cover two sources that resolve the same descriptor to different media.

else VideoMetadataCache())
self._metadata_cache_owned = metadata_cache is None
self._owner_pid = os.getpid()

def __call__(self, rows):
Expand All @@ -528,7 +585,8 @@ def close(self):
self._decode_pool.close()
resources = list(self._decoders.values())
self._decoders.clear()
self._video_metadata_cache = _VideoMetadataCache()
if self._metadata_cache_owned:
self._video_metadata_cache = VideoMetadataCache()
first_error = None
for resource in resources:
try:
Expand All @@ -546,6 +604,7 @@ def __getstate__(self):
state["_decoders"] = OrderedDict()
state["_decode_pool"] = _VideoDecodePool()
state["_video_metadata_cache"] = None
state["_metadata_cache_owned"] = True
state["_owner_pid"] = None
return state

Expand Down Expand Up @@ -711,7 +770,7 @@ def _decoder(self, descriptor, replica=0):
del payload
# Replica decoders share metadata, while their decode state stays separate.
stream.video_metadata_cache = self._video_metadata_cache
stream.video_metadata_key = descriptor
stream.video_metadata_key = (_VideoStorageScope(self.file_io), descriptor)
stream.video_length = descriptor.length
stream.video_moov_range = (getattr(descriptor, "moov_offset", 0),
getattr(descriptor, "moov_length", 0))
Expand Down Expand Up @@ -758,6 +817,8 @@ def _ensure_process_local_cache(self):
try:
self.close()
finally:
self._video_metadata_cache = VideoMetadataCache()
self._metadata_cache_owned = True
self._owner_pid = pid

@staticmethod
Expand Down
Loading
Loading