| """ |
| Useful methods shared by all scripts. |
| Reference: https://github.com/google-research/google-research/tree/master/xirl |
| """ |
|
|
| import os |
| import pickle |
| import typing |
| from typing import Any, Dict, Optional |
|
|
| from absl import logging |
| from gymnasium.wrappers import RescaleAction |
| import matplotlib.pyplot as plt |
| from ml_collections import config_dict |
| import numpy as np |
| from sac import replay_buffer |
| from sac import wrappers |
| import torch |
| from torchkit import CheckpointManager |
| from torchkit.experiment import git_revision_hash |
| from xirl import common |
| import yaml |
| import robosuite as suite |
| from gymnasium import spaces |
| import gymnasium as gym |
| from robosuite.wrappers import GymWrapper as RoboGymWrapper |
| from robosuite.controllers import load_composite_controller_config |
| from robosuite.utils.placement_samplers import ObjectPositionSampler |
|
|
| from metaworld.envs import ALL_V2_ENVIRONMENTS_GOAL_OBSERVABLE as env_dict |
|
|
|
|
| class _StackPlacementSampler(ObjectPositionSampler): |
| """Stack cube placement: red (cubeA) near robot, green (cubeB) far, low xy noise.""" |
|
|
| TABLE_Z = 0.8 + 0.01 |
| QUAT = np.array([1.0, 0.0, 0.0, 0.0]) |
| |
| CUBE_CENTERS = { |
| "cubeA": np.array([-0.110, 0.0, TABLE_Z]), |
| "cubeB": np.array([-0.030, 0.0, TABLE_Z]), |
| } |
|
|
| def __init__(self, xy_noise=0.01, **kwargs): |
| super().__init__(**kwargs) |
| self.xy_noise = xy_noise |
|
|
| def sample(self, fixtures=None, reference=None, on_top=True): |
| placed = {} if fixtures is None else dict(fixtures) |
| rng = getattr(self, "rng", np.random) |
| for obj in self.mujoco_objects: |
| if obj.name in placed: |
| continue |
| center = self.CUBE_CENTERS.get( |
| obj.name, np.array([0.0, 0.0, self.TABLE_Z]) |
| ) |
| pos = center.copy() |
| if self.xy_noise > 0: |
| pos[:2] += rng.uniform(-self.xy_noise, self.xy_noise, size=2) |
| placed[obj.name] = (pos, self.QUAT.copy(), obj) |
| return placed |
|
|
| |
|
|
| ConfigDict = config_dict.ConfigDict |
| FrozenConfigDict = config_dict.FrozenConfigDict |
|
|
|
|
| |
| |
| |
|
|
| def setup_experiment(exp_dir, config, resume = False): |
| """Initializes a pretraining or RL experiment.""" |
| |
| |
| |
| |
| if os.path.exists(exp_dir): |
| if not resume: |
| raise ValueError( |
| "Experiment already exists. Run with --resume to continue.") |
| load_config_from_dir(exp_dir, config) |
| else: |
| os.makedirs(exp_dir) |
| with open(os.path.join(exp_dir, "config.yaml"), "w") as fp: |
| yaml.dump(ConfigDict.to_dict(config), fp) |
| with open(os.path.join(exp_dir, "git_hash.txt"), "w") as fp: |
| fp.write(git_revision_hash()) |
|
|
| def load_config_from_dir( |
| exp_dir, |
| config = None, |
| ): |
| """Load experiment config.""" |
| with open(os.path.join(exp_dir, "config.yaml"), "r") as fp: |
| cfg = yaml.load(fp, Loader=yaml.FullLoader) |
| |
| if config is not None: |
| config.update(cfg) |
| return ConfigDict(cfg) |
|
|
| def dump_config(exp_dir, config): |
| """Dump config to disk.""" |
| |
| |
| with open(os.path.join(exp_dir, "config.yaml"), "w") as fp: |
| yaml.dump(ConfigDict.to_dict(config), fp) |
|
|
| def copy_config_and_replace( |
| config, |
| update_dict = None, |
| freeze = False, |
| ): |
| """Makes a copy of a config and optionally updates its values.""" |
| |
| |
| new_config = ConfigDict(config) |
| if update_dict is not None: |
| new_config.update(update_dict) |
| if freeze: |
| return FrozenConfigDict(new_config) |
| return new_config |
|
|
| def load_model_checkpoint(pretrained_path, device): |
| """Load a pretrained model and optionally a precomputed goal embedding.""" |
| config = load_config_from_dir(pretrained_path) |
| model = common.get_model(config) |
| model.to(device).eval() |
| checkpoint_dir = os.path.join(pretrained_path, "checkpoints") |
| checkpoint_manager = CheckpointManager(checkpoint_dir, model=model) |
| global_step = checkpoint_manager.restore_or_initialize() |
| logging.info("Restored model from checkpoint %d.", global_step) |
| return config, model |
|
|
| def save_pickle(experiment_path, arr, name): |
| """Save an array as a pickle file.""" |
| filename = os.path.join(experiment_path, name) |
| with open(filename, "wb") as fp: |
| pickle.dump(arr, fp) |
| logging.info("Saved %s to %s", name, filename) |
|
|
| def load_pickle(pretrained_path, name): |
| """Load a pickled array.""" |
| filename = os.path.join(pretrained_path, name) |
| with open(filename, "rb") as fp: |
| arr = pickle.load(fp) |
| logging.info("Successfully loaded %s from %s", name, filename) |
| return arr |
|
|
|
|
| |
| |
| |
|
|
| def make_env( |
| env_name, |
| seed, |
| save_dir = None, |
| add_episode_monitor = True, |
| action_repeat = 1, |
| frame_stack = 1, |
| robots="XArm7", |
| camera_heights=84, |
| camera_widths=84, |
| randomize_initial_state = True, |
| terminate_on_success = True, |
| has_renderer = False, |
| render_camera = None, |
| **robosuite_kwargs, |
| ): |
| """Env factory with wrapping for robosuite benchmark. |
| |
| Args: |
| env_name: The name of the environment. |
| seed: The RNG seed. |
| save_dir: Specifiy a save directory to wrap with `VideoRecorder`. |
| add_episode_monitor: Set to True to wrap with `EpisodeMonitor`. |
| action_repeat: A value > 1 will wrap with `ActionRepeat`. |
| frame_stack: A value > 1 will wrap with `FrameStack`. |
| randomize_initial_state: If True (default), each reset() randomizes object |
| positions and (if applicable) robot initialization noise. If False, |
| robot init noise is disabled. Stack always uses a low-noise placement |
| sampler with red cubeA near the robot and green cubeB farther away. |
| terminate_on_success: If True (default), end the episode as soon as |
| robosuite reports task success (e.g. cube lifted / stacked). |
| |
| Returns: |
| gym.Env object. |
| """ |
| robosuite_kwargs = dict(robosuite_kwargs) |
| if env_name == "Stack": |
| cube_xy_noise = 0.015 if randomize_initial_state else 0.01 |
| robosuite_kwargs.setdefault( |
| "placement_initializer", |
| _StackPlacementSampler( |
| name="StackPlacementSampler", |
| mujoco_objects=None, |
| reference_pos=np.array([0.0, 0.0, 0.8]), |
| z_offset=0.01, |
| xy_noise=cube_xy_noise, |
| ), |
| ) |
| if not randomize_initial_state: |
| |
| robosuite_kwargs.setdefault( |
| "initialization_noise", |
| {"magnitude": 0.0, "type": "gaussian"}, |
| ) |
| elif env_name == "Stack": |
| robosuite_kwargs.setdefault( |
| "initialization_noise", |
| {"magnitude": 0.02, "type": "gaussian"}, |
| ) |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| env = RobosuiteGymnasiumEnv( |
| env_name=env_name, |
| robots=robots, |
| control_freq=30, |
| has_renderer=has_renderer, |
| render_camera=render_camera, |
| camera_heights=camera_heights, |
| camera_widths=camera_widths, |
| rot_eps=0.01, |
| **robosuite_kwargs, |
| ) |
|
|
| env = wrappers.RenderWrapper(env) |
| env = wrappers.EnforceMaxPathLength(env) |
| if terminate_on_success: |
| env = wrappers.TerminateOnSuccess(env) |
|
|
| if add_episode_monitor: |
| env = wrappers.EpisodeMonitor(env) |
| if action_repeat > 1: |
| env = wrappers.ActionRepeat(env, action_repeat) |
| |
| if save_dir is not None: |
| env = wrappers.VideoRecorder(env, save_dir=save_dir) |
| if frame_stack > 1: |
| env = wrappers.FrameStack(env, frame_stack) |
|
|
| |
| env.action_space.seed(seed) |
| np.random.seed(seed) |
|
|
| return env |
|
|
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| |
|
|
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
|
|
| |
| |
| |
| |
|
|
| |
| |
| |
|
|
| |
| |
|
|
| import gymnasium as gym |
| import numpy as np |
| from gymnasium import spaces |
|
|
| |
| |
|
|
|
|
| class RobosuiteGymnasiumEnv(gym.Env): |
| metadata = {"render_modes": ["rgb_array"]} |
|
|
| def __init__( |
| self, |
| env_name, |
| robots="XArm7", |
| camera_names="agentview", |
| camera_heights=84, |
| camera_widths=84, |
| rot_eps=0.01, |
| has_renderer=False, |
| render_camera=None, |
| **robosuite_kwargs, |
| ): |
| super().__init__() |
|
|
| |
| robosuite_kwargs.pop("has_renderer", None) |
| robosuite_kwargs.pop("render_camera", None) |
|
|
| |
| controller_config = load_composite_controller_config(controller="BASIC") |
| controller_config["body_parts"] = {"right": controller_config["body_parts"]["right"]} |
|
|
| |
| |
|
|
| arm_cfg = controller_config["body_parts"]["right"] |
| assert arm_cfg["type"] == "OSC_POSE" |
|
|
| arm_cfg["output_max"][3] = rot_eps |
| arm_cfg["output_min"][3] = -rot_eps |
| arm_cfg["output_max"][4] = rot_eps |
| arm_cfg["output_min"][4] = -rot_eps |
| arm_cfg["output_max"][5] = 0.1 |
| arm_cfg["output_min"][5] = -0.1 |
|
|
|
|
| |
| self._rs_env = suite.make( |
| env_name=env_name, |
| robots=robots, |
| controller_configs=controller_config, |
| has_renderer=has_renderer, |
| render_camera=render_camera, |
| has_offscreen_renderer=True, |
| use_camera_obs=True, |
| camera_names=camera_names, |
| camera_heights=camera_heights, |
| camera_widths=camera_widths, |
| **robosuite_kwargs, |
| ) |
|
|
| self._camera_names = ( |
| camera_names if isinstance(camera_names, (list, tuple)) else [camera_names] |
| ) |
|
|
| |
| low, high = self._rs_env.action_spec |
| low = low.astype(np.float32) |
| high = high.astype(np.float32) |
| self.action_space = spaces.Box(low=low, high=high, dtype=np.float32) |
|
|
| |
| obs = self._rs_env.reset() |
| img = self._obs_from_dict(obs) |
| H, W, C = img.shape |
| self.observation_space = spaces.Box(low=0, high=255, shape=(H, W, C), dtype=np.uint8) |
|
|
| self._last_obs = img |
|
|
| def _obs_from_dict(self, obs_dict): |
| img = obs_dict["agentview_image"] |
| img = img[::-1, :, :] |
| return img |
|
|
| def reset(self, *, seed=None, options=None): |
| if seed is not None: |
| np.random.seed(seed) |
| obs_dict = self._rs_env.reset() |
| img = self._obs_from_dict(obs_dict) |
| self._last_obs = img |
| return img, {} |
|
|
| def step(self, action): |
| |
| action = np.asarray(action, dtype=np.float32) |
| action = np.clip(action, self.action_space.low, self.action_space.high) |
|
|
| obs_dict, reward, done, info = self._rs_env.step(action) |
| img = self._obs_from_dict(obs_dict) |
| self._last_obs = img |
|
|
| terminated = bool(done) |
| truncated = False |
| return img, reward, terminated, truncated, info |
|
|
| def render(self): |
| return self._last_obs |
|
|
| def close(self): |
| self._rs_env.close() |
|
|
| def make_env_thunk(env_name, seed, **kwargs): |
| def _thunk(): |
| return make_env(env_name=env_name, seed=seed, **kwargs) |
| return _thunk |
|
|
| def wrap_learned_reward(env, config): |
| """Wrap the environment with a learned reward wrapper. |
| |
| Args: |
| env: A `gym.Env` to wrap with a `LearnedVisualRewardWrapper` wrapper. |
| config: RL config dict, must inherit from base config defined in |
| `configs/rl_default.py`. |
| |
| Returns: |
| gym.Env object. |
| """ |
| pretrained_path = config.reward_wrapper.pretrained_path |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| model_config, model = load_model_checkpoint(pretrained_path, device) |
|
|
| kwargs = { |
| "env": env, |
| "model": model, |
| "device": device, |
| "res_hw": model_config.data_augmentation.image_size, |
| } |
|
|
| if config.reward_wrapper.type == "goal_classifier": |
| env = wrappers.GoalClassifierLearnedVisualReward(**kwargs) |
|
|
| elif config.reward_wrapper.type == "distance_to_goal": |
| kwargs["goal_emb"] = load_pickle(pretrained_path, "goal_emb.pkl") |
| kwargs["distance_scale"] = load_pickle(pretrained_path, "distance_scale.pkl") |
| env = wrappers.DistanceToGoalLearnedVisualReward(**kwargs) |
|
|
| else: |
| raise ValueError( |
| f"{config.reward_wrapper.type} is not a valid reward wrapper.") |
|
|
| return env |
|
|
| def make_buffer( |
| env, |
| device, |
| config, |
| ): |
| """Replay buffer factory. |
| |
| Args: |
| env: A `gym.Env`. |
| device: A `torch.device` object. |
| config: RL config dict, must inherit from base config defined in |
| `configs/rl_default.py`. |
| |
| Returns: |
| ReplayBuffer. |
| """ |
|
|
| kwargs = { |
| "obs_shape": (config.sac.obs_dim,), |
| "action_shape": (config.sac.actor.action_dim,), |
| "capacity": config.replay_buffer_capacity, |
| "device": device, |
| } |
|
|
| pretrained_path = config.reward_wrapper.pretrained_path |
| if not pretrained_path: |
| return replay_buffer.ReplayBuffer(**kwargs) |
|
|
| model_config, model = load_model_checkpoint(pretrained_path, device) |
| kwargs["model"] = model |
| kwargs["res_hw"] = model_config.data_augmentation.image_size |
|
|
| if config.reward_wrapper.type == "goal_classifier": |
| buffer = replay_buffer.ReplayBufferGoalClassifier(**kwargs) |
|
|
| elif config.reward_wrapper.type == "distance_to_goal": |
| kwargs["goal_emb"] = load_pickle(pretrained_path, "subgoals_emb.pkl") |
| kwargs["distance_scale"] = load_pickle(pretrained_path, "distance_scale.pkl") |
| kwargs["scale_factors"] = load_pickle(pretrained_path, "subgoal_scale_factors.pkl") |
| buffer = replay_buffer.ReplayBufferDistanceToGoal(**kwargs) |
|
|
| else: |
| raise ValueError( |
| f"{config.reward_wrapper.type} is not a valid reward wrapper.") |
|
|
| return buffer, kwargs["goal_emb"], kwargs["scale_factors"] |
|
|
| |
| |
| |
|
|
| def get_paths_from_dir(dir_path): |
| paths = glob.glob(os.path.join(dir_path, 'im*.jpg')) |
| try: |
| paths = sorted(paths, key=lambda x: int((x.split('/')[-1].split('.')[0])[3:])) |
| except: |
| print(paths) |
| return paths |
|
|
| |
| |
| |
|
|
| def plot_reward(rews): |
| """Plot raw and cumulative rewards over an episode.""" |
| _, axes = plt.subplots(1, 2, figsize=(12, 4), sharex=True) |
| axes[0].plot(rews) |
| axes[0].set_xlabel("Timestep") |
| axes[0].set_ylabel("Reward") |
| axes[1].plot(np.cumsum(rews)) |
| axes[1].set_xlabel("Timestep") |
| axes[1].set_ylabel("Cumulative Reward") |
| for ax in axes: |
| ax.grid(visible=True, which="major", linestyle="-") |
| ax.grid(visible=True, which="minor", linestyle="-", alpha=0.2) |
| plt.minorticks_on() |
|
|
| def plot_distance_by_subgoal(dist_txt_path, subgoal_steps, save_dir): |
| """ |
| Plots reward curves broken down by subgoal, handling multiple lines (episodes) |
| from a single text log file. |
| |
| Args: |
| dist_txt_path: Path to the text log file containing comma-separated distances. |
| subgoal_steps: A list of integers representing the number of total steps for each subgoal. |
| save_dir: The directory to save the generated plot. |
| """ |
| if not os.path.exists(dist_txt_path): |
| print(f"Distance log file not found at {dist_txt_path}") |
| return |
|
|
| try: |
| all_dists = np.genfromtxt(dist_txt_path, delimiter=',') |
| if all_dists.ndim == 1: |
| all_dists = all_dists.reshape(1, -1) |
| except Exception as e: |
| print(f"Error reading file {dist_txt_path}: {e}") |
| return |
|
|
| num_episodes = all_dists.shape[0] |
| num_subgoals = len(subgoal_steps) |
| total_steps_expected = sum(subgoal_steps) |
|
|
| if all_dists.shape[1] != total_steps_expected: |
| print(f"Data in file has {all_dists.shape[1]} steps, but expected {total_steps_expected}.") |
| print("This may be due to early termination of an episode.") |
| |
| num_rows = int(np.ceil(num_subgoals / 2.0)) |
| fig, axes = plt.subplots(num_rows, 2, figsize=(12, 5 * num_rows)) |
| axes = axes.flatten() |
|
|
| |
| handles = [] |
| labels = [] |
|
|
| start_idx = 0 |
| for i, steps in enumerate(subgoal_steps): |
| |
| num_reward_points = steps // 3 |
| end_idx = start_idx + num_reward_points |
| |
| |
| |
| subgoal_dists = all_dists[:, start_idx:min(end_idx, all_dists.shape[1])] |
| |
| |
| x_values = np.arange(0, steps, 3) |
| |
| |
| if subgoal_dists.shape[1] < len(x_values): |
| x_values = x_values[:subgoal_dists.shape[1]] |
|
|
| for j in range(num_episodes): |
| ax = axes[i] |
| |
| if len(subgoal_dists[j, :]) == len(x_values): |
| |
| line, = ax.plot(x_values, subgoal_dists[j, :], label=f'Episode {j+1}') |
| if i == 0: |
| handles.append(line) |
| labels.append(f'Episode {j+1}') |
|
|
| ax.set_title(f"Subgoal {i+1} Reward Curve") |
| ax.set_xlabel("Episode Steps") |
| ax.set_ylabel("Negative Distance Reward") |
| ax.grid(True) |
| |
| |
| |
| |
| |
| start_idx = end_idx |
|
|
| for i in range(num_subgoals, len(axes)): |
| fig.delaxes(axes[i]) |
|
|
| |
| |
| fig.legend(handles, labels, loc='lower center', ncol=num_episodes, bbox_to_anchor=(0.5, -0.05)) |
|
|
| plt.tight_layout() |
| plt.savefig(os.path.join(save_dir, "distance_by_subgoal.png")) |
| plt.close(fig) |
|
|