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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
263 changes: 101 additions & 162 deletions paimon-python/pypaimon/multimodal/lerobot/aggregate.py

Large diffs are not rendered by default.

10 changes: 6 additions & 4 deletions paimon-python/pypaimon/multimodal/lerobot/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,12 @@ def load_from_lerobot(
"""Import one or more LeRobot v3 sources into a new Paimon table group.

``table_name`` is the group prefix; frames are stored in ``<table_name>_frames``.
Schema evolution adds new columns by default; missing values become null.
Common fields must keep their types and feature definitions. Differing
source FPS is handled automatically. ``dataset_name`` is a label or an ordered
list of labels. ``extra_dataset_fields`` maps columns to relative UTF-8
Schema evolution adds new columns by default and fills missing values with null.
It also widens compatible frame numbers and one-dimensional array elements
from float32 to float64 or int32 to int64. Shared columns must have
compatible storage types and agree on video storage. Each Dataset retains
its own feature definitions and statistics. ``dataset_name`` is a
label or an ordered list of labels. ``extra_dataset_fields`` maps columns to relative UTF-8
text file paths or globs in each source. Globs produce maps keyed by paths
relative to their static directory prefix, without the final suffix.
``_datasets`` retains source metadata. ``tag_name`` pins component snapshots.
Expand Down
100 changes: 73 additions & 27 deletions paimon-python/pypaimon/multimodal/lerobot/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,14 @@
from pypaimon.multimodal.lerobot.loader import _DECLARED_NUMERIC_RANGES, _video_fps
from pypaimon.multimodal.lerobot.reader import _PaimonTableFrameReader
from pypaimon.multimodal.lerobot.schema import (
_NUMERIC_DTYPE_WIDENINGS,
_feature_field,
_feature_shape,
_merge_schemas,
_require_v3,
_schema_from_info,
_validate_lerobot_schema,
_widen_frame_feature,
)
from pypaimon.multimodal.lerobot.source import _info_dict
from pypaimon.multimodal.table import _target_schema, _time_travel_table
Expand Down Expand Up @@ -750,6 +753,11 @@ def __init__(self, reader, datasets, vocabulary_maps=None):
[source[2] - source[1] for source in ranges], type=pa.int64())
self._vocabulary = {}
for name, sources in (vocabulary_maps or {}).items():
if any(isinstance(source, dict) for source in sources):
self._vocabulary[name] = [
source if isinstance(source, dict) else dict(enumerate(source))
for source in sources]
continue
offsets, counts, values = [], [], []
for source in sources:
offsets.append(len(values))
Expand Down Expand Up @@ -810,18 +818,25 @@ def read_indices(self, indices, columns):
data.schema.get_field_index("episode_index"),
data.schema.field("episode_index"), ordinals)
for name in mapped:
offsets, counts, values = self._vocabulary[name]
vocabulary = self._vocabulary[name]
try:
local_ids = data[name]
if name == "task_index" and local_ids.null_count:
raise ValueError("LeRobot frame has an invalid source task_index.")
valid = pc.and_(pc.greater_equal(local_ids, 0),
pc.less(local_ids, pc.take(counts, source_ids)))
if not pc.all(pc.fill_null(valid, True)).as_py():
raise ValueError("LeRobot frame has an invalid source %s." % name)
translated = pc.take(
values, pc.add_checked(pc.take(offsets, source_ids), local_ids))
except (pa.ArrowInvalid, pa.ArrowIndexError, TypeError) as error:
if isinstance(vocabulary, list):
translated = pa.array([vocabulary[source_id][task_id]
for source_id, task_id in zip(
source_ids.to_pylist(), data[name].to_pylist())],
type=pa.int64())
else:
offsets, counts, values = vocabulary
local_ids = data[name]
if name == "task_index" and local_ids.null_count:
raise ValueError("LeRobot frame has an invalid source task_index.")
valid = pc.and_(pc.greater_equal(local_ids, 0),
pc.less(local_ids, pc.take(counts, source_ids)))
if not pc.all(pc.fill_null(valid, True)).as_py():
raise ValueError("LeRobot frame has an invalid source %s." % name)
translated = pc.take(
values, pc.add_checked(pc.take(offsets, source_ids), local_ids))
except (KeyError, pa.ArrowInvalid, pa.ArrowIndexError, TypeError) as error:
raise ValueError("LeRobot frame has an invalid source %s." % name) from error
data = data.set_column(data.schema.get_field_index(name),
data.schema.field(name), translated)
Expand Down Expand Up @@ -1126,7 +1141,7 @@ def _load_dataset(table, tag_name):

info = (json.loads(source_rows[0]["info"])
if not source_local_layout else _merged_source_info(
source_rows, tasks, subtasks))
source_rows, tasks, subtasks, _target_schema(frames)))
for feature in info.get("features", {}).values():
feature["shape"] = tuple(feature["shape"])
if source_local_layout:
Expand Down Expand Up @@ -1158,28 +1173,33 @@ def _source_vocabulary(sources, singular):
raise ValueError("LeRobot sources disagree on %s metadata." % field)
by_text, rows, maps = {}, [], []
for ordinal, entries in enumerate(values):
mapping = [None] * len(entries)
labels = {}
seen = set()
for entry in entries:
local, label = entry[index], entry[singular]
if not isinstance(local, int) or not 0 <= local < len(entries) \
or mapping[local] is not None or not isinstance(label, str) \
or label in seen:
if not isinstance(local, int) or local < 0 or local in labels \
or not isinstance(label, str) or label in seen:
raise ValueError("LeRobot source %d has invalid %s metadata." %
(ordinal, field))
seen.add(label)
mapping[local] = label
for local, label in enumerate(mapping):
labels[local] = label
mapping = {}
for local, label in sorted(labels.items()):
if label not in by_text:
by_text[label] = len(rows)
rows.append({index: len(rows), singular: label})
mapping[local] = by_text[label]
maps.append(mapping)
if list(mapping) == list(range(len(mapping))):
maps.append(list(mapping.values()))
elif singular == "task":
maps.append(mapping)
else:
raise ValueError("LeRobot source %d has invalid %s metadata." % (ordinal, field))
frame = pd.DataFrame(rows, columns=[index, singular]).set_index(singular)
return frame, maps


def _merged_source_info(sources, tasks, subtasks):
def _merged_source_info(sources, tasks, subtasks, frame_schema):
if not sources:
raise ValueError("LeRobot Dataset metadata is required for info.")
infos = []
Expand All @@ -1195,14 +1215,30 @@ def _merged_source_info(sources, tasks, subtasks):
merged["features"] = {}
for info in infos:
for name, feature in info["features"].items():
merged["features"].setdefault(name, copy.deepcopy(feature))
for field in _merge_schemas([_schema_from_info(info) for info in infos]):
previous = merged["features"].get(name)
if previous is None:
merged["features"][name] = copy.deepcopy(feature)
continue
previous_dtype = previous["dtype"]
dtype = feature["dtype"]
if (_NUMERIC_DTYPE_WIDENINGS.get(previous_dtype, previous_dtype)
!= _NUMERIC_DTYPE_WIDENINGS.get(dtype, dtype)
or _feature_shape(previous, name) != _feature_shape(feature, name)
or previous.get("names") != feature.get("names")):
raise ValueError(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P1] Apply dataset_index before checking feature compatibility across sources

I could read a source with a two-element joints feature through dataset_index=0. After appending a source with three elements, the same reader fails to initialize because _load_dataset() checks the entire group's feature definitions before applying the source selection. Please select the source first and use that Dataset's feature definitions, statistics, and frame ranges.

"LeRobot feature %s has different definitions across Datasets. "
"Read the table by dataset_id and use each Dataset's info." % name)
for field in _merge_schemas([_schema_from_info(info) for info in infos], widen_numeric=True):
if field.name in frame_schema.names:
_widen_frame_feature(merged["features"][field.name], frame_schema.field(field.name))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Validate timestamps using the source Dataset's dtype

After widening, the reader uses float64 to compute the expected timestamp for existing float32 rows. At 30 FPS, the stored timestamp for frame_index=61441 is 2048.033447265625 after widening. The reader expects 2048.0333333333333 and rejects the row at the default 1e-4 tolerance. Please keep the widened storage type and use the source Dataset's timestamp dtype for validation.

if field.nullable:
merged["features"][field.name]["nullable"] = True
for key in list(merged):
if key not in _REBUILT_INFO and key not in ("codebase_version", "robot_type", "fps") \
and any(info.get(key) != merged[key] for info in infos):
del merged[key]
if any(info.get("robot_type") != merged.get("robot_type") for info in infos):
merged["robot_type"] = None
merged.update(total_frames=sum(info["total_frames"] for info in infos),
total_episodes=sum(info["total_episodes"] for info in infos),
total_tasks=len(tasks))
Expand Down Expand Up @@ -1237,10 +1273,8 @@ def _merged_source_info(sources, tasks, subtasks):

def _merged_source_stats(sources, episodes_table):
values = [source.get("stats") for source in sources]
if all(value is None for value in values):
return None
if any(value is None for value in values):
raise ValueError("LeRobot sources disagree on stats metadata.")
return None
decoded = [json.loads(value) for value in values]
names = dict.fromkeys(name for value in decoded for name in value)
merged = {
Expand Down Expand Up @@ -1550,6 +1584,18 @@ def _build_frame_validation_context(
subtask_names = _index_names(subtasks, "subtask_index")
episode_tasks = _episode_tasks(metadata) \
if episode_ranges is not None else None
datasets = _metadata_member(metadata, "datasets")
if datasets is None:
timestamp_types = [timestamp_type] * len(episode_fps)
else:
timestamp_types = []
for info, begin, end, _, _ in _source_dataset_ranges(datasets):
features = info.get("features")
timestamp = features.get("timestamp") if isinstance(features, dict) else None
source_type = timestamp_type
if isinstance(timestamp, dict) and timestamp.get("dtype") is not None:
source_type = _feature_field("timestamp", timestamp).type
timestamp_types.extend([source_type] * (end - begin))
return {
"episode_ranges": episode_ranges,
"episode_ends": (
Expand All @@ -1559,7 +1605,7 @@ def _build_frame_validation_context(
"task_names": task_names,
"subtask_names": subtask_names,
"episode_tasks": episode_tasks,
"timestamp_type": timestamp_type,
"timestamp_types": timestamp_types,
}


Expand Down Expand Up @@ -1810,7 +1856,7 @@ def _validate_control_row(index, row, validation_context, tolerance_s):
timestamp = row.get("timestamp")
expected_timestamp = pa.scalar(
frame / validation_context["episode_fps"][episode],
type=validation_context["timestamp_type"],
type=validation_context["timestamp_types"][episode],
).as_py()
if isinstance(timestamp, bool) or not isinstance(timestamp, (int, float)) \
or not math.isfinite(float(timestamp)) \
Expand Down
Loading
Loading