gaussian_noise.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. from gymnasium.spaces import Space
  2. import numpy as np
  3. from typing import Union, Optional
  4. from ray.rllib.models.action_dist import ActionDistribution
  5. from ray.rllib.models.modelv2 import ModelV2
  6. from ray.rllib.utils.annotations import override, PublicAPI
  7. from ray.rllib.utils.exploration.exploration import Exploration
  8. from ray.rllib.utils.exploration.random import Random
  9. from ray.rllib.utils.framework import (
  10. try_import_tf,
  11. try_import_torch,
  12. get_variable,
  13. TensorType,
  14. )
  15. from ray.rllib.utils.numpy import convert_to_numpy
  16. from ray.rllib.utils.schedules import Schedule
  17. from ray.rllib.utils.schedules.piecewise_schedule import PiecewiseSchedule
  18. from ray.rllib.utils.tf_utils import zero_logps_from_actions
  19. tf1, tf, tfv = try_import_tf()
  20. torch, _ = try_import_torch()
  21. @PublicAPI
  22. class GaussianNoise(Exploration):
  23. """An exploration that adds white noise to continuous actions.
  24. If explore=True, returns actions plus scale (annealed over time) x
  25. Gaussian noise. Also, some completely random period is possible at the
  26. beginning.
  27. If explore=False, returns the deterministic action.
  28. """
  29. def __init__(
  30. self,
  31. action_space: Space,
  32. *,
  33. framework: str,
  34. model: ModelV2,
  35. random_timesteps: int = 1000,
  36. stddev: float = 0.1,
  37. initial_scale: float = 1.0,
  38. final_scale: float = 0.02,
  39. scale_timesteps: int = 10000,
  40. scale_schedule: Optional[Schedule] = None,
  41. **kwargs
  42. ):
  43. """Initializes a GaussianNoise instance.
  44. Args:
  45. random_timesteps: The number of timesteps for which to act
  46. completely randomly. Only after this number of timesteps, the
  47. `self.scale` annealing process will start (see below).
  48. stddev: The stddev (sigma) to use for the
  49. Gaussian noise to be added to the actions.
  50. initial_scale: The initial scaling weight to multiply
  51. the noise with.
  52. final_scale: The final scaling weight to multiply
  53. the noise with.
  54. scale_timesteps: The timesteps over which to linearly anneal
  55. the scaling factor (after(!) having used random actions for
  56. `random_timesteps` steps).
  57. scale_schedule: An optional Schedule object
  58. to use (instead of constructing one from the given parameters).
  59. """
  60. assert framework is not None
  61. super().__init__(action_space, model=model, framework=framework, **kwargs)
  62. # Create the Random exploration module (used for the first n
  63. # timesteps).
  64. self.random_timesteps = random_timesteps
  65. self.random_exploration = Random(
  66. action_space, model=self.model, framework=self.framework, **kwargs
  67. )
  68. self.stddev = stddev
  69. # The `scale` annealing schedule.
  70. self.scale_schedule = scale_schedule or PiecewiseSchedule(
  71. endpoints=[
  72. (random_timesteps, initial_scale),
  73. (random_timesteps + scale_timesteps, final_scale),
  74. ],
  75. outside_value=final_scale,
  76. framework=self.framework,
  77. )
  78. # The current timestep value (tf-var or python int).
  79. self.last_timestep = get_variable(
  80. np.array(0, np.int64),
  81. framework=self.framework,
  82. tf_name="timestep",
  83. dtype=np.int64,
  84. )
  85. # Build the tf-info-op.
  86. if self.framework == "tf":
  87. self._tf_state_op = self.get_state()
  88. @override(Exploration)
  89. def get_exploration_action(
  90. self,
  91. *,
  92. action_distribution: ActionDistribution,
  93. timestep: Union[int, TensorType],
  94. explore: bool = True
  95. ):
  96. # Adds IID Gaussian noise for exploration, TD3-style.
  97. if self.framework == "torch":
  98. return self._get_torch_exploration_action(
  99. action_distribution, explore, timestep
  100. )
  101. else:
  102. return self._get_tf_exploration_action_op(
  103. action_distribution, explore, timestep
  104. )
  105. def _get_tf_exploration_action_op(
  106. self,
  107. action_dist: ActionDistribution,
  108. explore: bool,
  109. timestep: Union[int, TensorType],
  110. ):
  111. ts = timestep if timestep is not None else self.last_timestep
  112. # The deterministic actions (if explore=False).
  113. deterministic_actions = action_dist.deterministic_sample()
  114. # Take a Gaussian sample with our stddev (mean=0.0) and scale it.
  115. gaussian_sample = self.scale_schedule(ts) * tf.random.normal(
  116. tf.shape(deterministic_actions), stddev=self.stddev
  117. )
  118. # Stochastic actions could either be: random OR action + noise.
  119. random_actions, _ = self.random_exploration.get_tf_exploration_action_op(
  120. action_dist, explore
  121. )
  122. stochastic_actions = tf.cond(
  123. pred=tf.convert_to_tensor(ts < self.random_timesteps),
  124. true_fn=lambda: random_actions,
  125. false_fn=lambda: tf.clip_by_value(
  126. deterministic_actions + gaussian_sample,
  127. self.action_space.low * tf.ones_like(deterministic_actions),
  128. self.action_space.high * tf.ones_like(deterministic_actions),
  129. ),
  130. )
  131. # Chose by `explore` (main exploration switch).
  132. action = tf.cond(
  133. pred=tf.constant(explore, dtype=tf.bool)
  134. if isinstance(explore, bool)
  135. else explore,
  136. true_fn=lambda: stochastic_actions,
  137. false_fn=lambda: deterministic_actions,
  138. )
  139. # Logp=always zero.
  140. logp = zero_logps_from_actions(deterministic_actions)
  141. # Increment `last_timestep` by 1 (or set to `timestep`).
  142. if self.framework == "tf2":
  143. if timestep is None:
  144. self.last_timestep.assign_add(1)
  145. else:
  146. self.last_timestep.assign(tf.cast(timestep, tf.int64))
  147. return action, logp
  148. else:
  149. assign_op = (
  150. tf1.assign_add(self.last_timestep, 1)
  151. if timestep is None
  152. else tf1.assign(self.last_timestep, timestep)
  153. )
  154. with tf1.control_dependencies([assign_op]):
  155. return action, logp
  156. def _get_torch_exploration_action(
  157. self,
  158. action_dist: ActionDistribution,
  159. explore: bool,
  160. timestep: Union[int, TensorType],
  161. ):
  162. # Set last timestep or (if not given) increase by one.
  163. self.last_timestep = (
  164. timestep if timestep is not None else self.last_timestep + 1
  165. )
  166. # Apply exploration.
  167. if explore:
  168. # Random exploration phase.
  169. if self.last_timestep < self.random_timesteps:
  170. action, _ = self.random_exploration.get_torch_exploration_action(
  171. action_dist, explore=True
  172. )
  173. # Take a Gaussian sample with our stddev (mean=0.0) and scale it.
  174. else:
  175. det_actions = action_dist.deterministic_sample()
  176. scale = self.scale_schedule(self.last_timestep)
  177. gaussian_sample = scale * torch.normal(
  178. mean=torch.zeros(det_actions.size()), std=self.stddev
  179. ).to(self.device)
  180. action = torch.min(
  181. torch.max(
  182. det_actions + gaussian_sample,
  183. torch.tensor(
  184. self.action_space.low,
  185. dtype=torch.float32,
  186. device=self.device,
  187. ),
  188. ),
  189. torch.tensor(
  190. self.action_space.high, dtype=torch.float32, device=self.device
  191. ),
  192. )
  193. # No exploration -> Return deterministic actions.
  194. else:
  195. action = action_dist.deterministic_sample()
  196. # Logp=always zero.
  197. logp = torch.zeros((action.size()[0],), dtype=torch.float32, device=self.device)
  198. return action, logp
  199. @override(Exploration)
  200. def get_state(self, sess: Optional["tf.Session"] = None):
  201. """Returns the current scale value.
  202. Returns:
  203. Union[float,tf.Tensor[float]]: The current scale value.
  204. """
  205. if sess:
  206. return sess.run(self._tf_state_op)
  207. scale = self.scale_schedule(self.last_timestep)
  208. return {
  209. "cur_scale": convert_to_numpy(scale) if self.framework != "tf" else scale,
  210. "last_timestep": convert_to_numpy(self.last_timestep)
  211. if self.framework != "tf"
  212. else self.last_timestep,
  213. }
  214. @override(Exploration)
  215. def set_state(self, state: dict, sess: Optional["tf.Session"] = None) -> None:
  216. if self.framework == "tf":
  217. self.last_timestep.load(state["last_timestep"], session=sess)
  218. elif isinstance(self.last_timestep, int):
  219. self.last_timestep = state["last_timestep"]
  220. else:
  221. self.last_timestep.assign(state["last_timestep"])