Skip to content
Merged
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
27 changes: 18 additions & 9 deletions python/rcs/envs/storage_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import pyarrow.dataset as ds
import simplejpeg
from PIL import Image
from rcs._core import __version__ as rcs_version


class StorageWrapper(gym.Wrapper):
Expand Down Expand Up @@ -46,6 +47,13 @@ def __init__(
3. **Consolidation:** On a clean exit (`close()`), the many small batch files are
merged into larger, optimized Parquet files.

Row layout: each row is one ``step(action)``. ``obs`` is the observation the
action was applied from (the reset observation for the first row), ``action``
is the action passed to ``step`` and ``env_obs`` is the observation returned
by that step, without camera frames (it equals the next row's ``obs``).
``(obs, action)`` is therefore the pair a policy is trained on. ``rcs_version``
marks this layout; recordings without it store the observation after the step.

Observation handling:
- Expects observations to be dictionaries.
- RGB camera frames are JPEG-encoded.
Expand Down Expand Up @@ -91,8 +99,7 @@ def __init__(
self.always_record = always_record
self.instruction = instruction
self._success = False
self._prev_action = None
self._prev_absolute_action = None
self._prev_obs: dict[str, Any] | None = None
self.success_from_env = success_from_env
self.allow_wrapper_instruction = allow_wrapper_instruction

Expand Down Expand Up @@ -268,36 +275,38 @@ def step(self, action):
raise RuntimeError(msg) from exc

obs_original, reward, terminated, truncated, info = self.env.step(action)
obs = copy.deepcopy(obs_original)

if not self._pause:
# obs: observation the action was chosen from (before the step), env_obs: observation after the step
obs = self._prev_obs
assert isinstance(obs, dict)
if "frames" in obs and not obs["frames"]:
del obs["frames"]
if "frames" in obs:
self._encode_images(obs)
self._flatten_arrays(obs)
env_obs = copy.deepcopy({k: v for k, v in obs_original.items() if k != "frames"})
self._flatten_arrays(env_obs)
if info.get("success") and self.success_from_env:
self.success()
if info.get("instruction") is not None and self.allow_wrapper_instruction:
self.instruction = info.get("instruction")

frame = {
"obs": obs,
"env_obs": env_obs,
"info": info,
"reward": reward,
"step": self.step_cnt,
"uuid": self.uuid.hex,
"date": datetime.date.today().isoformat(),
"success": self._success,
"action": self._prev_action,
"env_action": action,
"action": action,
"instruction": self.instruction,
"timestamp": datetime.datetime.now().timestamp(),
"rcs_version": rcs_version,
}

self._prev_action = action

self.buffer.append(frame)

self.step_cnt += 1
Expand All @@ -306,6 +315,7 @@ def step(self, action):
# can still mark the episode as successful even if the batch boundary was hit.
self._flush(keep_last=True)

self._prev_obs = copy.deepcopy(obs_original)
return obs_original, reward, terminated, truncated, info

def set_instruction(self, instruction: str):
Expand All @@ -327,9 +337,8 @@ def reset(self, *, seed: int | None = None, options: dict[str, Any] | None = Non
self._flush()
self._pause = not self.always_record
self._success = False
self._prev_action = None
self._prev_absolute_action = None
obs, info = self.env.reset(seed=seed, options=options)
self._prev_obs = copy.deepcopy(obs)
self.step_cnt = 0
self.uuid = uuid4()
return obs, info
Expand Down
77 changes: 52 additions & 25 deletions python/rcs/lerobot_joint_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@ def __init__(
self.binarize_gripper = binarize_gripper
self.gripper_binarize_threshold = gripper_binarize_threshold
self.source_sql = self._build_source_sql(self.dataset_paths)
# Recordings without an rcs_version column store the observation after the step (paired with env_action):
# pair each action with the previous row's observation instead.
columns = {row[0] for row in self.conn.execute(f"DESCRIBE SELECT * FROM ({self.source_sql}) AS src").fetchall()}
self.legacy_layout = "rcs_version" not in columns
self.video_encoding = video_encoding

self.tcp_offset = rcs.GRIPPER_TCP_OFFSETS[self.gripper_type]
Expand Down Expand Up @@ -195,27 +199,41 @@ def generate_examples(self, success: bool = True, n: int = -1):

self.lrds.finalize()

def _observation_column(self, column: str) -> str:
return f"LAG({column}) OVER (ORDER BY step)" if self.legacy_layout else column

def _fetch_transition_table(self, episode_id: str) -> pd.DataFrame:
observation_selects = ",\n ".join(
[f"obs.{robot_key}.joints AS observation_joints_{robot_key}" for robot_key in self.robot_keys]
+ [f"obs.{robot_key}.gripper AS observation_gripper_{robot_key}" for robot_key in self.robot_keys]
[
f"{self._observation_column(f'obs.{robot_key}.joints')} AS observation_joints_{robot_key}"
for robot_key in self.robot_keys
]
+ [
f"{self._observation_column(f'obs.{robot_key}.gripper')} AS observation_gripper_{robot_key}"
for robot_key in self.robot_keys
]
)
action_column = "env_action" if self.legacy_layout else "action"
action_selects = ",\n ".join(
[f"info.{robot_key}.absolute_action AS absolute_action_{robot_key}" for robot_key in self.robot_keys]
+ [f"env_action.{robot_key}.gripper AS action_gripper_{robot_key}" for robot_key in self.robot_keys]
+ [f"{action_column}.{robot_key}.gripper AS action_gripper_{robot_key}" for robot_key in self.robot_keys]
)

# the first row of a legacy recording has no observation before its action
return self.conn.execute(
f"""
SELECT
uuid,
step,
success,
instruction,
{observation_selects},
{action_selects}
FROM ({self.source_sql}) AS src
WHERE uuid = ?
SELECT * FROM (
SELECT
uuid,
step,
success,
instruction,
{observation_selects},
{action_selects}
FROM ({self.source_sql}) AS src
WHERE uuid = ?
)
WHERE observation_joints_{self.robot_keys[0]} IS NOT NULL
ORDER BY step
""",
[episode_id],
Expand All @@ -231,10 +249,11 @@ def _fetch_episode_success(self, episode_id: str) -> bool:

def _image_query(self) -> str:
image_selects = ",\n ".join(
f"obs.frames.{camera.frame_name}.rgb.data AS {camera.image_column}" for camera in self.cameras
f"{self._observation_column(f'obs.frames.{camera.frame_name}.rgb.data')} AS {camera.image_column}"
for camera in self.cameras
)
image_not_null_checks = "\n ".join(
f"AND obs.frames.{camera.frame_name}.rgb.data IS NOT NULL" for camera in self.cameras
image_not_null_checks = "\n AND ".join(
f"{camera.image_column} IS NOT NULL" for camera in self.cameras
)
image_columns = ",\n ".join(camera.image_column for camera in self.cameras)

Expand All @@ -246,12 +265,12 @@ def _image_query(self) -> str:
{image_selects}
FROM ({self.source_sql}) AS src
WHERE uuid = ?
{image_not_null_checks}
)
SELECT
step,
{image_columns}
FROM ordered
WHERE {image_not_null_checks}
ORDER BY step
"""

Expand Down Expand Up @@ -346,16 +365,24 @@ def _prepare_transition_table(self, table: pd.DataFrame) -> pd.DataFrame:
df["observation_state"] = df.apply(self._build_observation_state, axis=1)
df["action_vector"] = df.apply(self._convert_action_to_joint_space, axis=1)

df = df[df["action_vector"].notna()] # noqa: PD901

prev_action: np.ndarray | None = None
keep_mask = []
for action_vec in df["action_vector"]:
assert isinstance(action_vec, np.ndarray)
keep_mask.append(prev_action is None or not np.allclose(action_vec, prev_action, atol=1e-4, rtol=0))
prev_action = action_vec
# skip a step only if the robot does not move during it (its observation equals the next one); the last
# step has no next observation and is kept
raw_state = np.stack(
[
np.concatenate(
[
np.asarray(row[f"observation_{part}_{robot_key}"], dtype=np.float64)
for robot_key in self.robot_keys
for part in ("joints", "gripper")
]
)
for _, row in df.iterrows()
]
)
moved = np.ones(len(df), dtype=bool)
moved[:-1] = ~np.all(np.isclose(raw_state[1:], raw_state[:-1], atol=1e-4, rtol=0), axis=1)

return df.loc[keep_mask].reset_index(drop=True)
return df[moved & df["action_vector"].notna().to_numpy()].reset_index(drop=True)

def parse_episode(self, episode_id: str, table: pd.DataFrame, success: bool):
table = self._prepare_transition_table(table)
Expand Down
8 changes: 7 additions & 1 deletion python/rcs/sim/replayer.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,14 @@ def load_distinct_uuids(dataset_path: Path | str) -> list[str]:
def load_trajectory(dataset_path: Path | str, trajectory_uuid: str) -> list[RecordedSimStep]:
connection = duckdb.connect()
try:
columns = {
row[0]
for row in connection.execute("DESCRIBE SELECT * FROM read_parquet(?)", [str(dataset_path)]).fetchall()
}
# recordings without rcs_version store the stepped action as env_action
action_column = "action" if "rcs_version" in columns else "env_action"
rows = connection.execute(
"SELECT uuid, step, timestamp, obs, info, env_action, instruction, success "
f"SELECT uuid, step, timestamp, obs, info, {action_column}, instruction, success "
"FROM read_parquet(?) WHERE uuid = ? ORDER BY step",
[str(dataset_path), trajectory_uuid],
).fetchall()
Expand Down
61 changes: 53 additions & 8 deletions python/tests/test_replayer.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def _source_rows(dataset_dir: Path, limit: int):
uuid = load_distinct_uuids(dataset_dir)[0]
return connection.execute(
"""
SELECT step, obs, info, reward, success, action, env_action, instruction
SELECT step, obs, info, reward, success, action, env_obs, instruction
FROM read_parquet(?)
WHERE uuid = ?
ORDER BY step
Expand All @@ -133,7 +133,7 @@ def _replay_rows(dataset_dir: Path):
try:
return connection.execute(
"""
SELECT step, obs, info, reward, success, action, env_action, instruction
SELECT step, obs, info, reward, success, action, env_obs, instruction
FROM read_parquet(?)
ORDER BY step
""",
Expand Down Expand Up @@ -263,6 +263,51 @@ def _joint_qpos_in_root_frame(env: StorageWrapper, joint_name: str, root_frame_t
return np.concatenate((joint_pose_root.translation(), joint_pose_root.rotation_q_wxyz()))


def _to_py(value: Any) -> Any:
if isinstance(value, dict):
return {key: _to_py(item) for key, item in value.items()}
if isinstance(value, np.ndarray):
return value.tolist()
if isinstance(value, np.generic):
return value.item()
return value


def test_storage_wrapper_pairs_obs_with_the_action_applied_to_it(tmp_path: Path):
env = _build_env(tmp_path / "recorded", with_cameras=False)
actions = [
{
robot: {
"tquat": np.array([0.0, 0.0, 0.02 * (i + 1), 0.0, 0.0, 0.0, 1.0]),
"gripper": np.array([1.0], dtype=np.float32),
}
for robot in ("left", "right")
}
for i in range(3)
]
try:
observations = [env.reset()[0]]
observations += [env.step(action)[0] for action in actions]
finally:
env.close()

connection = duckdb.connect()
try:
rows = connection.execute(
"SELECT obs, action, env_obs, rcs_version FROM read_parquet(?) ORDER BY step", [str(tmp_path / "recorded")]
).fetchall()
finally:
connection.close()

assert len(rows) == len(actions)
for i, (obs, action, env_obs, rcs_version) in enumerate(rows):
assert rcs_version == rcs.__version__
# obs is the observation the action was applied from, env_obs the one it led to
_assert_nested_close(obs, _to_py(_strip_frames(observations[i])), atol=1e-6)
_assert_nested_close(action, _to_py(actions[i]), atol=1e-8)
_assert_nested_close(env_obs, _to_py(_strip_frames(observations[i + 1])), atol=1e-6)


def test_replayer_reproduces_existing_parquet_prefix_without_cameras(tmp_path: Path):
source_dir = tmp_path / "source"
replay_dir = tmp_path / "replayed"
Expand All @@ -285,7 +330,7 @@ def test_replayer_reproduces_existing_parquet_prefix_without_cameras(tmp_path: P
replay_reward,
replay_success,
replay_action,
replay_env_action,
replay_env_obs,
replay_instruction,
) = replay_row
(
Expand All @@ -295,7 +340,7 @@ def test_replayer_reproduces_existing_parquet_prefix_without_cameras(tmp_path: P
source_reward,
source_success,
source_action,
source_env_action,
source_env_obs,
source_instruction,
) = source_row

Expand All @@ -307,7 +352,7 @@ def test_replayer_reproduces_existing_parquet_prefix_without_cameras(tmp_path: P
_assert_nested_close(replay_reward, source_reward, atol=1e-7)
_assert_nested_close(replay_success, source_success)
_assert_nested_close(replay_action, source_action, atol=1e-8)
_assert_nested_close(replay_env_action, source_env_action, atol=1e-8)
_assert_nested_close(replay_env_obs, source_env_obs, atol=1e-5)
_assert_nested_close(replay_instruction, source_instruction)


Expand Down Expand Up @@ -360,7 +405,7 @@ def test_replayer_adds_cameras_to_existing_episode_without_cameras(tmp_path: Pat
replay_reward,
replay_success,
replay_action,
replay_env_action,
replay_env_obs,
replay_instruction,
) = replay_row
(
Expand All @@ -370,7 +415,7 @@ def test_replayer_adds_cameras_to_existing_episode_without_cameras(tmp_path: Pat
source_reward,
source_success,
source_action,
source_env_action,
source_env_obs,
source_instruction,
) = source_row

Expand All @@ -385,7 +430,7 @@ def test_replayer_adds_cameras_to_existing_episode_without_cameras(tmp_path: Pat
_assert_nested_close(replay_reward, source_reward, atol=1e-7)
_assert_nested_close(replay_success, source_success)
_assert_nested_close(replay_action, source_action, atol=1e-8)
_assert_nested_close(replay_env_action, source_env_action, atol=1e-8)
_assert_nested_close(replay_env_obs, source_env_obs, atol=1e-5)
_assert_nested_close(replay_instruction, source_instruction)


Expand Down
Loading