torch_mixins.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. from ray.rllib.policy.policy import PolicyState
  2. from ray.rllib.policy.sample_batch import SampleBatch
  3. from ray.rllib.policy.torch_policy import TorchPolicy
  4. from ray.rllib.utils.annotations import OldAPIStack
  5. from ray.rllib.utils.framework import try_import_torch
  6. from ray.rllib.utils.schedules import PiecewiseSchedule
  7. torch, nn = try_import_torch()
  8. @OldAPIStack
  9. class LearningRateSchedule:
  10. """Mixin for TorchPolicy that adds a learning rate schedule."""
  11. def __init__(self, lr, lr_schedule, lr2=None, lr2_schedule=None):
  12. self._lr_schedule = None
  13. self._lr2_schedule = None
  14. # Disable any scheduling behavior related to learning if Learner API is active.
  15. # Schedules are handled by Learner class.
  16. if lr_schedule is None:
  17. self.cur_lr = lr
  18. else:
  19. self._lr_schedule = PiecewiseSchedule(
  20. lr_schedule, outside_value=lr_schedule[-1][-1], framework=None
  21. )
  22. self.cur_lr = self._lr_schedule.value(0)
  23. if lr2_schedule is None:
  24. self.cur_lr2 = lr2
  25. else:
  26. self._lr2_schedule = PiecewiseSchedule(
  27. lr2_schedule, outside_value=lr2_schedule[-1][-1], framework=None
  28. )
  29. self.cur_lr2 = self._lr2_schedule.value(0)
  30. def on_global_var_update(self, global_vars):
  31. super().on_global_var_update(global_vars)
  32. if self._lr_schedule:
  33. self.cur_lr = self._lr_schedule.value(global_vars["timestep"])
  34. for opt in self._optimizers:
  35. for p in opt.param_groups:
  36. p["lr"] = self.cur_lr
  37. if self._lr2_schedule:
  38. assert len(self._optimizers) == 2
  39. self.cur_lr2 = self._lr2_schedule.value(global_vars["timestep"])
  40. opt = self._optimizers[1]
  41. for p in opt.param_groups:
  42. p["lr"] = self.cur_lr2
  43. @OldAPIStack
  44. class EntropyCoeffSchedule:
  45. """Mixin for TorchPolicy that adds entropy coeff decay."""
  46. def __init__(self, entropy_coeff, entropy_coeff_schedule):
  47. self._entropy_coeff_schedule = None
  48. # Disable any scheduling behavior related to learning if Learner API is active.
  49. # Schedules are handled by Learner class.
  50. if entropy_coeff_schedule is None:
  51. self.entropy_coeff = entropy_coeff
  52. else:
  53. # Allows for custom schedule similar to lr_schedule format
  54. if isinstance(entropy_coeff_schedule, list):
  55. self._entropy_coeff_schedule = PiecewiseSchedule(
  56. entropy_coeff_schedule,
  57. outside_value=entropy_coeff_schedule[-1][-1],
  58. framework=None,
  59. )
  60. else:
  61. # Implements previous version but enforces outside_value
  62. self._entropy_coeff_schedule = PiecewiseSchedule(
  63. [[0, entropy_coeff], [entropy_coeff_schedule, 0.0]],
  64. outside_value=0.0,
  65. framework=None,
  66. )
  67. self.entropy_coeff = self._entropy_coeff_schedule.value(0)
  68. def on_global_var_update(self, global_vars):
  69. super(EntropyCoeffSchedule, self).on_global_var_update(global_vars)
  70. if self._entropy_coeff_schedule is not None:
  71. self.entropy_coeff = self._entropy_coeff_schedule.value(
  72. global_vars["timestep"]
  73. )
  74. @OldAPIStack
  75. class KLCoeffMixin:
  76. """Assigns the `update_kl()` method to a TorchPolicy.
  77. This is used by Algorithms to update the KL coefficient
  78. after each learning step based on `config.kl_target` and
  79. the measured KL value (from the train_batch).
  80. """
  81. def __init__(self, config):
  82. # The current KL value (as python float).
  83. self.kl_coeff = config["kl_coeff"]
  84. # Constant target value.
  85. self.kl_target = config["kl_target"]
  86. def update_kl(self, sampled_kl):
  87. # Update the current KL value based on the recently measured value.
  88. if sampled_kl > 2.0 * self.kl_target:
  89. self.kl_coeff *= 1.5
  90. elif sampled_kl < 0.5 * self.kl_target:
  91. self.kl_coeff *= 0.5
  92. # Return the current KL value.
  93. return self.kl_coeff
  94. def get_state(self) -> PolicyState:
  95. state = super().get_state()
  96. # Add current kl-coeff value.
  97. state["current_kl_coeff"] = self.kl_coeff
  98. return state
  99. def set_state(self, state: PolicyState) -> None:
  100. # Set current kl-coeff value first.
  101. self.kl_coeff = state.pop("current_kl_coeff", self.config["kl_coeff"])
  102. # Call super's set_state with rest of the state dict.
  103. super().set_state(state)
  104. @OldAPIStack
  105. class ValueNetworkMixin:
  106. """Assigns the `_value()` method to a TorchPolicy.
  107. This way, Policy can call `_value()` to get the current VF estimate on a
  108. single(!) observation (as done in `postprocess_trajectory_fn`).
  109. Note: When doing this, an actual forward pass is being performed.
  110. This is different from only calling `model.value_function()`, where
  111. the result of the most recent forward pass is being used to return an
  112. already calculated tensor.
  113. """
  114. def __init__(self, config):
  115. # When doing GAE, we need the value function estimate on the
  116. # observation.
  117. if config.get("use_gae") or config.get("vtrace"):
  118. # Input dict is provided to us automatically via the Model's
  119. # requirements. It's a single-timestep (last one in trajectory)
  120. # input_dict.
  121. def value(**input_dict):
  122. input_dict = SampleBatch(input_dict)
  123. input_dict = self._lazy_tensor_dict(input_dict)
  124. model_out, _ = self.model(input_dict)
  125. # [0] = remove the batch dim.
  126. return self.model.value_function()[0].item()
  127. # When not doing GAE, we do not require the value function's output.
  128. else:
  129. def value(*args, **kwargs):
  130. return 0.0
  131. self._value = value
  132. def extra_action_out(self, input_dict, state_batches, model, action_dist):
  133. """Defines extra fetches per action computation.
  134. Args:
  135. input_dict (Dict[str, TensorType]): The input dict used for the action
  136. computing forward pass.
  137. state_batches (List[TensorType]): List of state tensors (empty for
  138. non-RNNs).
  139. model (ModelV2): The Model object of the Policy.
  140. action_dist: The instantiated distribution
  141. object, resulting from the model's outputs and the given
  142. distribution class.
  143. Returns:
  144. Dict[str, TensorType]: Dict with extra tf fetches to perform per
  145. action computation.
  146. """
  147. # Return value function outputs. VF estimates will hence be added to
  148. # the SampleBatches produced by the sampler(s) to generate the train
  149. # batches going into the loss function.
  150. return {
  151. SampleBatch.VF_PREDS: model.value_function(),
  152. }
  153. @OldAPIStack
  154. class TargetNetworkMixin:
  155. """Mixin class adding a method for (soft) target net(s) synchronizations.
  156. - Adds the `update_target` method to the policy.
  157. Calling `update_target` updates all target Q-networks' weights from their
  158. respective "main" Q-networks, based on tau (smooth, partial updating).
  159. """
  160. def __init__(self):
  161. # Hard initial update from Q-net(s) to target Q-net(s).
  162. tau = self.config.get("tau", 1.0)
  163. self.update_target(tau=tau)
  164. def update_target(self, tau=None):
  165. # Update_target_fn will be called periodically to copy Q network to
  166. # target Q network, using (soft) tau-synching.
  167. tau = tau or self.config.get("tau", 1.0)
  168. model_state_dict = self.model.state_dict()
  169. # Support partial (soft) synching.
  170. # If tau == 1.0: Full sync from Q-model to target Q-model.
  171. # Support partial (soft) synching.
  172. # If tau == 1.0: Full sync from Q-model to target Q-model.
  173. target_state_dict = next(iter(self.target_models.values())).state_dict()
  174. model_state_dict = {
  175. k: tau * model_state_dict[k] + (1 - tau) * v
  176. for k, v in target_state_dict.items()
  177. }
  178. for target in self.target_models.values():
  179. target.load_state_dict(model_state_dict)
  180. def set_weights(self, weights):
  181. # Makes sure that whenever we restore weights for this policy's
  182. # model, we sync the target network (from the main model)
  183. # at the same time.
  184. TorchPolicy.set_weights(self, weights)
  185. self.update_target()