Skip to content
Draft
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
20 changes: 12 additions & 8 deletions docs/docs/pypaimon/lerobot.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,9 @@ conn.load_from_lerobot(
)
```

Each source has one row in `_datasets`. Episode `stats` preserves the source
values; `_datasets.__paimon_lerobot_read_control_stats` stores derived statistics for the
combined training reader.
Each source has one row in `_datasets`. Single-source readers use its original
Dataset statistics. `PaimonMultiLeRobotDataset` provides combined metadata and
statistics for all sources; Episode `stats` preserves the source values.
`dataset_name` accepts a string for one source or a list/tuple with one label per
source in input order. Omitted names are null, and duplicate labels do not merge
sources. [Dataset fields](#dataset-fields) describes the retained source metadata.
Expand All @@ -213,10 +213,9 @@ a source vocabulary is rejected to avoid ambiguous frame IDs.

Sources must share robot type and compatible definitions for common features. Each source retains its own
FPS from `info`; different source frame rates are handled automatically. Use
`PaimonLeRobotDataset` to train from mixed-FPS groups. Pass `dataset_index=N` to
that reader to select the source at position `N` in UUID order; this reader
argument is not the stored UUID. Frame-rate handling is automatic and does not
require an import option.
`PaimonMultiLeRobotDataset` to train from mixed-FPS groups. For one source, use
`PaimonLeRobotDataset` with its stored `dataset_id` UUID or `dataset_index=N`
(position in UUID order). Frame-rate handling is automatic.

### Schema evolution

Expand Down Expand Up @@ -545,15 +544,20 @@ If a source feature uses the mask name, underscores are prepended until the name

For map-style training, pass an image- or video-backed table group with LeRobot
Episode and Dataset companions to `PaimonLeRobotDataset`.
A group with multiple sources requires `dataset_id="<Dataset UUID>"` or
`dataset_index=N`. Indices, Episode selection, and metadata stay source-local.
Use `PaimonMultiLeRobotDataset` for combined training with global indices and
merged metadata.

```python
from pypaimon.multimodal import PaimonLeRobotDataset
from pypaimon.multimodal import PaimonLeRobotDataset, PaimonMultiLeRobotDataset

table = conn.get_table("robot_data_frames")
dataset = PaimonLeRobotDataset(
table,
tag_name=tag,
)
# To combine the group: dataset = PaimonMultiLeRobotDataset(table, tag_name=tag)
loader = dataset.to_dataloader(
batch_size=32,
shuffle=True,
Expand Down
2 changes: 2 additions & 0 deletions paimon-python/pypaimon/multimodal/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
from pypaimon.multimodal.lerobot.dataset import (
PaimonDatasetReader,
PaimonLeRobotDataset,
PaimonMultiLeRobotDataset,
)
from pypaimon.multimodal.rosbag import (
RosbagLoadResult,
Expand Down Expand Up @@ -75,6 +76,7 @@
"ObjectInfo",
"PaimonDatasetReader",
"PaimonLeRobotDataset",
"PaimonMultiLeRobotDataset",
"PutObjectResult",
"RosbagLoadResult",
"RosbagSource",
Expand Down
2 changes: 2 additions & 0 deletions paimon-python/pypaimon/multimodal/lerobot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,15 @@
from pypaimon.multimodal.lerobot.dataset import (
PaimonDatasetReader,
PaimonLeRobotDataset,
PaimonMultiLeRobotDataset,
)
from pypaimon.multimodal.lerobot.writer import PaimonLeRobotWriter


__all__ = [
"PaimonDatasetReader",
"PaimonLeRobotDataset",
"PaimonMultiLeRobotDataset",
"PaimonLeRobotWriter",
"load_from_lerobot",
"export_to_lerobot",
Expand Down
190 changes: 168 additions & 22 deletions paimon-python/pypaimon/multimodal/lerobot/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -670,33 +670,27 @@ def __repr__(self):

class _PaimonTableDatasetReader(PaimonDatasetReader):

@staticmethod
def _load_metadata(table, tag_name, dataset_index, dataset_id):
return _load_source_dataset(table, tag_name, dataset_index, dataset_id)

def __init__(
self,
table,
*,
tag_name=None,
episodes=None,
dataset_index=None,
dataset_id=None,
image_transforms=None,
delta_timestamps=None,
tolerance_s=1e-4,
blob_parallelism=16,
video_backend=None,
video_metadata_cache=None,
return_uint8=False):
self._frames_table, meta = _load_dataset(table, tag_name)
if dataset_index is not None:
if episodes is not None:
raise ValueError("Select either dataset_index or episodes.")
if isinstance(dataset_index, bool) or not isinstance(dataset_index, int) \
or dataset_index < 0:
raise ValueError("dataset_index must be a non-negative integer.")
sources = meta.datasets
if sources is None or dataset_index >= len(sources):
raise ValueError("LeRobot source dataset_index %d does not exist."
% dataset_index)
begin, end = _source_dataset_ranges(sources)[dataset_index][1:3]
episodes = list(range(begin, end))
self._frames_table, meta = self._load_metadata(table, tag_name, dataset_index, dataset_id)
self.dataset_id = getattr(meta, "dataset_id", None)
self.tag_name = tag_name
super().__init__(
meta,
Expand All @@ -721,17 +715,58 @@ def _validate_physical_metadata(self):
def _open_frame_rows(self, projection):
rows = _PaimonTableFrameReader(
self._frames_table, columns=projection)
if rows.num_rows != self._total_frames:
table_total_frames = getattr(self.meta, "_table_total_frames", self._total_frames)
if rows.num_rows != table_total_frames:
raise ValueError(
"Paimon table has %d rows but metadata declares %d frames."
% (rows.num_rows, self._total_frames))
% (rows.num_rows, table_total_frames))
return self._wrap_frame_rows(rows)

def _wrap_frame_rows(self, rows):
if self.meta.datasets is not None:
return _SourceFrameReader(rows, self.dataset_id, self._total_frames)
return rows


class _PaimonMultiTableDatasetReader(_PaimonTableDatasetReader):

@staticmethod
def _load_metadata(table, tag_name, dataset_index, dataset_id):
return _load_dataset(table, tag_name)

def _wrap_frame_rows(self, rows):
if self.meta.datasets is not None:
rows = _SourceEpisodeFrameReader(
rows, self.meta.datasets,
getattr(self.meta, "_source_vocabulary_maps", None))
return rows


class _SourceFrameReader:
"""Read one source's physical keys without translating its local IDs."""

def __init__(self, reader, dataset_id, num_rows):
self._reader = reader
self._dataset_id = dataset_id
self.num_rows = num_rows
self.file_io = reader.file_io
self.snapshot_id = reader.snapshot_id
self._table = reader._table
self._locator = reader._locator

def read_indices(self, indices, columns):
keys = [(self._dataset_id, index) for index in indices]
data = self._reader.read_keys(keys, columns)
expected = set(keys)
actual = list(zip(data["dataset_id"].to_pylist(), data["index"].to_pylist()))
if len(actual) != len(expected) or set(actual) != expected:
raise ValueError("LeRobot frame keys are missing or duplicated.")
return data.select(columns)

def close(self):
self._reader.close()


class _SourceEpisodeFrameReader:
"""Present source-local Episode IDs as ordinals to the training reader."""

Expand Down Expand Up @@ -831,8 +866,8 @@ def close(self):
self._reader.close()


class PaimonLeRobotDataset:
"""Map-style Dataset facade backed by :class:`PaimonDatasetReader`."""
class _LeRobotDataset:
"""Map-style facade shared by the single-source and combined readers."""

def __init__(
self,
Expand All @@ -841,6 +876,7 @@ def __init__(
tag_name=None,
episodes=None,
dataset_index=None,
dataset_id=None,
image_transforms=None,
delta_timestamps=None,
tolerance_s=1e-4,
Expand All @@ -854,6 +890,7 @@ def __init__(
tag_name is not None
or episodes is not None
or dataset_index is not None
or dataset_id is not None
or image_transforms is not None
or delta_timestamps is not None
or tolerance_s != 1e-4
Expand All @@ -866,11 +903,12 @@ def __init__(
"Configure Dataset options on PaimonDatasetReader.")
self.reader = table
else:
self.reader = _PaimonTableDatasetReader(
self.reader = self._reader_class(
table,
tag_name=tag_name,
episodes=episodes,
dataset_index=dataset_index,
dataset_id=dataset_id,
image_transforms=image_transforms,
delta_timestamps=delta_timestamps,
tolerance_s=tolerance_s,
Expand All @@ -894,7 +932,7 @@ def to_dataloader(self, **kwargs):
collate_fn = kwargs.pop("collate_fn", None)
if collate_fn is not None:
raise ValueError(
"PaimonLeRobotDataset.to_dataloader manages collate_fn.")
"%s.to_dataloader manages collate_fn." % type(self).__name__)
from torch.utils.data import DataLoader
num_workers = kwargs.get("num_workers", 0)
batched = _LeRobotDataLoaderAdapter(
Expand Down Expand Up @@ -941,6 +979,48 @@ def __repr__(self):
self.reader.__class__.__name__, self.__class__.__name__, 1)


class PaimonLeRobotDataset(_LeRobotDataset):
"""Read one source dataset, retaining its local indices and statistics.

Select ``dataset_id`` (the stored UUID) or ``dataset_index`` (UUID order)
when the table group contains multiple sources. ``episodes`` is local to
that source. A group with one source needs no selector.
"""

_reader_class = _PaimonTableDatasetReader


class PaimonMultiLeRobotDataset(_LeRobotDataset):
"""Read all sources in a table group with combined training metadata.

Frame and Episode indices are global to the group; task and subtask IDs
use the combined vocabulary. Select ``episodes`` with those global IDs.
Use :class:`PaimonLeRobotDataset` to read an individual source instead.
"""

_reader_class = _PaimonMultiTableDatasetReader

def __init__(
self,
table,
*,
tag_name=None,
episodes=None,
image_transforms=None,
delta_timestamps=None,
tolerance_s=1e-4,
blob_parallelism=16,
video_backend=None,
video_metadata_cache=None,
return_uint8=False):
super().__init__(
table, tag_name=tag_name, episodes=episodes,
image_transforms=image_transforms, delta_timestamps=delta_timestamps,
tolerance_s=tolerance_s, blob_parallelism=blob_parallelism,
video_backend=video_backend, video_metadata_cache=video_metadata_cache,
return_uint8=return_uint8)


class _LeRobotDataLoaderAdapter:

def __init__(self, dataset, share_memory):
Expand Down Expand Up @@ -1142,6 +1222,66 @@ def _load_dataset(table, tag_name):
return frames, metadata


def _load_source_dataset(table, tag_name, dataset_index, dataset_id):
raw_table = getattr(table, "raw_table", None)
if raw_table is None:
raise TypeError("table must be a MultimodalTable.")
if tag_name is not None:
_validate_tag_name(tag_name)
identifiers = _companion_table_identifiers(raw_table)
catalog = table.catalog
frames = _component_table(catalog, raw_table, tag_name)
episodes_table = _component_table(
catalog, catalog.get_table(identifiers["episodes"]), tag_name)
datasets_table = _component_table(
catalog, catalog.get_table(identifiers["datasets"]), tag_name)
source_rows = _read_arrow(datasets_table, [
"id", "name", "info", "tasks", "subtasks", "stats"]).sort_by("id").to_pylist()
if not source_rows:
raise ValueError("LeRobot Dataset metadata is required.")
table_total_frames = _source_dataset_ranges(source_rows)[-1][4]
source = _select_source(source_rows, dataset_index, dataset_id)
source_local_layout = "dataset_id" in _target_schema(episodes_table).names
datasets = [{key: source[key] for key in ("id", "name", "info")}] if source_local_layout else None
episodes = _episode_dataset(
episodes_table, datasets, dataset_id=source["id"] if source_local_layout else None)
tasks, _ = _source_vocabulary([source], "task")
subtasks, _ = _source_vocabulary([source], "subtask")
info = json.loads(source["info"])
for feature in info.get("features", {}).values():
feature["shape"] = tuple(feature["shape"])
stats = _numpy_stats(json.loads(source["stats"])) if source["stats"] is not None else None
metadata = _PaimonLeRobotMetadata(
str(table.identifier), tag_name, info, stats, episodes, tasks, subtasks, datasets)
metadata.dataset_id = source["id"]
metadata._table_total_frames = table_total_frames
metadata._compress_episodes = True
return frames, metadata


def _select_source(sources, dataset_index, dataset_id):
if dataset_index is not None and dataset_id is not None:
raise ValueError("Select either dataset_id or dataset_index.")
if dataset_id is not None:
if not isinstance(dataset_id, str):
raise ValueError("dataset_id must be a stored Dataset UUID string.")
for source in sources:
if source["id"] == dataset_id:
return source
raise ValueError("LeRobot source dataset_id %r does not exist." % dataset_id)
if dataset_index is None:
if len(sources) != 1:
raise ValueError(
"Multiple LeRobot sources: select dataset_id or dataset_index, "
"or use PaimonMultiLeRobotDataset to combine them.")
return sources[0]
if isinstance(dataset_index, bool) or not isinstance(dataset_index, int) or dataset_index < 0:
raise ValueError("dataset_index must be a non-negative integer.")
if dataset_index >= len(sources):
raise ValueError("LeRobot source dataset_index %d does not exist." % dataset_index)
return sources[dataset_index]


def _source_vocabulary(sources, singular):
import pandas as pd

Expand Down Expand Up @@ -1313,15 +1453,17 @@ def _component_table(catalog, table, tag_name):
return _time_travel_table(table, tag_name=tag_name)


def _read_arrow(table, projection=None):
def _read_arrow(table, projection=None, predicate=None):
builder = table.new_read_builder()
if projection is not None:
builder = builder.with_projection(projection)
if predicate is not None:
builder = builder.with_filter(predicate)
plan = builder.new_scan().plan()
return builder.new_read().to_arrow(plan.splits())


def _episode_dataset(table, datasets=None):
def _episode_dataset(table, datasets=None, dataset_id=None):
try:
from datasets import Dataset
except ImportError as error:
Expand All @@ -1335,7 +1477,11 @@ def _episode_dataset(table, datasets=None):
else:
projection = [name for name in _target_schema(table).names
if not name.startswith("stats/") and name != "stats"]
data = _read_arrow(table, projection)
if dataset_id is None:
data = _read_arrow(table, projection)
else:
predicate = table.new_read_builder().new_predicate_builder().equal("dataset_id", dataset_id)
data = _read_arrow(table, projection, predicate)
if datasets is not None:
physical_ids = [dataset["id"] for dataset in datasets]
ordinals = pc.index_in(data["dataset_id"],
Expand Down
Loading
Loading