preprocessors.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. from collections import OrderedDict
  2. import logging
  3. import numpy as np
  4. import gym
  5. from typing import Any, List
  6. from ray.rllib.utils.annotations import override, PublicAPI
  7. from ray.rllib.utils.spaces.repeated import Repeated
  8. from ray.rllib.utils.typing import TensorType
  9. from ray.rllib.utils.images import resize
  10. from ray.rllib.utils.spaces.space_utils import convert_element_to_space_type
  11. ATARI_OBS_SHAPE = (210, 160, 3)
  12. ATARI_RAM_OBS_SHAPE = (128, )
  13. # Only validate env observations vs the observation space every n times in a
  14. # Preprocessor.
  15. OBS_VALIDATION_INTERVAL = 100
  16. logger = logging.getLogger(__name__)
  17. @PublicAPI
  18. class Preprocessor:
  19. """Defines an abstract observation preprocessor function.
  20. Attributes:
  21. shape (List[int]): Shape of the preprocessed output.
  22. """
  23. @PublicAPI
  24. def __init__(self, obs_space: gym.Space, options: dict = None):
  25. legacy_patch_shapes(obs_space)
  26. self._obs_space = obs_space
  27. if not options:
  28. from ray.rllib.models.catalog import MODEL_DEFAULTS
  29. self._options = MODEL_DEFAULTS.copy()
  30. else:
  31. self._options = options
  32. self.shape = self._init_shape(obs_space, self._options)
  33. self._size = int(np.product(self.shape))
  34. self._i = 0
  35. self._obs_for_type_matching = self._obs_space.sample()
  36. @PublicAPI
  37. def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
  38. """Returns the shape after preprocessing."""
  39. raise NotImplementedError
  40. @PublicAPI
  41. def transform(self, observation: TensorType) -> np.ndarray:
  42. """Returns the preprocessed observation."""
  43. raise NotImplementedError
  44. def write(self, observation: TensorType, array: np.ndarray,
  45. offset: int) -> None:
  46. """Alternative to transform for more efficient flattening."""
  47. array[offset:offset + self._size] = self.transform(observation)
  48. def check_shape(self, observation: Any) -> None:
  49. """Checks the shape of the given observation."""
  50. if self._i % OBS_VALIDATION_INTERVAL == 0:
  51. # Convert lists to np.ndarrays.
  52. if type(observation) is list and isinstance(
  53. self._obs_space, gym.spaces.Box):
  54. observation = np.array(observation).astype(np.float32)
  55. if not self._obs_space.contains(observation):
  56. observation = convert_element_to_space_type(
  57. observation, self._obs_for_type_matching)
  58. try:
  59. if not self._obs_space.contains(observation):
  60. raise ValueError(
  61. "Observation ({} dtype={}) outside given space ({})!",
  62. observation, observation.dtype if isinstance(
  63. self._obs_space,
  64. gym.spaces.Box) else None, self._obs_space)
  65. except AttributeError:
  66. raise ValueError(
  67. "Observation for a Box/MultiBinary/MultiDiscrete space "
  68. "should be an np.array, not a Python list.", observation)
  69. self._i += 1
  70. @property
  71. @PublicAPI
  72. def size(self) -> int:
  73. return self._size
  74. @property
  75. @PublicAPI
  76. def observation_space(self) -> gym.Space:
  77. obs_space = gym.spaces.Box(-1., 1., self.shape, dtype=np.float32)
  78. # Stash the unwrapped space so that we can unwrap dict and tuple spaces
  79. # automatically in modelv2.py
  80. classes = (DictFlatteningPreprocessor, OneHotPreprocessor,
  81. RepeatedValuesPreprocessor, TupleFlatteningPreprocessor)
  82. if isinstance(self, classes):
  83. obs_space.original_space = self._obs_space
  84. return obs_space
  85. class GenericPixelPreprocessor(Preprocessor):
  86. """Generic image preprocessor.
  87. Note: for Atari games, use config {"preprocessor_pref": "deepmind"}
  88. instead for deepmind-style Atari preprocessing.
  89. """
  90. @override(Preprocessor)
  91. def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
  92. self._grayscale = options.get("grayscale")
  93. self._zero_mean = options.get("zero_mean")
  94. self._dim = options.get("dim")
  95. if self._grayscale:
  96. shape = (self._dim, self._dim, 1)
  97. else:
  98. shape = (self._dim, self._dim, 3)
  99. return shape
  100. @override(Preprocessor)
  101. def transform(self, observation: TensorType) -> np.ndarray:
  102. """Downsamples images from (210, 160, 3) by the configured factor."""
  103. self.check_shape(observation)
  104. scaled = observation[25:-25, :, :]
  105. if self._dim < 84:
  106. scaled = resize(scaled, height=84, width=84)
  107. # OpenAI: Resize by half, then down to 42x42 (essentially mipmapping).
  108. # If we resize directly we lose pixels that, when mapped to 42x42,
  109. # aren't close enough to the pixel boundary.
  110. scaled = resize(scaled, height=self._dim, width=self._dim)
  111. if self._grayscale:
  112. scaled = scaled.mean(2)
  113. scaled = scaled.astype(np.float32)
  114. # Rescale needed for maintaining 1 channel
  115. scaled = np.reshape(scaled, [self._dim, self._dim, 1])
  116. if self._zero_mean:
  117. scaled = (scaled - 128) / 128
  118. else:
  119. scaled *= 1.0 / 255.0
  120. return scaled
  121. class AtariRamPreprocessor(Preprocessor):
  122. @override(Preprocessor)
  123. def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
  124. return (128, )
  125. @override(Preprocessor)
  126. def transform(self, observation: TensorType) -> np.ndarray:
  127. self.check_shape(observation)
  128. return (observation.astype("float32") - 128) / 128
  129. class OneHotPreprocessor(Preprocessor):
  130. """One-hot preprocessor for Discrete and MultiDiscrete spaces.
  131. Examples:
  132. >>> self.transform(Discrete(3).sample())
  133. ... np.array([0.0, 1.0, 0.0])
  134. >>> self.transform(MultiDiscrete([2, 3]).sample())
  135. ... np.array([0.0, 1.0, 0.0, 0.0, 1.0])
  136. """
  137. @override(Preprocessor)
  138. def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
  139. if isinstance(obs_space, gym.spaces.Discrete):
  140. return (self._obs_space.n, )
  141. else:
  142. return (np.sum(self._obs_space.nvec), )
  143. @override(Preprocessor)
  144. def transform(self, observation: TensorType) -> np.ndarray:
  145. self.check_shape(observation)
  146. arr = np.zeros(self._init_shape(self._obs_space, {}), dtype=np.float32)
  147. if isinstance(self._obs_space, gym.spaces.Discrete):
  148. arr[observation] = 1
  149. else:
  150. for i, o in enumerate(observation):
  151. arr[np.sum(self._obs_space.nvec[:i]) + o] = 1
  152. return arr
  153. @override(Preprocessor)
  154. def write(self, observation: TensorType, array: np.ndarray,
  155. offset: int) -> None:
  156. array[offset:offset + self.size] = self.transform(observation)
  157. class NoPreprocessor(Preprocessor):
  158. @override(Preprocessor)
  159. def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
  160. return self._obs_space.shape
  161. @override(Preprocessor)
  162. def transform(self, observation: TensorType) -> np.ndarray:
  163. self.check_shape(observation)
  164. return observation
  165. @override(Preprocessor)
  166. def write(self, observation: TensorType, array: np.ndarray,
  167. offset: int) -> None:
  168. array[offset:offset + self._size] = np.array(
  169. observation, copy=False).ravel()
  170. @property
  171. @override(Preprocessor)
  172. def observation_space(self) -> gym.Space:
  173. return self._obs_space
  174. class TupleFlatteningPreprocessor(Preprocessor):
  175. """Preprocesses each tuple element, then flattens it all into a vector.
  176. RLlib models will unpack the flattened output before _build_layers_v2().
  177. """
  178. @override(Preprocessor)
  179. def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
  180. assert isinstance(self._obs_space, gym.spaces.Tuple)
  181. size = 0
  182. self.preprocessors = []
  183. for i in range(len(self._obs_space.spaces)):
  184. space = self._obs_space.spaces[i]
  185. logger.debug("Creating sub-preprocessor for {}".format(space))
  186. preprocessor_class = get_preprocessor(space)
  187. if preprocessor_class is not None:
  188. preprocessor = preprocessor_class(space, self._options)
  189. size += preprocessor.size
  190. else:
  191. preprocessor = None
  192. size += int(np.product(space.shape))
  193. self.preprocessors.append(preprocessor)
  194. return (size, )
  195. @override(Preprocessor)
  196. def transform(self, observation: TensorType) -> np.ndarray:
  197. self.check_shape(observation)
  198. array = np.zeros(self.shape, dtype=np.float32)
  199. self.write(observation, array, 0)
  200. return array
  201. @override(Preprocessor)
  202. def write(self, observation: TensorType, array: np.ndarray,
  203. offset: int) -> None:
  204. assert len(observation) == len(self.preprocessors), observation
  205. for o, p in zip(observation, self.preprocessors):
  206. p.write(o, array, offset)
  207. offset += p.size
  208. class DictFlatteningPreprocessor(Preprocessor):
  209. """Preprocesses each dict value, then flattens it all into a vector.
  210. RLlib models will unpack the flattened output before _build_layers_v2().
  211. """
  212. @override(Preprocessor)
  213. def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
  214. assert isinstance(self._obs_space, gym.spaces.Dict)
  215. size = 0
  216. self.preprocessors = []
  217. for space in self._obs_space.spaces.values():
  218. logger.debug("Creating sub-preprocessor for {}".format(space))
  219. preprocessor_class = get_preprocessor(space)
  220. if preprocessor_class is not None:
  221. preprocessor = preprocessor_class(space, self._options)
  222. size += preprocessor.size
  223. else:
  224. preprocessor = None
  225. size += int(np.product(space.shape))
  226. self.preprocessors.append(preprocessor)
  227. return (size, )
  228. @override(Preprocessor)
  229. def transform(self, observation: TensorType) -> np.ndarray:
  230. self.check_shape(observation)
  231. array = np.zeros(self.shape, dtype=np.float32)
  232. self.write(observation, array, 0)
  233. return array
  234. @override(Preprocessor)
  235. def write(self, observation: TensorType, array: np.ndarray,
  236. offset: int) -> None:
  237. if not isinstance(observation, OrderedDict):
  238. observation = OrderedDict(sorted(observation.items()))
  239. assert len(observation) == len(self.preprocessors), \
  240. (len(observation), len(self.preprocessors))
  241. for o, p in zip(observation.values(), self.preprocessors):
  242. p.write(o, array, offset)
  243. offset += p.size
  244. class RepeatedValuesPreprocessor(Preprocessor):
  245. """Pads and batches the variable-length list value."""
  246. @override(Preprocessor)
  247. def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
  248. assert isinstance(self._obs_space, Repeated)
  249. child_space = obs_space.child_space
  250. self.child_preprocessor = get_preprocessor(child_space)(child_space,
  251. self._options)
  252. # The first slot encodes the list length.
  253. size = 1 + self.child_preprocessor.size * obs_space.max_len
  254. return (size, )
  255. @override(Preprocessor)
  256. def transform(self, observation: TensorType) -> np.ndarray:
  257. array = np.zeros(self.shape)
  258. if isinstance(observation, list):
  259. for elem in observation:
  260. self.child_preprocessor.check_shape(elem)
  261. else:
  262. pass # ValueError will be raised in write() below.
  263. self.write(observation, array, 0)
  264. return array
  265. @override(Preprocessor)
  266. def write(self, observation: TensorType, array: np.ndarray,
  267. offset: int) -> None:
  268. if not isinstance(observation, list):
  269. raise ValueError("Input for {} must be list type, got {}".format(
  270. self, observation))
  271. elif len(observation) > self._obs_space.max_len:
  272. raise ValueError("Input {} exceeds max len of space {}".format(
  273. observation, self._obs_space.max_len))
  274. # The first slot encodes the list length.
  275. array[offset] = len(observation)
  276. for i, elem in enumerate(observation):
  277. offset_i = offset + 1 + i * self.child_preprocessor.size
  278. self.child_preprocessor.write(elem, array, offset_i)
  279. @PublicAPI
  280. def get_preprocessor(space: gym.Space) -> type:
  281. """Returns an appropriate preprocessor class for the given space."""
  282. legacy_patch_shapes(space)
  283. obs_shape = space.shape
  284. if isinstance(space, (gym.spaces.Discrete, gym.spaces.MultiDiscrete)):
  285. preprocessor = OneHotPreprocessor
  286. elif obs_shape == ATARI_OBS_SHAPE:
  287. preprocessor = GenericPixelPreprocessor
  288. elif obs_shape == ATARI_RAM_OBS_SHAPE:
  289. preprocessor = AtariRamPreprocessor
  290. elif isinstance(space, gym.spaces.Tuple):
  291. preprocessor = TupleFlatteningPreprocessor
  292. elif isinstance(space, gym.spaces.Dict):
  293. preprocessor = DictFlatteningPreprocessor
  294. elif isinstance(space, Repeated):
  295. preprocessor = RepeatedValuesPreprocessor
  296. else:
  297. preprocessor = NoPreprocessor
  298. return preprocessor
  299. def legacy_patch_shapes(space: gym.Space) -> List[int]:
  300. """Assigns shapes to spaces that don't have shapes.
  301. This is only needed for older gym versions that don't set shapes properly
  302. for Tuple and Discrete spaces.
  303. """
  304. if not hasattr(space, "shape"):
  305. if isinstance(space, gym.spaces.Discrete):
  306. space.shape = ()
  307. elif isinstance(space, gym.spaces.Tuple):
  308. shapes = []
  309. for s in space.spaces:
  310. shape = legacy_patch_shapes(s)
  311. shapes.append(shape)
  312. space.shape = tuple(shapes)
  313. return space.shape