Repository navigation
[python] Support heterogeneous LeRobot v3 imports #11622
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
d6ac5bb
e462986
5a925f7
f4fb2b8
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
@@ -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)) | ||
|
|
@@ -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) | ||
|
|
@@ -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: | ||
|
|
@@ -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 = [] | ||
|
|
@@ -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( | ||
| "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)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
| 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)) | ||
|
|
@@ -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 = { | ||
|
|
@@ -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": ( | ||
|
|
@@ -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, | ||
| } | ||
|
|
||
|
|
||
|
|
@@ -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)) \ | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P1] Apply
dataset_indexbefore checking feature compatibility across sourcesI could read a source with a two-element
jointsfeature throughdataset_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.