ornstein_uhlenbeck_noise.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import numpy as np
  2. from typing import Optional, Union
  3. from ray.rllib.models.action_dist import ActionDistribution
  4. from ray.rllib.utils.annotations import override, PublicAPI
  5. from ray.rllib.utils.exploration.gaussian_noise import GaussianNoise
  6. from ray.rllib.utils.framework import (
  7. try_import_tf,
  8. try_import_torch,
  9. get_variable,
  10. TensorType,
  11. )
  12. from ray.rllib.utils.numpy import convert_to_numpy
  13. from ray.rllib.utils.schedules import Schedule
  14. from ray.rllib.utils.tf_utils import zero_logps_from_actions
  15. tf1, tf, tfv = try_import_tf()
  16. torch, _ = try_import_torch()
  17. @PublicAPI
  18. class OrnsteinUhlenbeckNoise(GaussianNoise):
  19. """An exploration that adds Ornstein-Uhlenbeck noise to continuous actions.
  20. If explore=True, returns sampled actions plus a noise term X,
  21. which changes according to this formula:
  22. Xt+1 = -theta*Xt + sigma*N[0,stddev], where theta, sigma and stddev are
  23. constants. Also, some completely random period is possible at the
  24. beginning.
  25. If explore=False, returns the deterministic action.
  26. """
  27. def __init__(
  28. self,
  29. action_space,
  30. *,
  31. framework: str,
  32. ou_theta: float = 0.15,
  33. ou_sigma: float = 0.2,
  34. ou_base_scale: float = 0.1,
  35. random_timesteps: int = 1000,
  36. initial_scale: float = 1.0,
  37. final_scale: float = 0.02,
  38. scale_timesteps: int = 10000,
  39. scale_schedule: Optional[Schedule] = None,
  40. **kwargs
  41. ):
  42. """Initializes an Ornstein-Uhlenbeck Exploration object.
  43. Args:
  44. action_space: The gym action space used by the environment.
  45. ou_theta: The theta parameter of the Ornstein-Uhlenbeck process.
  46. ou_sigma: The sigma parameter of the Ornstein-Uhlenbeck process.
  47. ou_base_scale: A fixed scaling factor, by which all OU-
  48. noise is multiplied. NOTE: This is on top of the parent
  49. GaussianNoise's scaling.
  50. random_timesteps: The number of timesteps for which to act
  51. completely randomly. Only after this number of timesteps, the
  52. `self.scale` annealing process will start (see below).
  53. initial_scale: The initial scaling weight to multiply the
  54. noise with.
  55. final_scale: The final scaling weight to multiply the noise with.
  56. scale_timesteps: The timesteps over which to linearly anneal the
  57. scaling factor (after(!) having used random actions for
  58. `random_timesteps` steps.
  59. scale_schedule: An optional Schedule object to use (instead
  60. of constructing one from the given parameters).
  61. framework: One of None, "tf", "torch".
  62. """
  63. # The current OU-state value (gets updated each time, an eploration
  64. # action is computed).
  65. self.ou_state = get_variable(
  66. np.array(action_space.low.size * [0.0], dtype=np.float32),
  67. framework=framework,
  68. tf_name="ou_state",
  69. torch_tensor=True,
  70. device=None,
  71. )
  72. super().__init__(
  73. action_space,
  74. framework=framework,
  75. random_timesteps=random_timesteps,
  76. initial_scale=initial_scale,
  77. final_scale=final_scale,
  78. scale_timesteps=scale_timesteps,
  79. scale_schedule=scale_schedule,
  80. stddev=1.0, # Force `self.stddev` to 1.0.
  81. **kwargs
  82. )
  83. self.ou_theta = ou_theta
  84. self.ou_sigma = ou_sigma
  85. self.ou_base_scale = ou_base_scale
  86. # Now that we know the device, move ou_state there, in case of PyTorch.
  87. if self.framework == "torch" and self.device is not None:
  88. self.ou_state = self.ou_state.to(self.device)
  89. @override(GaussianNoise)
  90. def _get_tf_exploration_action_op(
  91. self,
  92. action_dist: ActionDistribution,
  93. explore: Union[bool, TensorType],
  94. timestep: Union[int, TensorType],
  95. ):
  96. ts = timestep if timestep is not None else self.last_timestep
  97. scale = self.scale_schedule(ts)
  98. # The deterministic actions (if explore=False).
  99. deterministic_actions = action_dist.deterministic_sample()
  100. # Apply base-scaled and time-annealed scaled OU-noise to
  101. # deterministic actions.
  102. gaussian_sample = tf.random.normal(
  103. shape=[self.action_space.low.size], stddev=self.stddev
  104. )
  105. ou_new = self.ou_theta * -self.ou_state + self.ou_sigma * gaussian_sample
  106. if self.framework == "tf2":
  107. self.ou_state.assign_add(ou_new)
  108. ou_state_new = self.ou_state
  109. else:
  110. ou_state_new = tf1.assign_add(self.ou_state, ou_new)
  111. high_m_low = self.action_space.high - self.action_space.low
  112. high_m_low = tf.where(
  113. tf.math.is_inf(high_m_low), tf.ones_like(high_m_low), high_m_low
  114. )
  115. noise = scale * self.ou_base_scale * ou_state_new * high_m_low
  116. stochastic_actions = tf.clip_by_value(
  117. deterministic_actions + noise,
  118. self.action_space.low * tf.ones_like(deterministic_actions),
  119. self.action_space.high * tf.ones_like(deterministic_actions),
  120. )
  121. # Stochastic actions could either be: random OR action + noise.
  122. random_actions, _ = self.random_exploration.get_tf_exploration_action_op(
  123. action_dist, explore
  124. )
  125. exploration_actions = tf.cond(
  126. pred=tf.convert_to_tensor(ts < self.random_timesteps),
  127. true_fn=lambda: random_actions,
  128. false_fn=lambda: stochastic_actions,
  129. )
  130. # Chose by `explore` (main exploration switch).
  131. action = tf.cond(
  132. pred=tf.constant(explore, dtype=tf.bool)
  133. if isinstance(explore, bool)
  134. else explore,
  135. true_fn=lambda: exploration_actions,
  136. false_fn=lambda: deterministic_actions,
  137. )
  138. # Logp=always zero.
  139. logp = zero_logps_from_actions(deterministic_actions)
  140. # Increment `last_timestep` by 1 (or set to `timestep`).
  141. if self.framework == "tf2":
  142. if timestep is None:
  143. self.last_timestep.assign_add(1)
  144. else:
  145. self.last_timestep.assign(tf.cast(timestep, tf.int64))
  146. else:
  147. assign_op = (
  148. tf1.assign_add(self.last_timestep, 1)
  149. if timestep is None
  150. else tf1.assign(self.last_timestep, timestep)
  151. )
  152. with tf1.control_dependencies([assign_op, ou_state_new]):
  153. action = tf.identity(action)
  154. logp = tf.identity(logp)
  155. return action, logp
  156. @override(GaussianNoise)
  157. def _get_torch_exploration_action(
  158. self,
  159. action_dist: ActionDistribution,
  160. explore: bool,
  161. timestep: Union[int, TensorType],
  162. ):
  163. # Set last timestep or (if not given) increase by one.
  164. self.last_timestep = (
  165. timestep if timestep is not None else self.last_timestep + 1
  166. )
  167. # Apply exploration.
  168. if explore:
  169. # Random exploration phase.
  170. if self.last_timestep < self.random_timesteps:
  171. action, _ = self.random_exploration.get_torch_exploration_action(
  172. action_dist, explore=True
  173. )
  174. # Apply base-scaled and time-annealed scaled OU-noise to
  175. # deterministic actions.
  176. else:
  177. det_actions = action_dist.deterministic_sample()
  178. scale = self.scale_schedule(self.last_timestep)
  179. gaussian_sample = scale * torch.normal(
  180. mean=torch.zeros(self.ou_state.size()), std=1.0
  181. ).to(self.device)
  182. ou_new = (
  183. self.ou_theta * -self.ou_state + self.ou_sigma * gaussian_sample
  184. )
  185. self.ou_state += ou_new
  186. high_m_low = torch.from_numpy(
  187. self.action_space.high - self.action_space.low
  188. ).to(self.device)
  189. high_m_low = torch.where(
  190. torch.isinf(high_m_low),
  191. torch.ones_like(high_m_low).to(self.device),
  192. high_m_low,
  193. )
  194. noise = scale * self.ou_base_scale * self.ou_state * high_m_low
  195. action = torch.min(
  196. torch.max(
  197. det_actions + noise,
  198. torch.tensor(
  199. self.action_space.low,
  200. dtype=torch.float32,
  201. device=self.device,
  202. ),
  203. ),
  204. torch.tensor(
  205. self.action_space.high, dtype=torch.float32, device=self.device
  206. ),
  207. )
  208. # No exploration -> Return deterministic actions.
  209. else:
  210. action = action_dist.deterministic_sample()
  211. # Logp=always zero.
  212. logp = torch.zeros((action.size()[0],), dtype=torch.float32, device=self.device)
  213. return action, logp
  214. @override(GaussianNoise)
  215. def get_state(self, sess: Optional["tf.Session"] = None):
  216. """Returns the current scale value.
  217. Returns:
  218. Union[float,tf.Tensor[float]]: The current scale value.
  219. """
  220. if sess:
  221. return sess.run(
  222. dict(
  223. self._tf_state_op,
  224. **{
  225. "ou_state": self.ou_state,
  226. }
  227. )
  228. )
  229. state = super().get_state()
  230. return dict(
  231. state,
  232. **{
  233. "ou_state": convert_to_numpy(self.ou_state)
  234. if self.framework != "tf"
  235. else self.ou_state,
  236. }
  237. )
  238. @override(GaussianNoise)
  239. def set_state(self, state: dict, sess: Optional["tf.Session"] = None) -> None:
  240. if self.framework == "tf":
  241. self.ou_state.load(state["ou_state"], session=sess)
  242. elif isinstance(self.ou_state, np.ndarray):
  243. self.ou_state = state["ou_state"]
  244. elif torch and torch.is_tensor(self.ou_state):
  245. self.ou_state = torch.from_numpy(state["ou_state"])
  246. else:
  247. self.ou_state.assign(state["ou_state"])
  248. super().set_state(state, sess=sess)