callbacks.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. import gc
  2. import os
  3. import platform
  4. import tracemalloc
  5. from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
  6. import gymnasium as gym
  7. from ray.rllib.core.rl_module.rl_module import RLModule
  8. from ray.rllib.env.base_env import BaseEnv
  9. from ray.rllib.env.env_context import EnvContext
  10. from ray.rllib.evaluation.episode_v2 import EpisodeV2
  11. from ray.rllib.offline.offline_evaluation_runner_group import (
  12. OfflineEvaluationRunnerGroup,
  13. )
  14. from ray.rllib.policy import Policy
  15. from ray.rllib.policy.sample_batch import SampleBatch
  16. from ray.rllib.utils.annotations import (
  17. OldAPIStack,
  18. OverrideToImplementCustomLogic,
  19. PublicAPI,
  20. override,
  21. )
  22. from ray.rllib.utils.metrics.metrics_logger import MetricsLogger
  23. from ray.rllib.utils.typing import AgentID, EnvType, EpisodeType, PolicyID
  24. from ray.tune.callback import _CallbackMeta
  25. # Import psutil after ray so the packaged version is used.
  26. import psutil
  27. if TYPE_CHECKING:
  28. from ray.rllib.algorithms.algorithm import Algorithm
  29. from ray.rllib.env.env_runner import EnvRunner
  30. from ray.rllib.env.env_runner_group import EnvRunnerGroup
  31. @PublicAPI
  32. class RLlibCallback(metaclass=_CallbackMeta):
  33. """Abstract base class for RLlib callbacks (similar to Keras callbacks).
  34. These callbacks can be used for custom metrics and custom postprocessing.
  35. By default, all of these callbacks are no-ops. To configure custom training
  36. callbacks, subclass RLlibCallback and then set
  37. {"callbacks": YourCallbacksClass} in the algo config.
  38. """
  39. @OverrideToImplementCustomLogic
  40. def on_algorithm_init(
  41. self,
  42. *,
  43. algorithm: "Algorithm",
  44. metrics_logger: Optional[MetricsLogger] = None,
  45. **kwargs,
  46. ) -> None:
  47. """Callback run when a new Algorithm instance has finished setup.
  48. This method gets called at the end of Algorithm.setup() after all
  49. the initialization is done, and before actually training starts.
  50. Args:
  51. algorithm: Reference to the Algorithm instance.
  52. metrics_logger: The MetricsLogger object inside the `Algorithm`. Can be
  53. used to log custom metrics after algo initialization.
  54. kwargs: Forward compatibility placeholder.
  55. """
  56. pass
  57. @OverrideToImplementCustomLogic
  58. def on_train_result(
  59. self,
  60. *,
  61. algorithm: "Algorithm",
  62. metrics_logger: Optional[MetricsLogger] = None,
  63. result: dict,
  64. **kwargs,
  65. ) -> None:
  66. """Called at the end of Algorithm.train().
  67. Args:
  68. algorithm: Current Algorithm instance.
  69. metrics_logger: The MetricsLogger object inside the Algorithm. Can be
  70. used to log custom metrics after traing results are available.
  71. result: Dict of results returned from Algorithm.train() call.
  72. You can mutate this object to add additional metrics.
  73. kwargs: Forward compatibility placeholder.
  74. """
  75. pass
  76. @OverrideToImplementCustomLogic
  77. def on_evaluate_start(
  78. self,
  79. *,
  80. algorithm: "Algorithm",
  81. metrics_logger: Optional[MetricsLogger] = None,
  82. **kwargs,
  83. ) -> None:
  84. """Callback before evaluation starts.
  85. This method gets called at the beginning of Algorithm.evaluate().
  86. Args:
  87. algorithm: Reference to the algorithm instance.
  88. metrics_logger: The MetricsLogger object inside the `Algorithm`. Can be
  89. used to log custom metrics before running the next round of evaluation.
  90. kwargs: Forward compatibility placeholder.
  91. """
  92. pass
  93. @OverrideToImplementCustomLogic
  94. def on_evaluate_offline_start(
  95. self,
  96. *,
  97. algorithm: "Algorithm",
  98. metrics_logger: Optional[MetricsLogger] = None,
  99. **kwargs,
  100. ) -> None:
  101. """Callback before offline evaluation starts.
  102. This method gets called at the beginning of Algorithm.evaluate_offline().
  103. Args:
  104. algorithm: Reference to the algorithm instance.
  105. metrics_logger: The MetricsLogger object inside the `Algorithm`. Can be
  106. used to log custom metrics before running the next round of offline
  107. evaluation.
  108. kwargs: Forward compatibility placeholder.
  109. """
  110. pass
  111. @OverrideToImplementCustomLogic
  112. def on_evaluate_end(
  113. self,
  114. *,
  115. algorithm: "Algorithm",
  116. metrics_logger: Optional[MetricsLogger] = None,
  117. evaluation_metrics: dict,
  118. **kwargs,
  119. ) -> None:
  120. """Runs when the evaluation is done.
  121. Runs at the end of Algorithm.evaluate().
  122. Args:
  123. algorithm: Reference to the algorithm instance.
  124. metrics_logger: The MetricsLogger object inside the `Algorithm`. Can be
  125. used to log custom metrics after the most recent evaluation round.
  126. evaluation_metrics: Results dict to be returned from algorithm.evaluate().
  127. You can mutate this object to add additional metrics.
  128. kwargs: Forward compatibility placeholder.
  129. """
  130. pass
  131. @OverrideToImplementCustomLogic
  132. def on_evaluate_offline_end(
  133. self,
  134. *,
  135. algorithm: "Algorithm",
  136. metrics_logger: Optional[MetricsLogger] = None,
  137. evaluation_metrics: dict,
  138. **kwargs,
  139. ) -> None:
  140. """Runs when the offline evaluation is done.
  141. Runs at the end of Algorithm.evaluate_offline().
  142. Args:
  143. algorithm: Reference to the algorithm instance.
  144. metrics_logger: The MetricsLogger object inside the `Algorithm`. Can be
  145. used to log custom metrics after the most recent offline evaluation
  146. round.
  147. evaluation_metrics: Results dict to be returned from
  148. Algorithm.evaluate_offline(). You can mutate this object to add
  149. additional metrics.
  150. kwargs: Forward compatibility placeholder.
  151. """
  152. pass
  153. @OverrideToImplementCustomLogic
  154. def on_env_runners_recreated(
  155. self,
  156. *,
  157. algorithm: "Algorithm",
  158. env_runner_group: "EnvRunnerGroup",
  159. env_runner_indices: List[int],
  160. is_evaluation: bool,
  161. **kwargs,
  162. ) -> None:
  163. """Callback run after one or more EnvRunner actors have been recreated.
  164. You can access and change the EnvRunners in question through the following code
  165. snippet inside your custom override of this method:
  166. .. testcode::
  167. from ray.rllib.callbacks.callbacks import RLlibCallback
  168. class MyCallbacks(RLlibCallback):
  169. def on_env_runners_recreated(
  170. self,
  171. *,
  172. algorithm,
  173. env_runner_group,
  174. env_runner_indices,
  175. is_evaluation,
  176. **kwargs,
  177. ):
  178. # Define what you would like to do on the recreated EnvRunner:
  179. def func(env_runner):
  180. # Here, we just set some arbitrary property to 1.
  181. if is_evaluation:
  182. env_runner._custom_property_for_evaluation = 1
  183. else:
  184. env_runner._custom_property_for_training = 1
  185. # Use the `foreach_env_runner` method of the worker set and
  186. # only loop through those worker IDs that have been restarted.
  187. # Note that we set `local_worker=False` to NOT include it (local
  188. # workers are never recreated; if they fail, the entire Algorithm
  189. # fails).
  190. env_runner_group.foreach_env_runner(
  191. func,
  192. remote_worker_ids=env_runner_indices,
  193. local_env_runner=False,
  194. )
  195. Args:
  196. algorithm: Reference to the Algorithm instance.
  197. env_runner_group: The EnvRunnerGroup object in which the workers in question
  198. reside. You can use a `env_runner_group.foreach_env_runner(
  199. remote_worker_ids=..., local_env_runner=False)` method call to execute
  200. custom code on the recreated (remote) workers. Note that the local
  201. worker is never recreated as a failure of this would also crash the
  202. Algorithm.
  203. env_runner_indices: The list of (remote) worker IDs that have been
  204. recreated.
  205. is_evaluation: Whether `worker_set` is the evaluation EnvRunnerGroup
  206. (located in `Algorithm.eval_env_runner_group`) or not.
  207. """
  208. pass
  209. @OverrideToImplementCustomLogic
  210. def on_offline_eval_runners_recreated(
  211. self,
  212. *,
  213. algorithm: "Algorithm",
  214. offline_eval_runner_group: "OfflineEvaluationRunnerGroup",
  215. offline_eval_runner_indices: List[int],
  216. **kwargs,
  217. ) -> None:
  218. """Callback run after one or more OfflineEvaluationRunner actors have been recreated.
  219. You can access and change the OfflineEvaluationRunners in question through the following code
  220. snippet inside your custom override of this method:
  221. .. testcode::
  222. from ray.rllib.callbacks.callbacks import RLlibCallback
  223. class MyCallbacks(RLlibCallback):
  224. def on_offline_eval_runners_recreated(
  225. self,
  226. *,
  227. algorithm,
  228. offline_eval_runner_group,
  229. offline_eval_runner_indices,
  230. **kwargs,
  231. ):
  232. # Define what you would like to do on the recreated EnvRunner:
  233. def func(offline_eval_runner):
  234. # Here, we just set some arbitrary property to 1.
  235. if is_evaluation:
  236. offline_eval_runner._custom_property_for_evaluation = 1
  237. else:
  238. offline_eval_runner._custom_property_for_training = 1
  239. # Use the `foreach_runner` method of the worker set and
  240. # only loop through those worker IDs that have been restarted.
  241. # Note that `local_runner=False` as long as there are remote
  242. # runners.
  243. offline_eval_runner_group.foreach_runner(
  244. func,
  245. remote_runner_ids=offline_eval_runner_indices,
  246. local_runner=False,
  247. )
  248. Args:
  249. algorithm: Reference to the Algorithm instance.
  250. offline_eval_runner_group: The OfflineEvaluationRunnerGroup object in which
  251. the workers in question reside. You can use a `runner_group.foreach_runner(
  252. remote_worker_ids=..., local_runner=False)` method call to execute
  253. custom code on the recreated (remote) workers.
  254. offline_eval_runner_indices: The list of (remote) worker IDs that have been
  255. recreated.
  256. """
  257. pass
  258. @OverrideToImplementCustomLogic
  259. def on_checkpoint_loaded(
  260. self,
  261. *,
  262. algorithm: "Algorithm",
  263. **kwargs,
  264. ) -> None:
  265. """Callback run when an Algorithm has loaded a new state from a checkpoint.
  266. This method gets called at the end of `Algorithm.load_checkpoint()`.
  267. Args:
  268. algorithm: Reference to the Algorithm instance.
  269. kwargs: Forward compatibility placeholder.
  270. """
  271. pass
  272. @OverrideToImplementCustomLogic
  273. def on_environment_created(
  274. self,
  275. *,
  276. env_runner: "EnvRunner",
  277. metrics_logger: Optional[MetricsLogger] = None,
  278. env: gym.Env,
  279. env_context: EnvContext,
  280. **kwargs,
  281. ) -> None:
  282. """Callback run when a new environment object has been created.
  283. Note: This only applies to the new API stack. The env used is usually a
  284. gym.Env (or more specifically a gym.vector.Env).
  285. Args:
  286. env_runner: Reference to the current EnvRunner instance.
  287. metrics_logger: The MetricsLogger object inside the `env_runner`. Can be
  288. used to log custom metrics after environment creation.
  289. env: The environment object that has been created on `env_runner`. This is
  290. usually a gym.Env (or a gym.vector.Env) object.
  291. env_context: The `EnvContext` object that has been passed to the
  292. `gym.make()` call as kwargs (and to the gym.Env as `config`). It should
  293. have all the config key/value pairs in it as well as the
  294. EnvContext-typical properties: `worker_index`, `num_workers`, and
  295. `remote`.
  296. kwargs: Forward compatibility placeholder.
  297. """
  298. pass
  299. @OverrideToImplementCustomLogic
  300. def on_episode_created(
  301. self,
  302. *,
  303. # TODO (sven): Deprecate Episode/EpisodeV2 with new API stack.
  304. episode: Union[EpisodeType, EpisodeV2],
  305. # TODO (sven): Deprecate this arg new API stack (in favor of `env_runner`).
  306. worker: Optional["EnvRunner"] = None,
  307. env_runner: Optional["EnvRunner"] = None,
  308. metrics_logger: Optional[MetricsLogger] = None,
  309. # TODO (sven): Deprecate this arg new API stack (in favor of `env`).
  310. base_env: Optional[BaseEnv] = None,
  311. env: Optional[gym.Env] = None,
  312. # TODO (sven): Deprecate this arg new API stack (in favor of `rl_module`).
  313. policies: Optional[Dict[PolicyID, Policy]] = None,
  314. rl_module: Optional[RLModule] = None,
  315. env_index: int,
  316. **kwargs,
  317. ) -> None:
  318. """Callback run when a new episode is created (but has not started yet!).
  319. This method gets called after a new SingleAgentEpisode or MultiAgentEpisode
  320. instance has been created. This happens before the respective sub-environment's
  321. `reset()` is called by RLlib.
  322. 1) SingleAgentEpisode/MultiAgentEpisode created: This callback is called.
  323. 2) Respective sub-environment (gym.Env) is `reset()`.
  324. 3) Callback `on_episode_start` is called.
  325. 4) Stepping through sub-environment/episode commences.
  326. Args:
  327. episode: The newly created SingleAgentEpisode or MultiAgentEpisode.
  328. This is the episode that is about to be started with an upcoming
  329. `env.reset()`. Only after this reset call, the `on_episode_start`
  330. callback will be called.
  331. env_runner: Reference to the current EnvRunner.
  332. metrics_logger: The MetricsLogger object inside the `env_runner`. Can be
  333. used to log custom metrics after Episode creation.
  334. env: The gym.Env running the episode.
  335. rl_module: The RLModule used to compute actions for stepping the env. In
  336. single-agent mode, this is a simple RLModule, in multi-agent mode, this
  337. is a MultiRLModule.
  338. env_index: The index of the sub-environment that is about to be reset.
  339. kwargs: Forward compatibility placeholder.
  340. """
  341. pass
  342. @OverrideToImplementCustomLogic
  343. def on_episode_start(
  344. self,
  345. *,
  346. episode: Union[EpisodeType, EpisodeV2],
  347. env_runner: Optional["EnvRunner"] = None,
  348. metrics_logger: Optional[MetricsLogger] = None,
  349. env: Optional[gym.Env] = None,
  350. env_index: int,
  351. rl_module: Optional[RLModule] = None,
  352. # TODO (sven): Deprecate these args.
  353. worker: Optional["EnvRunner"] = None,
  354. base_env: Optional[BaseEnv] = None,
  355. policies: Optional[Dict[PolicyID, Policy]] = None,
  356. **kwargs,
  357. ) -> None:
  358. """Callback run right after an Episode has been started.
  359. This method gets called after a SingleAgentEpisode or MultiAgentEpisode instance
  360. has been reset with a call to `env.reset()` by the EnvRunner.
  361. 1) Single-/MultiAgentEpisode created: `on_episode_created()` is called.
  362. 2) Respective sub-environment (gym.Env) is `reset()`.
  363. 3) Single-/MultiAgentEpisode starts: This callback is called.
  364. 4) Stepping through sub-environment/episode commences.
  365. Args:
  366. episode: The just started (after `env.reset()`) SingleAgentEpisode or
  367. MultiAgentEpisode object.
  368. env_runner: Reference to the EnvRunner running the env and episode.
  369. metrics_logger: The MetricsLogger object inside the `env_runner`. Can be
  370. used to log custom metrics during env/episode stepping.
  371. env: The gym.Env or gym.vector.Env object running the started episode.
  372. env_index: The index of the sub-environment that is about to be reset
  373. (within the vector of sub-environments of the BaseEnv).
  374. rl_module: The RLModule used to compute actions for stepping the env. In
  375. single-agent mode, this is a simple RLModule, in multi-agent mode, this
  376. is a MultiRLModule.
  377. kwargs: Forward compatibility placeholder.
  378. """
  379. pass
  380. @OverrideToImplementCustomLogic
  381. def on_episode_step(
  382. self,
  383. *,
  384. episode: Union[EpisodeType, EpisodeV2],
  385. env_runner: Optional["EnvRunner"] = None,
  386. metrics_logger: Optional[MetricsLogger] = None,
  387. env: Optional[gym.Env] = None,
  388. env_index: int,
  389. rl_module: Optional[RLModule] = None,
  390. # TODO (sven): Deprecate these args.
  391. worker: Optional["EnvRunner"] = None,
  392. base_env: Optional[BaseEnv] = None,
  393. policies: Optional[Dict[PolicyID, Policy]] = None,
  394. **kwargs,
  395. ) -> None:
  396. """Called on each episode step (after the action(s) has/have been logged).
  397. Note that on the new API stack, this callback is also called after the final
  398. step of an episode, meaning when terminated/truncated are returned as True
  399. from the `env.step()` call, but is still provided with the non-numpy'ized
  400. episode object (meaning the data has NOT been converted to numpy arrays yet).
  401. The exact time of the call of this callback is after `env.step([action])` and
  402. also after the results of this step (observation, reward, terminated, truncated,
  403. infos) have been logged to the given `episode` object.
  404. Args:
  405. episode: The just stepped SingleAgentEpisode or MultiAgentEpisode object
  406. (after `env.step()` and after returned obs, rewards, etc.. have been
  407. logged to the episode object).
  408. env_runner: Reference to the EnvRunner running the env and episode.
  409. metrics_logger: The MetricsLogger object inside the `env_runner`. Can be
  410. used to log custom metrics during env/episode stepping.
  411. env: The gym.Env or gym.vector.Env object running the started episode.
  412. env_index: The index of the sub-environment that has just been stepped.
  413. rl_module: The RLModule used to compute actions for stepping the env. In
  414. single-agent mode, this is a simple RLModule, in multi-agent mode, this
  415. is a MultiRLModule.
  416. kwargs: Forward compatibility placeholder.
  417. """
  418. pass
  419. @OverrideToImplementCustomLogic
  420. def on_episode_end(
  421. self,
  422. *,
  423. episode: Union[EpisodeType, EpisodeV2],
  424. prev_episode_chunks: Optional[List[EpisodeType]] = None,
  425. env_runner: Optional["EnvRunner"] = None,
  426. metrics_logger: Optional[MetricsLogger] = None,
  427. env: Optional[gym.Env] = None,
  428. env_index: int,
  429. rl_module: Optional[RLModule] = None,
  430. # TODO (sven): Deprecate these args.
  431. worker: Optional["EnvRunner"] = None,
  432. base_env: Optional[BaseEnv] = None,
  433. policies: Optional[Dict[PolicyID, Policy]] = None,
  434. **kwargs,
  435. ) -> None:
  436. """Called when an episode is done (after terminated/truncated have been logged).
  437. The exact time of the call of this callback is after `env.step([action])` and
  438. also after the results of this step (observation, reward, terminated, truncated,
  439. infos) have been logged to the given `episode` object, where either terminated
  440. or truncated were True:
  441. - The env is stepped: `final_obs, rewards, ... = env.step([action])`
  442. - The step results are logged `episode.add_env_step(final_obs, rewards)`
  443. - Callback `on_episode_step` is fired.
  444. - Another env-to-module connector call is made (even though we won't need any
  445. RLModule forward pass anymore). We make this additional call to ensure that in
  446. case users use the connector pipeline to process observations (and write them
  447. back into the episode), the episode object has all observations - even the
  448. terminal one - properly processed.
  449. - ---> This callback `on_episode_end()` is fired. <---
  450. - The episode is numpy'ized (i.e. lists of obs/rewards/actions/etc.. are
  451. converted into numpy arrays).
  452. Args:
  453. episode: The terminated/truncated SingleAgent- or MultiAgentEpisode object
  454. (after `env.step()` that returned terminated=True OR truncated=True and
  455. after the returned obs, rewards, etc.. have been logged to the episode
  456. object). Note that this method is still called before(!) the episode
  457. object is numpy'ized, meaning all its timestep data is still present in
  458. lists of individual timestep data.
  459. prev_episode_chunks: A complete list of all previous episode chunks
  460. with the same ID as `episode` that have been sampled on this EnvRunner.
  461. In order to compile metrics across the complete episode, users should
  462. loop through the list: `[episode] + previous_episode_chunks` and
  463. accumulate the required information.
  464. env_runner: Reference to the EnvRunner running the env and episode.
  465. metrics_logger: The MetricsLogger object inside the `env_runner`. Can be
  466. used to log custom metrics during env/episode stepping.
  467. env: The gym.Env or gym.vector.Env object running the started episode.
  468. env_index: The index of the sub-environment that has just been terminated
  469. or truncated.
  470. rl_module: The RLModule used to compute actions for stepping the env. In
  471. single-agent mode, this is a simple RLModule, in multi-agent mode, this
  472. is a MultiRLModule.
  473. kwargs: Forward compatibility placeholder.
  474. """
  475. pass
  476. @OverrideToImplementCustomLogic
  477. def on_sample_end(
  478. self,
  479. *,
  480. env_runner: Optional["EnvRunner"] = None,
  481. metrics_logger: Optional[MetricsLogger] = None,
  482. samples: Union[SampleBatch, List[EpisodeType]],
  483. # TODO (sven): Deprecate these args.
  484. worker: Optional["EnvRunner"] = None,
  485. **kwargs,
  486. ) -> None:
  487. """Called at the end of `EnvRunner.sample()`.
  488. Args:
  489. env_runner: Reference to the current EnvRunner object.
  490. metrics_logger: The MetricsLogger object inside the `env_runner`. Can be
  491. used to log custom metrics during env/episode stepping.
  492. samples: Lists of SingleAgentEpisode or MultiAgentEpisode instances to be
  493. returned. You can mutate the episodes to modify the returned training
  494. data.
  495. kwargs: Forward compatibility placeholder.
  496. """
  497. pass
  498. @OldAPIStack
  499. def on_sub_environment_created(
  500. self,
  501. *,
  502. worker: "EnvRunner",
  503. sub_environment: EnvType,
  504. env_context: EnvContext,
  505. env_index: Optional[int] = None,
  506. **kwargs,
  507. ) -> None:
  508. """Callback run when a new sub-environment has been created.
  509. This method gets called after each sub-environment (usually a
  510. gym.Env) has been created, validated (RLlib built-in validation
  511. + possible custom validation function implemented by overriding
  512. `Algorithm.validate_env()`), wrapped (e.g. video-wrapper), and seeded.
  513. Args:
  514. worker: Reference to the current EnvRunner.
  515. sub_environment: The sub-environment instance that has been
  516. created. This is usually a gym.Env object.
  517. env_context: The `EnvContext` object that has been passed to
  518. the env's constructor.
  519. env_index: The index of the sub-environment that has been created
  520. (within the vector of sub-environments of the gym.vector.Env).
  521. kwargs: Forward compatibility placeholder.
  522. """
  523. pass
  524. @OldAPIStack
  525. def on_postprocess_trajectory(
  526. self,
  527. *,
  528. worker: "EnvRunner",
  529. episode,
  530. agent_id: AgentID,
  531. policy_id: PolicyID,
  532. policies: Dict[PolicyID, Policy],
  533. postprocessed_batch: SampleBatch,
  534. original_batches: Dict[AgentID, Tuple[Policy, SampleBatch]],
  535. **kwargs,
  536. ) -> None:
  537. """Called immediately after a policy's postprocess_fn is called.
  538. You can use this callback to do additional postprocessing for a policy,
  539. including looking at the trajectory data of other agents in multi-agent
  540. settings.
  541. Args:
  542. worker: Reference to the current rollout worker.
  543. episode: Episode object.
  544. agent_id: Id of the current agent.
  545. policy_id: Id of the current policy for the agent.
  546. policies: Dict mapping policy IDs to policy objects. In single
  547. agent mode there will only be a single "default_policy".
  548. postprocessed_batch: The postprocessed sample batch
  549. for this agent. You can mutate this object to apply your own
  550. trajectory postprocessing.
  551. original_batches: Dict mapping agent IDs to their unpostprocessed
  552. trajectory data. You should not mutate this object.
  553. kwargs: Forward compatibility placeholder.
  554. """
  555. pass
  556. @OldAPIStack
  557. def on_create_policy(self, *, policy_id: PolicyID, policy: Policy) -> None:
  558. """Callback run whenever a new policy is added to an algorithm.
  559. Args:
  560. policy_id: ID of the newly created policy.
  561. policy: The policy just created.
  562. """
  563. pass
  564. @OldAPIStack
  565. def on_learn_on_batch(
  566. self, *, policy: Policy, train_batch: SampleBatch, result: dict, **kwargs
  567. ) -> None:
  568. """Called at the beginning of Policy.learn_on_batch().
  569. Note: This is called before 0-padding via
  570. `pad_batch_to_sequences_of_same_size`.
  571. Also note, SampleBatch.INFOS column will not be available on
  572. train_batch within this callback if framework is tf1, due to
  573. the fact that tf1 static graph would mistake it as part of the
  574. input dict if present.
  575. It is available though, for tf2 and torch frameworks.
  576. Args:
  577. policy: Reference to the current Policy object.
  578. train_batch: SampleBatch to be trained on. You can
  579. mutate this object to modify the samples generated.
  580. result: A results dict to add custom metrics to.
  581. kwargs: Forward compatibility placeholder.
  582. """
  583. pass
  584. # Deprecated, use `on_env_runners_recreated`, instead.
  585. def on_workers_recreated(
  586. self,
  587. *,
  588. algorithm,
  589. worker_set,
  590. worker_ids,
  591. is_evaluation,
  592. **kwargs,
  593. ) -> None:
  594. pass
  595. class MemoryTrackingCallbacks(RLlibCallback):
  596. """MemoryTrackingCallbacks can be used to trace and track memory usage
  597. in rollout workers.
  598. The Memory Tracking Callbacks uses tracemalloc and psutil to track
  599. python allocations during rollouts,
  600. in training or evaluation.
  601. The tracking data is logged to the custom_metrics of an episode and
  602. can therefore be viewed in tensorboard
  603. (or in WandB etc..)
  604. Add MemoryTrackingCallbacks callback to the tune config
  605. e.g. { ...'callbacks': MemoryTrackingCallbacks ...}
  606. Note:
  607. This class is meant for debugging and should not be used
  608. in production code as tracemalloc incurs
  609. a significant slowdown in execution speed.
  610. """
  611. def __init__(self):
  612. super().__init__()
  613. # Will track the top 10 lines where memory is allocated
  614. tracemalloc.start(10)
  615. @override(RLlibCallback)
  616. def on_episode_end(
  617. self,
  618. *,
  619. episode: Union[EpisodeType, EpisodeV2],
  620. env_runner: Optional["EnvRunner"] = None,
  621. metrics_logger: Optional[MetricsLogger] = None,
  622. env: Optional[gym.Env] = None,
  623. env_index: int,
  624. rl_module: Optional[RLModule] = None,
  625. # TODO (sven): Deprecate these args.
  626. worker: Optional["EnvRunner"] = None,
  627. base_env: Optional[BaseEnv] = None,
  628. policies: Optional[Dict[PolicyID, Policy]] = None,
  629. **kwargs,
  630. ) -> None:
  631. gc.collect()
  632. snapshot = tracemalloc.take_snapshot()
  633. top_stats = snapshot.statistics("lineno")
  634. for stat in top_stats[:10]:
  635. count = stat.count
  636. # Convert total size from Bytes to KiB.
  637. size = stat.size / 1024
  638. trace = str(stat.traceback)
  639. episode.custom_metrics[f"tracemalloc/{trace}/size"] = size
  640. episode.custom_metrics[f"tracemalloc/{trace}/count"] = count
  641. process = psutil.Process(os.getpid())
  642. worker_rss = process.memory_info().rss
  643. worker_vms = process.memory_info().vms
  644. if platform.system() == "Linux":
  645. # This is only available on Linux
  646. worker_data = process.memory_info().data
  647. episode.custom_metrics["tracemalloc/worker/data"] = worker_data
  648. episode.custom_metrics["tracemalloc/worker/rss"] = worker_rss
  649. episode.custom_metrics["tracemalloc/worker/vms"] = worker_vms