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 2a769723c0 [python] Preserve source LeRobot Episode statistics (#11082)
2a769723c0 is described below
commit 2a769723c04a127a590ee2c148dac31bb25100f8
Author: XiaoHongbo <[email protected]>
AuthorDate: Mon Nov 16 00:04:51 2026 +0800
[python] Preserve source LeRobot Episode statistics (#11082)
---
docs/docs/pypaimon/lerobot.md | 7 +-
.../pypaimon/multimodal/lerobot/aggregate.py | 50 ++++++++---
.../pypaimon/multimodal/lerobot/dataset.py | 47 +++++++++--
.../pypaimon/tests/lerobot_aggregate_test.py | 97 +++++++++++++++++++---
4 files changed, 164 insertions(+), 37 deletions(-)
diff --git a/docs/docs/pypaimon/lerobot.md b/docs/docs/pypaimon/lerobot.md
index 7367541c7e..00f34e40da 100644
--- a/docs/docs/pypaimon/lerobot.md
+++ b/docs/docs/pypaimon/lerobot.md
@@ -189,6 +189,9 @@ conn.load_from_lerobot(
)
```
+Each source has one row in `_datasets`. Episode `stats` preserves the source
+values; `_datasets.__paimon_lerobot_read_control_stats` stores derived
statistics for the
+combined training reader.
`dataset_name` accepts a string for one source or a list/tuple with one label
per
source in input order. Omitted names are null, and duplicate labels do not
merge
sources. [Dataset fields](#dataset-fields) describes the retained source
metadata.
@@ -200,8 +203,8 @@ rejected before any target table is created. Episode fields
without `/` retain
their original names and Paimon-supported Arrow types as columns in
`_episodes`;
unsupported types are rejected before table creation.
Training metadata reads only Episode controls; query `_episodes` for
extensions.
-Control-field statistics reflect merged IDs; their original quantiles are
-omitted. Training reads skip `stats`. Repeated task/subtask text within one
+Episode statistics retain the original source values, including quantiles.
+Training reads skip Episode `stats`. Repeated task/subtask text within one
source is rejected before creating tables to avoid losing original frame IDs.
Sources must share robot type and compatible definitions for common features.
Each source retains its own
diff --git a/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
b/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
index d873484345..1a8ba272d3 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
@@ -70,6 +70,8 @@ _REBUILT_INFO = {
"data_files_size_in_mb", "video_files_size_in_mb", "features",
}
_DATASET_ID_COLUMN = "dataset_id"
+_READ_CONTROL_STATS_COLUMN = "__paimon_lerobot_read_control_stats"
+_READ_CONTROL_STATS_DESCRIPTION = "pypaimon.lerobot.read-control-stats"
_EPISODE_VARIANT_GROUPS = ("meta", "data", "videos", "stats")
_EPISODE_EXTRA_VARIANT_GROUP_DESCRIPTION =
"pypaimon.lerobot.episode-variant-group"
_VARIANT_TYPE = pa.struct([
@@ -91,6 +93,8 @@ _DATASETS_SCHEMA = pa.schema([
pa.field("tasks", _SOURCE_TASKS_TYPE, nullable=False),
pa.field("subtasks", _SOURCE_SUBTASKS_TYPE),
pa.field("stats", pa.string()),
+ pa.field(_READ_CONTROL_STATS_COLUMN, pa.string(),
+ metadata={b"description":
_READ_CONTROL_STATS_DESCRIPTION.encode("utf-8")}),
])
@@ -449,6 +453,7 @@ def _plan_merge(plans, extra_dataset_fields=None,
schema_evolution=True,
"tasks": _vocabulary_rows(plan["metadata"]["source_tasks_table"],
"task"),
"subtasks":
_vocabulary_rows(plan["metadata"]["source_subtasks_table"], "subtask"),
"stats": _stats_json(plan["metadata"]["stats_table"]),
+ _READ_CONTROL_STATS_COLUMN: None,
**plan.get("extra_dataset_fields", {}),
}
for ordinal, plan in enumerate(plans)
@@ -512,6 +517,8 @@ def _transform_frames(plan, batch, episode):
column, pa.scalar(offset, type=column.type))
elif name == "episode_index":
values = column
+ stat_column = pc.add_checked(
+ column, pa.scalar(plan["episode_offset"], type=column.type))
else:
mapping = plan[name]
mapped = pa.array([
@@ -521,8 +528,8 @@ def _transform_frames(plan, batch, episode):
], type=column.type)
values = column
batch = batch.set_column(batch.schema.get_field_index(name),
batch.schema.field(name), values)
- if name != "index":
- stat_column = mapped if name in ("task_index", "subtask_index")
else values
+ if name in ("task_index", "subtask_index"):
+ stat_column = mapped
stat_values = ([value for value in stat_column.to_pylist()
if value is not None]
if stat_column.null_count else stat_column.to_numpy())
@@ -573,18 +580,8 @@ def _merged_episodes(plans, schema):
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
+ stats.setdefault(feature, {})[statistic] = value
row[_DATASET_ID_COLUMN] = plan[_DATASET_ID_COLUMN]
- episode = row["episode_index"]
- if "subtask_index" not in plan["control_stats"][episode]:
- 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"] = _variant_value(stats)
records.append(row)
episode_offset += 1
@@ -593,6 +590,21 @@ def _merged_episodes(plans, schema):
raise ValueError("LeRobot Episode metadata changed after
validation.")
+def _store_read_control_stats(metadata, plans):
+ rows = metadata["datasets_table"].to_pylist()
+ for plan, row in zip(plans, rows):
+ stats = {}
+ for name in _CONTROLS:
+ parts = [values[name] for values in plan["control_stats"].values()
+ if name in values]
+ if parts:
+ stats[name] = _merge_stats(parts)
+ row[_READ_CONTROL_STATS_COLUMN] = json.dumps(
+ _json_value(stats), ensure_ascii=False, separators=(",", ":"))
+ metadata["datasets_table"] = pa.Table.from_pylist(
+ rows, schema=metadata["datasets_table"].schema)
+
+
def _import_sources(connection, table_name, sources, batch_size, options,
source_options, tag_name, parallelism=1,
dataset_name=None, extra_dataset_fields=None,
@@ -645,6 +657,15 @@ def _import_sources(connection, table_name, sources,
batch_size, options,
identifiers = _companion_table_identifiers(table.raw_table)
tables = {name: connection.catalog.get_table(identifier)
for name, identifier in identifiers.items()}
+ datasets_schema = _target_schema(tables["datasets"])
+ if _READ_CONTROL_STATS_COLUMN in datasets_schema.names:
+ field = datasets_schema.field(_READ_CONTROL_STATS_COLUMN)
+ if (field.metadata or {}).get(b"description") != \
+ _READ_CONTROL_STATS_DESCRIPTION.encode("utf-8"):
+ raise ValueError(
+ "LeRobot append cannot use internal Dataset column %s:
"
+ "the existing column is user-defined."
+ % _READ_CONTROL_STATS_COLUMN)
if tag_name is not None:
for component in (table.raw_table, *tables.values()):
if _tag_snapshot_id(connection.catalog,
component.identifier,
@@ -745,8 +766,10 @@ def _import_sources(connection, table_name, sources,
batch_size, options,
tables = {name: connection.catalog.get_table(component.identifier)
for name, component in tables.items()}
frame_offset = ranges[-1][4]
+ episode_offset = ranges[-1][2]
for plan in plans:
plan["frame_offset"] += frame_offset
+ plan["episode_offset"] += episode_offset
metadata["datasets_table"] = pa.Table.from_pylist(
metadata["datasets_table"].to_pylist(),
schema=_target_schema(tables["datasets"]))
@@ -777,6 +800,7 @@ def _import_sources(connection, table_name, sources,
batch_size, options,
transform=partial(_transform_frames, plan)))
plan["dataset_resources"].close()
plan["dataset"] = None
+ _store_read_control_stats(metadata, plans)
for episodes in _merged_episodes(plans, episode_schema):
strict_arrow_table(episodes, episode_schema,
"merged Episodes", 0, "LeRobot")
diff --git a/paimon-python/pypaimon/multimodal/lerobot/dataset.py
b/paimon-python/pypaimon/multimodal/lerobot/dataset.py
index 314fb6455b..e6887f4858 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/dataset.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/dataset.py
@@ -40,7 +40,8 @@ import pyarrow.compute as pc
from pypaimon.data.generic_variant import GenericVariant
from pypaimon.multimodal.lerobot.aggregate import (
- _CONTROLS, _REBUILT_INFO, _merge_stats,
+ _CONTROLS, _READ_CONTROL_STATS_COLUMN, _READ_CONTROL_STATS_DESCRIPTION,
+ _REBUILT_INFO, _merge_stats,
)
from pypaimon.common.options.core_options import CoreOptions
from pypaimon.multimodal.lerobot.metadata import (
@@ -1096,11 +1097,16 @@ def _load_dataset(table, tag_name):
source_local_layout = "dataset_id" in _target_schema(episodes_table).names
datasets_table = _component_table(
catalog, catalog.get_table(identifiers["datasets"]), tag_name)
- source_rows = _read_arrow(datasets_table, [
- "id", "name", "info", "tasks", "subtasks", "stats",
- ]).sort_by("id").to_pylist()
+ source_columns = ["id", "name", "info", "tasks", "subtasks", "stats"]
+ datasets_schema = _target_schema(datasets_table)
+ if _READ_CONTROL_STATS_COLUMN in datasets_schema.names:
+ field = datasets_schema.field(_READ_CONTROL_STATS_COLUMN)
+ if (field.metadata or {}).get(b"description") == \
+ _READ_CONTROL_STATS_DESCRIPTION.encode("utf-8"):
+ source_columns.append(_READ_CONTROL_STATS_COLUMN)
+ source_rows = _read_arrow(datasets_table,
source_columns).sort_by("id").to_pylist()
datasets = ([{key: value for key, value in row.items()
- if key not in ("tasks", "subtasks", "stats")}
+ if key not in ("tasks", "subtasks", "stats",
_READ_CONTROL_STATS_COLUMN)}
for row in source_rows] if source_local_layout else None)
episodes = _episode_dataset(episodes_table, datasets)
tasks, task_maps = _source_vocabulary(source_rows, "task")
@@ -1235,10 +1241,33 @@ def _merged_source_stats(sources, episodes_table):
for name in names if name not in _CONTROLS}
columns = _target_schema(episodes_table).names
if "stats" in columns:
- stats_rows = _read_arrow(episodes_table,
["stats"])["stats"].to_pylist()
- decoded_rows = [GenericVariant.from_arrow_struct(raw).to_python()
- if isinstance(raw, dict) else json.loads(raw)
- for raw in stats_rows if raw]
+ decoded_rows = []
+ legacy_ids = {source["id"] for source in sources
+ if not source.get(_READ_CONTROL_STATS_COLUMN)}
+ legacy_stats = {}
+ if legacy_ids:
+ legacy_rows = _read_arrow(episodes_table, ["dataset_id",
"stats"]).to_pylist()
+ for row in legacy_rows:
+ if row["dataset_id"] not in legacy_ids or not row["stats"]:
+ continue
+ raw = row["stats"]
+ stats = (GenericVariant.from_arrow_struct(raw).to_python()
+ if isinstance(raw, dict) else json.loads(raw))
+ legacy_stats.setdefault(row["dataset_id"], []).append(stats)
+ for source, (_, episode_offset, _, _, _) in zip(
+ sources, _source_dataset_ranges(sources)):
+ raw = source.get(_READ_CONTROL_STATS_COLUMN)
+ if raw:
+ decoded_rows.append(json.loads(raw))
+ else:
+ for stats in legacy_stats.get(source["id"], []):
+ episode = stats.get("episode_index")
+ if episode:
+ for name in ("min", "max", "mean"):
+ if episode.get(name) is not None:
+ episode[name] = [value + episode_offset
+ for value in episode[name]]
+ decoded_rows.append(stats)
for name in _CONTROLS:
parts = [row[name] for row in decoded_rows if name in row
and row[name].get("count") is not None]
diff --git a/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
b/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
index 0e9c1eebaf..9921d3e755 100644
--- a/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
+++ b/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
@@ -339,7 +339,7 @@ def test_append_preserves_episode_group_kind(setup):
]
-def test_append_episode_task_stats_use_group_vocabulary(setup):
+def test_append_preserves_source_episode_stats(setup):
conn, sources = setup
conn.load_from_lerobot("robot", [sources[0]])
conn.append_to_lerobot("robot", sources[1])
@@ -349,9 +349,9 @@ def
test_append_episode_task_stats_use_group_vocabulary(setup):
for row in episodes]
subtask_means = [variant_value(row["stats"])["subtask_index"]["mean"][0]
for row in episodes]
- assert task_means == [0, 1, 1, 2]
- assert subtask_means == pytest.approx([0.5, 1 / 3, 1.5, 4 / 3])
- assert sum(mean * count for mean, count in zip(task_means, (2, 3, 2, 3)))
/ 10 == 1.1
+ assert task_means == [0, 1, 0, 1]
+ assert subtask_means == pytest.approx([0.5, 1 / 3, 0.5, 1 / 3])
+ assert all("q50" in variant_value(row["stats"])["task_index"] for row in
episodes)
pytest.importorskip("datasets")
pytest.importorskip("torch")
@@ -359,10 +359,66 @@ def
test_append_episode_task_stats_use_group_vocabulary(setup):
try:
frames = dataset.reader.get_items(range(10))
assert [int(row["task_index"]) for row in frames] == [0] * 2 + [1] * 5
+ [2] * 3
+ assert dataset.reader.meta.stats["task_index"]["mean"] ==
pytest.approx([1.1])
+ assert dataset.reader.meta.stats["episode_index"]["mean"] ==
pytest.approx([1.6])
finally:
dataset.close()
+def test_legacy_user_read_control_stats_remains_text(setup, monkeypatch):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn, sources = setup
+ for uri in sources:
+ (Path(uri[7:]) / "notes.txt").write_text("ordinary text")
+ extra = {"read_control_stats": "notes.txt"}
+ with monkeypatch.context() as old_writer:
+ schema = aggregate._DATASETS_SCHEMA
+ old_writer.setattr(aggregate, "_DATASETS_SCHEMA", schema.remove(
+ schema.get_field_index(aggregate._READ_CONTROL_STATS_COLUMN)))
+ old_writer.setattr(aggregate, "_store_read_control_stats", lambda
metadata, plans: None)
+ conn.load_from_lerobot("robot", sources[0], extra_dataset_fields=extra)
+
+ conn.append_to_lerobot("robot", sources[1], extra_dataset_fields=extra)
+ datasets = rows(conn, "robot_datasets")
+ assert datasets["read_control_stats"].to_pylist() == ["ordinary text"] * 2
+ assert aggregate._READ_CONTROL_STATS_COLUMN in datasets.column_names
+ assert sum(value is not None for value in
+ datasets[aggregate._READ_CONTROL_STATS_COLUMN].to_pylist()) == 1
+ from pypaimon.multimodal.table import _target_schema
+ field = _target_schema(conn.get_table("robot_datasets").raw_table).field(
+ aggregate._READ_CONTROL_STATS_COLUMN)
+ assert (field.metadata or {}).get(b"description") == \
+ aggregate._READ_CONTROL_STATS_DESCRIPTION.encode("utf-8")
+ reader = pm.PaimonLeRobotDataset(conn.get_table("robot_frames"))
+ try:
+ assert reader.reader.meta.stats["index"]["mean"] ==
pytest.approx([4.5])
+ assert reader.reader.meta.stats["episode_index"]["mean"] ==
pytest.approx([1.6])
+ finally:
+ reader.close()
+
+
+def test_append_rejects_legacy_user_column_named_internal_stats(setup,
monkeypatch):
+ conn, sources = setup
+ path = Path(sources[0][7:]) / "notes.txt"
+ path.write_text("ordinary text")
+ name = aggregate._READ_CONTROL_STATS_COLUMN
+ with monkeypatch.context() as old_writer:
+ schema = aggregate._DATASETS_SCHEMA
+ old_writer.setattr(aggregate, "_DATASETS_SCHEMA", schema.remove(
+ schema.get_field_index(name)))
+ old_writer.setattr(aggregate, "_store_read_control_stats", lambda
metadata, plans: None)
+ conn.load_from_lerobot("robot", sources[0],
extra_dataset_fields={name: "notes.txt"})
+
+ with pytest.raises(ValueError, match="existing column is user-defined"):
+ conn.append_to_lerobot("robot", sources[1])
+ assert rows(conn, "robot_frames").num_rows == 5
+ assert rows(conn, "robot_episodes").num_rows == 2
+ datasets = rows(conn, "robot_datasets")
+ assert datasets.num_rows == 1
+ assert datasets[name].to_pylist() == ["ordinary text"]
+
+
@pytest.mark.parametrize("setup", [20], indirect=True)
def test_append_mixed_fps_group_remains_readable(setup):
pytest.importorskip("datasets")
@@ -481,6 +537,7 @@ def test_transform_frames_preserves_unlabelled_subtasks():
assert "source_index" not in converted.column_names
assert converted["task_index"].to_pylist() == [0, 0]
assert converted["subtask_index"].to_pylist() == [0, None]
+ assert plan["control_stats"][0]["episode_index"]["mean"] == [2.0]
assert plan["control_stats"][0]["subtask_index"]["count"] == [1]
@@ -527,7 +584,9 @@ def test_merge_numbering_stats_and_training(setup,
import_parallelism):
assert "source_frame_from_index" not in episodes.column_names
assert "source_frame_to_index" not in episodes.column_names
datasets = rows(conn, "merged_datasets").sort_by("id")
- assert datasets.column_names == ["id", "name", "info", "tasks",
"subtasks", "stats"]
+ assert datasets.column_names == [
+ "id", "name", "info", "tasks", "subtasks", "stats",
+ aggregate._READ_CONTROL_STATS_COLUMN]
assert datasets["name"].to_pylist() == [None, None]
assert "fps" not in datasets.column_names
assert [json.loads(value)["fps"] for value in
datasets["info"].to_pylist()] == [10, 10]
@@ -545,8 +604,9 @@ def test_merge_numbering_stats_and_training(setup,
import_parallelism):
assert not any(c.startswith("stats/") for c in episodes.column_names)
episode_stats = [variant_value(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)
+ [0.5], [3.0], [0.5], [3.0]]
+ assert all(item["index"]["q50"] == [0.0] for item in episode_stats)
+ assert metadata(conn, "stats")["task_index"]["mean"] ==
pytest.approx([1.1])
pytest.importorskip("datasets")
torch = pytest.importorskip("torch")
dataset = pm.PaimonLeRobotDataset(
@@ -561,6 +621,8 @@ def test_merge_numbering_stats_and_training(setup,
import_parallelism):
for name in ("index", "episode_index", "task_index", "subtask_index",
"observation.state", "action"):
values = np.array(([0, 0, 1, 1, 1, 1, 1, 2, 2, 2] if name ==
"task_index"
else [0, 1, 0, 1, 0, 1, 2, 1, 2, 1] if name ==
"subtask_index"
+ else [0, 0, 1, 1, 1, 2, 2, 3, 3, 3]
+ if name == "episode_index"
else list(range(10)) if name == "index"
else data[name].to_pylist()))
np.testing.assert_allclose(stats[name]["mean"],
np.atleast_1d(values.mean(0)))
@@ -600,9 +662,19 @@ def
test_merge_keeps_source_specific_episode_statistics_in_variant(setup):
for name in episodes.column_names)
for row in episodes.to_pylist():
stats = variant_value(row["stats"])
+ source_path = Path(sources[row["dataset_index"]][7:])
+ source_episodes = pq.read_table(
+ source_path /
"meta/episodes/chunk-000/file-000.parquet").to_pylist()
+ original = source_episodes[row["episode_index"]]
+ expected = {}
+ for name, value in original.items():
+ if name.startswith("stats/"):
+ feature, statistic = name[6:].rsplit("/", 1)
+ expected.setdefault(feature, {})[statistic] = value
+ assert stats == expected
assert stats["source_%d" % row["dataset_index"]]["mean"] == [
row["dataset_index"] + 0.5]
- assert "q50" not in stats["index"]
+ assert stats["index"]["q50"] == [0.0]
assert variant_value(row["meta"]) == {"episodes/chunk_index":
row["dataset_index"]}
assert variant_value(row["data"]) == {
"chunk_index": 0, "file_index": 0,
@@ -1280,9 +1352,8 @@ 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 all(all(metric is None for metric in variant_value(value)
- ["subtask_index"].values()) for value in
- rows(conn, "merged_episodes")["stats"].to_pylist())
+ assert all(variant_value(value)["subtask_index"]["mean"] is not None
+ for value in rows(conn,
"merged_episodes")["stats"].to_pylist())
if not all_null:
windowed = pm.PaimonLeRobotDataset(
conn.get_table("merged_frames"),
delta_timestamps={"subtask_index": [-0.1, 0, 0.1]})
@@ -1347,7 +1418,7 @@ def
test_episode_fps_rejects_conflicting_video_feature(tmp_path):
@pytest.mark.parametrize("import_parallelism", [1, 2], indirect=True)
@pytest.mark.parametrize("empty_episode", [False, True])
-def test_reconstructed_subtask_stats_use_output_schema(setup,
import_parallelism, empty_episode):
+def test_source_subtask_stats_are_preserved(setup, import_parallelism,
empty_episode):
conn, sources = setup
for uri in sources:
root = Path(uri[7:])
@@ -1372,7 +1443,7 @@ def
test_reconstructed_subtask_stats_use_output_schema(setup, import_parallelism
episodes = episode_rows(conn, "merged_episodes")
stats = [variant_value(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]])
+ [[0.5], [0.5]] if empty_episode else [None, None])
assert not any(name.startswith("stats/") for name in episodes.column_names)
assert rows(conn, "merged_frames").num_rows == 10