VGCP_robosuite / utils.py
Renton-Ren's picture
Upload folder using huggingface_hub (part 65)
c99d198 verified
Raw
History Blame Contribute Delete
23 kB
"""
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])
# Negative x = closer to robot base; positive x = farther from robot.
CUBE_CENTERS = {
"cubeA": np.array([-0.110, 0.0, TABLE_Z]), # red, near robot
"cubeB": np.array([-0.030, 0.0, TABLE_Z]), # green, farther but still close
}
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
# pylint: disable=logging-fstring-interpolation
ConfigDict = config_dict.ConfigDict
FrozenConfigDict = config_dict.FrozenConfigDict
# ========================================= #
# Experiment utils.
# ========================================= #
def setup_experiment(exp_dir, config, resume = False):
"""Initializes a pretraining or RL experiment."""
# If the experiment directory doesn't exist yet, creates it and dumps the
# config dict as a yaml file and git hash as a text file.
# If it exists already, raises a ValueError to prevent overwriting
# unless resume is set to True.
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)
# Inplace update the config if one is provided.
if config is not None:
config.update(cfg)
return ConfigDict(cfg)
def dump_config(exp_dir, config):
"""Dump config to disk."""
# Note: No need to explicitly delete the previous config file as "w" will
# overwrite the file if it already exists.
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."""
# Using the ConfigDict constructor leaves the `FieldReferences` untouched
# unlike `ConfigDict.copy_and_resolve_references`.
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
# ========================================= #
# RL utils.
# ========================================= #
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:
# Disable robot joint initialization noise so reset is deterministic.
robosuite_kwargs.setdefault(
"initialization_noise",
{"magnitude": 0.0, "type": "gaussian"},
)
elif env_name == "Stack":
robosuite_kwargs.setdefault(
"initialization_noise",
{"magnitude": 0.02, "type": "gaussian"},
)
# ------- base robosuite env -------.
# controller_config = load_controller_config(default_controller="OSC_POSE")
# robosuite_kwargs["controller_configs"] = controller_config
# env = RobosuiteGymnasiumEnv(
# env_name=env_name,
# robots=robots,
# control_freq=30,
# camera_heights=camera_heights,
# camera_widths=camera_widths,
# **robosuite_kwargs,
# )
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)
# env = RescaleAction(env, -1.0, 1.0)
if save_dir is not None:
env = wrappers.VideoRecorder(env, save_dir=save_dir)
if frame_stack > 1:
env = wrappers.FrameStack(env, frame_stack)
# Seed.
env.action_space.seed(seed)
np.random.seed(seed)
return env
# class RobosuiteGymnasiumEnv(gym.Env):
# metadata = {"render_modes": ["rgb_array"]}
# def __init__(
# self,
# env_name,
# robots="Panda",
# camera_names="agentview",
# camera_heights=84,
# camera_widths=84,
# **robosuite_kwargs,
# ):
# super().__init__()
# # --- create raw robosuite env (very close to your example) ---
# self._rs_env = suite.make(
# env_name=env_name,
# robots=robots,
# has_renderer=False,
# 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]
# )
# # --- action space from robosuite action_spec ---
# low, high = self._rs_env.action_spec
# low[3:6] = -0.01
# high[3:6] = 0.01
# self.action_space = spaces.Box(low=low, high=high, dtype=np.float32)
# # --- observation space: use agentview image ---
# obs = self._rs_env.reset()
# img = self._obs_from_dict(obs) # (H, W, C)
# 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):
# # adjust key if you want another camera
# img = obs_dict["agentview_image"]
# # robosuite images are usually upside-down; flip vertically if desired
# img = img[::-1, :, :]
# return img
# def reset(self, *, seed=None, options=None):
# if seed is not None:
# # robosuite doesn’t always implement seed(), so just do numpy here
# np.random.seed(seed)
# obs_dict = self._rs_env.reset()
# img = self._obs_from_dict(obs_dict)
# self._last_obs = img
# # gymnasium API: (obs, info)
# return img, {}
# def step(self, action):
# obs_dict, reward, done, info = self._rs_env.step(action)
# img = self._obs_from_dict(obs_dict)
# self._last_obs = img
# # gymnasium API: terminated / truncated
# terminated = bool(done)
# truncated = False # you can refine this if you track time limits
# return img, reward, terminated, truncated, info
# def render(self):
# # Let your wrappers grab the latest observation as an image
# return self._last_obs
# def close(self):
# self._rs_env.close()
import gymnasium as gym
import numpy as np
from gymnasium import spaces
# import robosuite as suite
# from robosuite.controllers import load_composite_controller_config
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, # <-- physical rotation constraint (per-step / per-command units)
has_renderer=False,
render_camera=None,
**robosuite_kwargs,
):
super().__init__()
# Avoid duplicate kwargs if caller also passed these via robosuite_kwargs.
robosuite_kwargs.pop("has_renderer", None)
robosuite_kwargs.pop("render_camera", None)
# 1) Controller config: keep policy action in [-1,1], but shrink *applied* rotation
controller_config = load_composite_controller_config(controller="BASIC")
controller_config["body_parts"] = {"right": controller_config["body_parts"]["right"]}
# For OSC_POSE, action = [dx, dy, dz, dRx, dRy, dRz] (+ gripper handled separately by robosuite if present)
# Constrain ONLY rotation outputs (indices 3:6) to [-rot_eps, rot_eps]
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
# 2) Create robosuite env with controller_configs (this is where the real constraint lives)
self._rs_env = suite.make(
env_name=env_name,
robots=robots,
controller_configs=controller_config, # <-- important
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]
)
# 3) Action space: DO NOT manually tighten bounds here
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)
# 4) Observation space
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, :, :] # flip vertically if desired
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):
# Safety: clip to env bounds so executed == valid (good for consistency)
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,), #env.observation_space.shape,
"action_shape": (config.sac.actor.action_dim,), #env.action_space.shape,
"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") #goal_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"]
# ========================================= #
# AVDC utils.
# ========================================= #
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
# ========================================= #
# Misc. utils.
# ========================================= #
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()
# Create empty lists to store handles and labels for the single legend
handles = []
labels = []
start_idx = 0
for i, steps in enumerate(subgoal_steps):
# Calculate the number of reward data points for this subgoal
num_reward_points = steps // 3
end_idx = start_idx + num_reward_points
# Correctly slice the data for all episodes for the current subgoal
# Note: The reward data is sparse, with one point for every 3 steps.
subgoal_dists = all_dists[:, start_idx:min(end_idx, all_dists.shape[1])]
# Get the corresponding x-axis values (0, 3, 6, ...)
x_values = np.arange(0, steps, 3)
# Ensure x and y dimensions match, handling potential partial data
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]
# Ensure the data for this episode is the correct length
if len(subgoal_dists[j, :]) == len(x_values):
# We need to get handles and labels for the legend
line, = ax.plot(x_values, subgoal_dists[j, :], label=f'Episode {j+1}')
if i == 0: # Only add handles and labels once to avoid duplicates
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)
# REMOVE THIS BLOCK:
# if num_episodes > 1:
# ax.legend()
start_idx = end_idx
for i in range(num_subgoals, len(axes)):
fig.delaxes(axes[i])
# ADD THIS BLOCK:
# Create a single legend at the bottom of the figure
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)