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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
* Fixed automatic HDF5 episode numbering to skip IDs already used by custom episodes.
Episode counts now include explicitly numbered episodes before reopening the dataset.
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def __init__(self):
self._hdf5_file_stream = None
self._hdf5_data_group = None
self._demo_count = 0
self._next_demo_id = 0
self._env_args = {}

def open(self, file_path: str, mode: str = "r"):
Expand All @@ -70,6 +71,7 @@ def open(self, file_path: str, mode: str = "r"):
self._hdf5_file_stream = _open_non_inheritable(file_path, mode)
self._hdf5_data_group = self._hdf5_file_stream["data"]
self._demo_count = len(self._hdf5_data_group)
self._next_demo_id = self._demo_count

def create(self, file_path: str, env_name: str | None = None):
"""Create a new dataset file."""
Expand All @@ -89,6 +91,7 @@ def create(self, file_path: str, env_name: str | None = None):
self._hdf5_data_group = self._hdf5_file_stream.create_group("data")
self._hdf5_data_group.attrs["total"] = 0
self._demo_count = 0
self._next_demo_id = 0

# set environment arguments
# the environment type (we use gym environment type) is set to be compatible with robomimic
Expand Down Expand Up @@ -221,17 +224,23 @@ def write_episode(self, episode: EpisodeData, demo_id: int | None = None, datase

Args:
episode: The episode data to add.
demo_id: Custom index for the episode. If None, uses default index.
demo_id: Custom index for the episode. If None, uses the next available automatic index.
dataset_compression: Whether to gzip-compress the stored datasets at compression level 2.
Defaults to True. If False, datasets are written without compression.
"""
self._raise_if_not_initialized()
if episode.is_empty():
return

episode_group_name = f"demo_{self._demo_count if demo_id is None else demo_id}"
if episode_group_name in self._hdf5_data_group:
raise ValueError(f"Episode group '{episode_group_name}' already exists in the dataset")
if demo_id is None:
next_demo_id = self._next_demo_id
while f"demo_{next_demo_id}" in self._hdf5_data_group:
next_demo_id += 1
episode_group_name = f"demo_{next_demo_id}"

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.

🟡 Warning · Implementation — Avoid the second membership lookup

The loop establishes that the automatic ID is free, but the shared duplicate check queries HDF5 again on every automatic write. Check duplicates only in the explicit-ID branch.

else:
episode_group_name = f"demo_{demo_id}"
if episode_group_name in self._hdf5_data_group:
raise ValueError(f"Episode group '{episode_group_name}' already exists in the dataset")
h5_episode_group = self._hdf5_data_group.create_group(episode_group_name)

h5_episode_group.attrs["num_samples"] = len(episode.data.get("actions", ()))
Expand All @@ -257,9 +266,9 @@ def create_dataset_helper(group, key, value):
create_dataset_helper(h5_episode_group, key, value)

self._hdf5_data_group.attrs["total"] += h5_episode_group.attrs["num_samples"]
# custom demo ids do not advance the default naming sequence
self._demo_count += 1
if demo_id is None:
self._demo_count += 1
self._next_demo_id = next_demo_id + 1

def flush(self):
"""Flush the episode data to disk."""
Expand Down
32 changes: 32 additions & 0 deletions source/isaaclab/test/utils/test_hdf5_dataset_file_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import json
import subprocess
import sys
from pathlib import Path

import h5py
import pytest
Expand All @@ -16,6 +17,37 @@
pytestmark = [pytest.mark.unit, pytest.mark.windows_ci]


@pytest.mark.kitless
def test_append_uses_free_demo_ids_after_custom_write(tmp_path: Path) -> None:
"""Append an episode to a reopened file whose default ID is already taken."""
path = str(tmp_path / "mixed_ids.hdf5")
handler = HDF5DatasetFileHandler()
episode = EpisodeData()
episode.data = {"actions": torch.tensor([[2.0]])}
try:
handler.create(path)
handler.write_episode(episode, demo_id=2)
episode.data = {"actions": torch.tensor([[0.0]])}
handler.write_episode(episode)
count_before_reopen = handler.get_num_episodes()
handler.close()

handler.open(path, mode="r+")
episode.data = {"actions": torch.tensor([[3.0]])}
handler.write_episode(episode)

assert count_before_reopen == 2
assert handler.get_num_episodes() == 3
assert set(handler.get_episode_names()) == {"demo_0", "demo_2", "demo_3"}
original = handler.load_episode("demo_2", device="cpu")
assert original is not None
torch.testing.assert_close(original.data["actions"], torch.tensor([[2.0]]))
with pytest.raises(ValueError, match="demo_2.*already exists"):
handler.write_episode(episode, demo_id=2)
finally:
handler.close()


def test_create_dataset_file(tmp_path, monkeypatch):
"""Accept absolute paths, omitted extensions and bare filenames."""
monkeypatch.chdir(tmp_path)
Expand Down