File size: 8,220 Bytes
c99d198 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 | # 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.
"""Lightweight in-memory replay buffer. From XIRL by Zakka et al. [1]
Adapted from https://github.com/ikostrikov/jaxrl.
[1]: https://github.com/google-research/google-research/tree/master/xirl
"""
import abc
import collections
from typing import Optional, Tuple
import cv2
import numpy as np
import torch
# from xirl.models import SelfSupervisedModel
Batch = collections.namedtuple(
"Batch", ["obses", "actions", "rewards", "next_obses", "masks", "subgoals"]
)
TensorType = torch.Tensor
# ModelType = SelfSupervisedModel
class ReplayBuffer:
"""Buffer to store environment transitions."""
def __init__(
self,
obs_shape,
action_shape,
capacity,
device,
):
"""Constructor.
Args:
obs_shape: The dimensions of the observation space.
action_shape: The dimensions of the action space
capacity: The maximum length of the replay buffer.
device: The torch device wherein to return sampled transitions.
"""
self.capacity = capacity
self.device = device
obs_dtype = np.float32 if len(obs_shape) == 1 else np.uint8
self.obses = self._empty_arr(obs_shape, obs_dtype)
self.next_obses = self._empty_arr(obs_shape, obs_dtype)
self.actions = self._empty_arr(action_shape, np.float32)
print("In replay buffer, action shape is", action_shape)
self.rewards = self._empty_arr((1,), np.float32)
self.masks = self._empty_arr((1,), np.float32)
self.subgoals = self._empty_arr((256,), np.float32)
self.idx = 0
self.size = 0
def _empty_arr(self, shape, dtype):
"""Creates an empty array of specified shape and type."""
return np.empty((self.capacity, *shape), dtype=dtype)
def _to_tensor(self, arr):
"""Convert an ndarray to a torch Tensor and move it to the device."""
return torch.as_tensor(arr, device=self.device, dtype=torch.float32)
def insert(
self,
obs,
action,
reward,
next_obs,
mask,
subgoal,
):
"""Insert an episode transition into the buffer."""
np.copyto(self.obses[self.idx], obs)
np.copyto(self.actions[self.idx], action)
np.copyto(self.rewards[self.idx], reward)
np.copyto(self.next_obses[self.idx], next_obs)
np.copyto(self.masks[self.idx], mask)
np.copyto(self.subgoals[self.idx], subgoal)
self.idx = (self.idx + 1) % self.capacity
self.size = min(self.size + 1, self.capacity)
def sample(self, batch_size):
"""Sample an episode transition from the buffer."""
idxs = np.random.randint(low=0, high=self.size, size=(batch_size,))
return Batch(
obses=self._to_tensor(self.obses[idxs]),
actions=self._to_tensor(self.actions[idxs]),
rewards=self._to_tensor(self.rewards[idxs]),
next_obses=self._to_tensor(self.next_obses[idxs]),
masks=self._to_tensor(self.masks[idxs]),
subgoals=self._to_tensor(self.subgoals[idxs]),
)
def __len__(self):
return self.size
class ReplayBufferLearnedReward(abc.ABC, ReplayBuffer):
"""Buffer that replaces the environment reward with a learned one.
Subclasses should implement the `_get_reward_from_image` method.
"""
def __init__(
self,
model,
res_hw = None,
batch_size = 64,
**base_kwargs,
):
"""Constructor.
Args:
model: A model that ingests RGB frames and returns embeddings. Should be a
subclass of `xirl.models.SelfSupervisedModel`.
res_hw: Optional (H, W) to resize the environment image before feeding it
to the model.
batch_size: How many samples to forward through the model to compute the
learned reward. Controls the size of the staging lists.
**base_kwargs: Base keyword arguments.
"""
super().__init__(**base_kwargs)
self.model = model
self.res_hw = res_hw
self.batch_size = batch_size
self._reset_staging()
def _reset_staging(self):
self.obses_staging = []
self.next_obses_staging = []
self.actions_staging = []
self.rewards_staging = []
self.masks_staging = []
self.pixels_staging = []
self.subgoal_emb_staging = []
def _pixel_to_tensor(self, arr):
arr = torch.from_numpy(arr).permute(2, 0, 1).float()[None, None, Ellipsis]
arr = arr / 255.0
arr = arr.to(self.device)
return arr
@abc.abstractmethod
def _get_reward_from_image(self):
"""Forward the pixels through the model and compute the reward."""
def insert(
self,
obs,
action,
reward,
next_obs,
mask,
pixels,
subgoal_emb,
):
if len(self.obses_staging) < self.batch_size:
self.obses_staging.append(obs)
self.next_obses_staging.append(next_obs)
self.actions_staging.append(action)
self.rewards_staging.append(reward)
self.masks_staging.append(mask)
if self.res_hw is not None:
h, w = self.res_hw
pixels = cv2.resize(pixels, dsize=(w, h), interpolation=cv2.INTER_CUBIC)
self.pixels_staging.append(pixels)
self.subgoal_emb_staging.append(subgoal_emb)
else:
for obs_s, action_s, reward_s, next_obs_s, mask_s, subgoal_s, reward_env in zip(
self.obses_staging,
self.actions_staging,
self._get_reward_from_image(),
self.next_obses_staging,
self.masks_staging,
self.subgoal_emb_staging,
self.rewards_staging,
):
super().insert(obs_s, action_s, reward_env, next_obs_s, mask_s, subgoal_s)
self._reset_staging()
class ReplayBufferDistanceToGoal(ReplayBufferLearnedReward):
"""Replace the environment reward with distances in embedding space."""
def __init__(
self,
goal_emb,
scale_factors,
distance_scale = 1.0,
**base_kwargs,
):
super().__init__(**base_kwargs)
self.goal_emb = goal_emb[-1]
self.scale_factors = scale_factors
self.distance_scale = distance_scale
print("Using distance to goal reward.")
def _get_reward_from_image(self):
image_tensors = [self._pixel_to_tensor(i) for i in self.pixels_staging]
image_tensors = torch.cat(image_tensors, dim=1)
embs = self.model.infer(image_tensors, ["assembly"]*len(self.obses_staging)).numpy().embs # TODO automate env name
# subgoal_embs = np.stack(self.obses_staging, axis=0)[:, -embs.shape[1]:]
subgoal_embs = np.array(self.subgoal_emb_staging)
embs_norm = embs / (np.linalg.norm(embs, axis=-1, keepdims=True) + 1e-8)
goals_norm = subgoal_embs / (np.linalg.norm(subgoal_embs, axis=-1, keepdims=True) + 1e-8)
dists = -1.0 * np.linalg.norm(embs_norm - goals_norm, axis=-1)
return dists
# def _get_reward_from_image_for_evaluation(self, image_from_evaluation, goal_per_step):
# image_tensors = [self._pixel_to_tensor(i) for i in image_from_evaluation]
# image_tensors = torch.cat(image_tensors, dim=1)
# embs = self.model.infer(image_tensors, ["assembly"]*len(self.obses_staging)).numpy().embs # TODO automate env name
# subgoal_embs = np.array(goal_per_step)[:,:]
# dists = -1.0 * np.linalg.norm(embs - subgoal_embs, axis=-1)
# print(dists.min(), dists.max(), np.sum(dists > -0.16))
# return dists
class ReplayBufferGoalClassifier(ReplayBufferLearnedReward):
"""Replace the environment reward with the output of a goal classifier."""
def _get_reward_from_image(self):
print("Using goal classifier reward.")
image_tensors = [self._pixel_to_tensor(i) for i in self.pixels_staging]
image_tensors = torch.cat(image_tensors, dim=1)
prob = torch.sigmoid(self.model.infer(image_tensors).embs)
return prob.item()
|