callbacks.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. import gc
  2. import os
  3. import platform
  4. import tracemalloc
  5. from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Type, Union
  6. import numpy as np
  7. from ray.rllib.env.base_env import BaseEnv
  8. from ray.rllib.env.env_context import EnvContext
  9. from ray.rllib.evaluation.episode import Episode
  10. from ray.rllib.evaluation.episode_v2 import EpisodeV2
  11. from ray.rllib.evaluation.postprocessing import Postprocessing
  12. from ray.rllib.policy import Policy
  13. from ray.rllib.policy.sample_batch import SampleBatch
  14. from ray.rllib.utils.annotations import (
  15. override,
  16. OverrideToImplementCustomLogic,
  17. PublicAPI,
  18. )
  19. from ray.rllib.utils.deprecation import Deprecated, deprecation_warning
  20. from ray.rllib.utils.exploration.random_encoder import (
  21. _MovingMeanStd,
  22. compute_states_entropy,
  23. update_beta,
  24. )
  25. from ray.rllib.utils.typing import AgentID, EnvType, PolicyID
  26. from ray.tune.callback import _CallbackMeta
  27. # Import psutil after ray so the packaged version is used.
  28. import psutil
  29. if TYPE_CHECKING:
  30. from ray.rllib.algorithms.algorithm import Algorithm
  31. from ray.rllib.evaluation import RolloutWorker
  32. @PublicAPI
  33. class DefaultCallbacks(metaclass=_CallbackMeta):
  34. """Abstract base class for RLlib callbacks (similar to Keras callbacks).
  35. These callbacks can be used for custom metrics and custom postprocessing.
  36. By default, all of these callbacks are no-ops. To configure custom training
  37. callbacks, subclass DefaultCallbacks and then set
  38. {"callbacks": YourCallbacksClass} in the algo config.
  39. """
  40. def __init__(self, legacy_callbacks_dict: Dict[str, callable] = None):
  41. if legacy_callbacks_dict:
  42. deprecation_warning(
  43. "callbacks dict interface",
  44. (
  45. "a class extending rllib.algorithms.callbacks.DefaultCallbacks; see"
  46. " `rllib/examples/custom_metrics_and_callbacks.py` for an example."
  47. ),
  48. error=True,
  49. )
  50. @OverrideToImplementCustomLogic
  51. def on_algorithm_init(
  52. self,
  53. *,
  54. algorithm: "Algorithm",
  55. **kwargs,
  56. ) -> None:
  57. """Callback run when a new algorithm instance has finished setup.
  58. This method gets called at the end of Algorithm.setup() after all
  59. the initialization is done, and before actually training starts.
  60. Args:
  61. algorithm: Reference to the Algorithm instance.
  62. kwargs: Forward compatibility placeholder.
  63. """
  64. pass
  65. @OverrideToImplementCustomLogic
  66. def on_create_policy(self, *, policy_id: PolicyID, policy: Policy) -> None:
  67. """Callback run whenever a new policy is added to an algorithm.
  68. Args:
  69. policy_id: ID of the newly created policy.
  70. policy: the policy just created.
  71. """
  72. pass
  73. @OverrideToImplementCustomLogic
  74. def on_sub_environment_created(
  75. self,
  76. *,
  77. worker: "RolloutWorker",
  78. sub_environment: EnvType,
  79. env_context: EnvContext,
  80. env_index: Optional[int] = None,
  81. **kwargs,
  82. ) -> None:
  83. """Callback run when a new sub-environment has been created.
  84. This method gets called after each sub-environment (usually a
  85. gym.Env) has been created, validated (RLlib built-in validation
  86. + possible custom validation function implemented by overriding
  87. `Algorithm.validate_env()`), wrapped (e.g. video-wrapper), and seeded.
  88. Args:
  89. worker: Reference to the current rollout worker.
  90. sub_environment: The sub-environment instance that has been
  91. created. This is usually a gym.Env object.
  92. env_context: The `EnvContext` object that has been passed to
  93. the env's constructor.
  94. kwargs: Forward compatibility placeholder.
  95. """
  96. pass
  97. @OverrideToImplementCustomLogic
  98. def on_episode_created(
  99. self,
  100. *,
  101. worker: "RolloutWorker",
  102. base_env: BaseEnv,
  103. policies: Dict[PolicyID, Policy],
  104. env_index: int,
  105. episode: Union[Episode, EpisodeV2],
  106. **kwargs,
  107. ) -> None:
  108. """Callback run when a new episode is created (but has not started yet!).
  109. This method gets called after a new Episode(V2) instance is created to
  110. start a new episode. This happens before the respective sub-environment's
  111. (usually a gym.Env) `reset()` is called by RLlib.
  112. 1) Episode(V2) created: This callback fires.
  113. 2) Respective sub-environment (gym.Env) is `reset()`.
  114. 3) Callback `on_episode_start` is fired.
  115. 4) Stepping through sub-environment/episode commences.
  116. Args:
  117. worker: Reference to the current rollout worker.
  118. base_env: BaseEnv running the episode. The underlying
  119. sub environment objects can be retrieved by calling
  120. `base_env.get_sub_environments()`.
  121. policies: Mapping of policy id to policy objects. In single
  122. agent mode there will only be a single "default" policy.
  123. env_index: The index of the sub-environment that is about to be reset
  124. (within the vector of sub-environments of the BaseEnv).
  125. episode: The newly created episode. This is the one that will be started
  126. with the upcoming reset. Only after the reset call, the
  127. `on_episode_start` event will be triggered.
  128. kwargs: Forward compatibility placeholder.
  129. """
  130. pass
  131. @OverrideToImplementCustomLogic
  132. def on_episode_start(
  133. self,
  134. *,
  135. worker: "RolloutWorker",
  136. base_env: BaseEnv,
  137. policies: Dict[PolicyID, Policy],
  138. episode: Union[Episode, EpisodeV2],
  139. env_index: Optional[int] = None,
  140. **kwargs,
  141. ) -> None:
  142. """Callback run right after an Episode has started.
  143. This method gets called after the Episode(V2)'s respective sub-environment's
  144. (usually a gym.Env) `reset()` is called by RLlib.
  145. 1) Episode(V2) created: Triggers callback `on_episode_created`.
  146. 2) Respective sub-environment (gym.Env) is `reset()`.
  147. 3) Episode(V2) starts: This callback fires.
  148. 4) Stepping through sub-environment/episode commences.
  149. Args:
  150. worker: Reference to the current rollout worker.
  151. base_env: BaseEnv running the episode. The underlying
  152. sub environment objects can be retrieved by calling
  153. `base_env.get_sub_environments()`.
  154. policies: Mapping of policy id to policy objects. In single
  155. agent mode there will only be a single "default" policy.
  156. episode: Episode object which contains the episode's
  157. state. You can use the `episode.user_data` dict to store
  158. temporary data, and `episode.custom_metrics` to store custom
  159. metrics for the episode.
  160. env_index: The index of the sub-environment that started the episode
  161. (within the vector of sub-environments of the BaseEnv).
  162. kwargs: Forward compatibility placeholder.
  163. """
  164. pass
  165. @OverrideToImplementCustomLogic
  166. def on_episode_step(
  167. self,
  168. *,
  169. worker: "RolloutWorker",
  170. base_env: BaseEnv,
  171. policies: Optional[Dict[PolicyID, Policy]] = None,
  172. episode: Union[Episode, EpisodeV2],
  173. env_index: Optional[int] = None,
  174. **kwargs,
  175. ) -> None:
  176. """Runs on each episode step.
  177. Args:
  178. worker: Reference to the current rollout worker.
  179. base_env: BaseEnv running the episode. The underlying
  180. sub environment objects can be retrieved by calling
  181. `base_env.get_sub_environments()`.
  182. policies: Mapping of policy id to policy objects.
  183. In single agent mode there will only be a single
  184. "default_policy".
  185. episode: Episode object which contains episode
  186. state. You can use the `episode.user_data` dict to store
  187. temporary data, and `episode.custom_metrics` to store custom
  188. metrics for the episode.
  189. env_index: The index of the sub-environment that stepped the episode
  190. (within the vector of sub-environments of the BaseEnv).
  191. kwargs: Forward compatibility placeholder.
  192. """
  193. pass
  194. @OverrideToImplementCustomLogic
  195. def on_episode_end(
  196. self,
  197. *,
  198. worker: "RolloutWorker",
  199. base_env: BaseEnv,
  200. policies: Dict[PolicyID, Policy],
  201. episode: Union[Episode, EpisodeV2, Exception],
  202. env_index: Optional[int] = None,
  203. **kwargs,
  204. ) -> None:
  205. """Runs when an episode is done.
  206. Args:
  207. worker: Reference to the current rollout worker.
  208. base_env: BaseEnv running the episode. The underlying
  209. sub environment objects can be retrieved by calling
  210. `base_env.get_sub_environments()`.
  211. policies: Mapping of policy id to policy
  212. objects. In single agent mode there will only be a single
  213. "default_policy".
  214. episode: Episode object which contains episode
  215. state. You can use the `episode.user_data` dict to store
  216. temporary data, and `episode.custom_metrics` to store custom
  217. metrics for the episode.
  218. In case of environment failures, episode may also be an Exception
  219. that gets thrown from the environment before the episode finishes.
  220. Users of this callback may then handle these error cases properly
  221. with their custom logics.
  222. env_index: The index of the sub-environment that ended the episode
  223. (within the vector of sub-environments of the BaseEnv).
  224. kwargs: Forward compatibility placeholder.
  225. """
  226. pass
  227. @OverrideToImplementCustomLogic
  228. def on_evaluate_start(
  229. self,
  230. *,
  231. algorithm: "Algorithm",
  232. **kwargs,
  233. ) -> None:
  234. """Callback before evaluation starts.
  235. This method gets called at the beginning of Algorithm.evaluate().
  236. Args:
  237. algorithm: Reference to the algorithm instance.
  238. kwargs: Forward compatibility placeholder.
  239. """
  240. pass
  241. @OverrideToImplementCustomLogic
  242. def on_evaluate_end(
  243. self,
  244. *,
  245. algorithm: "Algorithm",
  246. evaluation_metrics: dict,
  247. **kwargs,
  248. ) -> None:
  249. """Runs when the evaluation is done.
  250. Runs at the end of Algorithm.evaluate().
  251. Args:
  252. algorithm: Reference to the algorithm instance.
  253. evaluation_metrics: Results dict to be returned from algorithm.evaluate().
  254. You can mutate this object to add additional metrics.
  255. kwargs: Forward compatibility placeholder.
  256. """
  257. pass
  258. @OverrideToImplementCustomLogic
  259. def on_postprocess_trajectory(
  260. self,
  261. *,
  262. worker: "RolloutWorker",
  263. episode: Episode,
  264. agent_id: AgentID,
  265. policy_id: PolicyID,
  266. policies: Dict[PolicyID, Policy],
  267. postprocessed_batch: SampleBatch,
  268. original_batches: Dict[AgentID, Tuple[Policy, SampleBatch]],
  269. **kwargs,
  270. ) -> None:
  271. """Called immediately after a policy's postprocess_fn is called.
  272. You can use this callback to do additional postprocessing for a policy,
  273. including looking at the trajectory data of other agents in multi-agent
  274. settings.
  275. Args:
  276. worker: Reference to the current rollout worker.
  277. episode: Episode object.
  278. agent_id: Id of the current agent.
  279. policy_id: Id of the current policy for the agent.
  280. policies: Mapping of policy id to policy objects. In single
  281. agent mode there will only be a single "default_policy".
  282. postprocessed_batch: The postprocessed sample batch
  283. for this agent. You can mutate this object to apply your own
  284. trajectory postprocessing.
  285. original_batches: Mapping of agents to their unpostprocessed
  286. trajectory data. You should not mutate this object.
  287. kwargs: Forward compatibility placeholder.
  288. """
  289. pass
  290. @OverrideToImplementCustomLogic
  291. def on_sample_end(
  292. self, *, worker: "RolloutWorker", samples: SampleBatch, **kwargs
  293. ) -> None:
  294. """Called at the end of RolloutWorker.sample().
  295. Args:
  296. worker: Reference to the current rollout worker.
  297. samples: Batch to be returned. You can mutate this
  298. object to modify the samples generated.
  299. kwargs: Forward compatibility placeholder.
  300. """
  301. pass
  302. @OverrideToImplementCustomLogic
  303. def on_learn_on_batch(
  304. self, *, policy: Policy, train_batch: SampleBatch, result: dict, **kwargs
  305. ) -> None:
  306. """Called at the beginning of Policy.learn_on_batch().
  307. Note: This is called before 0-padding via
  308. `pad_batch_to_sequences_of_same_size`.
  309. Also note, SampleBatch.INFOS column will not be available on
  310. train_batch within this callback if framework is tf1, due to
  311. the fact that tf1 static graph would mistake it as part of the
  312. input dict if present.
  313. It is available though, for tf2 and torch frameworks.
  314. Args:
  315. policy: Reference to the current Policy object.
  316. train_batch: SampleBatch to be trained on. You can
  317. mutate this object to modify the samples generated.
  318. result: A results dict to add custom metrics to.
  319. kwargs: Forward compatibility placeholder.
  320. """
  321. pass
  322. @OverrideToImplementCustomLogic
  323. def on_train_result(
  324. self,
  325. *,
  326. algorithm: "Algorithm",
  327. result: dict,
  328. **kwargs,
  329. ) -> None:
  330. """Called at the end of Algorithm.train().
  331. Args:
  332. algorithm: Current Algorithm instance.
  333. result: Dict of results returned from Algorithm.train() call.
  334. You can mutate this object to add additional metrics.
  335. kwargs: Forward compatibility placeholder.
  336. """
  337. pass
  338. class MemoryTrackingCallbacks(DefaultCallbacks):
  339. """MemoryTrackingCallbacks can be used to trace and track memory usage
  340. in rollout workers.
  341. The Memory Tracking Callbacks uses tracemalloc and psutil to track
  342. python allocations during rollouts,
  343. in training or evaluation.
  344. The tracking data is logged to the custom_metrics of an episode and
  345. can therefore be viewed in tensorboard
  346. (or in WandB etc..)
  347. Add MemoryTrackingCallbacks callback to the tune config
  348. e.g. { ...'callbacks': MemoryTrackingCallbacks ...}
  349. Note:
  350. This class is meant for debugging and should not be used
  351. in production code as tracemalloc incurs
  352. a significant slowdown in execution speed.
  353. """
  354. def __init__(self):
  355. super().__init__()
  356. # Will track the top 10 lines where memory is allocated
  357. tracemalloc.start(10)
  358. @override(DefaultCallbacks)
  359. def on_episode_end(
  360. self,
  361. *,
  362. worker: "RolloutWorker",
  363. base_env: BaseEnv,
  364. policies: Dict[PolicyID, Policy],
  365. episode: Union[Episode, EpisodeV2, Exception],
  366. env_index: Optional[int] = None,
  367. **kwargs,
  368. ) -> None:
  369. gc.collect()
  370. snapshot = tracemalloc.take_snapshot()
  371. top_stats = snapshot.statistics("lineno")
  372. for stat in top_stats[:10]:
  373. count = stat.count
  374. # Convert total size from Bytes to KiB.
  375. size = stat.size / 1024
  376. trace = str(stat.traceback)
  377. episode.custom_metrics[f"tracemalloc/{trace}/size"] = size
  378. episode.custom_metrics[f"tracemalloc/{trace}/count"] = count
  379. process = psutil.Process(os.getpid())
  380. worker_rss = process.memory_info().rss
  381. worker_vms = process.memory_info().vms
  382. if platform.system() == "Linux":
  383. # This is only available on Linux
  384. worker_data = process.memory_info().data
  385. episode.custom_metrics["tracemalloc/worker/data"] = worker_data
  386. episode.custom_metrics["tracemalloc/worker/rss"] = worker_rss
  387. episode.custom_metrics["tracemalloc/worker/vms"] = worker_vms
  388. def make_multi_callbacks(
  389. callback_class_list: List[Type[DefaultCallbacks]],
  390. ) -> DefaultCallbacks:
  391. """Allows combining multiple sub-callbacks into one new callbacks class.
  392. The resulting DefaultCallbacks will call all the sub-callbacks' callbacks
  393. when called.
  394. Args:
  395. callback_class_list: The list of sub-classes of DefaultCallbacks to
  396. be baked into the to-be-returned class. All of these sub-classes'
  397. implemented methods will be called in the given order.
  398. Returns:
  399. A DefaultCallbacks subclass that combines all the given sub-classes.
  400. """
  401. class _MultiCallbacks(DefaultCallbacks):
  402. IS_CALLBACK_CONTAINER = True
  403. def __init__(self):
  404. super().__init__()
  405. self._callback_list = [
  406. callback_class() for callback_class in callback_class_list
  407. ]
  408. @override(DefaultCallbacks)
  409. def on_algorithm_init(self, *, algorithm: "Algorithm", **kwargs) -> None:
  410. for callback in self._callback_list:
  411. callback.on_algorithm_init(algorithm=algorithm, **kwargs)
  412. @override(DefaultCallbacks)
  413. def on_create_policy(self, *, policy_id: PolicyID, policy: Policy) -> None:
  414. for callback in self._callback_list:
  415. callback.on_create_policy(policy_id=policy_id, policy=policy)
  416. @override(DefaultCallbacks)
  417. def on_sub_environment_created(
  418. self,
  419. *,
  420. worker: "RolloutWorker",
  421. sub_environment: EnvType,
  422. env_context: EnvContext,
  423. env_index: Optional[int] = None,
  424. **kwargs,
  425. ) -> None:
  426. for callback in self._callback_list:
  427. callback.on_sub_environment_created(
  428. worker=worker,
  429. sub_environment=sub_environment,
  430. env_context=env_context,
  431. **kwargs,
  432. )
  433. @override(DefaultCallbacks)
  434. def on_episode_created(
  435. self,
  436. *,
  437. worker: "RolloutWorker",
  438. base_env: BaseEnv,
  439. policies: Dict[PolicyID, Policy],
  440. env_index: int,
  441. episode: Union[Episode, EpisodeV2],
  442. **kwargs,
  443. ) -> None:
  444. for callback in self._callback_list:
  445. callback.on_episode_created(
  446. worker=worker,
  447. base_env=base_env,
  448. policies=policies,
  449. env_index=env_index,
  450. episode=episode,
  451. **kwargs,
  452. )
  453. @override(DefaultCallbacks)
  454. def on_episode_start(
  455. self,
  456. *,
  457. worker: "RolloutWorker",
  458. base_env: BaseEnv,
  459. policies: Dict[PolicyID, Policy],
  460. episode: Union[Episode, EpisodeV2],
  461. env_index: Optional[int] = None,
  462. **kwargs,
  463. ) -> None:
  464. for callback in self._callback_list:
  465. callback.on_episode_start(
  466. worker=worker,
  467. base_env=base_env,
  468. policies=policies,
  469. episode=episode,
  470. env_index=env_index,
  471. **kwargs,
  472. )
  473. @override(DefaultCallbacks)
  474. def on_episode_step(
  475. self,
  476. *,
  477. worker: "RolloutWorker",
  478. base_env: BaseEnv,
  479. policies: Optional[Dict[PolicyID, Policy]] = None,
  480. episode: Union[Episode, EpisodeV2],
  481. env_index: Optional[int] = None,
  482. **kwargs,
  483. ) -> None:
  484. for callback in self._callback_list:
  485. callback.on_episode_step(
  486. worker=worker,
  487. base_env=base_env,
  488. policies=policies,
  489. episode=episode,
  490. env_index=env_index,
  491. **kwargs,
  492. )
  493. @override(DefaultCallbacks)
  494. def on_episode_end(
  495. self,
  496. *,
  497. worker: "RolloutWorker",
  498. base_env: BaseEnv,
  499. policies: Dict[PolicyID, Policy],
  500. episode: Union[Episode, EpisodeV2, Exception],
  501. env_index: Optional[int] = None,
  502. **kwargs,
  503. ) -> None:
  504. for callback in self._callback_list:
  505. callback.on_episode_end(
  506. worker=worker,
  507. base_env=base_env,
  508. policies=policies,
  509. episode=episode,
  510. env_index=env_index,
  511. **kwargs,
  512. )
  513. @override(DefaultCallbacks)
  514. def on_evaluate_start(
  515. self,
  516. *,
  517. algorithm: "Algorithm",
  518. **kwargs,
  519. ) -> None:
  520. for callback in self._callback_list:
  521. callback.on_evaluate_start(
  522. algorithm=algorithm,
  523. **kwargs,
  524. )
  525. @override(DefaultCallbacks)
  526. def on_evaluate_end(
  527. self,
  528. *,
  529. algorithm: "Algorithm",
  530. evaluation_metrics: dict,
  531. **kwargs,
  532. ) -> None:
  533. for callback in self._callback_list:
  534. callback.on_evaluate_end(
  535. algorithm=algorithm,
  536. evaluation_metrics=evaluation_metrics,
  537. **kwargs,
  538. )
  539. @override(DefaultCallbacks)
  540. def on_postprocess_trajectory(
  541. self,
  542. *,
  543. worker: "RolloutWorker",
  544. episode: Episode,
  545. agent_id: AgentID,
  546. policy_id: PolicyID,
  547. policies: Dict[PolicyID, Policy],
  548. postprocessed_batch: SampleBatch,
  549. original_batches: Dict[AgentID, Tuple[Policy, SampleBatch]],
  550. **kwargs,
  551. ) -> None:
  552. for callback in self._callback_list:
  553. callback.on_postprocess_trajectory(
  554. worker=worker,
  555. episode=episode,
  556. agent_id=agent_id,
  557. policy_id=policy_id,
  558. policies=policies,
  559. postprocessed_batch=postprocessed_batch,
  560. original_batches=original_batches,
  561. **kwargs,
  562. )
  563. @override(DefaultCallbacks)
  564. def on_sample_end(
  565. self, *, worker: "RolloutWorker", samples: SampleBatch, **kwargs
  566. ) -> None:
  567. for callback in self._callback_list:
  568. callback.on_sample_end(worker=worker, samples=samples, **kwargs)
  569. @override(DefaultCallbacks)
  570. def on_learn_on_batch(
  571. self, *, policy: Policy, train_batch: SampleBatch, result: dict, **kwargs
  572. ) -> None:
  573. for callback in self._callback_list:
  574. callback.on_learn_on_batch(
  575. policy=policy, train_batch=train_batch, result=result, **kwargs
  576. )
  577. @override(DefaultCallbacks)
  578. def on_train_result(self, *, algorithm=None, result: dict, **kwargs) -> None:
  579. for callback in self._callback_list:
  580. callback.on_train_result(algorithm=algorithm, result=result, **kwargs)
  581. return _MultiCallbacks
  582. # This Callback is used by the RE3 exploration strategy.
  583. # See rllib/examples/re3_exploration.py for details.
  584. class RE3UpdateCallbacks(DefaultCallbacks):
  585. """Update input callbacks to mutate batch with states entropy rewards."""
  586. _step = 0
  587. def __init__(
  588. self,
  589. *args,
  590. embeds_dim: int = 128,
  591. k_nn: int = 50,
  592. beta: float = 0.1,
  593. rho: float = 0.0001,
  594. beta_schedule: str = "constant",
  595. **kwargs,
  596. ):
  597. self.embeds_dim = embeds_dim
  598. self.k_nn = k_nn
  599. self.beta = beta
  600. self.rho = rho
  601. self.beta_schedule = beta_schedule
  602. self._rms = _MovingMeanStd()
  603. super().__init__(*args, **kwargs)
  604. @override(DefaultCallbacks)
  605. def on_learn_on_batch(
  606. self,
  607. *,
  608. policy: Policy,
  609. train_batch: SampleBatch,
  610. result: dict,
  611. **kwargs,
  612. ):
  613. super().on_learn_on_batch(
  614. policy=policy, train_batch=train_batch, result=result, **kwargs
  615. )
  616. states_entropy = compute_states_entropy(
  617. train_batch[SampleBatch.OBS_EMBEDS], self.embeds_dim, self.k_nn
  618. )
  619. states_entropy = update_beta(
  620. self.beta_schedule, self.beta, self.rho, RE3UpdateCallbacks._step
  621. ) * np.reshape(
  622. self._rms(states_entropy),
  623. train_batch[SampleBatch.OBS_EMBEDS].shape[:-1],
  624. )
  625. train_batch[SampleBatch.REWARDS] = (
  626. train_batch[SampleBatch.REWARDS] + states_entropy
  627. )
  628. if Postprocessing.ADVANTAGES in train_batch:
  629. train_batch[Postprocessing.ADVANTAGES] = (
  630. train_batch[Postprocessing.ADVANTAGES] + states_entropy
  631. )
  632. train_batch[Postprocessing.VALUE_TARGETS] = (
  633. train_batch[Postprocessing.VALUE_TARGETS] + states_entropy
  634. )
  635. @override(DefaultCallbacks)
  636. def on_train_result(self, *, result: dict, algorithm=None, **kwargs) -> None:
  637. # TODO(gjoliver): Remove explicit _step tracking and pass
  638. # Algorithm._iteration as a parameter to on_learn_on_batch() call.
  639. RE3UpdateCallbacks._step = result["training_iteration"]
  640. super().on_train_result(algorithm=algorithm, result=result, **kwargs)
  641. @Deprecated(
  642. new="ray.rllib.algorithms.callbacks.make_multi_callback([list of "
  643. "`Callbacks` sub-classes to combine into one])",
  644. error=True,
  645. )
  646. class MultiCallbacks(DefaultCallbacks):
  647. pass