This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new 2857342cf1 [python] Import multiple LeRobot datasets into one table
group (#11056)
2857342cf1 is described below
commit 2857342cf1b510bef7918392d5701b1dae507c21
Author: XiaoHongbo <[email protected]>
AuthorDate: Tue Nov 10 21:23:45 2026 +0800
[python] Import multiple LeRobot datasets into one table group (#11056)
---
.github/workflows/ci-python.yml | 9 +
docs/docs/pypaimon/lerobot.md | 31 +-
paimon-python/pypaimon/multimodal/connection.py | 8 +-
.../pypaimon/multimodal/lerobot/aggregate.py | 514 +++++++
paimon-python/pypaimon/multimodal/lerobot/api.py | 40 +-
.../pypaimon/multimodal/lerobot/dataset.py | 220 ++-
.../pypaimon/multimodal/lerobot/loader.py | 4 +-
.../pypaimon/multimodal/lerobot/metadata.py | 62 +-
.../pypaimon/multimodal/lerobot/ray_loader.py | 83 +-
.../pypaimon/tests/lerobot_aggregate_test.py | 1491 ++++++++++++++++++++
10 files changed, 2413 insertions(+), 49 deletions(-)
diff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.yml
index 5fd72b9658..a40f5df9e3 100644
--- a/.github/workflows/ci-python.yml
+++ b/.github/workflows/ci-python.yml
@@ -318,9 +318,18 @@ jobs:
python -c 'from lerobot.datasets.lerobot_dataset import
LeRobotDataset'
python -m pytest -q \
pypaimon/tests/multimodal_lerobot_test.py \
+ pypaimon/tests/lerobot_aggregate_test.py \
pypaimon/tests/multimodal_lerobot_writer_test.py::PaimonLeRobotWriterTest::test_multiframe_boolean_statistics_preserve_extrema
\
pypaimon/tests/multimodal_lerobot_writer_test.py::PaimonLeRobotWriterTest::test_multiframe_int64_statistics_preserve_extrema
+ - name: Test Ray LeRobot import
+ if: matrix.lerobot == '0.4.4' && matrix.torchcodec == '0.3.0'
+ working-directory: paimon-python
+ run: |
+ python -m pip install 'ray==2.53.0'
+ python -c 'import ray'
+ python -m pytest -q pypaimon/tests/lerobot_aggregate_test.py
pypaimon/tests/multimodal_lerobot_ray_test.py
+
- name: Test indexed TorchCodec (no skips)
working-directory: paimon-python
run: |
diff --git a/docs/docs/pypaimon/lerobot.md b/docs/docs/pypaimon/lerobot.md
index 8a07b4b497..44214f0534 100644
--- a/docs/docs/pypaimon/lerobot.md
+++ b/docs/docs/pypaimon/lerobot.md
@@ -65,6 +65,32 @@ The call returns `None` on success. Omitting `tag_name`
imports the tables
without creating tags. The one-time importer requires a new target table and
a non-empty source dataset; subsequent table edits use the normal Paimon APIs.
+Pass an ordered list to merge sources into one table group:
+
+```python
+conn.load_from_lerobot(
+ "robot_all",
+ ["oss://bucket/dataset_a", "oss://bucket/dataset_b"],
+ dataset_names=["dataset_a", "dataset_b"],
+ fps_mode="source", # Allow different source FPS.
+)
+```
+
+Each source has one row in `__datasets`, including its original metadata and
FPS.
+`dataset_names` supplies optional labels; omitted names are null, and duplicate
+labels do not merge sources. Use `dataset_index` to link frames and Episodes;
+`(dataset_index, episode_index)` identifies an original Episode. Frames keep a
+merged `index` and their original `source_index`. Source task/subtask metadata
+and original Episode rows (`__episodes.source_episode_ipc`) use Arrow IPC to
+preserve extra columns and native types. Episode extension columns are shared
+only when present with matching types in every source. Repeated task/subtask
text within one
+source is rejected before creating tables to avoid losing original frame IDs.
+
+Sources must share robot type and training features. By default they must also
+share FPS; `fps_mode="source"` permits mixed FPS and requires
+`PaimonLeRobotDataset` for training. Pass `dataset_index=N` to that reader to
+select one source.
+
For FileIO URIs, pass credentials through `source_options`:
```python
@@ -89,7 +115,9 @@ conn.load_from_lerobot("robot_data",
"oss://source-bucket/lerobot_dataset",
parallelism=8)
```
-The default `parallelism=1` uses one process. Workers need source and target
+The default `parallelism=1` uses one process. Ray groups Episodes within each
source,
+keeping shared files together and limiting total concurrency to `parallelism`.
+Workers need source and target
storage access; pass OSS `source_options` as above. Ray accepts FileIO URIs or
shared directories, not Hub IDs. Keep the source unchanged during import.
Failed imports may leave partial tables; retry with a new name.
@@ -238,6 +266,7 @@ For datasets with `subtask_index`, `to_dataloader()` always
returns integer
`subtask_index` tensors and matching boolean `subtask_index_is_valid` masks,
including time windows. Missing labels use `-1` with a false mask; individual
sample reads retain `None`.
+If a source feature uses the mask name, underscores are prepended until the
name is unused.
For map-style training, pass an image- or video-backed table group created by
`load_from_lerobot` to `PaimonLeRobotDataset`. A frame-only table created by
diff --git a/paimon-python/pypaimon/multimodal/connection.py
b/paimon-python/pypaimon/multimodal/connection.py
index cdf83205dd..2677699119 100644
--- a/paimon-python/pypaimon/multimodal/connection.py
+++ b/paimon-python/pypaimon/multimodal/connection.py
@@ -141,8 +141,10 @@ class MultimodalConnection:
options=None,
source_options=None,
tag_name=None,
- parallelism=1) -> None:
- """Import LeRobot Dataset v3 into a new Paimon table group."""
+ parallelism=1,
+ fps_mode="dataset",
+ dataset_names=None) -> None:
+ """Import one or an ordered list of LeRobot v3 sources into a new
table group."""
from pypaimon.multimodal.lerobot import load_from_lerobot
load_from_lerobot(
self,
@@ -153,6 +155,8 @@ class MultimodalConnection:
source_options=source_options,
tag_name=tag_name,
parallelism=parallelism,
+ fps_mode=fps_mode,
+ dataset_names=dataset_names,
)
def create_lerobot_tag(self, table_name: str, tag_name: str):
diff --git a/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
b/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
new file mode 100644
index 0000000000..cf0ad9de85
--- /dev/null
+++ b/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
@@ -0,0 +1,514 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Merge source coordinates at the write boundary of a new table group."""
+
+import copy
+import json
+from contextlib import ExitStack
+
+import numpy as np
+import pyarrow as pa
+import pyarrow.compute as pc
+
+from pypaimon.multimodal.arrow_utils import strict_arrow_table
+from pypaimon.multimodal.lerobot.loader import (
+ _commit_messages, _prepare_dataset, _video_fps,
+)
+from pypaimon.multimodal.lerobot.metadata import (
+ _EPISODE_CONTROL_COLUMNS, _EPISODE_FPS_COLUMN, _commit_metadata,
_json_value,
+ _load_dataset_metadata,
+ _metadata_table, _prepare_metadata_tables,
+ _source_episode_tables, _validated_episode_tables,
+)
+from pypaimon.multimodal.lerobot.schema import (
+ _require_v3, _schema_from_info, _validate_v3_required_features,
+ _video_feature_names,
+)
+from pypaimon.multimodal.lerobot.source import (
+ _close_quietly, _import_lerobot_dataset, _load_hub_info,
+ _open_resolved_dataset, _pandas_index_column, _resolved_source,
+ _validate_info_paths,
+)
+from pypaimon.multimodal.source_utils import _validate_source_kerberos
+from pypaimon.multimodal.table import _target_schema
+
+
+_CONTROLS = ("index", "episode_index", "task_index", "subtask_index")
+_STATS = ("min", "max", "mean", "std", "count")
+_ENCODER_KEYS = {
+ "video.codec", "video.pix_fmt", "video.gop_size", "video.crf",
+ "video.encoder", "video.extra_options", "video.video_backend",
+ "video.has_audio", "has_audio", "video.bit_rate",
+}
+# These properties describe source storage or are rebuilt for the merged
dataset.
+_REBUILT_INFO = {
+ "total_frames", "total_episodes", "total_tasks", "total_subtasks",
"total_videos",
+ "total_chunks", "splits", "data_path", "video_path", "chunks_size",
+ "data_files_size_in_mb", "video_files_size_in_mb", "features",
+}
+_DATASET_INDEX_COLUMN = "dataset_index"
+_SOURCE_FRAME_INDEX_COLUMN = "source_index"
+_DATASETS_SCHEMA = pa.schema([
+ pa.field(_DATASET_INDEX_COLUMN, pa.int64(), nullable=False),
+ pa.field("dataset_name", pa.string()),
+ pa.field("fps", pa.int64(), nullable=False),
+ pa.field("episode_from_index", pa.int64(), nullable=False),
+ pa.field("episode_to_index", pa.int64(), nullable=False),
+ pa.field("frame_from_index", pa.int64(), nullable=False),
+ pa.field("frame_to_index", pa.int64(), nullable=False),
+ pa.field("info_json", pa.string(), nullable=False),
+ pa.field("tasks_ipc", pa.binary(), nullable=False),
+ pa.field("subtasks_ipc", pa.binary()),
+ pa.field("stats_ipc", pa.binary()),
+ pa.field("episodes_schema_ipc", pa.binary(), nullable=False),
+])
+
+
+def _arrow_ipc(table):
+ if table is None:
+ return None
+ sink = pa.BufferOutputStream()
+ with pa.ipc.new_stream(sink, table.schema) as writer:
+ writer.write_table(table)
+ return sink.getvalue().to_pybytes()
+
+
+def _json_table(table):
+ return {row["key"]: json.loads(row["value"]) for row in table.to_pylist()}
+
+
+def _merge_stats(items):
+ """Combine population moments; quantile summaries cannot be merged
exactly."""
+ if any(set(item) - set(_STATS) - {"q01", "q10", "q50", "q90", "q99"}
+ for item in items):
+ raise ValueError("Unsupported LeRobot statistics fields.")
+ if any(not set(_STATS).issubset(item) for item in items):
+ raise ValueError("LeRobot statistics require min/max/mean/std/count.")
+ arrays = [{key: np.asarray(item[key], dtype=np.float64 if key in ("mean",
"std") else None)
+ for key in _STATS}
+ for item in items]
+ first = arrays[0]
+ for item in arrays:
+ if any(item[key].shape != first[key].shape for key in _STATS):
+ raise ValueError("LeRobot statistics shapes must match.")
+ count = item["count"]
+ if count.shape != (1,) or not np.all(np.isfinite(count)) \
+ or np.any(count <= 0) or np.any(count != np.floor(count)):
+ raise ValueError("LeRobot statistics count must be one positive
integer.")
+ if any(item[key].shape != item["mean"].shape for key in ("min", "max",
"std")):
+ raise ValueError("LeRobot statistic shapes must match their mean.")
+ count = sum(int(item["count"][0]) for item in arrays)
+ mean = sum(item["mean"] * item["count"] for item in arrays) / count
+ variance = sum(item["count"] * (
+ item["std"] ** 2 + (item["mean"] - mean) ** 2) for item in arrays) /
count
+
+ def extrema(key, reduction):
+ dtype = object if all(np.issubdtype(item[key].dtype, np.integer)
+ for item in arrays) else np.float64
+ return reduction([item[key].astype(dtype) for item in arrays]).tolist()
+
+ return {
+ "min": extrema("min", np.minimum.reduce),
+ "max": extrema("max", np.maximum.reduce),
+ "mean": mean.tolist(), "std": np.sqrt(variance).tolist(),
+ "count": [count],
+ }
+
+
+def _batch_stats(values):
+ values = np.asarray(values)
+ return {"min": [values.min().item()], "max": [values.max().item()],
+ "mean": [values.mean()], "std": [values.std()],
+ "count": [len(values)]}
+
+
+def _vocabulary(plans, kind):
+ key = kind + "_table"
+ tables = [plan["metadata"][key] for plan in plans]
+ if all(table is None for table in tables):
+ return None
+ if any(table is None for table in tables):
+ raise ValueError("LeRobot sources disagree on %s metadata." % kind)
+ singular = kind[:-1]
+ index_name = singular + "_index"
+ schema = tables[0].schema
+ label = _pandas_index_column(schema, singular)
+ schema = tables[0].select([index_name, label]).schema
+ rows, by_text = [], {}
+ for ordinal, (plan, table) in enumerate(zip(plans, tables)):
+ source_label = _pandas_index_column(table.schema, singular)
+ if (not table.schema.field(index_name).equals(
+ schema.field(index_name), check_metadata=False)
+ or not
(pa.types.is_string(table.schema.field(source_label).type)
+ or
pa.types.is_large_string(table.schema.field(source_label).type))):
+ raise ValueError("LeRobot source %d has incompatible %s schema." %
(ordinal, kind))
+ mapping = {}
+ source_texts = set()
+ for row in sorted(table.select([index_name, source_label]).to_pylist(),
+ key=lambda row: row[index_name]):
+ text = row[source_label]
+ if text in source_texts:
+ raise ValueError("LeRobot source %d has duplicate %s text %r; "
+ "original frame IDs would be ambiguous."
+ % (ordinal, singular, text))
+ source_texts.add(text)
+ if text not in by_text:
+ by_text[text] = len(rows)
+ rows.append({index_name: len(rows), label: text})
+ mapping[row[index_name]] = by_text[text]
+ plan[index_name] = mapping
+ return pa.Table.from_pylist(rows, schema=schema)
+
+
+def _feature_contract(features):
+ result = copy.deepcopy(features)
+ for feature in result.values():
+ if feature.get("dtype") == "video":
+ feature.pop("fps", None)
+ for key in ("info", "video_info"):
+ details = feature.get(key)
+ details = details if isinstance(details, dict) else {}
+ feature[key] = {k: v for k, v in details.items()
+ if k not in _ENCODER_KEYS
+ and k != "video.fps"}
+ return result
+
+
+def _same_fields(left, right):
+ return (set(left.names) == set(right.names)
+ and all(left.field(name).equals(right.field(name),
check_metadata=False)
+ for name in right.names))
+
+
+def _plan_merge(plans, fps_mode="dataset"):
+ first = plans[0]
+ reserved_frame_fields = {
+ _DATASET_INDEX_COLUMN, _SOURCE_FRAME_INDEX_COLUMN,
+ }
+ if reserved_frame_fields.intersection(first["schema"].names):
+ raise ValueError("LeRobot source frame features use reserved source
index columns.")
+ info = copy.deepcopy(first["info"])
+ metadata = dict(first["metadata"])
+ # Quantiles are omitted rather than presenting source summaries as merged
values.
+ metadata["episodes_schema"] = pa.schema([
+ field.with_nullable(True) if
field.name.startswith("stats/subtask_index/") else field
+ for field in metadata["episodes_schema"]
+ if not any(field.name.startswith("stats/%s/q" % name) for name in
_CONTROLS)
+ and not (fps_mode == "source" and field.name == _EPISODE_FPS_COLUMN)
+ ], metadata=metadata["episodes_schema"].metadata)
+ required_episode_fields = set(_EPISODE_CONTROL_COLUMNS) | {
+ "videos/%s/%s" % (name, suffix)
+ for name in first["videos"]
+ for suffix in ("chunk_index", "file_index", "from_timestamp",
"to_timestamp")
+ }
+ # Optional source-specific fields remain lossless in source_episode_ipc.
+ metadata["episodes_schema"] = pa.schema([
+ field if field.name in required_episode_fields else
field.with_nullable(
+ field.nullable or
any(plan["metadata"]["episodes_schema"].field(field.name).nullable
+ for plan in plans))
+ for field in metadata["episodes_schema"]
+ if field.name in required_episode_fields or all(
+ field.name in plan["metadata"]["episodes_schema"].names
+ and
field.type.equals(plan["metadata"]["episodes_schema"].field(field.name).type)
+ for plan in plans)
+ ], metadata=metadata["episodes_schema"].metadata)
+ frame_offset = episode_offset = 0
+ for ordinal, plan in enumerate(plans):
+ other = plan["info"]
+ compared_keys = ("codebase_version", "robot_type")
+ if fps_mode == "dataset":
+ compared_keys += ("fps",)
+ for key in compared_keys:
+ if info.get(key) != other.get(key):
+ raise ValueError("LeRobot source %d has incompatible info.%s."
% (ordinal, key))
+ expected_features = _feature_contract(info["features"])
+ actual_features = _feature_contract(other["features"])
+ for name in set(expected_features) | set(actual_features):
+ if expected_features.get(name) != actual_features.get(name):
+ raise ValueError("LeRobot source %d has incompatible
features.%s." % (ordinal, name))
+ if not _same_fields(plan["schema"], first["schema"]):
+ raise ValueError("LeRobot source %d has incompatible frame
schema." % ordinal)
+ episode_schema = plan["metadata"]["episodes_schema"]
+ if any(name not in episode_schema.names
+ or not episode_schema.field(name).equals(
+ metadata["episodes_schema"].field(name),
check_metadata=False)
+ for name in required_episode_fields):
+ raise ValueError("LeRobot source %d has incompatible Episode
schema." % ordinal)
+ # Validate every Episode before creating any target table.
+ plan["metadata"]["fps_mode"] = fps_mode
+ try:
+ for name in plan["videos"]:
+ _video_fps(other, other["features"][name], name)
+ for unused in _validated_episode_tables(plan["metadata"],
first["videos"]):
+ pass
+ except ValueError as error:
+ raise ValueError("LeRobot source %d: %s" % (ordinal, error)) from
error
+ plan["frame_offset"] = frame_offset
+ plan["episode_offset"] = episode_offset
+ plan["control_stats"] = {}
+ frame_offset += other["total_frames"]
+ episode_offset += other["total_episodes"]
+ for key in list(info):
+ if key not in _REBUILT_INFO and key not in ("codebase_version",
"robot_type", "fps") \
+ and any(plan["info"].get(key) != info[key] for plan in plans):
+ del info[key]
+ metadata["tasks_table"] = _vocabulary(plans, "tasks")
+ metadata["subtasks_table"] = _vocabulary(plans, "subtasks")
+ reserved_episode_fields = {
+ _DATASET_INDEX_COLUMN,
+ "source_frame_from_index", "source_frame_to_index",
+ "source_episode_ipc",
+ }
+ if reserved_episode_fields.intersection(metadata["episodes_schema"].names):
+ raise ValueError("Source Episode metadata uses reserved source index
columns.")
+ for field in (
+ pa.field(_DATASET_INDEX_COLUMN, pa.int64(), nullable=False),
+ pa.field("source_frame_from_index", pa.int64(), nullable=False),
+ pa.field("source_frame_to_index", pa.int64(), nullable=False),
+ pa.field("source_episode_ipc", pa.binary(), nullable=False)):
+ metadata["episodes_schema"] = metadata["episodes_schema"].append(field)
+ metadata["datasets_table"] = pa.Table.from_pylist([
+ {
+ _DATASET_INDEX_COLUMN: ordinal,
+ "dataset_name": plan["dataset_name"],
+ "fps": plan["metadata"]["fps"],
+ "episode_from_index": plan["episode_offset"],
+ "episode_to_index": (plan["episode_offset"]
+ + plan["info"]["total_episodes"]),
+ "frame_from_index": plan["frame_offset"],
+ "frame_to_index": plan["frame_offset"] +
plan["info"]["total_frames"],
+ "info_json": json.dumps(_json_value(plan["info"]),
+ ensure_ascii=False, separators=(",", ":")),
+ "tasks_ipc": _arrow_ipc(plan["metadata"]["source_tasks_table"]),
+ "subtasks_ipc":
_arrow_ipc(plan["metadata"]["source_subtasks_table"]),
+ "stats_ipc": _arrow_ipc(plan["metadata"]["stats_table"]),
+ "episodes_schema_ipc":
plan["metadata"]["episodes_schema"].serialize().to_pybytes(),
+ }
+ for ordinal, plan in enumerate(plans)
+ ], schema=_DATASETS_SCHEMA)
+ info.update(total_frames=frame_offset, total_episodes=episode_offset,
+ total_tasks=metadata["tasks_table"].num_rows,
+ splits={"train": "0:%d" % episode_offset})
+ mixed_fps = len({plan["metadata"]["fps"] for plan in plans}) > 1
+ info.pop("fps_mode", None)
+ if fps_mode == "source":
+ info["fps_mode"] = "source"
+ if mixed_fps:
+ info["fps"] = None
+ for feature in info["features"].values():
+ if feature.get("dtype") != "video":
+ continue
+ feature.pop("fps", None)
+ for key in ("info", "video_info"):
+ if isinstance(feature.get(key), dict):
+ feature[key].pop("video.fps", None)
+ if metadata["subtasks_table"] is not None:
+ info["total_subtasks"] = metadata["subtasks_table"].num_rows
+ for key in ("total_chunks", "total_videos", "data_path", "video_path",
+ "chunks_size", "data_files_size_in_mb",
"video_files_size_in_mb"):
+ info.pop(key, None)
+ # Encoder descriptions are not training features. Retain only shared
values.
+ for name in first["videos"]:
+ for key in ("info", "video_info"):
+ details = [p["info"]["features"][name].get(key) for p in plans]
+ details = [d if isinstance(d, dict) else {} for d in details]
+ info["features"][name][key] = {
+ k: v for k, v in details[0].items()
+ if all(d.get(k) == v for d in details[1:])}
+ stats = [p["metadata"]["stats_table"] for p in plans]
+ if any(s is None for s in stats) and not all(s is None for s in stats):
+ raise ValueError("LeRobot stats must be present in all sources or
absent in all.")
+ merged_stats = None
+ if stats[0] is not None:
+ decoded = [_json_table(s) for s in stats]
+ if any(set(s) != set(decoded[0]) for s in decoded[1:]):
+ raise ValueError("LeRobot statistics features must match.")
+ merged_stats = {name: _merge_stats([s[name] for s in decoded])
+ for name in decoded[0] if name not in _CONTROLS}
+ metadata["info_table"] = _metadata_table(info)
+ metadata["stats_table"] = (None if merged_stats is None
+ else _metadata_table(merged_stats))
+ return metadata, merged_stats
+
+
+def _transform_frames(plan, batch, episode):
+ batch = batch.append_column(
+ pa.field(_DATASET_INDEX_COLUMN, pa.int64(), nullable=False),
+ pa.array([plan[_DATASET_INDEX_COLUMN]] * batch.num_rows,
type=pa.int64()))
+ batch = batch.append_column(pa.field(_SOURCE_FRAME_INDEX_COLUMN,
pa.int64(),
+ nullable=False), batch["index"])
+ for name in _CONTROLS:
+ if name not in batch.column_names:
+ continue
+ column = batch[name]
+ if name == "index":
+ offset = plan["frame_offset"]
+ values = pc.add_checked(column, pa.scalar(offset,
type=column.type))
+ elif name == "episode_index":
+ values = column
+ else:
+ mapping = plan[name]
+ values = pa.array([
+ None if name == "subtask_index" and value is None
+ else mapping[value]
+ for value in column.to_pylist()
+ ], type=column.type)
+ batch = batch.set_column(batch.schema.get_field_index(name),
batch.schema.field(name), values)
+ stat_values = ([value for value in values.to_pylist()
+ if value is not None]
+ if values.null_count else values.to_numpy())
+ if len(stat_values) == 0:
+ continue
+ stats = _batch_stats(stat_values)
+ episode_stats = plan["control_stats"].setdefault(episode, {})
+ episode_stats[name] = (_merge_stats([episode_stats[name], stats])
+ if name in episode_stats else stats)
+ return batch
+
+
+def _stat_value(data_type, value):
+ if pa.types.is_list(data_type) or pa.types.is_large_list(data_type):
+ return [_stat_value(data_type.value_type, value)]
+ if pa.types.is_fixed_size_list(data_type):
+ return [_stat_value(data_type.value_type, value)] * data_type.list_size
+ return value
+
+
+def _merged_episodes(plans, schema):
+ for dataset_index, plan in enumerate(plans):
+ for table in _source_episode_tables(plan["metadata"]):
+ records = []
+ for offset, original in enumerate(table.to_pylist()):
+ row = {name: original[name] for name in schema.names
+ if name in original}
+ row[_DATASET_INDEX_COLUMN] = dataset_index
+ row["source_frame_from_index"] = original["dataset_from_index"]
+ row["source_frame_to_index"] = original["dataset_to_index"]
+ row["source_episode_ipc"] = _arrow_ipc(table.slice(offset, 1))
+ episode = row["episode_index"]
+ for key in ("dataset_from_index", "dataset_to_index"):
+ row[key] += plan["frame_offset"]
+ if "subtask_index" not in plan["control_stats"][episode]:
+ for key in row:
+ if key.startswith("stats/subtask_index/"):
+ row[key] = None
+ for name, stats in plan["control_stats"][episode].items():
+ for stat, value in stats.items():
+ key = "stats/%s/%s" % (name, stat)
+ if key in row:
+ row[key] = _stat_value(schema.field(key).type,
value[0])
+ records.append(row)
+ yield pa.Table.from_pylist(records, schema=schema)
+
+
+def _import_sources(connection, table_name, sources, batch_size, options,
+ source_options, tag_name, parallelism=1,
+ fps_mode="dataset", dataset_names=None):
+ from functools import partial
+ from pypaimon.multimodal.lerobot.api import _create_target_table,
_validated_counts
+
+ if parallelism > 1:
+ from pypaimon.multimodal.lerobot.ray_loader import _require_ray,
_ray_source_uri
+ _require_ray()
+ sources = [_ray_source_uri(source) for source in sources]
+ _validate_source_kerberos(sources, source_options, "LeRobot")
+ with ExitStack() as stack:
+ plans = []
+ for ordinal, source in enumerate(sources):
+ resolved, info = stack.enter_context(_resolved_source(source,
source_options))
+ if info is None:
+ info = _load_hub_info(resolved)
+ _require_v3(info, "source %d" % ordinal)
+ _validate_info_paths(info)
+ _validated_counts(info, "source %d" % ordinal)
+ _validate_v3_required_features(info)
+ schema = _schema_from_info(info)
+ videos = _video_feature_names(info)
+ dataset = _open_resolved_dataset(
+ None if resolved.file_io is not None else
_import_lerobot_dataset(),
+ resolved, info, download_videos=bool(videos))
+ dataset_resources = stack.enter_context(ExitStack())
+ if callable(getattr(dataset, "close", None)):
+ dataset_resources.callback(_close_quietly, dataset, "dataset")
+ plans.append({"dataset": dataset, "dataset_resources":
dataset_resources,
+ "source": resolved, "info": info,
+ _DATASET_INDEX_COLUMN: ordinal,
+ "dataset_name": (dataset_names[ordinal] if
dataset_names is not None
+ else None),
+ "schema": schema, "videos": videos,
+ "metadata": _load_dataset_metadata(dataset, info,
resolved)})
+ metadata, stats = _plan_merge(plans, fps_mode)
+ target_schema = plans[0]["schema"]
+ for field in (
+ pa.field(_DATASET_INDEX_COLUMN, pa.int64(), nullable=False),
+ pa.field(_SOURCE_FRAME_INDEX_COLUMN, pa.int64(),
nullable=False)):
+ target_schema = target_schema.append(field)
+ table = _create_target_table(connection, table_name, target_schema,
+ options, metadata, plans[0]["videos"])
+ tables = _prepare_metadata_tables(connection, table.raw_table,
metadata)
+ episode_schema = _target_schema(tables["episodes"])
+ commit = table.raw_table.new_batch_write_builder().new_commit()
+ stack.callback(commit.close)
+ episode_builder = tables["episodes"].new_batch_write_builder()
+ episode_commit = episode_builder.new_commit()
+ stack.callback(episode_commit.close)
+ episode_write = episode_builder.new_write()
+ stack.callback(episode_write.close)
+ episode_commit_started = False
+ episode_messages = None
+ try:
+ messages = []
+ try:
+ if parallelism > 1:
+ from pypaimon.multimodal.lerobot.ray_loader import
_prepare_sources_ray
+ messages = _prepare_sources_ray(
+ table.raw_table, plans, source_options, batch_size,
parallelism)
+ for plan in plans:
+ if parallelism == 1:
+ messages.extend(_prepare_dataset(
+ table.raw_table, plan["dataset"], plan["info"],
plan["source"],
+ plan["schema"], batch_size, plan["metadata"],
plan["videos"],
+ transform=partial(_transform_frames, plan)))
+ plan["dataset_resources"].close()
+ plan["dataset"] = None
+ for episodes in _merged_episodes(plans, episode_schema):
+ strict_arrow_table(episodes, episode_schema,
+ "merged Episodes", 0, "LeRobot")
+ episode_write.write_arrow(episodes)
+ episode_messages = episode_write.prepare_commit()
+ except BaseException:
+ commit.abort(messages)
+ raise
+ frames_snapshot = _commit_messages(commit, messages)
+ episode_commit_started = True
+ episodes_snapshot = _commit_messages(episode_commit,
episode_messages)
+ finally:
+ if not episode_commit_started:
+ if episode_messages is None:
+ episode_write.abort()
+ else:
+ episode_commit.abort(episode_messages)
+ if stats is not None:
+ for name in _CONTROLS:
+ parts = [s[name] for p in plans for s in
p["control_stats"].values() if name in s]
+ if parts:
+ stats[name] = _merge_stats(parts)
+ else:
+ stats.pop(name, None)
+ metadata["stats_table"] = _metadata_table(stats)
+ _commit_metadata(connection, tables, tag_name, metadata,
table.identifier,
+ frames_snapshot, episodes_snapshot)
diff --git a/paimon-python/pypaimon/multimodal/lerobot/api.py
b/paimon-python/pypaimon/multimodal/lerobot/api.py
index 2a819df369..16b0a897f7 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/api.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/api.py
@@ -71,15 +71,16 @@ def load_from_lerobot(
source_options: Optional[Mapping[str, object]] = None,
tag_name: Optional[str] = None,
parallelism: int = 1,
+ fps_mode: str = "dataset",
+ dataset_names=None,
) -> None:
- """Import LeRobot Dataset v3 into a new Paimon table group.
+ """Import one or more LeRobot v3 sources into a new Paimon table group.
- A new target table is created from LeRobot metadata. Episode, task, and
- info/stats metadata are stored in companion Paimon tables. If provided,
- ``tag_name`` pins all components to their imported snapshots.
- FileIO URI credentials come only from ``source_options`` and are not
- inherited from the target Catalog. ``parallelism > 1`` distributes Episode
- groups on an initialized Ray cluster. All workers need source and target
access.
+ Sources must share training features. ``fps_mode='source'`` allows mixed
+ FPS. ``__datasets`` retains source metadata; optional ``dataset_names``
+ are caller-provided labels, never inferred from paths. ``tag_name`` pins
+ component snapshots.
+ FileIO credentials come from ``source_options``; ``parallelism > 1`` uses
Ray.
"""
if sys.version_info < (3, 10):
raise RuntimeError(
@@ -92,6 +93,28 @@ def load_from_lerobot(
if isinstance(parallelism, bool) or not isinstance(parallelism, int) \
or parallelism <= 0:
raise ValueError("parallelism must be a positive integer.")
+ if fps_mode not in ("dataset", "source"):
+ raise ValueError("fps_mode must be 'dataset' or 'source'.")
+ if dataset_names is not None:
+ if not isinstance(dataset_names, (list, tuple)) or len(dataset_names)
!= (
+ len(source) if isinstance(source, (list, tuple)) else 1) \
+ or any(not isinstance(name, str) or not name.strip()
+ for name in dataset_names):
+ raise ValueError("dataset_names must contain one non-empty name
per source.")
+ dataset_names = [name.strip() for name in dataset_names]
+ if isinstance(source, (list, tuple)) or fps_mode == "source" \
+ or dataset_names is not None:
+ if not isinstance(source, (list, tuple)):
+ source = [source]
+ if not source:
+ raise ValueError("LeRobot sources must not be empty.")
+ if tag_name is not None:
+ _validate_tag_name(tag_name)
+ from pypaimon.multimodal.lerobot.aggregate import _import_sources
+ return _import_sources(
+ connection, table_name, source, batch_size, options,
+ _validated_source_options(source_options), tag_name, parallelism,
+ fps_mode, dataset_names)
if parallelism > 1:
from pypaimon.multimodal.lerobot.ray_loader import _require_ray,
_ray_source_uri
_require_ray()
@@ -115,7 +138,8 @@ def load_from_lerobot(
_validate_v3_required_features(local_info)
video_fields = _video_feature_names(local_info)
LeRobotDataset = (_import_lerobot_dataset()
- if parallelism == 1 else None)
+ if parallelism == 1 and resolved_source.file_io is
None
+ else None)
dataset = _open_resolved_dataset(
LeRobotDataset,
resolved_source,
diff --git a/paimon-python/pypaimon/multimodal/lerobot/dataset.py
b/paimon-python/pypaimon/multimodal/lerobot/dataset.py
index 393ce7f95a..4702c7fdbf 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/dataset.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/dataset.py
@@ -34,16 +34,19 @@ from functools import partial
from types import SimpleNamespace
import pyarrow as pa
+import pyarrow.compute as pc
from pypaimon.common.options.core_options import CoreOptions
from pypaimon.multimodal.lerobot.metadata import (
_PANDAS_METADATA_OPTION,
+ _dataset_fps,
+ _positive_integer,
_companion_table_identifiers,
_restore_pandas_metadata,
_tag_snapshot_id,
_validate_tag_name,
)
-from pypaimon.multimodal.lerobot.loader import _DECLARED_NUMERIC_RANGES
+from pypaimon.multimodal.lerobot.loader import _DECLARED_NUMERIC_RANGES,
_video_fps
from pypaimon.multimodal.lerobot.reader import _PaimonTableFrameReader
from pypaimon.multimodal.lerobot.schema import (
_feature_shape,
@@ -216,10 +219,8 @@ class PaimonDatasetReader(ABC):
if self._total_tasks < 0:
raise ValueError("LeRobot metadata must define total_tasks.")
- self._fps = int(
- _metadata_member(self.meta, "fps", info.get("fps", 0)))
- if self._fps <= 0:
- raise ValueError("LeRobot metadata fps must be positive.")
+ fps = _metadata_member(self.meta, "fps", info.get("fps"))
+ self._fps = None if fps is None else _dataset_fps(fps)
return info
def _init_episodes(self, episodes):
@@ -232,7 +233,18 @@ class PaimonDatasetReader(ABC):
"dataset.")
self._episode_ends = [end for _, end in self._episode_ranges] \
if self._episode_ranges is not None else None
+ self._episode_fps = _episode_fps(
+ self.meta, self._fps, self._total_episodes)
+ for name in self._video_keys:
+ for fps in set(self._episode_fps):
+ _video_fps({"fps": fps}, self._features[name], name)
self.episodes = _selected_episodes(episodes, self._total_episodes)
+ selected_rates = [self._episode_fps[index] for index in (
+ self.episodes if self.episodes is not None
+ else range(self._total_episodes))]
+ if self._fps is None and selected_rates \
+ and len(set(selected_rates)) == 1:
+ self._fps = selected_rates[0]
if self.episodes is not None and self._episode_ranges is None:
raise ValueError("Episode selection requires episode metadata.")
self._selected_ranges = None
@@ -249,12 +261,13 @@ class PaimonDatasetReader(ABC):
size += end - begin
self._selected_ends.append(size)
- self._delta_indices = _delta_indices(
- self.delta_timestamps,
- self._fps,
- self.tolerance_s,
- self._features,
- )
+ self._delta_indices = (
+ {fps: _delta_indices(self.delta_timestamps, fps,
+ self.tolerance_s, self._features)
+ for fps in sorted({self._episode_fps[episode] for episode in (
+ self.episodes if self.episodes is not None
+ else range(self._total_episodes))})}
+ if self.delta_timestamps else None)
if self._delta_indices and self._episode_ranges is None:
raise ValueError("delta_timestamps requires episode metadata.")
@@ -340,7 +353,7 @@ class PaimonDatasetReader(ABC):
validation_context = _build_frame_validation_context(
self.meta,
self._episode_ranges,
- self._fps,
+ self._episode_fps,
tasks,
subtasks,
source_schema.field("timestamp").type,
@@ -364,7 +377,7 @@ class PaimonDatasetReader(ABC):
"task_index",
]
+ (["subtask_index"] if subtasks is not None else [])
- + list(self._delta_indices)
+ + list(self.delta_timestamps)
))
@property
@@ -375,6 +388,10 @@ class PaimonDatasetReader(ABC):
def fps(self):
return self._fps
+ @property
+ def episode_fps(self):
+ return self._episode_fps
+
@property
def num_frames(self):
if self.episodes is None:
@@ -622,7 +639,7 @@ class PaimonDatasetReader(ABC):
episode = bisect.bisect_right(self._episode_ends, index)
begin, end = self._episode_ranges[episode]
import torch
- for key, deltas in self._delta_indices.items():
+ for key, deltas in
self._delta_indices[self._episode_fps[episode]].items():
windows[key] = [
min(max(index + delta, begin), end - 1)
for delta in deltas
@@ -647,6 +664,7 @@ class _PaimonTableDatasetReader(PaimonDatasetReader):
*,
tag_name=None,
episodes=None,
+ dataset_index=None,
image_transforms=None,
delta_timestamps=None,
tolerance_s=1e-4,
@@ -654,6 +672,21 @@ class _PaimonTableDatasetReader(PaimonDatasetReader):
video_backend=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)
+ source = sources[dataset_index]
+ if source["dataset_index"] != dataset_index:
+ raise ValueError("LeRobot source dataset indices are not
contiguous.")
+ episodes = list(range(source["episode_from_index"],
+ source["episode_to_index"]))
self.tag_name = tag_name
super().__init__(
meta,
@@ -681,9 +714,57 @@ class _PaimonTableDatasetReader(PaimonDatasetReader):
raise ValueError(
"Paimon table has %d rows but metadata declares %d frames."
% (rows.num_rows, self._total_frames))
+ if self.meta.datasets is not None:
+ rows = _SourceEpisodeFrameReader(rows, self.meta.datasets)
return rows
+class _SourceEpisodeFrameReader:
+ """Present source-local Episode IDs as ordinals to the training reader."""
+
+ def __init__(self, reader, datasets):
+ self._reader = reader
+ self._episode_offsets = pa.array(
+ [source["episode_from_index"] for source in datasets],
+ type=pa.int64())
+ self._episode_counts = pa.array(
+ [source["episode_to_index"] - source["episode_from_index"]
+ for source in datasets], type=pa.int64())
+ self.num_rows = reader.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):
+ if "episode_index" not in columns:
+ return self._reader.read_indices(indices, columns)
+ projection = list(columns)
+ if "dataset_index" not in projection:
+ projection.append("dataset_index")
+ data = self._reader.read_indices(indices, projection)
+ try:
+ source_ids = data["dataset_index"]
+ local_ids = data["episode_index"]
+ offsets = pc.take(self._episode_offsets, source_ids)
+ counts = pc.take(self._episode_counts, source_ids)
+ valid = pc.and_(pc.greater_equal(local_ids, 0),
+ pc.less(local_ids, counts))
+ if valid.null_count or not pc.all(valid).as_py():
+ raise ValueError("LeRobot frame has an invalid source Episode
key.")
+ ordinals = pc.add_checked(offsets, local_ids)
+ except (pa.ArrowInvalid, pa.ArrowIndexError, TypeError) as error:
+ raise ValueError("LeRobot frame has an invalid source Episode
key.") from error
+ data = data.set_column(
+ data.schema.get_field_index("episode_index"),
+ data.schema.field("episode_index"),
+ ordinals)
+ return data.select(columns)
+
+ def close(self):
+ self._reader.close()
+
+
class PaimonLeRobotDataset:
"""Map-style Dataset facade backed by :class:`PaimonDatasetReader`."""
@@ -693,6 +774,7 @@ class PaimonLeRobotDataset:
*,
tag_name=None,
episodes=None,
+ dataset_index=None,
image_transforms=None,
delta_timestamps=None,
tolerance_s=1e-4,
@@ -704,6 +786,7 @@ class PaimonLeRobotDataset:
if (
tag_name is not None
or episodes is not None
+ or dataset_index is not None
or image_transforms is not None
or delta_timestamps is not None
or tolerance_s != 1e-4
@@ -719,6 +802,7 @@ class PaimonLeRobotDataset:
table,
tag_name=tag_name,
episodes=episodes,
+ dataset_index=dataset_index,
image_transforms=image_transforms,
delta_timestamps=delta_timestamps,
tolerance_s=tolerance_s,
@@ -832,7 +916,7 @@ class _PaimonLeRobotMetadata:
def __init__(
self, repo_id, tag_name, info, stats, episodes, tasks,
- subtasks):
+ subtasks, datasets=None):
self.repo_id = repo_id
self.revision = tag_name
self.info = info
@@ -840,6 +924,7 @@ class _PaimonLeRobotMetadata:
self.episodes = episodes
self.tasks = tasks
self.subtasks = subtasks
+ self.datasets = datasets
self._compress_episodes = False
def __getstate__(self):
@@ -933,6 +1018,7 @@ def _reader_metadata(metadata):
_metadata_member(metadata, "episodes"),
_metadata_member(metadata, "tasks"),
_metadata_member(metadata, "subtasks"),
+ _metadata_member(metadata, "datasets"),
)
@@ -945,9 +1031,16 @@ def _load_dataset(table, tag_name):
identifiers = _companion_table_identifiers(raw_table)
catalog = table.catalog
frames = _component_table(catalog, raw_table, tag_name)
+ datasets = None
+ if "datasets" in identifiers:
+ datasets_table = _component_table(
+ catalog, catalog.get_table(identifiers["datasets"]), tag_name)
+ projection = [name for name in _target_schema(datasets_table).names
+ if not name.endswith("_ipc")]
+ datasets = _read_arrow(datasets_table,
projection).sort_by("dataset_index").to_pylist()
episodes_table = _component_table(
catalog, catalog.get_table(identifiers["episodes"]), tag_name)
- episodes = _episode_dataset(episodes_table)
+ episodes = _episode_dataset(episodes_table, datasets)
tasks_table = _component_table(
catalog, catalog.get_table(identifiers["tasks"]), tag_name)
tasks = _component_dataframe(tasks_table, "task_index")
@@ -968,7 +1061,7 @@ def _load_dataset(table, tag_name):
"stats"))
metadata = _PaimonLeRobotMetadata(
str(table.identifier), tag_name, info, stats, episodes, tasks,
- subtasks)
+ subtasks, datasets)
metadata._compress_episodes = True
return frames, metadata
@@ -992,7 +1085,7 @@ def _read_arrow(table, projection=None):
return builder.new_read().to_arrow(plan.splits())
-def _episode_dataset(table):
+def _episode_dataset(table, datasets=None):
try:
from datasets import Dataset
except ImportError as error:
@@ -1003,8 +1096,30 @@ def _episode_dataset(table):
projection = [
name for name in _target_schema(table).names
if not name.startswith("stats/")
+ and (datasets is None or name != "source_episode_ipc")
]
- data = _read_arrow(table, projection).sort_by("episode_index")
+ data = _read_arrow(table, projection)
+ if datasets is not None:
+ data = data.sort_by([
+ ("dataset_index", "ascending"),
+ ("episode_index", "ascending"),
+ ])
+ expected = [
+ (dataset["dataset_index"], local)
+ for dataset in datasets
+ for local in range(dataset["episode_to_index"]
+ - dataset["episode_from_index"])
+ ]
+ actual = list(zip(data["dataset_index"].to_pylist(),
+ data["episode_index"].to_pylist()))
+ if actual != expected:
+ raise ValueError("LeRobot source Episode keys are not contiguous.")
+ data = data.set_column(
+ data.schema.get_field_index("episode_index"),
+ pa.field("episode_index", pa.int64()),
+ pa.array(range(data.num_rows), type=pa.int64()))
+ else:
+ data = data.sort_by("episode_index")
return Dataset(data)
@@ -1116,6 +1231,60 @@ def _episode_ranges(metadata, total_frames,
total_episodes):
return ranges
+def _episode_fps(metadata, fps, total_episodes):
+ mode = _info_dict(_metadata_member(metadata, "info")).get("fps_mode")
+ if _metadata_member(metadata, "datasets") is not None and mode == "source":
+ return _source_dataset_fps(metadata, fps, total_episodes)
+ if fps is None:
+ raise ValueError("LeRobot metadata is missing fps; enable source FPS
explicitly.")
+ return (fps,) * total_episodes
+
+
+def _source_dataset_fps(metadata, fps, total_episodes):
+ datasets = _metadata_member(metadata, "datasets")
+ episodes = _metadata_member(metadata, "episodes")
+ if not datasets or episodes is None:
+ raise ValueError("LeRobot source FPS requires datasets and episodes
metadata.")
+ rates = []
+ expected_episode = expected_frame = 0
+ for ordinal, dataset in enumerate(datasets):
+ try:
+ index = operator.index(dataset["dataset_index"])
+ begin = operator.index(dataset["episode_from_index"])
+ end = operator.index(dataset["episode_to_index"])
+ frame_begin = operator.index(dataset["frame_from_index"])
+ frame_end = operator.index(dataset["frame_to_index"])
+ source_info = json.loads(dataset["info_json"])
+ except (KeyError, TypeError, ValueError) as error:
+ raise ValueError("LeRobot source dataset %d metadata is invalid."
% ordinal) from error
+ rate = _positive_integer(dataset["fps"], "source dataset %d fps" %
ordinal)
+ if index != ordinal or begin != expected_episode or end <= begin \
+ or end > total_episodes or frame_begin != expected_frame \
+ or frame_end <= frame_begin or not isinstance(source_info,
dict) \
+ or _dataset_fps(source_info.get("fps")) != rate \
+ or source_info.get("total_episodes") != end - begin \
+ or source_info.get("total_frames") != frame_end - frame_begin:
+ raise ValueError(
+ "LeRobot source dataset %d has inconsistent fps or ranges."
+ % ordinal)
+ if fps is not None and rate != fps:
+ raise ValueError("LeRobot source dataset %d fps does not match
info.fps." % ordinal)
+ rates.extend([rate] * (end - begin))
+ expected_episode, expected_frame = end, frame_end
+ if expected_episode != total_episodes:
+ raise ValueError("LeRobot source datasets do not cover all episodes.")
+ for ordinal, row in enumerate(_episode_rows(episodes, ("dataset_index",))):
+ try:
+ index = operator.index(row["dataset_index"])
+ except (KeyError, TypeError) as error:
+ raise ValueError("LeRobot episode %d is missing dataset_index." %
ordinal) from error
+ if index < 0 or index >= len(datasets) \
+ or not (datasets[index]["episode_from_index"] <= ordinal
+ < datasets[index]["episode_to_index"]):
+ raise ValueError("LeRobot episode %d has invalid dataset_index." %
ordinal)
+ return tuple(rates)
+
+
def _validate_component_metadata(features, total_tasks, tasks, subtasks):
task_count = 0 if tasks is None else len(tasks)
if task_count != total_tasks:
@@ -1131,7 +1300,7 @@ def _validate_component_metadata(features, total_tasks,
tasks, subtasks):
def _build_frame_validation_context(
- metadata, episode_ranges, fps, tasks, subtasks, timestamp_type):
+ metadata, episode_ranges, episode_fps, tasks, subtasks,
timestamp_type):
task_names = _index_names(tasks, "task_index")
subtask_names = _index_names(subtasks, "subtask_index")
episode_tasks = _episode_tasks(metadata) \
@@ -1141,7 +1310,7 @@ def _build_frame_validation_context(
"episode_ends": (
[end for _, end in episode_ranges]
if episode_ranges is not None else None),
- "fps": fps,
+ "episode_fps": episode_fps,
"task_names": task_names,
"subtask_names": subtask_names,
"episode_tasks": episode_tasks,
@@ -1391,7 +1560,7 @@ def _validate_control_row(index, row, validation_context,
tolerance_s):
timestamp = row.get("timestamp")
expected_timestamp = pa.scalar(
- frame / validation_context["fps"],
+ frame / validation_context["episode_fps"][episode],
type=validation_context["timestamp_type"],
).as_py()
if isinstance(timestamp, bool) or not isinstance(timestamp, (int, float)) \
@@ -1716,6 +1885,9 @@ def _collate_lerobot_batch(rows, video_windows):
nullable = {}
if "subtask_index" in rows[0]:
labels = [row["subtask_index"] for row in rows]
+ mask_name = "subtask_index_is_valid"
+ while any(mask_name in row for row in rows):
+ mask_name = "_" + mask_name
if any(_contains_none(value) for value in labels):
def values(label):
if isinstance(label, list):
@@ -1724,10 +1896,10 @@ def _collate_lerobot_batch(rows, video_windows):
nullable["subtask_index"] = torch.tensor(
[values(label) for label in labels], dtype=torch.int64,
device="cpu")
- nullable["subtask_index_is_valid"] = nullable["subtask_index"] >= 0
+ nullable[mask_name] = nullable["subtask_index"] >= 0
else:
nullable["subtask_index"] = default_collate(labels)
- nullable["subtask_index_is_valid"] = torch.ones_like(
+ nullable[mask_name] = torch.ones_like(
nullable["subtask_index"], dtype=torch.bool)
if "subtask" in rows[0] and any(_contains_none(row["subtask"]) for row in
rows):
nullable["subtask"] = [row["subtask"] for row in rows]
diff --git a/paimon-python/pypaimon/multimodal/lerobot/loader.py
b/paimon-python/pypaimon/multimodal/lerobot/loader.py
index 5060456d99..4576ef2209 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/loader.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/loader.py
@@ -109,7 +109,7 @@ def _abort_messages(table, messages):
def _prepare_dataset(
table, dataset, info, source, source_schema, batch_size, metadata,
- video_fields=(), episode_indices=None):
+ video_fields=(), episode_indices=None, transform=None):
from pypaimon.common.options import CoreOptions
remux_videos =
table.options.options.get(CoreOptions.WRITE_LEROBOT_REMUX_EPISODES)
if video_fields and remux_videos:
@@ -182,6 +182,8 @@ def _prepare_dataset(
metadata["subtask_indices"],
)
observed_tasks.update(seen_tasks)
+ if transform is not None:
+ batch = transform(batch,
episode_index).select(target_schema.names)
batch = _strict_lerobot_table(
batch,
target_schema,
diff --git a/paimon-python/pypaimon/multimodal/lerobot/metadata.py
b/paimon-python/pypaimon/multimodal/lerobot/metadata.py
index e2d57dfa7f..d56530f257 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/metadata.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/metadata.py
@@ -36,8 +36,10 @@ from pypaimon.multimodal.table import _target_schema
_PANDAS_METADATA_OPTION = "pypaimon.lerobot.pandas-metadata"
+_EPISODE_FPS_COLUMN = "fps"
_TABLE_SUFFIXES = {
"info": "__info",
+ "datasets": "__datasets",
"stats": "__stats",
"episodes": "__episodes",
"tasks": "__tasks",
@@ -136,11 +138,15 @@ def _load_dataset_metadata(dataset, info, source):
fps = _dataset_fps(info.get("fps"))
stats = _source_stats(dataset, source)
stats_table = None if stats is None else _metadata_table(stats)
- tasks_table = _source_tasks(
- dataset, source, int(info["total_tasks"]))
+ source_tasks = _source_tasks(
+ dataset, source, int(info["total_tasks"]), normalize=False)
+ tasks_table = (source_tasks if int(info["total_tasks"]) == 0 else
+ _source_vocabulary_index(source_tasks, "task"))
task_indices = _task_indices(
tasks_table, int(info["total_tasks"]))
- subtasks_table = _source_subtasks(dataset, source)
+ source_subtasks = _source_subtasks(dataset, source, normalize=False)
+ subtasks_table = (None if source_subtasks is None else
+ _source_vocabulary_index(source_subtasks, "subtask"))
subtask_indices = _subtask_indices(subtasks_table, info)
total_episodes = int(info["total_episodes"])
episode_source = (
@@ -156,6 +162,8 @@ def _load_dataset_metadata(dataset, info, source):
"episodes": None,
"episodes_schema": episode_source["schema"],
"episode_paths": episode_source["paths"],
+ "source_tasks_table": source_tasks,
+ "source_subtasks_table": source_subtasks,
"tasks_table": tasks_table,
"subtasks_table": subtasks_table,
"source": source,
@@ -198,6 +206,9 @@ def _managed_table_options(frames_identifier,
metadata=None):
"LeRobot import does not support table branches.")
result = {}
for name, suffix in _TABLE_SUFFIXES.items():
+ if name == "datasets" and (metadata is None or
+ metadata.get("datasets_table") is None):
+ continue
if metadata is not None and name in ("stats", "subtasks") \
and metadata[name + "_table"] is None:
continue
@@ -212,7 +223,7 @@ def _companion_table_identifiers(frames_table):
for name, key in _COMPANION_OPTION_KEYS.items():
value = options.get(key)
if not value:
- if name in ("stats", "subtasks"):
+ if name in ("datasets", "stats", "subtasks"):
continue
raise ValueError(
"LeRobot table %s is missing managed option %s."
@@ -230,6 +241,8 @@ def _prepare_metadata_tables(connection, frames_table,
metadata):
for name in ("stats", "subtasks"):
if metadata[name + "_table"] is not None:
schemas[name] = metadata[name + "_table"].schema
+ if metadata.get("datasets_table") is not None:
+ schemas["datasets"] = metadata["datasets_table"].schema
identifiers = _companion_table_identifiers(frames_table)
tables = {}
for name, schema in schemas.items():
@@ -282,7 +295,7 @@ def _commit_metadata(
component_snapshots = [
(tables["episodes"].identifier, episodes_snapshot_id),
]
- for name in ("tasks", "subtasks", "stats", "info"):
+ for name in ("tasks", "subtasks", "stats", "info", "datasets"):
if name not in tables:
continue
snapshot_id = _append_arrow(tables[name], metadata[name + "_table"],
@@ -492,7 +505,7 @@ def _source_stats(dataset, source):
return json.load(file)
-def _source_tasks(dataset, source, total_tasks):
+def _source_tasks(dataset, source, total_tasks, normalize=True):
if total_tasks == 0:
return pa.Table.from_pylist([], schema=_EMPTY_TASKS_SCHEMA)
if source.file_io is not None:
@@ -501,17 +514,19 @@ def _source_tasks(dataset, source, total_tasks):
_remote_path,
)
path = _remote_path(source.path, "meta/tasks.parquet")
- return _read_remote_parquet(source.file_io, path)
+ table = _read_remote_parquet(source.file_io, path)
+ return _source_vocabulary_index(table, "task") if normalize else table
path = _metadata_root(dataset, source) / "meta" / "tasks.parquet"
try:
- return pq.read_table(path)
+ table = pq.read_table(path)
+ return _source_vocabulary_index(table, "task") if normalize else table
except (OSError, ValueError, pa.ArrowException) as error:
raise ValueError(
"Cannot read LeRobot task metadata %s: %s" % (path, error)
) from error
-def _source_subtasks(dataset, source):
+def _source_subtasks(dataset, source, normalize=True):
if source.file_io is not None:
from pypaimon.multimodal.lerobot.source import (
_read_remote_parquet,
@@ -522,18 +537,35 @@ def _source_subtasks(dataset, source):
source.file_io.get_file_status(path)
except FileNotFoundError:
return None
- return _read_remote_parquet(source.file_io, path)
+ table = _read_remote_parquet(source.file_io, path)
+ return _source_vocabulary_index(table, "subtask") if normalize else
table
path = _metadata_root(dataset, source) / "meta" / "subtasks.parquet"
if not path.is_file():
return None
try:
- return pq.read_table(path)
+ table = pq.read_table(path)
+ return _source_vocabulary_index(table, "subtask") if normalize else
table
except (OSError, ValueError, pa.ArrowException) as error:
raise ValueError(
"Cannot read LeRobot subtask metadata %s: %s" % (path, error)
) from error
+def _source_vocabulary_index(table, component):
+ """Accept a named text column when source Parquet omits Pandas metadata."""
+ if b"pandas" in (table.schema.metadata or {}):
+ return table
+ index_column = component + "_index"
+ if set(table.column_names) != {index_column, component} \
+ or not (pa.types.is_string(table.schema.field(component).type)
+ or
pa.types.is_large_string(table.schema.field(component).type)):
+ return table
+ import pandas as pd
+ frame = table.to_pandas().set_index(component)
+ frame.index = pd.Index(frame.index, name=component)
+ return pa.Table.from_pandas(frame, preserve_index=True)
+
+
def _source_episodes(dataset, source):
if source.file_io is not None:
from pypaimon.multimodal.lerobot.source import (
@@ -589,6 +621,14 @@ def _validated_episode_tables(metadata, video_fields=()):
raise ValueError(
"LeRobot Episode metadata is missing columns: %s."
% ", ".join(missing))
+ if metadata.get("fps_mode") in ("episode", "source") \
+ and _EPISODE_FPS_COLUMN in table.column_names:
+ for ordinal, value in
enumerate(table[_EPISODE_FPS_COLUMN].to_pylist()):
+ rate = _positive_integer(value, "episode fps")
+ if rate != metadata["fps"]:
+ raise ValueError(
+ "LeRobot episode %d fps does not match info.fps."
+ % (len(episodes) + ordinal))
controls = table.select(required_columns)
columns = {
name: controls.column(name)
diff --git a/paimon-python/pypaimon/multimodal/lerobot/ray_loader.py
b/paimon-python/pypaimon/multimodal/lerobot/ray_loader.py
index 22063bc396..a67620aa9c 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/ray_loader.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/ray_loader.py
@@ -91,7 +91,7 @@ def _task_groups(info, episodes, video_fields, parallelism):
def _prepare_group(table, source_path, source_options, info, schema,
- batch_size, metadata, video_fields, episode_indices):
+ batch_size, metadata, video_fields, episode_indices,
transform=None):
messages = None
try:
with _resolved_source(source_path, source_options) as (source,
current_info):
@@ -101,7 +101,7 @@ def _prepare_group(table, source_path, source_options,
info, schema,
try:
messages = _prepare_dataset(
table, dataset, info, source, schema, batch_size,
- metadata, video_fields, episode_indices)
+ metadata, video_fields, episode_indices,
transform=transform)
finally:
dataset.close()
return messages
@@ -170,3 +170,82 @@ def _write_dataset_ray(table, dataset, info, source,
source_schema, batch_size,
return _commit_messages(table_commit, messages)
finally:
table_commit.close()
+
+
+def _prepare_merged_source(table, source_path, source_options, info, schema,
+ batch_size, metadata, video_fields, mapping,
episode_indices):
+ from functools import partial
+ from pypaimon.multimodal.lerobot.aggregate import _transform_frames
+
+ mapping = dict(mapping, control_stats={})
+ messages = _prepare_group(
+ table, source_path, source_options, info, schema, batch_size,
+ metadata, video_fields, episode_indices, partial(_transform_frames,
mapping))
+ return messages, mapping["control_stats"]
+
+
+def _prepare_sources_ray(table, plans, source_options, batch_size,
parallelism):
+ ray = _require_ray()
+ table_ref = ray.put(table)
+ prepare = ray.remote(num_cpus=1, max_retries=0)(_prepare_merged_source)
+
+ def arguments():
+ for ordinal, plan in enumerate(plans):
+ info_ref = ray.put(plan["info"])
+ metadata_ref = ray.put({
+ "episodes": plan["metadata"]["episodes"],
+ "subtask_indices": plan["metadata"]["subtask_indices"],
+ })
+ mapping_ref = ray.put({key: plan[key] for key in (
+ "dataset_index", "frame_offset", "episode_offset",
+ "task_index", "subtask_index") if key in plan})
+ for group in _task_groups(plan["info"], plan["dataset"]._episodes,
+ plan["videos"], parallelism):
+ yield ordinal, (table_ref, plan["source"].path, source_options,
+ info_ref, plan["schema"], batch_size,
metadata_ref,
+ plan["videos"], mapping_ref, group)
+
+ tasks = iter(arguments())
+ pending, messages = {}, []
+ try:
+ exhausted = False
+ while pending or not exhausted:
+ # Limit concurrency across all sources, not separately per dataset.
+ while len(pending) < parallelism and not exhausted:
+ item = next(tasks, None)
+ if item is None:
+ exhausted = True
+ else:
+ ordinal, args = item
+ pending[prepare.remote(*args)] = ordinal
+ if not pending:
+ break
+ ready, _ = ray.wait(list(pending), num_returns=1)
+ task = ready[0]
+ prepared, stats = ray.get(task)
+ messages.extend(prepared)
+ ordinal = pending.pop(task)
+ plans[ordinal]["control_stats"].update(stats)
+ return messages
+ except BaseException:
+ for task in pending:
+ try:
+ ray.cancel(task)
+ except Exception:
+ logging.exception("Failed to cancel LeRobot import task.")
+ if pending:
+ try:
+ ready, _ = ray.wait(list(pending), num_returns=len(pending),
timeout=_CANCEL_DRAIN_SECONDS)
+ for task in ready:
+ try:
+ prepared, _ = ray.get(task, timeout=0)
+ messages.extend(prepared)
+ except Exception:
+ pass
+ except Exception:
+ logging.exception("Failed to drain cancelled LeRobot tasks.")
+ try:
+ _abort_messages(table, messages)
+ except Exception:
+ logging.exception("Failed to abort prepared LeRobot files.")
+ raise
diff --git a/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
b/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
new file mode 100644
index 0000000000..2d55c91cb7
--- /dev/null
+++ b/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
@@ -0,0 +1,1491 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import sys
+from pathlib import Path
+from unittest.mock import patch
+
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+import pyarrow.parquet as pq
+import pytest
+
+from pypaimon.catalog.catalog_exception import TableNotExistException
+import pypaimon.multimodal as pm
+from pypaimon.multimodal.lerobot.aggregate import _batch_stats,
_transform_frames
+from pypaimon.multimodal.lerobot.metadata import _restore_pandas_metadata
+from pypaimon.table.row.blob import Blob, VideoFrameDescriptor
+
+
+pytestmark = pytest.mark.skipif(sys.version_info < (3, 10), reason="LeRobot
import requires Python 3.10+")
+
+
+def source(root, tasks=("pick", "place"), subtasks=("reach", "grasp"),
video=False, value=0, fps=10, frames=5):
+ root.mkdir(parents=True)
+ meta = root / "meta"
+ (meta / "episodes/chunk-000").mkdir(parents=True)
+ (root / "data/chunk-000").mkdir(parents=True)
+ features = {key: {"dtype": "int64", "shape": [1], "names": None}
+ for key in ("index", "episode_index", "frame_index",
"task_index", "subtask_index")}
+ features["timestamp"] = {"dtype": "float32", "shape": [1], "names": None}
+ features["observation.state"] = {"dtype": "float32", "shape": [2],
"names": ["x", "y"]}
+ features["action"] = {"dtype": "float32", "shape": [2], "names": ["x",
"y"]}
+ if video:
+ features["camera"] = {"dtype": "video", "shape": [16, 16, 3],
+ "names": ["height", "width", "channels"],
+ "info": {"video.fps": fps}}
+ av = pytest.importorskip("av")
+ path = root / "videos/camera/chunk-000/file-000.mp4"
+ path.parent.mkdir(parents=True)
+ with av.open(str(path), "w") as container:
+ stream = container.add_stream("mpeg4", rate=fps)
+ stream.width = stream.height = 16
+ stream.pix_fmt = "yuv420p"
+ for i in range(frames):
+ frame = av.VideoFrame.from_ndarray(np.full((16, 16, 3), value
+ i * 3, np.uint8), format="rgb24")
+ for packet in stream.encode(frame):
+ container.mux(packet)
+ for packet in stream.encode():
+ container.mux(packet)
+ info = dict(codebase_version="v3.0", fps=fps, robot_type="test",
total_frames=frames,
+ total_episodes=2, total_tasks=2, features=features,
splits={"train": "0:2"},
+
data_path="data/chunk-{chunk_index:03d}/file-{file_index:03d}.parquet",
+
video_path="videos/{video_key}/chunk-{chunk_index:03d}/file-{file_index:03d}.mp4")
+ (meta / "info.json").write_text(json.dumps(info))
+ rows = []
+ episodes = []
+ for ep, (start, end) in enumerate(((0, frames // 2), (frames // 2,
frames))):
+ ep_rows = []
+ for index in range(start, end):
+ row = dict(index=index, episode_index=ep, frame_index=index-start,
+ timestamp=(index-start)/fps, task_index=ep,
subtask_index=index % 2)
+ row["observation.state"] = [float(value + index), float(index)]
+ row["action"] = [float(index), -float(index)]
+ ep_rows.append(row)
+ rows.extend(ep_rows)
+ episode = dict(episode_index=ep, dataset_from_index=start,
dataset_to_index=end,
+ length=end-start, tasks=[tasks[ep]])
+ episode.update({"data/chunk_index": 0, "data/file_index": 0})
+ if video:
+ episode.update({"videos/camera/chunk_index": 0,
"videos/camera/file_index": 0,
+ "videos/camera/from_timestamp": start/fps,
+ "videos/camera/to_timestamp": end/fps})
+ for name in ("index", "episode_index", "task_index", "subtask_index"):
+ stats = _batch_stats([r[name] for r in ep_rows])
+ for stat, v in stats.items():
+ episode["stats/%s/%s" % (name, stat)] = v
+ episode["stats/%s/q50" % name] = [0.0]
+ episodes.append(episode)
+ data = pa.Table.from_pylist(rows)
+ # Source float32 timestamps must match the training feature contract.
+ data = data.set_column(data.schema.get_field_index("timestamp"),
"timestamp",
+ data["timestamp"].cast(pa.float32()))
+ pq.write_table(data, root / "data/chunk-000/file-000.parquet")
+ pq.write_table(pa.Table.from_pylist(episodes), meta /
"episodes/chunk-000/file-000.parquet")
+ for kind, texts in (("task", tasks), ("subtask", subtasks)):
+ pq.write_table(pa.Table.from_pandas(pd.DataFrame(
+ {kind + "_index": [0, 1]}, index=pd.Index(texts, name=kind))),
meta / (kind + "s.parquet"))
+ stats = {name: _batch_stats([r[name] for r in rows])
+ for name in ("index", "episode_index", "task_index",
"subtask_index")}
+ for name in ("observation.state", "action"):
+ values = np.array([r[name] for r in rows])
+ stats[name] = {"min": values.min(0).tolist(), "max":
values.max(0).tolist(),
+ "mean": values.mean(0).tolist(), "std":
values.std(0).tolist(), "count": [frames],
+ "q50": np.median(values, axis=0).tolist()}
+ (meta / "stats.json").write_text(json.dumps(stats))
+ return root.as_uri()
+
+
[email protected]
+def setup(tmp_path):
+ a = source(tmp_path / "a")
+ b = source(tmp_path / "b", tasks=("place", "stack"), subtasks=("grasp",
"release"), value=20)
+ conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
+ return conn, [a, b]
+
+
+def rows(conn, name):
+ return conn.get_table(name).scan().to_arrow()
+
+
+def episode_rows(conn, name):
+ return rows(conn, name).sort_by([
+ ("dataset_index", "ascending"), ("episode_index", "ascending")])
+
+
+def metadata(conn, suffix):
+ return {r["key"]: json.loads(r["value"]) for r in rows(conn, "merged__" +
suffix).to_pylist()}
+
+
+def test_transform_frames_preserves_unlabelled_subtasks():
+ plan = {
+ "dataset_index": 1,
+ "frame_offset": 5,
+ "episode_offset": 2,
+ "task_index": {0: 1},
+ "subtask_index": {0: 3},
+ "control_stats": {},
+ }
+ batch = pa.table({
+ "index": pa.array([0, 1], type=pa.int64()),
+ "episode_index": pa.array([0, 0], type=pa.int64()),
+ "task_index": pa.array([0, 0], type=pa.int64()),
+ "subtask_index": pa.array([0, None], type=pa.int64()),
+ })
+
+ converted = _transform_frames(plan, batch, 0)
+
+ assert converted["index"].to_pylist() == [5, 6]
+ assert converted["episode_index"].to_pylist() == [0, 0]
+ assert converted["dataset_index"].to_pylist() == [1, 1]
+ assert converted["source_index"].to_pylist() == [0, 1]
+ assert converted["task_index"].to_pylist() == [1, 1]
+ assert converted["subtask_index"].to_pylist() == [3, None]
+ assert plan["control_stats"][0]["subtask_index"]["count"] == [1]
+
+
[email protected](scope="module")
+def ray_cluster():
+ ray = pytest.importorskip("ray")
+ started = not ray.is_initialized()
+ if started:
+ ray.init(address="local", num_cpus=2, include_dashboard=False,
+ object_store_memory=100 * 1024 * 1024)
+ try:
+ yield ray
+ finally:
+ if started:
+ ray.shutdown()
+
+
[email protected]
+def import_parallelism(request):
+ if request.param > 1:
+ request.getfixturevalue("ray_cluster")
+ return request.param
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_merge_numbering_stats_and_training(setup, import_parallelism):
+ conn, sources = setup
+ conn.load_from_lerobot("merged", sources, batch_size=2, tag_name="train",
+ parallelism=import_parallelism)
+ data = rows(conn, "merged").sort_by("index")
+ assert data["index"].to_pylist() == list(range(10))
+ assert data["episode_index"].to_pylist() == [0, 0, 1, 1, 1] * 2
+ assert data["dataset_index"].to_pylist() == [0] * 5 + [1] * 5
+ assert data["source_index"].to_pylist() == list(range(5)) * 2
+ assert data["frame_index"].to_pylist() == [0, 1, 0, 1, 2] * 2
+ assert data["task_index"].to_pylist() == [0, 0, 1, 1, 1, 1, 1, 2, 2, 2]
+ assert data["subtask_index"].to_pylist() == [0, 1, 0, 1, 0, 1, 2, 1, 2, 1]
+ episodes = episode_rows(conn, "merged__episodes")
+ assert "fps" not in episodes.column_names
+ assert episodes["dataset_index"].to_pylist() == [0, 0, 1, 1]
+ assert episodes["episode_index"].to_pylist() == [0, 1, 0, 1]
+ assert episodes["source_frame_from_index"].to_pylist() == [0, 2, 0, 2]
+ assert episodes["source_frame_to_index"].to_pylist() == [2, 5, 2, 5]
+ datasets = rows(conn, "merged__datasets").sort_by("dataset_index")
+ assert datasets["dataset_name"].to_pylist() == [None, None]
+ assert datasets["fps"].to_pylist() == [10, 10]
+ assert datasets["episode_from_index"].to_pylist() == [0, 2]
+ assert datasets["episode_to_index"].to_pylist() == [2, 4]
+ assert datasets["frame_from_index"].to_pylist() == [0, 5]
+ assert datasets["frame_to_index"].to_pylist() == [5, 10]
+ assert [json.loads(value)["total_frames"] for value in
+ datasets["info_json"].to_pylist()] == [5, 5]
+ assert [pa.ipc.open_stream(value).read_all().num_rows for value in
+ datasets["tasks_ipc"].to_pylist()] == [2, 2]
+ assert [pa.ipc.open_stream(value).read_all().num_rows for value in
+ datasets["subtasks_ipc"].to_pylist()] == [2, 2]
+ assert [pa.ipc.open_stream(value).read_all().num_rows for value in
+ datasets["stats_ipc"].to_pylist()] == [6, 6]
+ for value in datasets["episodes_schema_ipc"].to_pylist():
+ names = pa.ipc.read_schema(pa.BufferReader(value)).names
+ assert "episode_index" in names
+ assert "source_episode_ipc" not in names
+ assert [pa.ipc.open_stream(value).read_all()["episode_index"][0].as_py()
for value in
+ episodes["source_episode_ipc"].to_pylist()] == [0, 1, 0, 1]
+ assert
[pa.ipc.open_stream(value).read_all()["dataset_from_index"][0].as_py() for
value in
+ episodes["source_episode_ipc"].to_pylist()] == [0, 2, 0, 2]
+ assert
[pa.ipc.open_stream(value).read_all()["dataset_to_index"][0].as_py() for value
in
+ episodes["source_episode_ipc"].to_pylist()] == [2, 5, 2, 5]
+ assert conn.catalog.get_tag(
+ conn._identifier("merged__datasets"), "train").snapshot.id == 1
+ assert episodes["dataset_from_index"].to_pylist() == [0, 2, 5, 7]
+ assert episodes["dataset_to_index"].to_pylist() == [2, 5, 7, 10]
+ assert episodes["stats/index/mean"].to_pylist() == [[0.5], [3.0], [5.5],
[8.0]]
+ assert not any(c.endswith("/q50") for c in episodes.column_names)
+ info = metadata(conn, "info")
+ assert info["fps"] == 10
+ assert (info["total_frames"], info["total_episodes"], info["total_tasks"])
== (10, 4, 3)
+ assert info["splits"] == {"train": "0:4"}
+ assert info["total_subtasks"] == 3
+ stats = metadata(conn, "stats")
+ for name in ("index", "episode_index", "task_index", "subtask_index",
"observation.state", "action"):
+ values = np.array(data[name].to_pylist())
+ np.testing.assert_allclose(stats[name]["mean"],
np.atleast_1d(values.mean(0)))
+ np.testing.assert_allclose(stats[name]["std"],
np.atleast_1d(values.std(0)))
+ assert "q50" not in stats[name]
+ tasks = conn.catalog.get_table(conn._identifier("merged__tasks"))
+ table = rows(conn, "merged__tasks").sort_by("task_index")
+ restored = _restore_pandas_metadata(tasks, table).to_pandas()
+ assert restored.index.tolist() == ["pick", "place", "stack"]
+ pytest.importorskip("datasets")
+ torch = pytest.importorskip("torch")
+ dataset = pm.PaimonLeRobotDataset(
+ conn.get_table("merged"), tag_name="train",
+ delta_timestamps={"action": [-0.1, 0, 0.1]})
+ assert dataset[5]["task"] == "place"
+ assert dataset[7]["task"] == "stack"
+ assert dataset[5]["action_is_pad"].tolist() == [True, False, False]
+ batch = next(iter(dataset.to_dataloader(batch_size=3, num_workers=0)))
+ assert batch["action"].shape == (3, 3, 2)
+ assert batch["action"].dtype == torch.float32
+ selected = pm.PaimonLeRobotDataset(conn.get_table("merged"),
tag_name="train", episodes=[2])
+ assert len(selected) == 2
+ assert selected[0]["episode_index"].item() == 2
+
+
[email protected]("component", ["tasks", "subtasks", "episodes"])
+def test_merge_ignores_producer_metadata(setup, component):
+ conn, sources = setup
+ root = Path(sources[1][7:]) / "meta"
+ path = root / ("episodes/chunk-000/file-000.parquet" if component ==
"episodes"
+ else component + ".parquet")
+ table = pq.read_table(path)
+ schema_metadata = dict(table.schema.metadata or {})
+ if component == "episodes":
+ schema_metadata[b"producer"] = b"another-exporter"
+ else:
+ pandas_metadata = json.loads(schema_metadata[b"pandas"])
+ pandas_metadata["pandas_version"] = "1.5.0"
+ schema_metadata[b"pandas"] = json.dumps(pandas_metadata).encode()
+ pq.write_table(table.replace_schema_metadata(schema_metadata), path)
+ conn.load_from_lerobot("merged", sources)
+ assert rows(conn, "merged").num_rows == 10
+ assert rows(conn, "merged__episodes").num_rows == 4
+ for kind, expected in (("task", ["pick", "place", "stack"]),
+ ("subtask", ["reach", "grasp", "release"])):
+ target = conn.catalog.get_table(conn._identifier("merged__" + kind +
"s"))
+ data = rows(conn, "merged__" + kind + "s").sort_by(kind + "_index")
+ restored = _restore_pandas_metadata(target, data).to_pandas()
+ assert restored.index.tolist() == expected
+
+
[email protected]("custom_source", [0, 1])
+def test_merge_normalizes_task_text_columns(setup, custom_source):
+ conn, sources = setup
+ root = Path(sources[custom_source][7:]) / "meta"
+ for kind in ("task", "subtask"):
+ path = root / (kind + "s.parquet")
+ frame = pq.read_table(path).to_pandas()
+ frame.index.name = "instruction"
+ pq.write_table(pa.Table.from_pandas(frame), path)
+ conn.load_from_lerobot("merged", sources)
+ data = rows(conn, "merged").sort_by("index")
+ assert data["task_index"].to_pylist() == [0, 0, 1, 1, 1, 1, 1, 2, 2, 2]
+ assert data["subtask_index"].to_pylist() == [0, 1, 0, 1, 0, 1, 2, 1, 2, 1]
+ for kind, expected in (("task", ["pick", "place", "stack"]),
+ ("subtask", ["reach", "grasp", "release"])):
+ target = conn.catalog.get_table(conn._identifier("merged__" + kind +
"s"))
+ table = rows(conn, "merged__" + kind + "s").sort_by(kind + "_index")
+ restored = _restore_pandas_metadata(target, table).to_pandas()
+ assert restored.index.tolist() == expected
+ assert restored.index.name == ("instruction" if custom_source == 0
else kind)
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ dataset = pm.PaimonLeRobotDataset(conn.get_table("merged"))
+ assert dataset[5]["task"] == "place"
+ assert dataset[7]["task"] == "stack"
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_invalid_commit_options_fail_before_preparing_files(setup,
import_parallelism):
+ from pypaimon.multimodal.lerobot import aggregate, ray_loader
+
+ conn, sources = setup
+ with patch.object(aggregate, "_prepare_dataset") as serial, \
+ patch.object(ray_loader, "_prepare_sources_ray") as parallel:
+ with pytest.raises(ValueError):
+ conn.load_from_lerobot(
+ "merged", sources, parallelism=import_parallelism,
+ options={"commit.max-retries": "invalid"})
+ serial.assert_not_called()
+ parallel.assert_not_called()
+ table = conn.get_table("merged").raw_table
+ assert table.snapshot_manager().get_latest_snapshot() is None
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_merge_accepts_reordered_fields_and_control_quantiles(setup,
import_parallelism):
+ conn, sources = setup
+ root = Path(sources[1][7:])
+ info_path = root / "meta/info.json"
+ info = json.loads(info_path.read_text())
+ info["features"] = dict(reversed(list(info["features"].items())))
+ info_path.write_text(json.dumps(info))
+ path = root / "meta/episodes/chunk-000/file-000.parquet"
+ episodes = pq.read_table(path)
+ pq.write_table(episodes.select([
+ name for name in reversed(episodes.column_names) if not
name.endswith("/q50")]), path)
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism)
+ data = rows(conn, "merged").sort_by("index")
+ assert data["index"].to_pylist() == list(range(10))
+ assert data["observation.state"].to_pylist() == [
+ [float(offset + i), float(i)] for offset in (0, 20) for i in range(5)]
+ episodes = episode_rows(conn, "merged__episodes")
+ assert episodes["dataset_from_index"].to_pylist() == [0, 2, 5, 7]
+ assert not any(name.endswith("/q50") for name in episodes.column_names)
+
+
[email protected]("large_source", [0, 1])
+def test_merge_accepts_large_string_labels(setup, large_source):
+ conn, sources = setup
+ for kind in ("task", "subtask"):
+ path = Path(sources[large_source][7:]) / ("meta/" + kind + "s.parquet")
+ data = pq.read_table(path)
+ fields = [field.with_type(pa.large_string()) if field.name == kind
else field
+ for field in data.schema]
+ pq.write_table(data.cast(pa.schema(fields,
metadata=data.schema.metadata)), path)
+ conn.load_from_lerobot("merged", sources)
+ for kind, labels in (("task", ["pick", "place", "stack"]),
+ ("subtask", ["reach", "grasp", "release"])):
+ table = rows(conn, "merged__" + kind + "s").sort_by(kind + "_index")
+ assert table[kind].to_pylist() == labels
+ assert rows(conn, "merged").num_rows == 10
+
+
+def test_merge_preserves_integer_statistics(setup):
+ conn, sources = setup
+ extremes = [2**53 + 1, 2**53 + 3]
+ for uri, value in zip(sources, extremes):
+ root = Path(uri[7:])
+ path = root / "meta/info.json"
+ info = json.loads(path.read_text())
+ info["features"]["observation.state"]["dtype"] = "int64"
+ path.write_text(json.dumps(info))
+ path = root / "data/chunk-000/file-000.parquet"
+ data = pq.read_table(path)
+ data =
data.set_column(data.schema.get_field_index("observation.state"),
+ "observation.state", pa.array([[value, value]]
* 5,
+
type=pa.list_(pa.int64())))
+ pq.write_table(data, path)
+ path = root / "meta/stats.json"
+ stats = json.loads(path.read_text())
+ stats["observation.state"] = {
+ "min": [value, value], "max": [value, value],
+ "mean": [float(value)] * 2, "std": [0.0, 0.0], "count": [5]}
+ path.write_text(json.dumps(stats))
+ conn.load_from_lerobot("merged", sources)
+ stats = metadata(conn, "stats")["observation.state"]
+ assert stats["min"] == [extremes[0]] * 2
+ assert stats["max"] == [extremes[1]] * 2
+ assert stats["count"] == [10]
+ assert rows(conn,
"merged").sort_by("index")["observation.state"].to_pylist() == [
+ [value, value] for value in extremes for unused in range(5)]
+ assert _batch_stats(extremes)["min"] == [extremes[0]]
+ from pypaimon.multimodal.lerobot.aggregate import _merge_stats
+ summary = dict(stats, count=[2**53 + 1])
+ assert _merge_stats([summary, summary])["count"] == [2 * (2**53 + 1)]
+
+
[email protected]("field", ["fps", "robot_type", "features", "stats"])
+def test_incompatible_sources_fail_before_creation(setup, field):
+ conn, sources = setup
+ root = Path(sources[1][7:])
+ if field == "stats":
+ (root / "meta/stats.json").unlink()
+ else:
+ path = root / "meta/info.json"
+ info = json.loads(path.read_text())
+ if field == "features":
+ info[field]["action"]["names"] = ["different", "axes"]
+ else:
+ info[field] = 20 if field == "fps" else "different"
+ path.write_text(json.dumps(info))
+ with pytest.raises(ValueError):
+ conn.load_from_lerobot("merged", sources)
+ with pytest.raises(TableNotExistException):
+ conn.get_table("merged")
+
+
+def test_missing_stats_and_existing_target(setup):
+ conn, sources = setup
+ for uri in sources:
+ (Path(uri[7:]) / "meta/stats.json").unlink()
+ conn.load_from_lerobot("merged", sources)
+ with pytest.raises(TableNotExistException):
+ conn.get_table("merged__stats")
+ with pytest.raises(ValueError, match="already exists"):
+ conn.load_from_lerobot("merged", sources)
+ assert rows(conn, "merged").num_rows == 10
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_single_source_metadata_opt_in(setup, import_parallelism):
+ pytest.importorskip("torch")
+ conn, sources = setup
+ conn.load_from_lerobot("single", sources[0], fps_mode="source",
+ parallelism=import_parallelism)
+ info = {row["key"]: json.loads(row["value"])
+ for row in rows(conn, "single__info").to_pylist()}
+ assert info["fps"] == 10
+ assert info["fps_mode"] == "source"
+ assert rows(conn, "single__datasets")["fps"].to_pylist() == [10]
+ assert rows(conn, "single__episodes")["dataset_index"].to_pylist() == [0,
0]
+ pytest.importorskip("datasets")
+ reader = pm.PaimonLeRobotDataset(conn.get_table("single"))
+ assert reader.fps == 10
+ assert reader.episode_fps == (10, 10)
+
+
+def test_source_info_remains_distinct_from_merged_info(setup):
+ conn, sources = setup
+ for ordinal, uri in enumerate(sources):
+ path = Path(uri[7:]) / "meta/info.json"
+ info = json.loads(path.read_text())
+ info["vendor_extension"] = {"source": ordinal}
+ path.write_text(json.dumps(info))
+ conn.load_from_lerobot("merged", sources,
+ dataset_names=["move cup", "empty cup"])
+ assert "vendor_extension" not in metadata(conn, "info")
+ datasets = rows(conn, "merged__datasets").sort_by("dataset_index")
+ assert datasets["dataset_name"].to_pylist() == ["move cup", "empty cup"]
+ assert [json.loads(value)["vendor_extension"]["source"]
+ for value in datasets["info_json"].to_pylist()] == [0, 1]
+
+
+def test_nested_lerobot_source_does_not_infer_business_name(tmp_path):
+ conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
+ uri = source(tmp_path / "episode-uuid" / "lerobot")
+ conn.load_from_lerobot("merged", [uri])
+ assert rows(conn, "merged__datasets")["dataset_name"].to_pylist() == [None]
+
+
+def test_shared_business_label_does_not_merge_source_datasets(setup):
+ conn, sources = setup
+ conn.load_from_lerobot("merged", sources,
+ dataset_names=["same task", "same task"])
+ datasets = rows(conn, "merged__datasets").sort_by("dataset_index")
+ assert datasets["dataset_index"].to_pylist() == [0, 1]
+ assert datasets["dataset_name"].to_pylist() == ["same task", "same task"]
+ assert episode_rows(conn, "merged__episodes")["episode_index"].to_pylist()
== [
+ 0, 1, 0, 1]
+
+
+def test_dataset_names_validate_before_source_access(tmp_path):
+ conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
+ with patch("pypaimon.multimodal.lerobot.source._resolved_source",
+ side_effect=AssertionError("source accessed")):
+ with pytest.raises(ValueError, match="dataset_names"):
+ conn.load_from_lerobot("merged", ["a", "b"],
+ dataset_names=["only one name"])
+
+
[email protected]("sources,parallelism", [([], 1), (["unused",
"unused"], 0)])
+def test_invalid_arguments_before_io(tmp_path, sources, parallelism):
+ conn = pm.connect(options={"warehouse": str(tmp_path)})
+ with patch("pypaimon.multimodal.lerobot.source._resolved_source",
side_effect=AssertionError("source accessed")):
+ with pytest.raises(ValueError):
+ conn.load_from_lerobot("merged", sources, parallelism=parallelism)
+
+
[email protected]("failure", ["write", "tag"])
+def test_failure_does_not_publish_root_tag(setup, failure):
+ from pypaimon.multimodal.lerobot import aggregate
+ conn, sources = setup
+ if failure == "write":
+ prepare = aggregate._prepare_dataset
+ calls = []
+
+ def fail_second(*args, **kwargs):
+ calls.append(1)
+ if len(calls) == 2:
+ raise RuntimeError("injected")
+ return prepare(*args, **kwargs)
+ target = patch.object(aggregate, "_prepare_dataset",
side_effect=fail_second)
+ else:
+ target = patch("pypaimon.multimodal.lerobot.metadata._create_tag",
side_effect=RuntimeError("injected"))
+ with target, pytest.raises(RuntimeError, match="injected"):
+ conn.load_from_lerobot("merged", sources, tag_name="train")
+ table = conn.get_table("merged").raw_table
+ assert not table.tag_manager().tag_exists("train")
+ if failure == "write":
+ assert table.snapshot_manager().get_latest_snapshot() is None
+ else:
+ assert rows(conn, "merged").num_rows == 10
+ assert all(Path(uri[7:]).is_dir() for uri in sources)
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_video_sources_with_identical_paths(tmp_path, import_parallelism):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
+ sources = [source(tmp_path / "a", video=True, value=0),
+ source(tmp_path / "b", video=True, value=100)]
+ conn.load_from_lerobot("merged", sources, batch_size=2, tag_name="train",
+ parallelism=import_parallelism, fps_mode="source")
+ table = conn.get_table("merged").raw_table
+ imported = rows(conn, "merged").sort_by("index")
+ for source_index, uri in enumerate(sources):
+ descriptor = VideoFrameDescriptor.deserialize(
+ imported["camera"][source_index * 5].as_py()).payload_descriptor
+ reader = table.file_io.uri_reader_factory.create(descriptor.uri)
+ stored_mp4 = Blob.from_descriptor(reader, descriptor).to_data()
+ original_mp4 = (Path(uri[7:]) /
+ "videos/camera/chunk-000/file-000.mp4").read_bytes()
+ assert stored_mp4 == original_mp4
+ dataset = pm.PaimonLeRobotDataset(conn.get_table("merged"),
tag_name="train", video_backend="pyav")
+ assert dataset[0]["camera"].mean().item() < 0.05
+ assert dataset[5]["camera"].mean().item() > 0.3
+ assert dataset[5]["frame_index"].item() == 0
+ import av
+ for source_index, uri in enumerate(sources):
+ path = Path(uri[7:]) / "videos/camera/chunk-000/file-000.mp4"
+ with av.open(str(path)) as container:
+ expected = [frame.to_ndarray(format="rgb24") for frame in
container.decode(video=0)]
+ for frame_index in (0, 4):
+ actual = dataset[source_index * 5 + frame_index]["camera"].numpy()
+ np.testing.assert_allclose(actual,
expected[frame_index].transpose(2, 0, 1) / 255.0)
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_mixed_fps_group_keeps_episode_rates(tmp_path, import_parallelism):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
+ sources = [source(tmp_path / "a", video=True, fps=25, frames=16),
+ source(tmp_path / "b", video=True, fps=30, value=100,
frames=16)]
+ with pytest.raises(ValueError, match="incompatible info.fps"):
+ conn.load_from_lerobot("default_rejected", sources,
parallelism=import_parallelism)
+ with pytest.raises(TableNotExistException):
+ conn.get_table("default_rejected")
+ conn.load_from_lerobot("merged", sources, batch_size=2, tag_name="train",
+ parallelism=import_parallelism, fps_mode="source")
+ info = metadata(conn, "info")
+ assert info["fps"] is None
+ assert info["fps_mode"] == "source"
+ datasets = rows(conn, "merged__datasets").sort_by("dataset_index")
+ assert datasets["fps"].to_pylist() == [25, 30]
+ assert [json.loads(value)["fps"] for value in
+ datasets["info_json"].to_pylist()] == [25, 30]
+ episodes = episode_rows(conn, "merged__episodes")
+ assert "fps" not in episodes.column_names
+ assert episodes["dataset_index"].to_pylist() == [0, 0, 1, 1]
+ scoped = pm.PaimonLeRobotDataset(
+ conn.get_table("merged"), tag_name="train", dataset_index=1,
+ video_backend="pyav")
+ assert len(scoped) == 16
+ assert scoped.fps == 30
+ assert scoped[0]["index"].item() == 16
+ dataset = pm.PaimonLeRobotDataset(
+ conn.get_table("merged"), tag_name="train", video_backend="pyav",
+ delta_timestamps={"action": [-0.2, 0, 0.2]})
+ assert dataset.fps is None
+ assert dataset.episode_fps == (25, 25, 30, 30)
+ assert "video.fps" not in info["features"]["camera"]["info"]
+ # 0.2 seconds means five frames at 25 FPS and six frames at 30 FPS.
+ expected = {7: [2, 7, 7], 8: [8, 8, 13], 15: [10, 15, 15],
+ 16: [0, 0, 6], 23: [1, 7, 7]}
+ for index, positions in expected.items():
+ assert dataset[index]["action"][:, 0].tolist() == positions
+ assert dataset[7]["action_is_pad"].tolist() == [False, False, True]
+ assert dataset[16]["action_is_pad"].tolist() == [True, False, False]
+ assert dataset[1]["timestamp"].item() == pytest.approx(1 / 25)
+ assert dataset[17]["timestamp"].item() == pytest.approx(1 / 30)
+ av = pytest.importorskip("av")
+ for ordinal, directory in enumerate(("a", "b")):
+ with av.open(str(tmp_path / directory /
"videos/camera/chunk-000/file-000.mp4")) as container:
+ reference = [frame.to_ndarray(format="rgb24") for frame in
container.decode(video=0)]
+ for index, frame in enumerate(reference):
+ np.testing.assert_allclose(dataset[ordinal * 16 +
index]["camera"].numpy(),
+ frame.transpose(2, 0, 1) / 255.0)
+ selected = pm.PaimonLeRobotDataset(
+ conn.get_table("merged"), episodes=[2], video_backend="pyav",
+ delta_timestamps={"action": [0, 1 / 30]})
+ assert selected[0]["action"][:, 0].tolist() == [0, 1]
+ assert next(iter(dataset.to_dataloader(batch_size=2, num_workers=0)))[
+ "action"].shape == (2, 3, 2)
+ with pytest.raises(ValueError, match="multiples of 1/25"):
+ pm.PaimonLeRobotDataset(
+ conn.get_table("merged"), tag_name="train",
+ delta_timestamps={"action": [0.1]})
+
+
+def test_vocabulary_columns_without_pandas_index_are_preserved(setup):
+ conn, sources = setup
+ for uri in sources:
+ root = Path(uri[7:])
+ for component in ("tasks", "subtasks"):
+ path = root / ("meta/%s.parquet" % component)
+ table = pq.read_table(path).replace_schema_metadata(None)
+ pq.write_table(table, path)
+ conn.load_from_lerobot("merged", sources, fps_mode="source")
+ dataset = rows(conn,
"merged__datasets").sort_by("dataset_index").to_pylist()[0]
+ for component in ("tasks", "subtasks"):
+ expected = pq.read_table(Path(sources[0][7:]) / ("meta/%s.parquet" %
component))
+ actual = pa.ipc.open_stream(dataset[component + "_ipc"]).read_all()
+ assert actual.equals(expected)
+
+
+def test_official_merge_reference_and_local_sources(tmp_path):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ module = pytest.importorskip("lerobot.datasets.lerobot_dataset")
+ official = pytest.importorskip("lerobot.datasets.aggregate")
+ roots = []
+ for n in range(2):
+ root = tmp_path / ("source%d" % n)
+ dataset = module.LeRobotDataset.create(
+ repo_id="test/source%d" % n, root=root, fps=10, use_videos=False,
+ robot_type="test", features={
+ "observation.state": {"dtype": "float32", "shape": (2,),
"names": ["x", "y"]},
+ "action": {"dtype": "float32", "shape": (2,), "names": ["x",
"y"]},
+ })
+ for ep in range(2):
+ for i in range(3):
+ dataset.add_frame({
+ "observation.state": np.array([n, i], dtype=np.float32),
+ "action": np.array([i, -i], dtype=np.float32),
+ "task": ("pick", "place", "stack")[n + ep],
+ })
+ dataset.save_episode()
+ dataset.finalize()
+ roots.append(root)
+ reference = tmp_path / "official"
+ official.aggregate_datasets(
+ repo_ids=["test/source0", "test/source1"], aggr_repo_id="test/merged",
+ roots=roots, aggr_root=reference)
+ conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
+ conn.load_from_lerobot("merged", roots, tag_name="train", batch_size=2)
+ expected = pa.concat_tables([pq.read_table(p) for p in sorted((reference /
"data").rglob("*.parquet"))])
+ actual = rows(conn, "merged").sort_by("index")
+ for name in expected.column_names:
+ if name != "episode_index":
+ np.testing.assert_allclose(actual[name].to_pylist(),
expected[name].to_pylist())
+ assert actual["episode_index"].to_pylist() == [0] * 3 + [1] * 3 + [0] * 3
+ [1] * 3
+ assert actual["dataset_index"].to_pylist() == [0] * 6 + [1] * 6
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged"),
tag_name="train")
+ try:
+ assert [int(sample["episode_index"]) for sample in
reader.get_items(range(12))] == (
+ expected["episode_index"].to_pylist())
+ finally:
+ reader.close()
+ info = metadata(conn, "info")
+ reference_info = json.loads((reference / "meta/info.json").read_text())
+ for name in ("total_frames", "total_episodes", "total_tasks", "splits"):
+ assert info[name] == reference_info[name]
+ reference_stats = json.loads((reference / "meta/stats.json").read_text())
+ for name in ("observation.state", "action"):
+ for key in ("min", "max", "mean", "std", "count"):
+ np.testing.assert_allclose(metadata(conn, "stats")[name][key],
reference_stats[name][key])
+ # A string source continues through the unchanged single-source importer.
+ conn.load_from_lerobot("single", str(roots[0]))
+ assert rows(conn, "single").num_rows == 6
+
+
+def test_weighted_population_statistics():
+ from pypaimon.multimodal.lerobot.aggregate import _merge_stats
+ result = _merge_stats([_batch_stats([0, 2]), _batch_stats([10, 10, 10])])
+ np.testing.assert_allclose(result["mean"], [6.4])
+ np.testing.assert_allclose(result["std"], [np.std([0, 2, 10, 10, 10])])
+ assert result["count"] == [5]
+
+
+def test_invalid_episode_ranges_fail_before_creation(setup):
+ conn, sources = setup
+ path = Path(sources[1][7:]) / "meta/episodes/chunk-000/file-000.parquet"
+ data = pq.read_table(path)
+ data = data.set_column(data.schema.get_field_index("dataset_from_index"),
+ "dataset_from_index", pa.array([1, 2],
type=pa.int64()))
+ pq.write_table(data, path)
+ with pytest.raises(ValueError, match="source 1"):
+ conn.load_from_lerobot("merged", sources)
+ with pytest.raises(TableNotExistException):
+ conn.get_table("merged")
+
+
+def test_ray_merge_multifile_sources_matches_serial(setup, ray_cluster):
+ conn, sources = setup
+ for uri in sources:
+ root = Path(uri[7:])
+ path = root / "data/chunk-000/file-000.parquet"
+ data = pq.read_table(path)
+ pq.write_table(data.slice(0, 2), path)
+ pq.write_table(data.slice(2), path.with_name("file-001.parquet"))
+ episodes_path = root / "meta/episodes/chunk-000/file-000.parquet"
+ episodes = pq.read_table(episodes_path)
+ episodes = episodes.set_column(
+ episodes.schema.get_field_index("data/file_index"),
+ "data/file_index", pa.array([0, 1], type=pa.int64()))
+ pq.write_table(episodes, episodes_path)
+ conn.load_from_lerobot("serial", sources, batch_size=1)
+ conn.load_from_lerobot("parallel", sources, batch_size=1, parallelism=2)
+ for suffix, key in (("", "index"),
+ ("__episodes", [("dataset_index", "ascending"),
+ ("episode_index", "ascending")]),
+ ("__datasets", "dataset_index"),
+ ("__tasks", "task_index"), ("__subtasks",
"subtask_index"),
+ ("__info", "key"), ("__stats", "key")):
+ assert rows(conn, "serial" + suffix).sort_by(key).equals(
+ rows(conn, "parallel" + suffix).sort_by(key))
+
+
+def test_ray_worker_failure_does_not_commit(setup, ray_cluster):
+ conn, sources = setup
+ path = Path(sources[1][7:]) / "data/chunk-000/file-000.parquet"
+ data = pq.read_table(path)
+ data = data.set_column(data.schema.get_field_index("index"), "index",
+ pa.array([9, 1, 2, 3, 4], type=pa.int64()))
+ pq.write_table(data, path)
+ with pytest.raises(Exception, match="index"):
+ conn.load_from_lerobot("merged", sources, parallelism=2,
tag_name="train")
+ table = conn.get_table("merged").raw_table
+ assert table.snapshot_manager().get_latest_snapshot() is None
+ assert not table.tag_manager().tag_exists("train")
+ assert all(Path(uri[7:]).is_dir() for uri in sources)
+
+
[email protected]("mode", [None, "mixed", "", 1, ["episode"]])
+def test_invalid_fps_mode_before_io(tmp_path, mode):
+ conn = pm.connect(options={"warehouse": str(tmp_path)})
+ with pytest.raises(ValueError, match="fps_mode"):
+ conn.load_from_lerobot("invalid", ["unused"], fps_mode=mode)
+ assert conn.catalog.list_databases() == []
+
+
[email protected]("multiple", [False, True])
[email protected]("rate", [None, 0, -1, True, 10.5, 20])
+def test_source_fps_conflicts_before_creation(setup, tmp_path, multiple, rate):
+ conn, sources = setup
+ path = tmp_path / "a/meta/episodes/chunk-000/file-000.parquet"
+ data = pq.read_table(path).append_column("fps", pa.array([rate, rate]))
+ pq.write_table(data, path)
+ with pytest.raises(ValueError, match="fps"):
+ conn.load_from_lerobot("invalid", sources if multiple else sources[0],
fps_mode="source")
+ with pytest.raises(TableNotExistException):
+ conn.get_table("invalid")
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
[email protected]("multiple", [False, True])
+def test_existing_source_episode_fps(setup, tmp_path, import_parallelism,
multiple):
+ conn, sources = setup
+ path = tmp_path / "a/meta/episodes/chunk-000/file-000.parquet"
+ pq.write_table(pq.read_table(path).append_column("fps", pa.array([10,
10])), path)
+ conn.load_from_lerobot("merged", sources if multiple else sources[0],
+ fps_mode="source", parallelism=import_parallelism)
+ episodes = episode_rows(conn, "merged__episodes")
+ assert "fps" not in episodes.column_names
+ assert episodes["dataset_index"].to_pylist() == (
+ [0, 0, 1, 1] if multiple else [0, 0])
+ assert rows(conn, "merged__datasets")["fps"].to_pylist() == (
+ [10, 10] if multiple else [10])
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
[email protected]("all_null", [False, True])
+def test_merge_nullable_subtask_import(setup, tmp_path, import_parallelism,
all_null):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn, sources = setup
+ for directory in ("a", "b"):
+ path = tmp_path / directory / "data/chunk-000/file-000.parquet"
+ data = pq.read_table(path)
+ values = [None] * 5 if all_null else [0, None, 0, 1, None]
+ data = data.set_column(data.schema.get_field_index("subtask_index"),
+ "subtask_index", pa.array(values,
type=pa.int64()))
+ pq.write_table(data, path)
+ if all_null:
+ path = tmp_path / directory / "meta/subtasks.parquet"
+ pq.write_table(pq.read_table(path).slice(0, 0), path)
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism,
tag_name="train")
+ expected = [None] * 10 if all_null else [0, None, 0, 1, None, 1, None, 1,
2, None]
+ assert rows(conn, "merged").sort_by("index")["subtask_index"].to_pylist()
== expected
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged"),
tag_name="train")
+ assert reader[1]["subtask"] is None
+ batch = next(iter(reader.to_dataloader(batch_size=5, num_workers=0)))
+ assert batch["subtask_index"][1].item() == -1
+ assert not batch["subtask_index_is_valid"][1].item()
+ if all_null:
+ assert "subtask_index" not in metadata(conn, "stats")
+ assert rows(conn,
"merged__episodes")["stats/subtask_index/mean"].to_pylist() == [None] * 4
+ if not all_null:
+ windowed = pm.PaimonLeRobotDataset(
+ conn.get_table("merged"), delta_timestamps={"subtask_index":
[-0.1, 0, 0.1]})
+ first, second = windowed.get_items([0, 0])
+ first["subtask_index"][0].fill_(-100)
+ assert first["subtask_index"][1].item() == 0
+ assert second["subtask_index"][0].item() == 0
+
+
[email protected]("rate", [None, 0, -1, True, 10.5, 20])
+def test_reader_rejects_invalid_source_fps(setup, rate):
+
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+
+ class Reader(pm.PaimonDatasetReader):
+ def read_indices(self, indices, columns):
+ raise AssertionError("Invalid FPS must fail before reading frames")
+
+ conn, sources = setup
+ conn.load_from_lerobot("merged", sources, fps_mode="source")
+ meta = pm.PaimonLeRobotDataset(conn.get_table("merged")).meta
+ meta.datasets[0]["fps"] = rate
+ with pytest.raises(ValueError, match="fps"):
+ Reader(meta)
+
+
+def test_reader_requires_fps_without_episode_column(setup):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ from pypaimon.multimodal.lerobot.metadata import _overwrite_arrow
+ conn, sources = setup
+ conn.load_from_lerobot("merged", sources)
+ info = rows(conn, "merged__info").to_pylist()
+ for row in info:
+ if row["key"] == "fps":
+ row["value"] = "null"
+ _overwrite_arrow(conn.get_table("merged__info").raw_table,
pa.Table.from_pylist(info))
+ with pytest.raises(ValueError, match="missing fps"):
+ pm.PaimonLeRobotDataset(conn.get_table("merged"))
+
+
[email protected]("multiple", [False, True])
+def test_episode_fps_rejects_conflicting_video_feature(tmp_path, multiple):
+ conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
+ uri = source(tmp_path / "source", video=True, fps=25)
+ path = tmp_path / "source/meta/info.json"
+ info = json.loads(path.read_text())
+ info["features"]["camera"]["info"]["video.fps"] = 30
+ path.write_text(json.dumps(info))
+ with pytest.raises(ValueError, match="FPS"):
+ conn.load_from_lerobot("invalid", [uri] if multiple else uri,
fps_mode="source")
+ with pytest.raises(TableNotExistException):
+ conn.get_table("invalid")
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
[email protected]("empty_episode", [False, True])
+def test_reconstructed_subtask_stats_use_output_schema(setup,
import_parallelism, empty_episode):
+ conn, sources = setup
+ for uri in sources:
+ root = Path(uri[7:])
+ path = root / "data/chunk-000/file-000.parquet"
+ data = pq.read_table(path)
+ values = [None, None, 0, 1, 0] if empty_episode else [0, None, 0, 1, 0]
+ data = data.set_column(data.schema.get_field_index("subtask_index"),
"subtask_index",
+ pa.array(values, type=pa.int64()))
+ pq.write_table(data, path)
+ path = root / "meta/episodes/chunk-000/file-000.parquet"
+ episodes = pq.read_table(path)
+ key = "stats/subtask_index/mean"
+ if not empty_episode:
+ episodes =
episodes.set_column(episodes.schema.get_field_index(key), key,
+ pa.array([None, [0.5]],
type=pa.list_(pa.float64())))
+ schema = pa.schema([
+ field.with_nullable(not empty_episode and field.name == key)
+ if field.name.startswith("stats/subtask_index/") else field
+ for field in episodes.schema])
+ pq.write_table(episodes.cast(schema), path)
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism)
+ episodes = episode_rows(conn, "merged__episodes")
+ assert episodes["stats/subtask_index/mean"].to_pylist()[::2] == (
+ [None, None] if empty_episode else [[0.0], [1.0]])
+ assert episodes.schema.field("stats/subtask_index/min").nullable
+ assert rows(conn, "merged").num_rows == 10
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_episode_validation_failure_aborts_before_frames_commit(setup,
import_parallelism):
+ from pypaimon.multimodal.lerobot import aggregate
+ conn, sources = setup
+ original = aggregate._merged_episodes
+
+ def invalid(plans, schema):
+ for table in original(plans, schema):
+ # A malformed replacement must be rejected before any Frames
commit.
+ yield table.drop(["episode_index"])
+
+ with patch.object(aggregate, "_merged_episodes", side_effect=invalid):
+ with pytest.raises(ValueError, match="episode_index"):
+ conn.load_from_lerobot("merged", sources,
parallelism=import_parallelism, tag_name="train")
+ table = conn.get_table("merged").raw_table
+ assert table.snapshot_manager().get_latest_snapshot() is None
+ assert not table.tag_manager().tag_exists("train")
+
+
[email protected]("reverse", [False, True])
+def test_float_extrema_propagate_nan(setup, reverse):
+ conn, sources = setup
+ path = Path(sources[0][7:]) / "meta/stats.json"
+ stats = json.loads(path.read_text())
+ for key in ("min", "max"):
+ stats["observation.state"][key][0] = float("nan")
+ path.write_text(json.dumps(stats))
+ conn.load_from_lerobot("merged", sources[::-1] if reverse else sources)
+ merged = metadata(conn, "stats")["observation.state"]
+ assert np.isnan(merged["min"][0])
+ assert np.isnan(merged["max"][0])
+ assert merged["min"][1] == 0
+ assert merged["max"][1] == 4
+
+
[email protected]("multiple", [False, True])
[email protected]("video_rate", ["10", 10.000005])
+def test_default_fps_preserves_importer_contract(tmp_path, multiple,
video_rate):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
+ uri = source(tmp_path / "source", video=True)
+ path = tmp_path / "source/meta/info.json"
+ info = json.loads(path.read_text())
+ info["features"]["camera"]["info"]["video.fps"] = video_rate
+ path.write_text(json.dumps(info))
+ path = tmp_path / "source/meta/episodes/chunk-000/file-000.parquet"
+ pq.write_table(pq.read_table(path).append_column("fps", pa.array([10.0,
10.0])), path)
+ conn.load_from_lerobot("merged", [uri] if multiple else uri)
+ assert rows(conn, "merged__episodes")["fps"].to_pylist() == [10.0, 10.0]
+ assert "fps_mode" not in metadata(conn, "info")
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged"),
video_backend="pyav")
+ try:
+ assert reader.episode_fps == (10, 10)
+ assert tuple(reader[0]["camera"].shape) == (3, 16, 16)
+ finally:
+ reader.close()
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_nullable_batch_type_stays_stable_after_import(setup,
import_parallelism):
+ pytest.importorskip("datasets")
+ torch = pytest.importorskip("torch")
+ conn, sources = setup
+ path = Path(sources[0][7:]) / "data/chunk-000/file-000.parquet"
+ data = pq.read_table(path)
+ data = data.set_column(data.schema.get_field_index("subtask_index"),
"subtask_index",
+ pa.array([0, None, 0, 1, 0], type=pa.int64()))
+ pq.write_table(data, path)
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism)
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged"))
+ try:
+ batches = list(reader.to_dataloader(batch_size=2, num_workers=0))
+ assert batches[0]["subtask_index"].tolist() == [0, -1]
+ assert batches[0]["subtask_index_is_valid"].tolist() == [True, False]
+ for batch in batches:
+ assert batch["subtask_index"].dtype == torch.int64
+ assert batch["subtask_index_is_valid"].dtype == torch.bool
+ assert batch["subtask_index"].shape ==
batch["subtask_index_is_valid"].shape
+ assert batches[1]["subtask_index_is_valid"].all()
+ finally:
+ reader.close()
+
+
[email protected]("mode", ["episode", "source"])
+def test_legacy_single_source_extensions(setup, mode):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn, sources = setup
+ root = Path(sources[0][7:])
+ path = root / "meta/info.json"
+ info = json.loads(path.read_text())
+ info["fps_mode"] = mode
+ path.write_text(json.dumps(info))
+ path = root / "meta/episodes/chunk-000/file-000.parquet"
+ data = pq.read_table(path).append_column("source_episode_ipc",
pa.array([b"a", b"b"]))
+ pq.write_table(data, path)
+ conn.load_from_lerobot("single", sources[0], tag_name="train")
+ reader = pm.PaimonLeRobotDataset(conn.get_table("single"),
tag_name="train")
+ try:
+ assert reader.episode_fps == (10, 10)
+ assert reader.meta.episodes["source_episode_ipc"] == [b"a", b"b"]
+ assert int(reader[2]["episode_index"]) == 1
+ finally:
+ reader.close()
+
+
+def test_source_mode_rejects_broken_episode_link(setup):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ from datasets import Dataset
+
+ class Reader(pm.PaimonDatasetReader):
+ def read_indices(self, indices, columns):
+ raise AssertionError("Invalid metadata must fail before reading")
+
+ conn, sources = setup
+ conn.load_from_lerobot("merged", sources, fps_mode="source")
+ meta = pm.PaimonLeRobotDataset(conn.get_table("merged")).meta
+ episodes = meta.episodes.to_dict()
+ episodes["dataset_index"][0] = 1
+ meta.episodes = Dataset.from_dict(episodes)
+ with pytest.raises(ValueError, match="dataset_index"):
+ Reader(meta)
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_merge_preserves_vocabulary_extension_columns(setup,
import_parallelism):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn, sources = setup
+ originals = {}
+ for index, uri in enumerate(sources):
+ for kind in ("tasks", "subtasks"):
+ path = Path(uri[7:]) / ("meta/%s.parquet" % kind)
+ table = pq.read_table(path).append_column(
+ "native_bytes", pa.array([b"\xff" + bytes([index]), None],
type=pa.binary()))
+ if index == 1:
+ table = table.append_column("source_note", pa.array(["extra",
"column"]))
+ pq.write_table(table, path)
+ originals[index, kind] = pq.read_table(path)
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism,
tag_name="train")
+ datasets = rows(conn,
"merged__datasets").sort_by("dataset_index").to_pylist()
+ for index, dataset in enumerate(datasets):
+ for kind in ("tasks", "subtasks"):
+ restored = pa.ipc.open_stream(dataset[kind + "_ipc"]).read_all()
+ assert restored.equals(originals[index, kind], check_metadata=True)
+ for kind in ("tasks", "subtasks"):
+ assert set(rows(conn, "merged__" + kind).column_names) == {kind[:-1],
kind[:-1] + "_index"}
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged"),
tag_name="train")
+ try:
+ samples = reader.get_items([0, 5])
+ assert [sample["task"] for sample in samples] == ["pick", "place"]
+ assert [sample["subtask"] for sample in samples] == ["reach", "grasp"]
+ finally:
+ reader.close()
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_merge_preserves_arrow_native_episode_rows(setup, import_parallelism):
+ from decimal import Decimal
+
+ conn, sources = setup
+ originals = []
+ for index, uri in enumerate(sources):
+ path = Path(uri[7:]) / "meta/episodes/chunk-000/file-000.parquet"
+ table = pq.read_table(path)
+ table = table.append_column("native_bytes", pa.array([b"\xff" +
bytes([index]), None]))
+ table = table.append_column("captured_at", pa.array(
+ [1700000000123456789 + index, None], type=pa.timestamp("ns",
tz="UTC")))
+ table = table.append_column("measurement", pa.array(
+ [Decimal("123456789.123"), None], type=pa.decimal128(12, 3)))
+ table = table.replace_schema_metadata({b"producer": b"native-source"})
+ pq.write_table(table, path)
+ originals.append(pq.read_table(path))
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism,
tag_name="train")
+ datasets = rows(conn,
"merged__datasets").sort_by("dataset_index").to_pylist()
+ episodes = episode_rows(conn, "merged__episodes").to_pylist()
+ for row in episodes:
+ expected = originals[row["dataset_index"]].slice(row["episode_index"],
1)
+ restored = pa.ipc.open_stream(row["source_episode_ipc"]).read_all()
+ schema = pa.ipc.read_schema(pa.BufferReader(
+ datasets[row["dataset_index"]]["episodes_schema_ipc"]))
+ assert restored.schema.equals(schema, check_metadata=True)
+ assert restored.equals(expected, check_metadata=True)
+ assert rows(conn, "merged").num_rows == 10
+
+
[email protected]("dataset_index", [None, 1])
+def test_training_projects_out_source_ipc(setup, dataset_index):
+ from pypaimon.multimodal.lerobot import dataset as dataset_module
+
+ pytest.importorskip("torch")
+ pytest.importorskip("datasets")
+ conn, sources = setup
+ conn.load_from_lerobot("merged", sources, tag_name="train")
+ reads = {}
+ read_arrow = dataset_module._read_arrow
+
+ def checked_read(table, projection=None):
+ name = table.identifier.object
+ if name.endswith(("__datasets", "__episodes")):
+ assert projection is not None
+ assert not any(column.endswith("_ipc") for column in projection)
+ reads[name.rsplit("__", 1)[1]] = projection
+ result = read_arrow(table, projection)
+ if name.endswith(("__datasets", "__episodes")):
+ assert result.column_names == projection
+ return result
+
+ with patch.object(dataset_module, "_read_arrow", side_effect=checked_read):
+ dataset = pm.PaimonLeRobotDataset(
+ conn.get_table("merged"), tag_name="train",
dataset_index=dataset_index)
+ try:
+ assert dataset[0]["task"] == ("pick" if dataset_index is None else
"place")
+ assert not any(name.endswith("_ipc") for name in
dataset.meta.episodes.column_names)
+ assert all(not any(name.endswith("_ipc") for name in row)
+ for row in dataset.meta.datasets)
+ finally:
+ dataset.close()
+ assert set(reads) == {"datasets", "episodes"}
+ assert "tasks_ipc" in rows(conn, "merged__datasets").column_names
+ assert "source_episode_ipc" in episode_rows(conn,
"merged__episodes").column_names
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_merge_canonicalizes_episode_timezone(setup, import_parallelism):
+ conn, sources = setup
+ originals = []
+ for uri in sources:
+ path = Path(uri[7:]) / "meta/episodes/chunk-000/file-000.parquet"
+ data = pq.read_table(path).append_column("capture_time", pa.array(
+ [1700000000123, None], type=pa.timestamp("ms",
tz="America/New_York")))
+ pq.write_table(data, path)
+ originals.append(pq.read_table(path))
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism,
tag_name="train")
+ data = episode_rows(conn, "merged__episodes")
+ assert data.schema.field("capture_time").type == pa.timestamp("ms",
tz="UTC")
+ assert data["capture_time"].cast(pa.int64()).to_pylist() ==
[1700000000123, None] * 2
+ for row in data.to_pylist():
+ original = originals[row["dataset_index"]].slice(row["episode_index"],
1)
+ assert pa.ipc.open_stream(row["source_episode_ipc"]).read_all().equals(
+ original, check_metadata=True)
+ assert conn.catalog.get_tag(conn._identifier("merged"), "train") is not
None
+
+
[email protected]("kind", ["task", "subtask"])
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_merge_rejects_ambiguous_source_labels(setup, kind,
import_parallelism):
+ conn, sources = setup
+ path = Path(sources[0][7:]) / ("meta/%ss.parquet" % kind)
+ pq.write_table(pa.Table.from_pandas(pd.DataFrame(
+ {kind + "_index": [0, 1]}, index=pd.Index(["same", "same"],
name=kind))), path)
+ message = "repeats task" if kind == "task" else "source 0 has duplicate
subtask text"
+ with pytest.raises(ValueError, match=message):
+ conn.load_from_lerobot("merged", sources,
parallelism=import_parallelism)
+ with pytest.raises(TableNotExistException):
+ conn.get_table("merged")
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_merge_archives_original_arrow_vocabulary(setup, import_parallelism):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn, sources = setup
+ originals = {}
+ for index, uri in enumerate(sources):
+ for kind in ("task", "subtask"):
+ path = Path(uri[7:]) / ("meta/%ss.parquet" % kind)
+ data = pq.read_table(path).select([kind + "_index", kind])
+ schema = pa.schema([
+ data.schema.field(kind + "_index"),
+ pa.field(kind, pa.string(), nullable=False,
metadata={b"label": b"original"}),
+ ], metadata={b"producer": b"arrow"})
+ pq.write_table(data.cast(schema), path)
+ originals[index, kind] = pq.read_table(path)
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism)
+ for row in rows(conn, "merged__datasets").to_pylist():
+ for kind in ("task", "subtask"):
+ restored = pa.ipc.open_stream(row[kind + "s_ipc"]).read_all()
+ assert restored.equals(originals[row["dataset_index"], kind],
check_metadata=True)
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged"))
+ try:
+ assert reader[0]["task"] == "pick"
+ assert reader[5]["subtask"] == "grasp"
+ finally:
+ reader.close()
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_nullable_mask_preserves_source_feature(setup, import_parallelism):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn, sources = setup
+ for uri in sources:
+ root = Path(uri[7:])
+ path = root / "meta/info.json"
+ info = json.loads(path.read_text())
+ info["features"]["subtask_index_is_valid"] = {
+ "dtype": "bool", "shape": [1], "names": None}
+ path.write_text(json.dumps(info))
+ path = root / "data/chunk-000/file-000.parquet"
+ data = pq.read_table(path).append_column(
+ "subtask_index_is_valid", pa.array([False, True, False, True,
False]))
+ data = data.set_column(data.schema.get_field_index("subtask_index"),
"subtask_index",
+ pa.array([0, None, 0, 1, 0], type=pa.int64()))
+ pq.write_table(data, path)
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism)
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged"))
+ try:
+ batch = next(iter(reader.to_dataloader(batch_size=2, num_workers=0)))
+ assert batch["subtask_index_is_valid"].tolist() == [False, True]
+ assert batch["_subtask_index_is_valid"].tolist() == [True, False]
+ assert batch["subtask_index"].tolist() == [0, -1]
+ finally:
+ reader.close()
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
[email protected]("video_rate", ["10", 10.000005])
+def test_merge_normalizes_video_fps(setup, tmp_path, import_parallelism,
video_rate):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn, unused = setup
+ sources = [source(tmp_path / "video_a", video=True),
+ source(tmp_path / "video_b", video=True)]
+ path = tmp_path / "video_b/meta/info.json"
+ info = json.loads(path.read_text())
+ info["features"]["camera"]["info"]["video.fps"] = video_rate
+ path.write_text(json.dumps(info))
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism)
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged"),
video_backend="pyav")
+ try:
+ assert reader.episode_fps == (10, 10, 10, 10)
+ assert tuple(reader[5]["camera"].shape) == (3, 16, 16)
+ finally:
+ reader.close()
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
[email protected]("reverse", [False, True])
+def test_merge_source_specific_episode_extensions(setup, import_parallelism,
reverse):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn, sources = setup
+ originals = {}
+ for index, uri in enumerate(sources):
+ path = Path(uri[7:]) / "meta/episodes/chunk-000/file-000.parquet"
+ data = pq.read_table(path)
+ if index == 1:
+ data = data.append_column("vendor_note", pa.array(["note", None]))
+ data = data.append_column("vendor_value", pa.array(
+ [1, 2] if index == 0 else [b"a", b"b"]))
+ field = pa.field("shared_note", pa.string(), nullable=index == 1)
+ data = data.append_column(field, pa.array(["shared", "note"] if index
== 0 else [None, "note"]))
+ pq.write_table(data, path)
+ originals[uri] = pq.read_table(path)
+ if reverse:
+ sources.reverse()
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism,
tag_name="train")
+ data = episode_rows(conn, "merged__episodes")
+ assert "vendor_note" not in data.column_names
+ assert "vendor_value" not in data.column_names
+ assert "shared_note" in data.column_names
+ for row in data.to_pylist():
+ expected =
originals[sources[row["dataset_index"]]].slice(row["episode_index"], 1)
+ restored = pa.ipc.open_stream(row["source_episode_ipc"]).read_all()
+ assert restored.equals(expected, check_metadata=True)
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged"),
tag_name="train")
+ try:
+ assert [int(sample["episode_index"]) for sample in
reader.get_items([0, 2, 5, 7])] == [0, 1, 2, 3]
+ finally:
+ reader.close()
+
+
+def test_merge_rejects_incompatible_episode_controls(setup):
+ conn, sources = setup
+ path = Path(sources[1][7:]) / "meta/episodes/chunk-000/file-000.parquet"
+ data = pq.read_table(path)
+ data = data.set_column(data.schema.get_field_index("length"), "length",
data["length"].cast(pa.int32()))
+ pq.write_table(data, path)
+ with pytest.raises(ValueError, match="incompatible Episode schema"):
+ conn.load_from_lerobot("merged", sources)
+ with pytest.raises(TableNotExistException):
+ conn.get_table("merged")
+
+
[email protected]("key", ["info", "video_info"])
[email protected]("value", [None, "producer", []])
[email protected]("reverse", [False, True])
+def test_merge_optional_video_metadata(tmp_path, key, value, reverse):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
+ sources = [source(tmp_path / name, video=True, value=i * 30)
+ for i, name in enumerate(("a", "b"))]
+ for i, name in enumerate(("a", "b")):
+ path = tmp_path / name / "meta/info.json"
+ info = json.loads(path.read_text())
+ info["features"]["camera"].pop(key, None)
+ if i == 0:
+ info["features"]["camera"][key] = value
+ path.write_text(json.dumps(info))
+ if reverse:
+ sources.reverse()
+ conn.load_from_lerobot("merged", sources, tag_name="train")
+ assert metadata(conn, "info")["features"]["camera"][key] == {}
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged"),
tag_name="train", video_backend="pyav")
+ try:
+ assert tuple(reader[5]["camera"].shape) == (3, 16, 16)
+ assert reader.episode_fps == (10, 10, 10, 10)
+ finally:
+ reader.close()
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
[email protected]("fps_mode", ["dataset", "source"])
+def test_merge_reserves_fps_mode(setup, import_parallelism, fps_mode):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn, sources = setup
+ for uri in sources:
+ path = Path(uri[7:]) / "meta/info.json"
+ info = json.loads(path.read_text())
+ info["fps_mode"] = "episode"
+ path.write_text(json.dumps(info))
+ conn.load_from_lerobot("merged", sources, fps_mode=fps_mode,
+ parallelism=import_parallelism, tag_name="train")
+ info = metadata(conn, "info")
+ if fps_mode == "dataset":
+ assert "fps_mode" not in info
+ else:
+ assert info["fps_mode"] == "source"
+ for row in rows(conn, "merged__datasets").to_pylist():
+ assert json.loads(row["info_json"])["fps_mode"] == "episode"
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged"),
tag_name="train")
+ try:
+ assert int(reader[5]["episode_index"]) == 2
+ assert reader.episode_fps == (10, 10, 10, 10)
+ finally:
+ reader.close()
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_merge_int32_source_episode_ids(setup, import_parallelism):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn, sources = setup
+ for uri in sources:
+ path = Path(uri[7:]) / "meta/episodes/chunk-000/file-000.parquet"
+ data = pq.read_table(path)
+ data = data.set_column(data.schema.get_field_index("episode_index"),
"episode_index",
+ data["episode_index"].cast(pa.int32()))
+ pq.write_table(data, path)
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism,
tag_name="train")
+ data = episode_rows(conn, "merged__episodes")
+ assert data.schema.field("episode_index").type == pa.int32()
+ assert data["episode_index"].to_pylist() == [0, 1, 0, 1]
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged"),
tag_name="train")
+ try:
+ assert [int(s["episode_index"]) for s in reader.get_items([0, 2, 5,
7])] == [0, 1, 2, 3]
+ finally:
+ reader.close()
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_episode_sources_read_only_before_commit(setup, import_parallelism):
+ from pypaimon.multimodal.lerobot import aggregate
+ conn, sources = setup
+ original = aggregate._source_episode_tables
+ committed = []
+ real_commit = aggregate._commit_messages
+
+ def read_episodes(metadata):
+ if committed:
+ raise OSError("Episode source unavailable after Frames commit")
+ return original(metadata)
+
+ def commit(committer, messages):
+ snapshot = real_commit(committer, messages)
+ committed.append(snapshot)
+ return snapshot
+
+ with patch.object(aggregate, "_source_episode_tables",
side_effect=read_episodes), \
+ patch.object(aggregate, "_commit_messages", side_effect=commit):
+ conn.load_from_lerobot("merged", sources,
parallelism=import_parallelism, tag_name="train")
+ assert rows(conn, "merged").num_rows == 10
+ assert rows(conn, "merged__episodes").num_rows == 4
+ assert len(committed) == 2
+
+
[email protected]("multiple", [False, True])
+def test_ray_groups_within_each_source(setup, ray_cluster, multiple):
+ conn, sources = setup
+ for uri in sources:
+ root = Path(uri[7:])
+ path = root / "meta/episodes/chunk-000/file-000.parquet"
+ episodes = pq.read_table(path)
+ episodes =
episodes.set_column(episodes.schema.get_field_index("data/file_index"),
+ "data/file_index", pa.array([0, 1]))
+ pq.write_table(episodes, path)
+ path = root / "data/chunk-000/file-000.parquet"
+ data = pq.read_table(path)
+ pq.write_table(data.slice(0, 2), path)
+ pq.write_table(data.slice(2), path.with_name("file-001.parquet"))
+ dispatched = []
+ remote = ray_cluster.remote
+
+ def track_remote(**options):
+ def decorate(function):
+ worker = remote(**options)(function)
+
+ class TrackedWorker:
+ def remote(self, *args):
+ dispatched.append(args[-1])
+ return worker.remote(*args)
+
+ return TrackedWorker()
+ return decorate
+
+ with patch.object(ray_cluster, "remote", side_effect=track_remote):
+ conn.load_from_lerobot("merged", sources if multiple else sources[0],
+ dataset_names=["A", "B"] if multiple else
["A"], parallelism=2)
+ assert dispatched == [[0], [1]] * (2 if multiple else 1)
+ assert rows(conn, "merged").num_rows == (10 if multiple else 5)
+ assert rows(conn, "merged__episodes").num_rows == (4 if multiple else 2)
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_episode_prepare_io_failure_publishes_no_snapshots(setup,
import_parallelism):
+ from pypaimon.multimodal.lerobot import aggregate
+ conn, sources = setup
+ original = aggregate._merged_episodes
+
+ def fail_after_first_batch(plans, schema):
+ batches = original(plans, schema)
+ yield next(batches)
+ raise OSError("Episode source read failed")
+
+ with patch.object(aggregate, "_merged_episodes",
side_effect=fail_after_first_batch):
+ with pytest.raises(OSError, match="Episode source read failed"):
+ conn.load_from_lerobot("merged", sources,
parallelism=import_parallelism, tag_name="train")
+ for name in ("merged", "merged__episodes"):
+ table = conn.get_table(name).raw_table
+ assert table.snapshot_manager().get_latest_snapshot() is None
+ assert not table.tag_manager().tag_exists("train")
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
[email protected]("fail_commit", [1, 2])
+def test_uncertain_commit_preserves_published_files(setup, tmp_path,
fail_commit, import_parallelism):
+ from pypaimon.multimodal.lerobot import aggregate
+ conn, sources = setup
+ original = aggregate._commit_messages
+ calls = []
+
+ def lose_response(committer, messages):
+ result = original(committer, messages)
+ calls.append(result)
+ if len(calls) == fail_commit:
+ raise OSError("Lost commit response")
+ return result
+
+ with patch.object(aggregate, "_commit_messages",
side_effect=lose_response):
+ with pytest.raises(OSError, match="Lost commit response"):
+ conn.load_from_lerobot("merged", sources, tag_name="train",
parallelism=import_parallelism)
+ assert rows(conn, "merged").num_rows == 10
+ if fail_commit == 2:
+ assert rows(conn, "merged__episodes").num_rows == 4
+ else:
+ assert
conn.get_table("merged__episodes").raw_table.snapshot_manager().get_latest_snapshot()
is None
+ assert not
conn.get_table("merged").raw_table.tag_manager().tag_exists("train")
+ files = list((tmp_path / "warehouse").rglob("*.parquet"))
+ assert any("merged" in path.parts for path in files)
+ episode_files = [path for path in files if "merged__episodes" in
path.parts]
+ assert bool(episode_files) == (fail_commit == 2)