# coding=utf-8 # Copyright 2024 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Environment wrappers. From XIRL by Zakka et al.[1] [1]: https://github.com/google-research/google-research/tree/master/xirl """ import abc import collections import os import time import typing import cv2 import gymnasium import mujoco from gymnasium.envs.mujoco.mujoco_rendering import OffScreenViewer import imageio import numpy as np import torch # from xirl.models import SelfSupervisedModel TimeStep = typing.Tuple[np.ndarray, float, bool, dict] # ModelType = SelfSupervisedModel TensorType = torch.Tensor DistanceFuncType = typing.Callable[[float], float] InfoMetric = typing.Mapping[str, typing.Mapping[str, typing.Any]] class FrameStack(gymnasium.Wrapper): """Stack the last k frames of the env into a flat array. This is useful for allowing the RL policy to infer temporal information. Reference: https://github.com/ikostrikov/jaxrl/ """ def __init__(self, env, k): """Constructor. Args: env: A gym env. k: The number of frames to stack. """ super().__init__(env) assert isinstance(k, int), "k must be an integer." self._k = k self._frames = collections.deque([], maxlen=k) shp = env.observation_space.shape self.observation_space = gymnasium.spaces.Box( low=env.observation_space.low.min(), high=env.observation_space.high.max(), shape=((shp[0] * k,) + shp[1:]), dtype=env.observation_space.dtype, ) def reset(self, seed=None, options=None): obs = self.env.reset() for _ in range(self._k): self._frames.append(obs) return self._get_obs() def step(self, action): obs, reward, terminated, truncated, info = self.env.step(action) self._frames.append(obs) return self._get_obs(), reward, terminated, truncated, info def _get_obs(self): assert len(self._frames) == self._k return np.concatenate(list(self._frames), axis=0) class ActionRepeat(gymnasium.Wrapper): """Repeat the agent's action N times in the environment. Reference: https://github.com/ikostrikov/jaxrl/ """ def __init__(self, env, repeat): """Constructor. Args: env: A gym env. repeat: The number of times to repeat the action per single underlying env step. """ super().__init__(env) assert repeat > 1, "repeat should be greater than 1." self._repeat = repeat def step(self, action): total_reward = 0.0 for _ in range(self._repeat): obs, rew, terminated, truncated, info = self.env.step(action) total_reward += rew if terminated: break return obs, total_reward, terminated, truncated, info class RewardScale(gymnasium.Wrapper): """Scale the environment reward.""" def __init__(self, env, scale): """Constructor. Args: env: A gym env. scale: How much to scale the reward by. """ super().__init__(env) self._scale = scale def step(self, action): obs, reward, terminated, truncated, info = self.env.step(action) reward *= self._scale return obs, reward, terminated, truncated, info def _find_success_fn(env): """Return a callable that checks task success on the underlying env, if any.""" visited = set() def dfs(obj, depth=0, max_depth=20): if obj is None or depth > max_depth or id(obj) in visited: return None visited.add(id(obj)) if hasattr(obj, "is_success") and callable(getattr(obj, "is_success")): def fn(): res = obj.is_success() if isinstance(res, dict): return bool(res.get("task", False)) return bool(res) return fn if hasattr(obj, "_check_success") and callable(getattr(obj, "_check_success")): def fn(): return bool(obj._check_success()) return fn for name in ("env", "_env", "rs_env", "_rs_env", "wrapped_env", "unwrapped"): if hasattr(obj, name): child = getattr(obj, name) if child is not obj: candidate = dfs(child, depth + 1, max_depth) if candidate is not None: return candidate return None return dfs(env) class TerminateOnSuccess(gymnasium.Wrapper): """Terminate the episode as soon as the underlying env reports task success.""" def __init__(self, env): super().__init__(env) self._success_fn = _find_success_fn(env) def step(self, action): obs, rew, terminated, truncated, info = self.env.step(action) if not terminated and self._success_fn is not None: try: if self._success_fn(): terminated = True info["success"] = True except Exception: pass return obs, rew, terminated, truncated, info class EpisodeMonitor(gymnasium.Wrapper): """A class that computes episode metrics. At minimum, episode return, length and duration are computed. Additional metrics that are logged in the environment's info dict can be monitored by specifying them via `info_metrics`. Reference: https://github.com/ikostrikov/jaxrl/ """ def __init__(self, env): super().__init__(env) self._reset_stats() self.total_timesteps: int = 0 self._success_fn = _find_success_fn(self.env) def _reset_stats(self): self.reward_sum: float = 0.0 self.episode_length: int = 0 self.start_time = time.time() def step(self, action): obs, rew, terminated, truncated, info = self.env.step(action) self.reward_sum += rew self.episode_length += 1 self.total_timesteps += 1 info["total"] = {"timesteps": self.total_timesteps} if terminated: info["episode"] = dict() info["episode"]["return"] = self.reward_sum info["episode"]["length"] = self.episode_length info["episode"]["duration"] = time.time() - self.start_time info["episode"]["success"] = self._final_success() return obs, rew, terminated, truncated, info def reset(self, seed=None, options=None): self._reset_stats() return self.env.reset() def _final_success(self) -> bool: """Return success for the *current* final state, or False if unavailable.""" if self._success_fn is None: return False try: return bool(self._success_fn()) except Exception: # Never crash training because of logging return False class VideoRecorder(gymnasium.Wrapper): """Wrapper for rendering and saving rollouts to disk. Reference: https://github.com/ikostrikov/jaxrl/ """ def __init__( self, env, save_dir, resolution = (84, 84), fps = 30, camera = "corner2", # ['corner', 'corner2', 'corner3'] ): super().__init__(env) self.save_dir = save_dir os.makedirs(save_dir, exist_ok=True) self.width, self.height = resolution self.resolution = resolution self.fps = fps self.enabled = True self.current_episode = 0 self.frames = [] self.camera = camera def step(self, action): frame = self.env.render() # offscreen=True, # camera_name=self.camera, # resolution=self.resolution # ) frame = np.flipud(np.array(frame)) if frame.shape[:2] != (self.width, self.height): frame = cv2.resize( frame, dsize=(self.width, self.height), interpolation=cv2.INTER_CUBIC, ) self.frames.append(frame) observation, reward, terminated, truncated, info = self.env.step(action) if truncated or terminated: filename = os.path.join(self.save_dir, f"{self.current_episode}.mp4") imageio.mimsave(filename, self.frames, fps=self.fps) self.frames = [] self.current_episode += 1 return observation, reward, terminated, truncated, info class EnforceMaxPathLength(gymnasium.Wrapper): """Enforce `done=True` when `max_path_length` is reached in MetaWorld.""" def __init__(self, env): super().__init__(env) self.max_path_length = 300 self.episode_steps = 0 def reset(self, seed=None, options=None): self.episode_steps = 0 return self.env.reset() def step(self, action): obs, rew, terminated, truncated, info = self.env.step(action) self.episode_steps += 1 info['episode_steps'] = self.episode_steps if self.episode_steps >= self.max_path_length: terminated = True return obs, rew, terminated, truncated, info class RenderWrapper(gymnasium.Wrapper): """ Minimal RenderWrapper for robosuite. - Assumes observations contain a key like 'agentview_image'. - Extracts that image, optionally flips it vertically. - Stores the latest frame so env.render() returns an RGB array. - Everything else (step/reset) is passed through. """ def __init__(self, env, camera_key="agentview_image", flip_vertical=True): super().__init__(env) self.camera_key = camera_key self.flip_vertical = flip_vertical self._last_frame = None def _extract_frame(self, obs): """ obs can be: - a dict (robosuite obs with images) - already an image array (if a previous wrapper converted it) """ if isinstance(obs, dict): img = obs[self.camera_key] # e.g. obs["agentview_image"] else: # assume it's already an image array img = obs if self.flip_vertical: img = img[::-1, :, :] # flip vertically, like your example self._last_frame = img return obs def reset(self, **kwargs): # gymnasium-style reset: (obs, info) result = self.env.reset(**kwargs) # support both gymnasium (obs, info) and gym (obs) just in case if isinstance(result, tuple) and len(result) == 2: obs, info = result obs = self._extract_frame(obs) return obs, info else: obs = result obs = self._extract_frame(obs) return obs def step(self, action): # gymnasium-style step: (obs, reward, terminated, truncated, info) result = self.env.step(action) if len(result) == 5: obs, reward, terminated, truncated, info = result obs = self._extract_frame(obs) return obs, reward, terminated, truncated, info else: # fallback to gym-style (obs, reward, done, info) obs, reward, done, info = result obs = self._extract_frame(obs) return obs, reward, done, info def render(self): """ Return the latest camera frame as an RGB array, for VideoRecorder etc. """ return self._last_frame # ========================================= # # Learned reward wrappers. # ========================================= # # Note: While the below classes provide a nice wrapper API, they are not # efficient for training RL policies as rewards are computed individually at # every `env.step()` and so cannot take advantage of batching on the GPU. # For actually training policies, it is better to use the learned replay buffer # implementations in `sac.replay_buffer.py`. These store transitions in a # staging buffer which is forwarded as a batch through the GPU. class LearnedVisualReward(abc.ABC, gymnasium.Wrapper): """Base wrapper class that replaces the env reward with a learned one. Subclasses should implement the `_get_reward_from_image` method. """ def __init__( self, env, model, device, res_hw = None, ): """Constructor. Args: env: A gym env. model: A model that ingests RGB frames and returns embeddings. Should be a subclass of `xirl.models.SelfSupervisedModel`. device: Compute device. res_hw: Optional (H, W) to resize the environment image before feeding it to the model. """ super().__init__(env) self._device = device self._model = model.to(device).eval() self._res_hw = res_hw def _to_tensor(self, x): x = torch.from_numpy(x).permute(2, 0, 1).float()[None, None, Ellipsis] # TODO(kevin): Make this more generic for other preprocessing. x = x / 255.0 x = x.to(self._device) return x def _render_obs(self): """Render the pixels at the desired resolution.""" # TODO(kevin): Make sure this works for mujoco envs. pixels = self.env.render(mode="rgb_array") if self._res_hw is not None: h, w = self._res_hw pixels = cv2.resize(pixels, dsize=(w, h), interpolation=cv2.INTER_CUBIC) return pixels @abc.abstractmethod def _get_reward_from_image(self, image): """Forward the pixels through the model and compute the reward.""" def step(self, action): obs, env_reward, done, info = self.env.step(action) # We'll keep the original env reward in the info dict in case the user would # like to use it in conjunction with the learned reward. info["env_reward"] = env_reward pixels = self._render_obs() learned_reward = self._get_reward_from_image(pixels) return obs, learned_reward, done, info class DistanceToGoalLearnedVisualReward(LearnedVisualReward): """Replace the environment reward with distances in embedding space.""" def __init__( self, goal_emb, distance_scale = 1.0, **base_kwargs, ): """Constructor. Args: goal_emb: The goal embedding. distance_scale: Scales the distance from the current state embedding to that of the goal state. Set to `1.0` by default. **base_kwargs: Base keyword arguments. """ super().__init__(**base_kwargs) self._goal_emb = np.atleast_2d(goal_emb) self._distance_scale = distance_scale def _get_reward_from_image(self, image): """Forward the pixels through the model and compute the reward.""" image_tensor = self._to_tensor(image) emb = self._model.infer(image_tensor).numpy().embs dist = -1.0 * np.linalg.norm(emb - self._goal_emb) dist *= self._distance_scale return dist class GoalClassifierLearnedVisualReward(LearnedVisualReward): """Replace the environment reward with the output of a goal classifier.""" def _get_reward_from_image(self, image): """Forward the pixels through the model and compute the reward.""" image_tensor = self._to_tensor(image) prob = torch.sigmoid(self._model.infer(image_tensor).embs) return prob.item()