|
| 1 | +"""Helpers to convert between Trajectories and HuggingFace's datasets library.""" |
| 2 | +import functools |
| 3 | +from typing import Any, Dict, Iterable, Sequence, cast |
| 4 | + |
| 5 | +import datasets |
| 6 | +import jsonpickle |
| 7 | +import numpy as np |
| 8 | + |
| 9 | +from imitation.data import types |
| 10 | + |
| 11 | + |
| 12 | +class TrajectoryDatasetSequence(Sequence[types.Trajectory]): |
| 13 | + """A wrapper to present a HF dataset as a sequence of trajectories. |
| 14 | +
|
| 15 | + Converts the dataset to a sequence of trajectories on the fly. |
| 16 | + """ |
| 17 | + |
| 18 | + def __init__(self, dataset: datasets.Dataset): |
| 19 | + """Construct a TrajectoryDatasetSequence.""" |
| 20 | + # TODO: this is just a temporary workaround for |
| 21 | + # https://github.com/huggingface/datasets/issues/5517 |
| 22 | + # switch to .with_format("numpy") once it's fixed |
| 23 | + def numpy_transform(batch): |
| 24 | + return {key: np.asarray(val) for key, val in batch.items()} |
| 25 | + |
| 26 | + self._dataset = dataset.with_transform(numpy_transform) |
| 27 | + self._trajectory_class = ( |
| 28 | + types.TrajectoryWithRew if "rews" in dataset.features else types.Trajectory |
| 29 | + ) |
| 30 | + |
| 31 | + def __len__(self) -> int: |
| 32 | + return len(self._dataset) |
| 33 | + |
| 34 | + def __getitem__(self, idx): |
| 35 | + |
| 36 | + if isinstance(idx, slice): |
| 37 | + dataslice = self._dataset[idx] |
| 38 | + |
| 39 | + # Extract the trajectory kwargs from the dataset slice |
| 40 | + trajectory_kwargs = [ |
| 41 | + {key: dataslice[key][i] for key in dataslice} |
| 42 | + for i in range(len(dataslice["obs"])) |
| 43 | + ] |
| 44 | + |
| 45 | + # Ensure that the infos are decoded lazily using jsonpickle |
| 46 | + for kwargs in trajectory_kwargs: |
| 47 | + kwargs["infos"] = _LazyDecodedList(kwargs["infos"]) |
| 48 | + |
| 49 | + return [self._trajectory_class(**kwargs) for kwargs in trajectory_kwargs] |
| 50 | + else: |
| 51 | + # Extract the trajectory kwargs from the dataset |
| 52 | + kwargs = self._dataset[idx] |
| 53 | + |
| 54 | + # Ensure that the infos are decoded lazily using jsonpickle |
| 55 | + kwargs["infos"] = _LazyDecodedList(kwargs["infos"]) |
| 56 | + |
| 57 | + return self._trajectory_class(**kwargs) |
| 58 | + |
| 59 | + |
| 60 | +class _LazyDecodedList(Sequence[Any]): |
| 61 | + """A wrapper to lazily decode a list of jsonpickled strings. |
| 62 | +
|
| 63 | + Decoded results are cached to avoid decoding the same string multiple times. |
| 64 | +
|
| 65 | + This is used to decode the infos of a trajectory only when they are accessed. |
| 66 | + """ |
| 67 | + |
| 68 | + def __init__(self, encoded_list: Sequence[str]): |
| 69 | + self._encoded_list = encoded_list |
| 70 | + |
| 71 | + def __len__(self): |
| 72 | + return len(self._encoded_list) |
| 73 | + |
| 74 | + # arbitrary cache size just to put a limit on memory usage |
| 75 | + @functools.lru_cache(maxsize=100000) |
| 76 | + def __getitem__(self, idx): |
| 77 | + if isinstance(idx, slice): |
| 78 | + return [jsonpickle.decode(info) for info in self._encoded_list[idx]] |
| 79 | + else: |
| 80 | + return jsonpickle.decode(self._encoded_list[idx]) |
| 81 | + |
| 82 | + |
| 83 | +def make_dict_from_trajectory(trajectory: types.Trajectory): |
| 84 | + """Convert a Trajectory to a dict. |
| 85 | +
|
| 86 | + The dict has the following fields: |
| 87 | + * obs: The observations. Shape: (num_timesteps, obs_dim). dtype: float. |
| 88 | + * acts: The actions. Shape: (num_timesteps, act_dim). dtype: float. |
| 89 | + * infos: The infos. Shape: (num_timesteps, ). dtype: (jsonpickled) str. |
| 90 | + * terminal: The terminal flags. Shape: (num_timesteps, ). dtype: bool. |
| 91 | + * rews: The rewards. Shape: (num_timesteps, ). dtype: float. if applicable. |
| 92 | +
|
| 93 | + Args: |
| 94 | + trajectory: The trajectory to convert. |
| 95 | +
|
| 96 | + Returns: |
| 97 | + A dict representing the trajectory. |
| 98 | + """ |
| 99 | + # Replace 'None' values for `infos`` with array of empty dicts |
| 100 | + infos = cast( |
| 101 | + Sequence[Dict[str, Any]], |
| 102 | + trajectory.infos if trajectory.infos is not None else [{}] * len(trajectory), |
| 103 | + ) |
| 104 | + |
| 105 | + # Encode infos as jsonpickled strings |
| 106 | + encoded_infos = [jsonpickle.encode(info) for info in infos] |
| 107 | + |
| 108 | + trajectory_dict = dict( |
| 109 | + obs=trajectory.obs, |
| 110 | + acts=trajectory.acts, |
| 111 | + infos=encoded_infos, |
| 112 | + terminal=trajectory.terminal, |
| 113 | + ) |
| 114 | + |
| 115 | + # Add rewards if applicable |
| 116 | + if isinstance(trajectory, types.TrajectoryWithRew): |
| 117 | + trajectory_dict["rews"] = trajectory.rews |
| 118 | + |
| 119 | + return trajectory_dict |
| 120 | + |
| 121 | + |
| 122 | +def trajectories_to_dict( |
| 123 | + trajectories: Sequence[types.Trajectory], |
| 124 | +) -> Dict[str, Sequence[Any]]: |
| 125 | + """Convert a sequence of trajectories to a dict. |
| 126 | +
|
| 127 | + The dict has the following fields: |
| 128 | +
|
| 129 | + * obs: The observations. Shape: (num_trajectories, num_timesteps, obs_dim). |
| 130 | + * acts: The actions. Shape: (num_trajectories, num_timesteps, act_dim). |
| 131 | + * infos: The infos. Shape: (num_trajectories, num_timesteps) as jsonpickled str. |
| 132 | + * terminal: The terminal flags. Shape: (num_trajectories, num_timesteps, ). |
| 133 | + * rews: The rewards. Shape: (num_trajectories, num_timesteps) if applicable. |
| 134 | +
|
| 135 | + This dict can be used to construct a HuggingFace dataset. |
| 136 | +
|
| 137 | + Args: |
| 138 | + trajectories: The trajectories to save. |
| 139 | +
|
| 140 | + Raises: |
| 141 | + ValueError: If not all trajectories have the same type, i.e. some are |
| 142 | + `Trajectory` and others are `TrajectoryWithRew`. |
| 143 | +
|
| 144 | + Returns: |
| 145 | + A dict representing the trajectories. |
| 146 | + """ |
| 147 | + # Check that all trajectories have rewards or none have rewards |
| 148 | + has_reward = [isinstance(traj, types.TrajectoryWithRew) for traj in trajectories] |
| 149 | + all_trajectories_have_reward = all(has_reward) |
| 150 | + if not all_trajectories_have_reward and any(has_reward): |
| 151 | + raise ValueError("Some trajectories have rewards but not all") |
| 152 | + |
| 153 | + # Convert to dict |
| 154 | + trajectory_dict: Dict[str, Sequence[Any]] = dict( |
| 155 | + obs=[traj.obs for traj in trajectories], |
| 156 | + acts=[traj.acts for traj in trajectories], |
| 157 | + # Replace 'None' values for `infos`` with array of empty dicts |
| 158 | + infos=[ |
| 159 | + traj.infos if traj.infos is not None else [{}] * len(traj) |
| 160 | + for traj in trajectories |
| 161 | + ], |
| 162 | + terminal=[traj.terminal for traj in trajectories], |
| 163 | + ) |
| 164 | + |
| 165 | + # Encode infos as jsonpickled strings |
| 166 | + trajectory_dict["infos"] = [ |
| 167 | + [jsonpickle.encode(info) for info in traj_infos] |
| 168 | + for traj_infos in cast(Iterable[Iterable[Dict]], trajectory_dict["infos"]) |
| 169 | + ] |
| 170 | + |
| 171 | + # Add rewards if applicable |
| 172 | + if all_trajectories_have_reward: |
| 173 | + trajectory_dict["rews"] = [ |
| 174 | + cast(types.TrajectoryWithRew, traj).rews for traj in trajectories |
| 175 | + ] |
| 176 | + return trajectory_dict |
0 commit comments