Repository navigation
[python] Export LeRobot v2/v3 datasets to Object Tables - #11299
XiaoHongbo-Hope wants to merge 36 commits into
Conversation
|
Do we really need to support 2.0 and 2.1? |
Yes, some users still use version 2.x |
JingsongLi
left a comment
There was a problem hiding this comment.
I found two issues that can affect normal use. Concurrent exports can mix file layouts under the same Dataset ID, and the v2.1 reader fails when sampling exported image columns. The inline comments include the triggering cases and suggested fixes.
|
|
||
|
|
||
| def _upload_to_object_table(stage, prefix, file_io): | ||
| if _prefix_has_files(file_io, prefix): |
There was a problem hiding this comment.
[P1] Reserve the Dataset prefix atomically before publishing
Two exports of the same Dataset can both pass the prefix and per-file existence checks before either write is visible. Running the upload step concurrently on the FUSE path with v2.1 and v3.0 Parquet layouts reproduced the race. Both uploads returned successfully and left both layouts under the same prefix. If v3 metadata wins, the v3 reader can load duplicate frame rows because it scans all Parquet files under data/. Please acquire an exclusive reservation for the destination prefix before uploading any files.
There was a problem hiding this comment.
[P1] Reserve the Dataset prefix atomically before publishing
Two exports of the same Dataset can both pass the prefix and per-file existence checks before either write is visible. Running the upload step concurrently on the FUSE path with v2.1 and v3.0 Parquet layouts reproduced the race. Both uploads returned successfully and left both layouts under the same prefix. If v3 metadata wins, the v3 reader can load duplicate frame rows because it scans all Parquet files under
data/. Please acquire an exclusive reservation for the destination prefix before uploading any files.
Thanks, the race is real. I intended this PR to support one writer per Dataset ID. Cross-process exclusion needs a FileIO contract across OSS, FUSE, and REST, which would substantially widen this PR. I'm torn between keeping this PR focused and making the export API safe. What is your suggestion for this ?
There was a problem hiding this comment.
Rechecked 716e1ba994 with real FuseLocalFileIO. I paused v2.1 before its first upload, let v3.0 finish, then resumed v2.1. The resumed export wrote its two Parquet files and failed on the already published meta/paimon_source.json. The v3 marker still declared 5 frames while its data/ directory held 10 rows. The single-exporter requirement therefore needs to be enforced for each Object Table and Dataset ID, including retries and overlapping jobs.
| frame_columns = list(info["features"]) | ||
| columns = ["dataset_id"] + frame_columns | ||
| physical_schema = _target_schema(reader._table) | ||
| frame_schema = pa.schema([ |
There was a problem hiding this comment.
[P1] Preserve the Hugging Face Image feature in v2 Parquet
The exported image column is an Arrow struct without Hugging Face Image metadata. I loaded both v2.0 and v2.1 exports through datasets.load_dataset("parquet", ...) and got a {bytes, path} dict for each image. LeRobot's v2.1 reader infers features from Parquet and passes the dict to torch.tensor when fetching a sample, which raises an error. Please emit the Image metadata and test fetching an image sample with the legacy reader.
| episode_schema, version, batch_size) | ||
| reader.close() | ||
| reader = None | ||
| _upload_to_object_table(stage, target_uri, table.file_io) |
There was a problem hiding this comment.
[P2] Make an interrupted upload retryable
I injected a transient I/O error immediately before uploading meta/info.json. The files already uploaded remained in the target prefix, and a retry with healthy I/O immediately raised FileExistsError. Once the exporter owns the prefix, please clean up its partial upload on failure or provide a way to resume it.
| prefix = "videos/%s/" % key | ||
| episode[prefix + "chunk_index"] = chunk_index | ||
| episode[prefix + "file_index"] = file_index | ||
| if reader._table.options.options.get( |
There was a problem hiding this comment.
[P2] Use the stored clip's timeline for v3 video metadata
The write option can change after a clip has been stored. If an Episode was imported with remuxing enabled and the option is later disabled, export copies the remuxed clip while retaining the original video's Episode offset. A reproduction using an FFmpeg-remuxed clip started at 0.0s while the exported metadata pointed to 0.2s. Re-import failed when looking up frames. Please derive the offset from the copied payload and its frame descriptors.
|
|
||
| preserved = {field.name: field for field in source_schema or [] | ||
| if field.name in names} | ||
| inferred_names = [name for name in names if name not in preserved] |
There was a problem hiding this comment.
[P2] Preserve uint64 Episode extension fields on export
The existing test_episode_variant_preserves_uint64 fixture imports meta/large_id = 2**64 - 1 and stores it in the VARIANT as a Decimal. With the inferred export schema, the field becomes decimal128(20, 0) and load_from_lerobot rejects the exported dataset because the Episode field must use a JSON-native Arrow type. Please preserve the uint64 Arrow type when reconstructing the grouped field and cover this import/export/re-import case.
| video_frames = {key: [] for key in video_keys} | ||
| for offset in range(begin, end, batch_size): | ||
| indices = list(range(offset, min(offset + batch_size, end))) | ||
| table = reader.read_keys( |
There was a problem hiding this comment.
[P2] Apply the full frame predicate when the Python index lookup is inexact
In a multi-Dataset group using the Python reader, I dropped the dataset_id BTree and kept the index BTree. The lookup then returned rows from both Datasets for the same source-local frame index, causing LeRobot source Frame range is incomplete for a valid Dataset. _FrameLocator skips the residual filter when index coverage is complete, even when evaluation.result.is_exact() is false. Keep applying the full (dataset_id, index) predicate for inexact lookup results.
| parsed = urlparse(object_location) | ||
| if parsed.scheme != "oss" or not parsed.netloc: | ||
| raise ValueError("Object Table output must use OSS storage.") | ||
| try: |
There was a problem hiding this comment.
[P2] Resolve the group prefix when an unrelated table has the same name
An existing multimodal table named robot can coexist with a LeRobot group imported as robot_frames and its companion tables. In that setup the documented export_to_lerobot("robot", ...) resolves the unrelated table and fails on missing group metadata. Please accept the exact name only if it resolves to a managed Frames table, then try <prefix>_frames otherwise.
| raise ValueError( | ||
| "LeRobot v2 export supports RGB video without audio; " | ||
| "%s has depth or audio." % key) | ||
| output_info.update( |
There was a problem hiding this comment.
[P2] Supply robot_type for v2 exports from the direct writer
PaimonLeRobotWriter can produce info without a robot_type key, and the default is added only in the v3 branch. The v2.1 reader indexes that key directly, so accessing dataset.meta.robot_type raises KeyError for a direct-writer export. Please move the robot_type=None default before the version split.
JingsongLi
left a comment
There was a problem hiding this comment.
I rechecked cec7a7fdf7. Image decoding now works in all three output formats. I reproduced data loss during rollback and several format compatibility issues, and the merge build still fails on the new tests.
| except Exception as error: | ||
| # No info.json was published, so this attempt cannot be consumed yet. | ||
| # The destination is owned by one exporter at a time. | ||
| _clean_failed_upload(prefix, file_io, error) |
There was a problem hiding this comment.
[P1] Guard rollback with exclusive ownership
I paused export A after its prefix check, let export B finish, and then resumed A using FuseLocalFileIO. A hit FileExistsError on B's data file, and this cleanup deleted B's entire published dataset, including meta/info.json. Please acquire the destination prefix atomically before uploading and limit cleanup to objects owned by the failed attempt.
| output_info.setdefault("chunks_size", 1000) | ||
| output_info.setdefault("data_files_size_in_mb", 100) | ||
| output_info.setdefault("video_files_size_in_mb", 200) | ||
| output_info.setdefault("data_path", _V3_DATA_PATH) |
There was a problem hiding this comment.
[P2] Generate canonical paths for v3 output
I imported a source with data_path under frames/. The export succeeded. The LeRobot reader only discovers frame Parquet under data/. I also reproduced a collision with a literal video_path and Episode remuxing enabled. Two Episode mappings pointed to the same filename, and the second clip overwrote the first. Please generate canonical v3 output paths and update the Episode mappings to match.
| if frame_index >= len(v3_video_times[identity]): | ||
| raise ValueError( | ||
| "LeRobot video descriptor points beyond the MP4 frames.") | ||
| start = v3_video_times[identity][frame_index] |
There was a problem hiding this comment.
[P2] Validate the video offset against every frame in the Episode
At 10 fps, I imported an Episode with from_timestamp=0.2 and frame PTS values of 0.200075 and 0.299925. Both meet the importer's 100 µs tolerance. Export moves the offset to 0.200075, so the second frame is 150 µs from its lookup time and re-import fails. Please preserve the original offset when it matches the copied clip, and validate every frame descriptor when selecting an offset for a remuxed clip.
| episode[prefix + "to_timestamp"] = start + len(descriptors) / info["fps"] | ||
| if version.startswith("v2."): | ||
| episode_stats.append({"episode_index": episode_index, | ||
| "stats": _episode_stats(episode)}) |
There was a problem hiding this comment.
[P2] Preserve normalization stats in v2.1 exports
The existing source fixture has Dataset-level stats for action and observation.state. Its Episode stats omit both features. The v2.1 reader builds meta.stats by aggregating episodes_stats.jsonl, so the exported dataset loses the normalization stats for those features. Please compute the missing Episode stats from the selected frames and verify them with the v2.1 reader.
| unsigned = { | ||
| name: pa.field(name, pa.uint64()) for name in names | ||
| if name not in preserved and any( | ||
| isinstance(episode.get(name), Decimal) |
There was a problem hiding this comment.
[P2] Restore nested unsigned integers in Episode metadata
I imported a vendor/nested_ids column typed as list<uint64> with a value of 2**64 - 1. The scalar check misses the nested Decimal, so the export writes list<decimal128> and load_from_lerobot rejects it on re-import. Please preserve or reconstruct the unsigned Arrow types inside lists and structs, too.
| raise | ||
| info_uri = prefix + "/meta/info.json" | ||
| try: | ||
| _upload_file(info, info_uri, file_io) |
There was a problem hiding this comment.
[P2] Publish the FUSE completion marker atomically
I paused a single FuseLocalFileIO writer immediately after it opened meta/info.json. A concurrent reader saw an empty file and raised JSONDecodeError. Please write the marker to a temporary file and atomically publish it on FUSE after all data uploads complete.
| continue | ||
| uri = prefix + "/" + path.relative_to(stage).as_posix() | ||
| _upload_file(path, uri, file_io) | ||
| except Exception as error: |
There was a problem hiding this comment.
[P2] Keep an interrupted export retryable
I interrupted a single exporter with Ctrl+C after its first successful upload. KeyboardInterrupt bypasses this handler, leaving files in the target prefix. A retry then raises FileExistsError. Please include cancellation in rollback once the attempt has acquired ownership of the prefix.
| if parsed.scheme != "oss" or not parsed.netloc: | ||
| raise ValueError("Object Table output must use OSS storage.") | ||
| try: | ||
| frames = connection.get_table(table_name) |
There was a problem hiding this comment.
[P2] Resolve the group prefix behind an ordinary table
I created an ordinary append table named robot through the catalog and loaded a LeRobot group into robot_frames. The documented export_to_lerobot("robot", ...) call fails in Data Evolution validation before reaching the fallback. The new regression test creates a Data Evolution table through conn.create_table, so it misses this case. Please inspect whether the exact candidate is a managed Frames table before applying multimodal validation.
| locator = _FrameLocator.__new__(_FrameLocator) | ||
| locator._process_id = os.getpid() | ||
| locator._table = SimpleNamespace(options=SimpleNamespace( | ||
| scalar_index_search_mode=lambda: "ALL")) |
There was a problem hiding this comment.
[P2] Use real options in the frame locator regression test
Both parameterizations fail on the GitHub merge snapshot before the is_exact() assertion. The reader on master calls scalar_scan_search_mode(), and the mock only defines scalar_index_search_mode(). Please construct a real CoreOptions instance here so the test follows the production option contract.
| images = [value for path in data_files for value in | ||
| pq.read_table(path)["camera.image"].to_pylist()] | ||
| assert [value["bytes"] for value in images] == [payload] * 5 | ||
| from datasets import load_dataset |
There was a problem hiding this comment.
[P2] Run the image decode assertions with the LeRobot dependencies
All three image cases fail at this import in the Python Execution shard. Pillow is installed in that shard, so the existing skip lets the tests reach an import of the absent datasets package. Please keep the Arrow assertions in the regular test suite and run the Hugging Face decoding checks in the LeRobot compatibility job.
JingsongLi
left a comment
There was a problem hiding this comment.
Reviewed 4496dae465e and ran the Python and native export paths. LeRobot 0.3.3 and 0.4.4 both read ordinary exported image and video samples, and the numeric normalization statistics survived. I reproduced three remaining cases affecting export retry or legacy dataset usability.
| try: | ||
| if not file_io.try_to_write_atomic( | ||
| info_uri, info.read_text(encoding="utf-8")): | ||
| raise FileExistsError(info_uri) |
There was a problem hiding this comment.
[P2] Make a failed FUSE marker rename retryable
With one exporter, I injected a single EIO into Path.rename when publishing meta/info.json through FuseLocalFileIO. LocalFileIO.rename returned False, and this branch raised FileExistsError even though no marker existed. The Parquet and task metadata remained, so a healthy retry failed on the existing dataset prefix. Please distinguish an absent marker from a real collision and send the failed publication through owned-file cleanup. A regression test should inject the error at the FUSE rename.
| missing_stats = { | ||
| name: _RunningStats() for name in source_stats | ||
| if name not in existing_stats and name in frame_schema.names | ||
| and info["features"][name]["dtype"].startswith( |
There was a problem hiding this comment.
[P2] Preserve image normalization statistics for v2.1 readers
I imported a v3 dataset with camera.image normalization in meta/stats.json and no per-episode image statistics. The v2.1 export retained the file and LeRobot 0.3.3 decoded all five image samples, but dataset.meta.stats["camera.image"] raised KeyError. The legacy reader aggregates episodes_stats.jsonl, and this fallback only supplies numeric features. Please emit per-episode image statistics for those features or explicitly reject conversions that lose the expected normalization. LeRobot v2.1 metadata loader
| video = source.streams.video[0] | ||
| stream = target.add_stream("libx264", rate=fps) | ||
| stream.width, stream.height = video.width, video.height | ||
| stream.pix_fmt = "yuv420p" |
There was a problem hiding this comment.
[P2] Preserve supported RGB clip dimensions in v2 exports
A valid 17×15 H.264 yuv444p clip imported successfully and v3 exported the same MP4 byte for byte. Both v2.0 and v2.1 exports failed in libx264 with width not divisible by 2 (17x15) because the encoder always selects yuv420p. Please select a compatible pixel format for odd dimensions and record that format in the output metadata. Cover this with an import and export round trip.
JingsongLi
left a comment
There was a problem hiding this comment.
The previous ordinary odd-dimension, complete image statistics, and FUSE marker rename tests now pass. I also read back exports with LeRobot 0.3.3 and 0.4.4. I reproduced three remaining cases below.
| raise RuntimeError( | ||
| "LeRobot export info.json status is uncertain: %s" | ||
| % info_uri) from read_error | ||
| _clean_failed_upload(prefix, uploaded, file_io, error) |
There was a problem hiding this comment.
[P1] Keep uploaded data when the completion PUT may still commit
I used the real OssFileIO and oss2 final conditional PUT against a loopback HTTP endpoint. The client timed out while the server was still processing the request. The marker did not exist during the subsequent checks, so cleanup removed the Parquet and other metadata. The server then committed that same PUT. The Dataset now has meta/info.json with no data, and a healthy retry raises FileExistsError. This only takes one exporter. Please keep the payload after an ambiguous marker PUT until publication is resolved or the request cannot commit.
| file_io.delete(parent) | ||
| except OSError: | ||
| pass | ||
| cleaned = not any(file_io.exists(uri) for uri in uris) |
There was a problem hiding this comment.
[P2] Keep FUSE retryable if only an empty directory remains
With real FuseLocalFileIO, I injected one transient rename error while publishing info.json and one transient rmdir failure for the Dataset directory. Cleanup removed every file and left an empty directory. It reported only the original publication failure, then a healthy retry raised FileExistsError on that directory. Please allow reuse of an empty unpublished prefix or detect and report that rollback could not clear it.
| while position < len(wanted) and wanted[position] == ordinal: | ||
| pixels = frame.to_ndarray(format="rgb24") | ||
| if statistics is not None and position in sample_indices: | ||
| statistics.update_pixels(pixels) |
There was a problem hiding this comment.
[P2] Compute v2.1 normalization from the exported video frames
I imported a valid even-sized RGB yuv444p clip with source-level video stats and no per-episode video stats, then exported it to v2.1 and opened it in LeRobot 0.3.3. The exported red and blue standard deviations were 0.498/0.500 in dataset.meta.stats, versus 0.089/0.089 in the actual samples after the yuv420p re-encode. This fallback collects statistics before chroma subsampling and compression. Please compute the missing stats from decoded output frames, or use an encoding that preserves the distribution.
JingsongLi
left a comment
There was a problem hiding this comment.
The focused Python and Native paths passed 66 cases each. I also checked real samples with LeRobot 0.3.3 for v2.0/v2.1 and ran the v3 writer/export/reader case with LeRobot 0.4.4. One supported Paimon input still cannot use the advertised v2.0 export.
| output_info = copy.deepcopy(info) | ||
| output_info.setdefault("robot_type", None) | ||
| if version.startswith("v2."): | ||
| if version == "v2.0" and source["stats"] is None: |
There was a problem hiding this comment.
[P2] Handle Paimon datasets that store complete episode stats without a global stats file. I imported a v3 dataset with five frames and complete per-episode action, state, and video statistics, but no meta/stats.json. Import succeeds and _datasets.stats is NULL. The same group exports to v2.1 and LeRobot 0.3.3 reads all five action/video samples in its normalization stats. Exporting to v2.0 stops here before any upload, even though the per-episode min/max/mean/std/count are enough to build the required global file. Aggregate those stats for v2.0 and compute converted video stats as usual. If this input remains out of scope, document the source-level requirement next to the advertised v2.0 export support.
JingsongLi
left a comment
There was a problem hiding this comment.
Reviewed 716e1ba994 and tested its merge with master. The native regression run passed 126 tests. The LeRobot 0.3.3 run passed 89 tests, including all 13 legacy-specific checks. Live DLF publication remains unverified.
| and video.height % 2 == 0 else "yuv444p" | ||
| stream.pix_fmt = pixel_format | ||
| stream.options = {"crf": "18", "threads": "4"} | ||
| for ordinal, frame in enumerate(source.decode(video=0)): |
There was a problem hiding this comment.
[P2] Avoid decoding a shared source MP4 from frame zero for every Episode
I exported a v3 Dataset whose 32 Episodes share one MP4. For 640 output frames, the v2.1 export opened the same cached source 32 times and decoded 10,560 input frames. Each Episode decodes all earlier Episodes again, so decoding grows quadratically with the number of Episodes in the shared MP4. Please reuse decoding for adjacent Episodes in the same payload or seek to a preceding keyframe while retaining exact frame boundaries.
| raise RuntimeError( | ||
| "LeRobot export info.json status is uncertain: %s" | ||
| % info_uri) from read_error | ||
| if is_fuse and isinstance(error, OSError): |
There was a problem hiding this comment.
[P2] Clean up a cancelled FUSE export before marker publication
I interrupted a single FuseLocalFileIO exporter while it opened the temporary info.json, before rename. The KeyboardInterrupt is wrapped as an uncertain publication and all six payload files remain. The final marker is absent and a healthy retry raises FileExistsError. Please clean up after a cancelled local marker preparation when the final marker is absent, then propagate the interruption. Keep the payload when the marker is present.
| episode[prefix + "chunk_index"] = chunk_index | ||
| episode[prefix + "file_index"] = file_index | ||
| if identity not in v3_video_times: | ||
| v3_video_times[identity] = _video_frame_times(video_path) |
There was a problem hiding this comment.
[P2] Declare PyAV as a dependency for v3 video export
The guide and API docstring mention PyAV for v2. With PyAV unavailable, I ran a v3 video export from an existing Paimon group and got ModuleNotFoundError when this branch decoded the copied MP4 to inspect its timestamps. The same export published successfully after restoring PyAV. Please document the requirement for video exports in all three versions and report a clear dependency error before staging.
| tasks = sorted(source["tasks"], key=lambda row: row["task_index"]) | ||
| subtasks = source["subtasks"] | ||
| if version == "v3.0": | ||
| _write_v3_vocabulary(stage, "task", tasks) |
There was a problem hiding this comment.
[P1] Keep v3 exports readable for sparse task IDs when #11622 lands
I tested the joint merge of #11622 and #11299 with LeRobot 0.4.4. A standard export with task IDs 0, 1 reads its first sample as pick. An imported Dataset with a scoped task vocabulary 9, 10 also exports successfully, but the official reader indexes its two-row task table by position 9 and raises IndexError on the first sample. Please remap sparse IDs consistently in both frames and metadata before publishing, or reject them before upload until export supports them.
JingsongLi
left a comment
There was a problem hiding this comment.
Retested 80e53fae59 merged into master. Native regression passed 133 cases and the LeRobot 0.3.3 run passed 96. The 32-episode replay now opens the shared MP4 once and decodes 640 input frames for 640 outputs in both v2 formats. Cancellation before opening the marker's temporary file now cleans up and permits retry.
Three prior issues still reproduce. A v2.1/v3.0 overlap can leave a v3 marker declaring five frames above ten Parquet rows, so each target Dataset still needs exclusive export orchestration. V3 video export without PyAV still raises ModuleNotFoundError before publication. The joint merge with #11622 at 3a53863c93 still publishes sparse task IDs 9, 10, then LeRobot 0.4.4 fails on the first frame. Concurrent export · PyAV · Sparse tasks
| raise RuntimeError( | ||
| "LeRobot export info.json status is uncertain: %s" | ||
| % info_uri) from read_error | ||
| if is_fuse and (isinstance(error, OSError) |
There was a problem hiding this comment.
[P1] Keep the payload while a marker rename may still complete
The new cancellation branch also handles interrupts after the rename has started. I injected an OSSFS-style rename fault through FuseLocalFileIO using real oss2 and a loopback service. The service accepted the marker copy, sent SIGINT, and completed the copy after the client checked for the marker. 80e53fae59 removed the Parquet files and eventually left info.json declaring five frames with no data. The previous head retained the payload under this fault. Please restrict cleanup to confirmed pre-rename cancellation and retain data for an unresolved rename. This is a fault-injection result, and the deployed DLF mount still needs verification. OSSFS rename contract
Export one Paimon LeRobot Dataset to an Object Table as v2.0, v2.1, or v3.0. Output uses
<Object Table>/<dataset_id>/and publishesmeta/info.jsonlast. Video export requires PyAV; task/subtask IDs must be contiguous from zero.Run one exporter per Object Table and Dataset ID. Retry only after cleanup is confirmed; uncertain uploads or renames retain their data until the outcome is resolved.
Validation: 100 export tests, 13 legacy-reader checks, and 34 Native read/write regressions passed. Live DLF export was not tested.