From e3bd6ee2247ac209b60a2598cc35db4c42f0a870 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 27 Nov 2026 19:44:12 -0800 Subject: [PATCH 1/5] fix(recorder): store the observation an action was applied from Each row now holds obs (the observation before the step, the reset observation for the first row), action (the action passed to step) and env_obs (the observation returned by the step, without camera frames). Before, obs was the observation after the step, paired with env_action (the same step) and action (the previous step), so neither column gave the (observation, action) pair a policy is trained on. The replayer reads env_action for recordings in the old layout. --- python/rcs/envs/storage_wrapper.py | 24 +++++++----- python/rcs/sim/replayer.py | 8 +++- python/tests/test_replayer.py | 60 ++++++++++++++++++++++++++---- 3 files changed, 74 insertions(+), 18 deletions(-) diff --git a/python/rcs/envs/storage_wrapper.py b/python/rcs/envs/storage_wrapper.py index 3fe9090d..a15a6534 100644 --- a/python/rcs/envs/storage_wrapper.py +++ b/python/rcs/envs/storage_wrapper.py @@ -46,6 +46,12 @@ 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. + Observation handling: - Expects observations to be dictionaries. - RGB camera frames are JPEG-encoded. @@ -91,8 +97,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 @@ -268,15 +273,18 @@ 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: @@ -284,20 +292,18 @@ def step(self, action): 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(), } - self._prev_action = action - self.buffer.append(frame) self.step_cnt += 1 @@ -306,6 +312,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): @@ -327,9 +334,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 diff --git a/python/rcs/sim/replayer.py b/python/rcs/sim/replayer.py index d410b1a9..634de31d 100644 --- a/python/rcs/sim/replayer.py +++ b/python/rcs/sim/replayer.py @@ -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 from before env_obs was added store the stepped action as env_action + action_column = "env_action" if "env_action" in columns else "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() diff --git a/python/tests/test_replayer.py b/python/tests/test_replayer.py index 764d9b5a..1c2f3168 100644 --- a/python/tests/test_replayer.py +++ b/python/tests/test_replayer.py @@ -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 @@ -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 """, @@ -263,6 +263,50 @@ 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 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) in enumerate(rows): + # 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" @@ -285,7 +329,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 ( @@ -295,7 +339,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 @@ -307,7 +351,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) @@ -360,7 +404,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 ( @@ -370,7 +414,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 @@ -385,7 +429,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) From aea0aea0e9e8480207ca3127a5da8dd4a94cac8e Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 27 Nov 2026 19:44:57 -0800 Subject: [PATCH 2/5] fix(lerobot-convert): pair each action with the observation it was applied from Recordings with obs/action/env_obs rows are converted as they are. For recordings in the old layout (obs after the step, env_action), each row's action is paired with the previous row's observation and images, and the IK is seeded with that observation, which is the command the robot executed. The first row of such an episode has no observation before its action and is dropped. --- python/rcs/lerobot_joint_converter.py | 51 ++++++++++++++++++--------- 1 file changed, 35 insertions(+), 16 deletions(-) diff --git a/python/rcs/lerobot_joint_converter.py b/python/rcs/lerobot_joint_converter.py index f6015539..af9f3add 100644 --- a/python/rcs/lerobot_joint_converter.py +++ b/python/rcs/lerobot_joint_converter.py @@ -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 from before env_obs was added 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 = "env_action" in columns self.video_encoding = video_encoding self.tcp_offset = rcs.GRIPPER_TCP_OFFSETS[self.gripper_type] @@ -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], @@ -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) @@ -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 """ From 98f15e9bcd77e87f9c605f3149ceb4bda33f1740 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 27 Nov 2026 19:45:41 -0800 Subject: [PATCH 3/5] fix(lerobot-convert): skip a step only if the robot does not move Before, a step was dropped when its action equalled the previous one, which also removed steps in which the robot was still moving towards an unchanged target, e.g. while the gripper closed or the arm settled. Now a step is dropped only if the observed joints and gripper do not change during it. --- python/rcs/lerobot_joint_converter.py | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/python/rcs/lerobot_joint_converter.py b/python/rcs/lerobot_joint_converter.py index af9f3add..271393b7 100644 --- a/python/rcs/lerobot_joint_converter.py +++ b/python/rcs/lerobot_joint_converter.py @@ -365,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) From b82d26afb2cadfe767e37d81bd3ba18c35c1dd82 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 27 Nov 2026 20:23:29 -0800 Subject: [PATCH 4/5] feat(recorder): store the rcs version in every row Recordings with an rcs_version column use the obs/action/env_obs layout; the replayer uses it to tell them apart from older recordings. --- python/rcs/envs/storage_wrapper.py | 5 ++++- python/rcs/sim/replayer.py | 4 ++-- python/tests/test_replayer.py | 5 +++-- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/python/rcs/envs/storage_wrapper.py b/python/rcs/envs/storage_wrapper.py index a15a6534..d77d5f6f 100644 --- a/python/rcs/envs/storage_wrapper.py +++ b/python/rcs/envs/storage_wrapper.py @@ -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): @@ -50,7 +51,8 @@ def __init__( 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. + ``(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. @@ -302,6 +304,7 @@ def step(self, action): "action": action, "instruction": self.instruction, "timestamp": datetime.datetime.now().timestamp(), + "rcs_version": rcs_version, } self.buffer.append(frame) diff --git a/python/rcs/sim/replayer.py b/python/rcs/sim/replayer.py index 634de31d..55b95062 100644 --- a/python/rcs/sim/replayer.py +++ b/python/rcs/sim/replayer.py @@ -87,8 +87,8 @@ def load_trajectory(dataset_path: Path | str, trajectory_uuid: str) -> list[Reco row[0] for row in connection.execute("DESCRIBE SELECT * FROM read_parquet(?)", [str(dataset_path)]).fetchall() } - # recordings from before env_obs was added store the stepped action as env_action - action_column = "env_action" if "env_action" in columns else "action" + # 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( f"SELECT uuid, step, timestamp, obs, info, {action_column}, instruction, success " "FROM read_parquet(?) WHERE uuid = ? ORDER BY step", diff --git a/python/tests/test_replayer.py b/python/tests/test_replayer.py index 1c2f3168..036633cb 100644 --- a/python/tests/test_replayer.py +++ b/python/tests/test_replayer.py @@ -294,13 +294,14 @@ def test_storage_wrapper_pairs_obs_with_the_action_applied_to_it(tmp_path: Path) connection = duckdb.connect() try: rows = connection.execute( - "SELECT obs, action, env_obs FROM read_parquet(?) ORDER BY step", [str(tmp_path / "recorded")] + "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) in enumerate(rows): + 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) From 20620a72285a23d9ea67291aa4a39a9e06b38184 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 27 Nov 2026 20:23:37 -0800 Subject: [PATCH 5/5] fix(lerobot-convert): detect the recording layout by the rcs_version column Datasets with an rcs_version column are taken as recorded with the fixed obs/action pairing; datasets without it get the one-step shift. --- python/rcs/lerobot_joint_converter.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/rcs/lerobot_joint_converter.py b/python/rcs/lerobot_joint_converter.py index 271393b7..1c97dea8 100644 --- a/python/rcs/lerobot_joint_converter.py +++ b/python/rcs/lerobot_joint_converter.py @@ -118,10 +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 from before env_obs was added store the observation after the step (paired with env_action): + # 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 = "env_action" in columns + self.legacy_layout = "rcs_version" not in columns self.video_encoding = video_encoding self.tcp_offset = rcs.GRIPPER_TCP_OFFSETS[self.gripper_type]