gaussian_noise.py 9.2 KB

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