This is an automated email from the ASF dual-hosted git repository.
Zouxxyy 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 d458ca567d [python] Store merged LeRobot Episode metadata as JSON
(#11070)
d458ca567d is described below
commit d458ca567d35874fff2554097c232377c0075fd4
Author: XiaoHongbo <[email protected]>
AuthorDate: Wed Nov 11 02:34:44 2026 +0800
[python] Store merged LeRobot Episode metadata as JSON (#11070)
---
docs/docs/pypaimon/lerobot.md | 17 +++-
.../pypaimon/multimodal/lerobot/aggregate.py | 108 +++++++++++++++-----
.../pypaimon/multimodal/lerobot/dataset.py | 2 +-
.../pypaimon/tests/lerobot_aggregate_test.py | 109 ++++++++++++++++-----
4 files changed, 182 insertions(+), 54 deletions(-)
diff --git a/docs/docs/pypaimon/lerobot.md b/docs/docs/pypaimon/lerobot.md
index fb5a82c9d4..67764f89e2 100644
--- a/docs/docs/pypaimon/lerobot.md
+++ b/docs/docs/pypaimon/lerobot.md
@@ -86,11 +86,18 @@ labels do not merge sources. Frame and Episode
`dataset_index` values reference
original Episode. Frames keep a
merged `index` and their original `source_index`. Source task/subtask
ID-to-text
mappings use the typed arrays of rows `__datasets.tasks` and
`__datasets.subtasks`;
-stats remain JSON. Episode extension columns are retained only
-when present with matching types in every source; source-specific extension
-columns and original Episode schemas are not archived. Repeated task/subtask
text
-within one source is rejected before creating tables to avoid losing original
-frame IDs.
+stats remain JSON.
+
+Merged `__episodes` keeps typed Episode keys and frame ranges, with
+`meta/`, `data/`, `videos/`, and `stats/` fields grouped into JSON columns.
+Grouped fields must use JSON-native Arrow types: null, boolean, integer,
+floating point, string, list, or struct, including nested combinations.
+Binary, temporal, decimal, map, and extension types are rejected before any
+target table is created. Other Episode extension fields are not imported.
+Control-field statistics reflect merged IDs; their original quantiles are
+omitted. Training reads skip `stats`; the group-level `__stats` table is
+unchanged. 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
diff --git a/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
b/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
index 03eb1cd13a..5c9e61275c 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
@@ -62,6 +62,7 @@ _REBUILT_INFO = {
}
_DATASET_INDEX_COLUMN = "dataset_index"
_SOURCE_FRAME_INDEX_COLUMN = "source_index"
+_EPISODE_JSON_GROUPS = ("meta", "data", "videos", "stats")
_SOURCE_TASKS_TYPE = pa.list_(pa.struct([
pa.field("task_index", pa.int64(), nullable=False),
pa.field("task", pa.string(), nullable=False),
@@ -84,6 +85,53 @@ def _json_table(table):
return {row["key"]: json.loads(row["value"]) for row in table.to_pylist()}
+def _json_native_arrow_type(data_type):
+ if pa.types.is_null(data_type) or pa.types.is_boolean(data_type) \
+ or pa.types.is_integer(data_type) or
pa.types.is_floating(data_type) \
+ or pa.types.is_string(data_type) or
pa.types.is_large_string(data_type):
+ return True
+ if pa.types.is_list(data_type) or pa.types.is_large_list(data_type) \
+ or pa.types.is_fixed_size_list(data_type):
+ return _json_native_arrow_type(data_type.value_type)
+ if pa.types.is_struct(data_type):
+ return all(_json_native_arrow_type(field.type) for field in data_type)
+ if pa.types.is_dictionary(data_type):
+ return _json_native_arrow_type(data_type.value_type)
+ return False
+
+
+def _episode_json_group(original, group):
+ prefix = group + "/"
+ return json.dumps(
+ _json_value({key[len(prefix):]: value
+ for key, value in original.items()
+ if key.startswith(prefix)}),
+ ensure_ascii=False, separators=(",", ":"))
+
+
+def _validate_episode_json(table, source_index):
+ fields = [
+ field for field in table.schema
+ if field.name.startswith(tuple(group + "/" for group in
_EPISODE_JSON_GROUPS))
+ ]
+ for field in fields:
+ if not _json_native_arrow_type(field.type):
+ raise ValueError(
+ "LeRobot source %d Episode field %r must use a JSON-native "
+ "Arrow type; found %s."
+ % (source_index, field.name, field.type))
+ names = [field.name for field in fields]
+ for row_index, original in enumerate(table.select(names).to_pylist()):
+ for group in _EPISODE_JSON_GROUPS:
+ try:
+ _episode_json_group(original, group)
+ except (TypeError, ValueError, OverflowError) as error:
+ raise ValueError(
+ "LeRobot source %d Episode row %d has invalid JSON-native "
+ "%s metadata: %s."
+ % (source_index, row_index, group, error)) from error
+
+
def _vocabulary_rows(table, label):
if table is None:
return None
@@ -210,11 +258,11 @@ def _plan_merge(plans, fps_mode="dataset"):
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.
+ # Keep source file locations and statistics in four JSON columns rather
+ # than expanding their source-specific fields into the target schema.
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)
+ field for field in metadata["episodes_schema"]
+ if not field.name.startswith("stats/")
and not (fps_mode == "source" and field.name == _EPISODE_FPS_COLUMN)
], metadata=metadata["episodes_schema"].metadata)
required_episode_fields = set(_EPISODE_CONTROL_COLUMNS) | {
@@ -260,8 +308,8 @@ def _plan_merge(plans, fps_mode="dataset"):
try:
for name in plan["videos"]:
_video_fps(other, other["features"][name], name)
- for unused in _validated_episode_tables(plan["metadata"],
first["videos"]):
- pass
+ for table in _validated_episode_tables(plan["metadata"],
first["videos"]):
+ _validate_episode_json(table, ordinal)
except ValueError as error:
raise ValueError("LeRobot source %d: %s" % (ordinal, error)) from
error
plan["frame_offset"] = frame_offset
@@ -275,16 +323,27 @@ def _plan_merge(plans, fps_mode="dataset"):
del info[key]
metadata["tasks_table"] = _vocabulary(plans, "tasks")
metadata["subtasks_table"] = _vocabulary(plans, "subtasks")
+ metadata["episodes_schema"] = pa.schema([
+ metadata["episodes_schema"].field(name)
+ for name in _EPISODE_CONTROL_COLUMNS
+ ], metadata=metadata["episodes_schema"].metadata)
reserved_episode_fields = {
_DATASET_INDEX_COLUMN,
"source_frame_from_index", "source_frame_to_index",
+ "meta", "data", "videos", "stats",
}
- if reserved_episode_fields.intersection(metadata["episodes_schema"].names):
+ if any(reserved_episode_fields.intersection(
+ plan["metadata"]["episodes_schema"].names)
+ for plan in plans):
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_frame_to_index", pa.int64(), nullable=False),
+ pa.field("meta", pa.string(), nullable=False),
+ pa.field("data", pa.string(), nullable=False),
+ pa.field("videos", pa.string(), nullable=False),
+ pa.field("stats", pa.string(), nullable=False)):
metadata["episodes_schema"] = metadata["episodes_schema"].append(field)
metadata["datasets_table"] = pa.Table.from_pylist([
{
@@ -378,14 +437,6 @@ def _transform_frames(plan, batch, episode):
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"]):
@@ -393,6 +444,16 @@ def _merged_episodes(plans, schema):
for original in table.to_pylist():
row = {name: original[name] for name in schema.names
if name in original}
+ for group in ("meta", "data", "videos"):
+ row[group] = _episode_json_group(original, group)
+ stats = {}
+ for key, value in original.items():
+ if key.startswith("stats/"):
+ feature, statistic = key[6:].rsplit("/", 1)
+ # Rebased control values have new statistics. Their
+ # original quantiles cannot describe the merged IDs.
+ if feature not in _CONTROLS or not
statistic.startswith("q"):
+ stats.setdefault(feature, {})[statistic] = value
row[_DATASET_INDEX_COLUMN] = dataset_index
row["source_frame_from_index"] = original["dataset_from_index"]
row["source_frame_to_index"] = original["dataset_to_index"]
@@ -400,14 +461,13 @@ def _merged_episodes(plans, schema):
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])
+ if "subtask_index" in stats:
+ stats["subtask_index"] = {
+ metric: None for metric in stats["subtask_index"]}
+ for name, values in plan["control_stats"][episode].items():
+ stats[name] = values
+ row["stats"] = json.dumps(
+ _json_value(stats), ensure_ascii=False, separators=(",",
":"))
records.append(row)
yield pa.Table.from_pylist(records, schema=schema)
diff --git a/paimon-python/pypaimon/multimodal/lerobot/dataset.py
b/paimon-python/pypaimon/multimodal/lerobot/dataset.py
index d8f8a7bf6c..4bc750ae88 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/dataset.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/dataset.py
@@ -1099,7 +1099,7 @@ def _episode_dataset(table, datasets=None):
projection = [
name for name in _target_schema(table).names
- if not name.startswith("stats/")
+ if not name.startswith("stats/") and name != "stats"
and (datasets is None or name not in (
"source_episode_patch_json", "source_episode_json",
"source_episode_ipc"))
]
diff --git a/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
b/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
index 2d85054923..1dba47b866 100644
--- a/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
+++ b/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
@@ -16,6 +16,7 @@
import json
import sys
+from decimal import Decimal
from pathlib import Path
from unittest.mock import patch
@@ -215,8 +216,11 @@ def test_merge_numbering_stats_and_training(setup,
import_parallelism):
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)
+ assert not any(c.startswith("stats/") for c in episodes.column_names)
+ episode_stats = [json.loads(value) for value in
episodes["stats"].to_pylist()]
+ assert [item["index"]["mean"] for item in episode_stats] == [
+ [0.5], [3.0], [5.5], [8.0]]
+ assert all("q50" not in item["index"] for item in episode_stats)
info = metadata(conn, "info")
assert info["fps"] == 10
assert (info["total_frames"], info["total_episodes"], info["total_tasks"])
== (10, 4, 3)
@@ -248,6 +252,58 @@ def test_merge_numbering_stats_and_training(setup,
import_parallelism):
assert selected[0]["episode_index"].item() == 2
+def test_merge_keeps_source_specific_episode_statistics_in_json(setup):
+ conn, sources = setup
+ for index, uri in enumerate(sources):
+ path = Path(uri[7:]) / "meta/episodes/chunk-000/file-000.parquet"
+ table = pq.read_table(path)
+ name = "stats/source_%d/mean" % index
+ table = table.append_column(name, pa.array([[index + 0.5]] * 2))
+ table = table.append_column("meta/episodes/chunk_index",
pa.array([index] * 2))
+ table = table.append_column("data/vendor_%d" % index,
pa.array(["source"] * 2))
+ pq.write_table(table, path)
+
+ conn.load_from_lerobot("merged", sources)
+ episodes = episode_rows(conn, "merged__episodes")
+ assert episodes.schema.field("stats").type == pa.string()
+ assert all(episodes.schema.field(name).type == pa.string()
+ for name in ("meta", "data", "videos", "stats"))
+ assert not any(name.startswith(("meta/", "data/", "videos/", "stats/"))
+ for name in episodes.column_names)
+ for row in episodes.to_pylist():
+ stats = json.loads(row["stats"])
+ assert stats["source_%d" % row["dataset_index"]]["mean"] == [
+ row["dataset_index"] + 0.5]
+ assert "q50" not in stats["index"]
+ assert json.loads(row["meta"]) == {"episodes/chunk_index":
row["dataset_index"]}
+ assert json.loads(row["data"]) == {
+ "chunk_index": 0, "file_index": 0,
+ "vendor_%d" % row["dataset_index"]: "source"}
+ assert json.loads(row["videos"]) == {}
+
+
[email protected]("name,values", [
+ ("data/checksum", pa.array([b"\xff", None], type=pa.binary())),
+ ("meta/captured_at", pa.array(
+ [1700000000123456789, None], type=pa.timestamp("ns", tz="UTC"))),
+ ("stats/measurement/mean", pa.array(
+ [Decimal("123456789.123"), None], type=pa.decimal128(12, 3))),
+])
+def test_merge_rejects_non_json_episode_fields_before_create(setup, name,
values):
+ conn, sources = setup
+ path = Path(sources[0][7:]) / "meta/episodes/chunk-000/file-000.parquet"
+ pq.write_table(pq.read_table(path).append_column(name, values), path)
+
+ with pytest.raises(ValueError, match=(
+ "source 0 Episode field .* must use a JSON-native Arrow type")):
+ conn.load_from_lerobot("merged", sources)
+
+ for suffix in ("", "__datasets", "__episodes", "__info", "__stats",
+ "__subtasks", "__tasks"):
+ with pytest.raises(TableNotExistException):
+ conn.get_table("merged" + suffix)
+
+
@pytest.mark.parametrize("component", ["tasks", "subtasks", "episodes"])
def test_merge_ignores_producer_metadata(setup, component):
conn, sources = setup
@@ -586,6 +642,12 @@ def test_video_sources_with_identical_paths(tmp_path,
import_parallelism):
parallelism=import_parallelism, fps_mode="source")
table = conn.get_table("merged").raw_table
imported = rows(conn, "merged").sort_by("index")
+ episodes = episode_rows(conn, "merged__episodes")
+ assert not any(name.startswith("videos/") for name in
episodes.column_names)
+ for episode in episodes.to_pylist():
+ video = json.loads(episode["videos"])
+ assert set(video) == {"camera/" + suffix for suffix in (
+ "chunk_index", "file_index", "from_timestamp", "to_timestamp")}
for source_index, uri in enumerate(sources):
descriptor = VideoFrameDescriptor.deserialize(
imported["camera"][source_index * 5].as_py()).payload_descriptor
@@ -869,7 +931,9 @@ def test_merge_nullable_subtask_import(setup, tmp_path,
import_parallelism, all_
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
+ assert all(all(metric is None for metric in json.loads(value)
+ ["subtask_index"].values()) for value in
+ rows(conn, "merged__episodes")["stats"].to_pylist())
if not all_null:
windowed = pm.PaimonLeRobotDataset(
conn.get_table("merged"), delta_timestamps={"subtask_index":
[-0.1, 0, 0.1]})
@@ -973,9 +1037,10 @@ def
test_reconstructed_subtask_stats_use_output_schema(setup, import_parallelism
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] == (
+ stats = [json.loads(value) for value in episodes["stats"].to_pylist()]
+ assert [value.get("subtask_index", {}).get("mean") for value in
stats[::2]] == (
[None, None] if empty_episode else [[0.0], [1.0]])
- assert episodes.schema.field("stats/subtask_index/min").nullable
+ assert not any(name.startswith("stats/") for name in episodes.column_names)
assert rows(conn, "merged").num_rows == 10
@@ -1028,7 +1093,11 @@ def
test_default_fps_preserves_importer_contract(tmp_path, multiple, video_rate)
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]
+ episodes = rows(conn, "merged__episodes")
+ if multiple:
+ assert "fps" not in episodes.column_names
+ else:
+ assert 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:
@@ -1139,11 +1208,8 @@ def
test_merge_archives_standard_vocabulary_columns(setup, import_parallelism):
@pytest.mark.parametrize("import_parallelism", [1, 2], indirect=True)
-def test_merge_preserves_shared_arrow_episode_fields(setup,
import_parallelism):
- from decimal import Decimal
-
+def test_merge_omits_unmapped_arrow_native_episode_fields(setup,
import_parallelism):
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)
@@ -1154,12 +1220,10 @@ def
test_merge_preserves_shared_arrow_episode_fields(setup, import_parallelism):
[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")
- columns = ["native_bytes", "captured_at", "measurement"]
- episodes = episode_rows(conn, "merged__episodes").select(columns)
- expected = pa.concat_tables([table.select(columns) for table in originals])
- assert episodes.equals(expected, check_metadata=False)
+ episodes = episode_rows(conn, "merged__episodes")
+ assert not {"native_bytes", "captured_at", "measurement"}.intersection(
+ episodes.column_names)
assert rows(conn, "merged").num_rows == 10
@@ -1182,6 +1246,8 @@ def test_training_projects_out_source_archives(setup,
dataset_index):
if name.endswith("__datasets"):
assert "tasks" not in projection
assert "subtasks" not in projection
+ else:
+ assert "stats" not in projection
reads[name.rsplit("__", 1)[1]] = projection
result = read_arrow(table, projection)
if name.endswith(("__datasets", "__episodes")):
@@ -1194,6 +1260,7 @@ def test_training_projects_out_source_archives(setup,
dataset_index):
try:
assert dataset[0]["task"] == ("pick" if dataset_index is None else
"place")
assert "source_episode_patch_json" not in
dataset.meta.episodes.column_names
+ assert "stats" not in dataset.meta.episodes.column_names
assert all("tasks" not in row and "subtasks" not in row
for row in dataset.meta.datasets)
finally:
@@ -1205,7 +1272,7 @@ def test_training_projects_out_source_archives(setup,
dataset_index):
@pytest.mark.parametrize("import_parallelism", [1, 2], indirect=True)
-def test_merge_canonicalizes_episode_timezone(setup, import_parallelism):
+def test_merge_omits_unmapped_episode_timestamp(setup, import_parallelism):
conn, sources = setup
for uri in sources:
path = Path(uri[7:]) / "meta/episodes/chunk-000/file-000.parquet"
@@ -1214,8 +1281,7 @@ def test_merge_canonicalizes_episode_timezone(setup,
import_parallelism):
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("capture_time").type == pa.timestamp("ms",
tz="UTC")
- assert data["capture_time"].cast(pa.int64()).to_pylist() ==
[1700000000123, None] * 2
+ assert "capture_time" not in data.column_names
assert conn.catalog.get_tag(conn._identifier("merged"), "train") is not
None
@@ -1318,7 +1384,6 @@ def test_merge_source_specific_episode_extensions(setup,
import_parallelism, rev
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)
@@ -1329,17 +1394,13 @@ def
test_merge_source_specific_episode_extensions(setup, import_parallelism, rev
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).to_pylist()[0]
- assert row["shared_note"] == expected["shared_note"]
+ assert "shared_note" not in data.column_names
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]