sampler.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  1. from abc import abstractmethod, ABCMeta
  2. from collections import defaultdict, namedtuple
  3. import logging
  4. import numpy as np
  5. import queue
  6. import threading
  7. import time
  8. import tree # pip install dm_tree
  9. from typing import Any, Callable, Dict, List, Iterator, Optional, Set, Tuple,\
  10. Type, TYPE_CHECKING, Union
  11. from ray.util.debug import log_once
  12. from ray.rllib.evaluation.collectors.sample_collector import \
  13. SampleCollector
  14. from ray.rllib.evaluation.collectors.simple_list_collector import \
  15. SimpleListCollector
  16. from ray.rllib.evaluation.episode import Episode
  17. from ray.rllib.evaluation.metrics import RolloutMetrics
  18. from ray.rllib.evaluation.sample_batch_builder import \
  19. MultiAgentSampleBatchBuilder
  20. from ray.rllib.env.base_env import BaseEnv, ASYNC_RESET_RETURN
  21. from ray.rllib.env.wrappers.atari_wrappers import get_wrapper_by_cls, \
  22. MonitorEnv
  23. from ray.rllib.models.preprocessors import Preprocessor
  24. from ray.rllib.offline import InputReader
  25. from ray.rllib.policy.policy import Policy
  26. from ray.rllib.policy.policy_map import PolicyMap
  27. from ray.rllib.policy.sample_batch import SampleBatch
  28. from ray.rllib.utils.annotations import override, DeveloperAPI
  29. from ray.rllib.utils.debug import summarize
  30. from ray.rllib.utils.deprecation import deprecation_warning
  31. from ray.rllib.utils.filter import Filter
  32. from ray.rllib.utils.numpy import convert_to_numpy
  33. from ray.rllib.utils.spaces.space_utils import clip_action, \
  34. unsquash_action, unbatch
  35. from ray.rllib.utils.typing import SampleBatchType, AgentID, PolicyID, \
  36. EnvObsType, EnvInfoDict, EnvID, MultiEnvDict, EnvActionType, \
  37. TensorStructType
  38. if TYPE_CHECKING:
  39. from ray.rllib.agents.callbacks import DefaultCallbacks
  40. from ray.rllib.evaluation.observation_function import ObservationFunction
  41. from ray.rllib.evaluation.rollout_worker import RolloutWorker
  42. from ray.rllib.utils import try_import_tf
  43. _, tf, _ = try_import_tf()
  44. from gym.envs.classic_control.rendering import SimpleImageViewer
  45. logger = logging.getLogger(__name__)
  46. PolicyEvalData = namedtuple("PolicyEvalData", [
  47. "env_id", "agent_id", "obs", "info", "rnn_state", "prev_action",
  48. "prev_reward"
  49. ])
  50. # A batch of RNN states with dimensions [state_index, batch, state_object].
  51. StateBatch = List[List[Any]]
  52. class NewEpisodeDefaultDict(defaultdict):
  53. def __missing__(self, env_id):
  54. if self.default_factory is None:
  55. raise KeyError(env_id)
  56. else:
  57. ret = self[env_id] = self.default_factory(env_id)
  58. return ret
  59. class _PerfStats:
  60. """Sampler perf stats that will be included in rollout metrics."""
  61. def __init__(self):
  62. self.iters = 0
  63. self.raw_obs_processing_time = 0.0
  64. self.inference_time = 0.0
  65. self.action_processing_time = 0.0
  66. self.env_wait_time = 0.0
  67. self.env_render_time = 0.0
  68. def get(self):
  69. # Mean multiplicator (1000 = ms -> sec).
  70. factor = 1000 / self.iters
  71. return {
  72. # Raw observation preprocessing.
  73. "mean_raw_obs_processing_ms": self.raw_obs_processing_time *
  74. factor,
  75. # Computing actions through policy.
  76. "mean_inference_ms": self.inference_time * factor,
  77. # Processing actions (to be sent to env, e.g. clipping).
  78. "mean_action_processing_ms": self.action_processing_time * factor,
  79. # Waiting for environment (during poll).
  80. "mean_env_wait_ms": self.env_wait_time * factor,
  81. # Environment rendering (False by default).
  82. "mean_env_render_ms": self.env_render_time * factor,
  83. }
  84. @DeveloperAPI
  85. class SamplerInput(InputReader, metaclass=ABCMeta):
  86. """Reads input experiences from an existing sampler."""
  87. @override(InputReader)
  88. def next(self) -> SampleBatchType:
  89. batches = [self.get_data()]
  90. batches.extend(self.get_extra_batches())
  91. if len(batches) > 1:
  92. return batches[0].concat_samples(batches)
  93. else:
  94. return batches[0]
  95. @abstractmethod
  96. @DeveloperAPI
  97. def get_data(self) -> SampleBatchType:
  98. """Called by `self.next()` to return the next batch of data.
  99. Override this in child classes.
  100. Returns:
  101. The next batch of data.
  102. """
  103. raise NotImplementedError
  104. @abstractmethod
  105. @DeveloperAPI
  106. def get_metrics(self) -> List[RolloutMetrics]:
  107. """Returns list of episode metrics since the last call to this method.
  108. The list will contain one RolloutMetrics object per completed episode.
  109. Returns:
  110. List of RolloutMetrics objects, one per completed episode since
  111. the last call to this method.
  112. """
  113. raise NotImplementedError
  114. @abstractmethod
  115. @DeveloperAPI
  116. def get_extra_batches(self) -> List[SampleBatchType]:
  117. """Returns list of extra batches since the last call to this method.
  118. The list will contain all SampleBatches or
  119. MultiAgentBatches that the user has provided thus-far. Users can
  120. add these "extra batches" to an episode by calling the episode's
  121. `add_extra_batch([SampleBatchType])` method. This can be done from
  122. inside an overridden `Policy.compute_actions_from_input_dict(...,
  123. episodes)` or from a custom callback's `on_episode_[start|step|end]()`
  124. methods.
  125. Returns:
  126. List of SamplesBatches or MultiAgentBatches provided thus-far by
  127. the user since the last call to this method.
  128. """
  129. raise NotImplementedError
  130. @DeveloperAPI
  131. class SyncSampler(SamplerInput):
  132. """Sync SamplerInput that collects experiences when `get_data()` is called.
  133. """
  134. def __init__(
  135. self,
  136. *,
  137. worker: "RolloutWorker",
  138. env: BaseEnv,
  139. clip_rewards: Union[bool, float],
  140. rollout_fragment_length: int,
  141. count_steps_by: str = "env_steps",
  142. callbacks: "DefaultCallbacks",
  143. horizon: int = None,
  144. multiple_episodes_in_batch: bool = False,
  145. normalize_actions: bool = True,
  146. clip_actions: bool = False,
  147. soft_horizon: bool = False,
  148. no_done_at_end: bool = False,
  149. observation_fn: Optional["ObservationFunction"] = None,
  150. sample_collector_class: Optional[Type[SampleCollector]] = None,
  151. render: bool = False,
  152. # Obsolete.
  153. policies=None,
  154. policy_mapping_fn=None,
  155. preprocessors=None,
  156. obs_filters=None,
  157. tf_sess=None,
  158. ):
  159. """Initializes a SyncSampler instance.
  160. Args:
  161. worker: The RolloutWorker that will use this Sampler for sampling.
  162. env: Any Env object. Will be converted into an RLlib BaseEnv.
  163. clip_rewards: True for +/-1.0 clipping,
  164. actual float value for +/- value clipping. False for no
  165. clipping.
  166. rollout_fragment_length: The length of a fragment to collect
  167. before building a SampleBatch from the data and resetting
  168. the SampleBatchBuilder object.
  169. count_steps_by: One of "env_steps" (default) or "agent_steps".
  170. Use "agent_steps", if you want rollout lengths to be counted
  171. by individual agent steps. In a multi-agent env,
  172. a single env_step contains one or more agent_steps, depending
  173. on how many agents are present at any given time in the
  174. ongoing episode.
  175. callbacks: The Callbacks object to use when episode
  176. events happen during rollout.
  177. horizon: Hard-reset the Env after this many timesteps.
  178. multiple_episodes_in_batch: Whether to pack multiple
  179. episodes into each batch. This guarantees batches will be
  180. exactly `rollout_fragment_length` in size.
  181. normalize_actions: Whether to normalize actions to the
  182. action space's bounds.
  183. clip_actions: Whether to clip actions according to the
  184. given action_space's bounds.
  185. soft_horizon: If True, calculate bootstrapped values as if
  186. episode had ended, but don't physically reset the environment
  187. when the horizon is hit.
  188. no_done_at_end: Ignore the done=True at the end of the
  189. episode and instead record done=False.
  190. observation_fn: Optional multi-agent observation func to use for
  191. preprocessing observations.
  192. sample_collector_class: An optional Samplecollector sub-class to
  193. use to collect, store, and retrieve environment-, model-,
  194. and sampler data.
  195. render: Whether to try to render the environment after each step.
  196. """
  197. # All of the following arguments are deprecated. They will instead be
  198. # provided via the passed in `worker` arg, e.g. `worker.policy_map`.
  199. if log_once("deprecated_sync_sampler_args"):
  200. if policies is not None:
  201. deprecation_warning(old="policies")
  202. if policy_mapping_fn is not None:
  203. deprecation_warning(old="policy_mapping_fn")
  204. if preprocessors is not None:
  205. deprecation_warning(old="preprocessors")
  206. if obs_filters is not None:
  207. deprecation_warning(old="obs_filters")
  208. if tf_sess is not None:
  209. deprecation_warning(old="tf_sess")
  210. self.base_env = BaseEnv.to_base_env(env)
  211. self.rollout_fragment_length = rollout_fragment_length
  212. self.horizon = horizon
  213. self.extra_batches = queue.Queue()
  214. self.perf_stats = _PerfStats()
  215. if not sample_collector_class:
  216. sample_collector_class = SimpleListCollector
  217. self.sample_collector = sample_collector_class(
  218. worker.policy_map,
  219. clip_rewards,
  220. callbacks,
  221. multiple_episodes_in_batch,
  222. rollout_fragment_length,
  223. count_steps_by=count_steps_by)
  224. self.render = render
  225. # Create the rollout generator to use for calls to `get_data()`.
  226. self._env_runner = _env_runner(
  227. worker, self.base_env, self.extra_batches.put, self.horizon,
  228. normalize_actions, clip_actions, multiple_episodes_in_batch,
  229. callbacks, self.perf_stats, soft_horizon, no_done_at_end,
  230. observation_fn, self.sample_collector, self.render)
  231. self.metrics_queue = queue.Queue()
  232. @override(SamplerInput)
  233. def get_data(self) -> SampleBatchType:
  234. while True:
  235. item = next(self._env_runner)
  236. if isinstance(item, RolloutMetrics):
  237. self.metrics_queue.put(item)
  238. else:
  239. return item
  240. @override(SamplerInput)
  241. def get_metrics(self) -> List[RolloutMetrics]:
  242. completed = []
  243. while True:
  244. try:
  245. completed.append(self.metrics_queue.get_nowait()._replace(
  246. perf_stats=self.perf_stats.get()))
  247. except queue.Empty:
  248. break
  249. return completed
  250. @override(SamplerInput)
  251. def get_extra_batches(self) -> List[SampleBatchType]:
  252. extra = []
  253. while True:
  254. try:
  255. extra.append(self.extra_batches.get_nowait())
  256. except queue.Empty:
  257. break
  258. return extra
  259. @DeveloperAPI
  260. class AsyncSampler(threading.Thread, SamplerInput):
  261. """Async SamplerInput that collects experiences in thread and queues them.
  262. Once started, experiences are continuously collected in the background
  263. and put into a Queue, from where they can be unqueued by the caller
  264. of `get_data()`.
  265. """
  266. def __init__(
  267. self,
  268. *,
  269. worker: "RolloutWorker",
  270. env: BaseEnv,
  271. clip_rewards: Union[bool, float],
  272. rollout_fragment_length: int,
  273. count_steps_by: str = "env_steps",
  274. callbacks: "DefaultCallbacks",
  275. horizon: Optional[int] = None,
  276. multiple_episodes_in_batch: bool = False,
  277. normalize_actions: bool = True,
  278. clip_actions: bool = False,
  279. soft_horizon: bool = False,
  280. no_done_at_end: bool = False,
  281. observation_fn: Optional["ObservationFunction"] = None,
  282. sample_collector_class: Optional[Type[SampleCollector]] = None,
  283. render: bool = False,
  284. blackhole_outputs: bool = False,
  285. # Obsolete.
  286. policies=None,
  287. policy_mapping_fn=None,
  288. preprocessors=None,
  289. obs_filters=None,
  290. tf_sess=None,
  291. ):
  292. """Initializes an AsyncSampler instance.
  293. Args:
  294. worker: The RolloutWorker that will use this Sampler for sampling.
  295. env: Any Env object. Will be converted into an RLlib BaseEnv.
  296. clip_rewards: True for +/-1.0 clipping,
  297. actual float value for +/- value clipping. False for no
  298. clipping.
  299. rollout_fragment_length: The length of a fragment to collect
  300. before building a SampleBatch from the data and resetting
  301. the SampleBatchBuilder object.
  302. count_steps_by: One of "env_steps" (default) or "agent_steps".
  303. Use "agent_steps", if you want rollout lengths to be counted
  304. by individual agent steps. In a multi-agent env,
  305. a single env_step contains one or more agent_steps, depending
  306. on how many agents are present at any given time in the
  307. ongoing episode.
  308. horizon: Hard-reset the Env after this many timesteps.
  309. multiple_episodes_in_batch: Whether to pack multiple
  310. episodes into each batch. This guarantees batches will be
  311. exactly `rollout_fragment_length` in size.
  312. normalize_actions: Whether to normalize actions to the
  313. action space's bounds.
  314. clip_actions: Whether to clip actions according to the
  315. given action_space's bounds.
  316. blackhole_outputs: Whether to collect samples, but then
  317. not further process or store them (throw away all samples).
  318. soft_horizon: If True, calculate bootstrapped values as if
  319. episode had ended, but don't physically reset the environment
  320. when the horizon is hit.
  321. no_done_at_end: Ignore the done=True at the end of the
  322. episode and instead record done=False.
  323. observation_fn: Optional multi-agent observation func to use for
  324. preprocessing observations.
  325. sample_collector_class: An optional SampleCollector sub-class to
  326. use to collect, store, and retrieve environment-, model-,
  327. and sampler data.
  328. render: Whether to try to render the environment after each step.
  329. """
  330. # All of the following arguments are deprecated. They will instead be
  331. # provided via the passed in `worker` arg, e.g. `worker.policy_map`.
  332. if log_once("deprecated_async_sampler_args"):
  333. if policies is not None:
  334. deprecation_warning(old="policies")
  335. if policy_mapping_fn is not None:
  336. deprecation_warning(old="policy_mapping_fn")
  337. if preprocessors is not None:
  338. deprecation_warning(old="preprocessors")
  339. if obs_filters is not None:
  340. deprecation_warning(old="obs_filters")
  341. if tf_sess is not None:
  342. deprecation_warning(old="tf_sess")
  343. self.worker = worker
  344. for _, f in worker.filters.items():
  345. assert getattr(f, "is_concurrent", False), \
  346. "Observation Filter must support concurrent updates."
  347. self.base_env = BaseEnv.to_base_env(env)
  348. threading.Thread.__init__(self)
  349. self.queue = queue.Queue(5)
  350. self.extra_batches = queue.Queue()
  351. self.metrics_queue = queue.Queue()
  352. self.rollout_fragment_length = rollout_fragment_length
  353. self.horizon = horizon
  354. self.clip_rewards = clip_rewards
  355. self.daemon = True
  356. self.multiple_episodes_in_batch = multiple_episodes_in_batch
  357. self.callbacks = callbacks
  358. self.normalize_actions = normalize_actions
  359. self.clip_actions = clip_actions
  360. self.blackhole_outputs = blackhole_outputs
  361. self.soft_horizon = soft_horizon
  362. self.no_done_at_end = no_done_at_end
  363. self.perf_stats = _PerfStats()
  364. self.shutdown = False
  365. self.observation_fn = observation_fn
  366. self.render = render
  367. if not sample_collector_class:
  368. sample_collector_class = SimpleListCollector
  369. self.sample_collector = sample_collector_class(
  370. self.worker.policy_map,
  371. self.clip_rewards,
  372. self.callbacks,
  373. self.multiple_episodes_in_batch,
  374. self.rollout_fragment_length,
  375. count_steps_by=count_steps_by)
  376. @override(threading.Thread)
  377. def run(self):
  378. try:
  379. self._run()
  380. except BaseException as e:
  381. self.queue.put(e)
  382. raise e
  383. def _run(self):
  384. if self.blackhole_outputs:
  385. queue_putter = (lambda x: None)
  386. extra_batches_putter = (lambda x: None)
  387. else:
  388. queue_putter = self.queue.put
  389. extra_batches_putter = (
  390. lambda x: self.extra_batches.put(x, timeout=600.0))
  391. env_runner = _env_runner(
  392. self.worker, self.base_env, extra_batches_putter, self.horizon,
  393. self.normalize_actions, self.clip_actions,
  394. self.multiple_episodes_in_batch, self.callbacks, self.perf_stats,
  395. self.soft_horizon, self.no_done_at_end, self.observation_fn,
  396. self.sample_collector, self.render)
  397. while not self.shutdown:
  398. # The timeout variable exists because apparently, if one worker
  399. # dies, the other workers won't die with it, unless the timeout is
  400. # set to some large number. This is an empirical observation.
  401. item = next(env_runner)
  402. if isinstance(item, RolloutMetrics):
  403. self.metrics_queue.put(item)
  404. else:
  405. queue_putter(item)
  406. @override(SamplerInput)
  407. def get_data(self) -> SampleBatchType:
  408. if not self.is_alive():
  409. raise RuntimeError("Sampling thread has died")
  410. rollout = self.queue.get(timeout=600.0)
  411. # Propagate errors.
  412. if isinstance(rollout, BaseException):
  413. raise rollout
  414. return rollout
  415. @override(SamplerInput)
  416. def get_metrics(self) -> List[RolloutMetrics]:
  417. completed = []
  418. while True:
  419. try:
  420. completed.append(self.metrics_queue.get_nowait()._replace(
  421. perf_stats=self.perf_stats.get()))
  422. except queue.Empty:
  423. break
  424. return completed
  425. @override(SamplerInput)
  426. def get_extra_batches(self) -> List[SampleBatchType]:
  427. extra = []
  428. while True:
  429. try:
  430. extra.append(self.extra_batches.get_nowait())
  431. except queue.Empty:
  432. break
  433. return extra
  434. def _env_runner(
  435. worker: "RolloutWorker",
  436. base_env: BaseEnv,
  437. extra_batch_callback: Callable[[SampleBatchType], None],
  438. horizon: Optional[int],
  439. normalize_actions: bool,
  440. clip_actions: bool,
  441. multiple_episodes_in_batch: bool,
  442. callbacks: "DefaultCallbacks",
  443. perf_stats: _PerfStats,
  444. soft_horizon: bool,
  445. no_done_at_end: bool,
  446. observation_fn: "ObservationFunction",
  447. sample_collector: Optional[SampleCollector] = None,
  448. render: bool = None,
  449. ) -> Iterator[SampleBatchType]:
  450. """This implements the common experience collection logic.
  451. Args:
  452. worker: Reference to the current rollout worker.
  453. base_env: Env implementing BaseEnv.
  454. extra_batch_callback: function to send extra batch data to.
  455. horizon: Horizon of the episode.
  456. multiple_episodes_in_batch: Whether to pack multiple
  457. episodes into each batch. This guarantees batches will be exactly
  458. `rollout_fragment_length` in size.
  459. normalize_actions: Whether to normalize actions to the action
  460. space's bounds.
  461. clip_actions: Whether to clip actions to the space range.
  462. callbacks: User callbacks to run on episode events.
  463. perf_stats: Record perf stats into this object.
  464. soft_horizon: Calculate rewards but don't reset the
  465. environment when the horizon is hit.
  466. no_done_at_end: Ignore the done=True at the end of the episode
  467. and instead record done=False.
  468. observation_fn: Optional multi-agent
  469. observation func to use for preprocessing observations.
  470. sample_collector: An optional
  471. SampleCollector object to use.
  472. render: Whether to try to render the environment after each
  473. step.
  474. Yields:
  475. Object containing state, action, reward, terminal condition,
  476. and other fields as dictated by `policy`.
  477. """
  478. # May be populated with used for image rendering
  479. simple_image_viewer: Optional["SimpleImageViewer"] = None
  480. # Try to get Env's `max_episode_steps` prop. If it doesn't exist, ignore
  481. # error and continue with max_episode_steps=None.
  482. max_episode_steps = None
  483. try:
  484. max_episode_steps = base_env.get_sub_environments()[
  485. 0].spec.max_episode_steps
  486. except Exception:
  487. pass
  488. # Trainer has a given `horizon` setting.
  489. if horizon:
  490. # `horizon` is larger than env's limit.
  491. if max_episode_steps and horizon > max_episode_steps:
  492. # Try to override the env's own max-step setting with our horizon.
  493. # If this won't work, throw an error.
  494. try:
  495. base_env.get_sub_environments()[
  496. 0].spec.max_episode_steps = horizon
  497. base_env.get_sub_environments()[0]._max_episode_steps = horizon
  498. except Exception:
  499. raise ValueError(
  500. "Your `horizon` setting ({}) is larger than the Env's own "
  501. "timestep limit ({}), which seems to be unsettable! Try "
  502. "to increase the Env's built-in limit to be at least as "
  503. "large as your wanted `horizon`.".format(
  504. horizon, max_episode_steps))
  505. # Otherwise, set Trainer's horizon to env's max-steps.
  506. elif max_episode_steps:
  507. horizon = max_episode_steps
  508. logger.debug(
  509. "No episode horizon specified, setting it to Env's limit ({}).".
  510. format(max_episode_steps))
  511. # No horizon/max_episode_steps -> Episodes may be infinitely long.
  512. else:
  513. horizon = float("inf")
  514. logger.debug("No episode horizon specified, assuming inf.")
  515. # Pool of batch builders, which can be shared across episodes to pack
  516. # trajectory data.
  517. batch_builder_pool: List[MultiAgentSampleBatchBuilder] = []
  518. def get_batch_builder():
  519. if batch_builder_pool:
  520. return batch_builder_pool.pop()
  521. else:
  522. return None
  523. def new_episode(env_id):
  524. episode = Episode(
  525. worker.policy_map,
  526. worker.policy_mapping_fn,
  527. get_batch_builder,
  528. extra_batch_callback,
  529. env_id=env_id,
  530. worker=worker,
  531. )
  532. # Call each policy's Exploration.on_episode_start method.
  533. # Note: This may break the exploration (e.g. ParameterNoise) of
  534. # policies in the `policy_map` that have not been recently used
  535. # (and are therefore stashed to disk). However, we certainly do not
  536. # want to loop through all (even stashed) policies here as that
  537. # would counter the purpose of the LRU policy caching.
  538. for p in worker.policy_map.cache.values():
  539. if getattr(p, "exploration", None) is not None:
  540. p.exploration.on_episode_start(
  541. policy=p,
  542. environment=base_env,
  543. episode=episode,
  544. tf_sess=p.get_session())
  545. callbacks.on_episode_start(
  546. worker=worker,
  547. base_env=base_env,
  548. policies=worker.policy_map,
  549. episode=episode,
  550. env_index=env_id,
  551. )
  552. return episode
  553. active_episodes: Dict[EnvID, Episode] = \
  554. NewEpisodeDefaultDict(new_episode)
  555. while True:
  556. perf_stats.iters += 1
  557. t0 = time.time()
  558. # Get observations from all ready agents.
  559. # types: MultiEnvDict, MultiEnvDict, MultiEnvDict, MultiEnvDict, ...
  560. unfiltered_obs, rewards, dones, infos, off_policy_actions = \
  561. base_env.poll()
  562. perf_stats.env_wait_time += time.time() - t0
  563. if log_once("env_returns"):
  564. logger.info("Raw obs from env: {}".format(
  565. summarize(unfiltered_obs)))
  566. logger.info("Info return from env: {}".format(summarize(infos)))
  567. # Process observations and prepare for policy evaluation.
  568. t1 = time.time()
  569. # types: Set[EnvID], Dict[PolicyID, List[PolicyEvalData]],
  570. # List[Union[RolloutMetrics, SampleBatchType]]
  571. active_envs, to_eval, outputs = \
  572. _process_observations(
  573. worker=worker,
  574. base_env=base_env,
  575. active_episodes=active_episodes,
  576. unfiltered_obs=unfiltered_obs,
  577. rewards=rewards,
  578. dones=dones,
  579. infos=infos,
  580. horizon=horizon,
  581. multiple_episodes_in_batch=multiple_episodes_in_batch,
  582. callbacks=callbacks,
  583. soft_horizon=soft_horizon,
  584. no_done_at_end=no_done_at_end,
  585. observation_fn=observation_fn,
  586. sample_collector=sample_collector,
  587. )
  588. perf_stats.raw_obs_processing_time += time.time() - t1
  589. for o in outputs:
  590. yield o
  591. # Do batched policy eval (accross vectorized envs).
  592. t2 = time.time()
  593. # types: Dict[PolicyID, Tuple[TensorStructType, StateBatch, dict]]
  594. eval_results = _do_policy_eval(
  595. to_eval=to_eval,
  596. policies=worker.policy_map,
  597. sample_collector=sample_collector,
  598. active_episodes=active_episodes,
  599. )
  600. perf_stats.inference_time += time.time() - t2
  601. # Process results and update episode state.
  602. t3 = time.time()
  603. actions_to_send: Dict[EnvID, Dict[AgentID, EnvActionType]] = \
  604. _process_policy_eval_results(
  605. to_eval=to_eval,
  606. eval_results=eval_results,
  607. active_episodes=active_episodes,
  608. active_envs=active_envs,
  609. off_policy_actions=off_policy_actions,
  610. policies=worker.policy_map,
  611. normalize_actions=normalize_actions,
  612. clip_actions=clip_actions,
  613. )
  614. perf_stats.action_processing_time += time.time() - t3
  615. # Return computed actions to ready envs. We also send to envs that have
  616. # taken off-policy actions; those envs are free to ignore the action.
  617. t4 = time.time()
  618. base_env.send_actions(actions_to_send)
  619. perf_stats.env_wait_time += time.time() - t4
  620. # Try to render the env, if required.
  621. if render:
  622. t5 = time.time()
  623. # Render can either return an RGB image (uint8 [w x h x 3] numpy
  624. # array) or take care of rendering itself (returning True).
  625. rendered = base_env.try_render()
  626. # Rendering returned an image -> Display it in a SimpleImageViewer.
  627. if isinstance(rendered, np.ndarray) and len(rendered.shape) == 3:
  628. # ImageViewer not defined yet, try to create one.
  629. if simple_image_viewer is None:
  630. try:
  631. from gym.envs.classic_control.rendering import \
  632. SimpleImageViewer
  633. simple_image_viewer = SimpleImageViewer()
  634. except (ImportError, ModuleNotFoundError):
  635. render = False # disable rendering
  636. logger.warning(
  637. "Could not import gym.envs.classic_control."
  638. "rendering! Try `pip install gym[all]`.")
  639. if simple_image_viewer:
  640. simple_image_viewer.imshow(rendered)
  641. elif rendered not in [True, False, None]:
  642. raise ValueError(
  643. "The env's ({base_env}) `try_render()` method returned an"
  644. " unsupported value! Make sure you either return a "
  645. "uint8/w x h x 3 (RGB) image or handle rendering in a "
  646. "window and then return `True`.")
  647. perf_stats.env_render_time += time.time() - t5
  648. def _process_observations(
  649. *,
  650. worker: "RolloutWorker",
  651. base_env: BaseEnv,
  652. active_episodes: Dict[EnvID, Episode],
  653. unfiltered_obs: Dict[EnvID, Dict[AgentID, EnvObsType]],
  654. rewards: Dict[EnvID, Dict[AgentID, float]],
  655. dones: Dict[EnvID, Dict[AgentID, bool]],
  656. infos: Dict[EnvID, Dict[AgentID, EnvInfoDict]],
  657. horizon: int,
  658. multiple_episodes_in_batch: bool,
  659. callbacks: "DefaultCallbacks",
  660. soft_horizon: bool,
  661. no_done_at_end: bool,
  662. observation_fn: "ObservationFunction",
  663. sample_collector: SampleCollector,
  664. ) -> Tuple[Set[EnvID], Dict[PolicyID, List[PolicyEvalData]], List[Union[
  665. RolloutMetrics, SampleBatchType]]]:
  666. """Record new data from the environment and prepare for policy evaluation.
  667. Args:
  668. worker: Reference to the current rollout worker.
  669. base_env: Env implementing BaseEnv.
  670. active_episodes: Mapping from
  671. episode ID to currently ongoing Episode object.
  672. unfiltered_obs: Doubly keyed dict of env-ids -> agent ids
  673. -> unfiltered observation tensor, returned by a `BaseEnv.poll()`
  674. call.
  675. rewards: Doubly keyed dict of env-ids -> agent ids ->
  676. rewards tensor, returned by a `BaseEnv.poll()` call.
  677. dones: Doubly keyed dict of env-ids -> agent ids ->
  678. boolean done flags, returned by a `BaseEnv.poll()` call.
  679. infos: Doubly keyed dict of env-ids -> agent ids ->
  680. info dicts, returned by a `BaseEnv.poll()` call.
  681. horizon: Horizon of the episode.
  682. multiple_episodes_in_batch: Whether to pack multiple
  683. episodes into each batch. This guarantees batches will be exactly
  684. `rollout_fragment_length` in size.
  685. callbacks: User callbacks to run on episode events.
  686. soft_horizon: Calculate rewards but don't reset the
  687. environment when the horizon is hit.
  688. no_done_at_end: Ignore the done=True at the end of the episode
  689. and instead record done=False.
  690. observation_fn: Optional multi-agent
  691. observation func to use for preprocessing observations.
  692. sample_collector: The SampleCollector object
  693. used to store and retrieve environment samples.
  694. Returns:
  695. Tuple consisting of 1) active_envs: Set of non-terminated env ids.
  696. 2) to_eval: Map of policy_id to list of agent PolicyEvalData.
  697. 3) outputs: List of metrics and samples to return from the sampler.
  698. """
  699. # Output objects.
  700. active_envs: Set[EnvID] = set()
  701. to_eval: Dict[PolicyID, List[PolicyEvalData]] = defaultdict(list)
  702. outputs: List[Union[RolloutMetrics, SampleBatchType]] = []
  703. # For each (vectorized) sub-environment.
  704. # types: EnvID, Dict[AgentID, EnvObsType]
  705. for env_id, all_agents_obs in unfiltered_obs.items():
  706. is_new_episode: bool = env_id not in active_episodes
  707. episode: Episode = active_episodes[env_id]
  708. if not is_new_episode:
  709. sample_collector.episode_step(episode)
  710. episode._add_agent_rewards(rewards[env_id])
  711. # Check episode termination conditions.
  712. if dones[env_id]["__all__"] or episode.length >= horizon:
  713. hit_horizon = (episode.length >= horizon
  714. and not dones[env_id]["__all__"])
  715. all_agents_done = True
  716. atari_metrics: List[RolloutMetrics] = _fetch_atari_metrics(
  717. base_env)
  718. if atari_metrics is not None:
  719. for m in atari_metrics:
  720. outputs.append(
  721. m._replace(custom_metrics=episode.custom_metrics))
  722. else:
  723. outputs.append(
  724. RolloutMetrics(episode.length, episode.total_reward,
  725. dict(episode.agent_rewards),
  726. episode.custom_metrics, {},
  727. episode.hist_data, episode.media))
  728. # Check whether we have to create a fake-last observation
  729. # for some agents (the environment is not required to do so if
  730. # dones[__all__]=True).
  731. for ag_id in episode.get_agents():
  732. if not episode.last_done_for(
  733. ag_id) and ag_id not in all_agents_obs:
  734. # Create a fake (all-0s) observation.
  735. obs_sp = worker.policy_map[episode.policy_for(
  736. ag_id)].observation_space
  737. obs_sp = getattr(obs_sp, "original_space", obs_sp)
  738. all_agents_obs[ag_id] = tree.map_structure(
  739. np.zeros_like, obs_sp.sample())
  740. else:
  741. hit_horizon = False
  742. all_agents_done = False
  743. active_envs.add(env_id)
  744. # Custom observation function is applied before preprocessing.
  745. if observation_fn:
  746. all_agents_obs: Dict[AgentID, EnvObsType] = observation_fn(
  747. agent_obs=all_agents_obs,
  748. worker=worker,
  749. base_env=base_env,
  750. policies=worker.policy_map,
  751. episode=episode)
  752. if not isinstance(all_agents_obs, dict):
  753. raise ValueError(
  754. "observe() must return a dict of agent observations")
  755. # For each agent in the environment.
  756. # types: AgentID, EnvObsType
  757. for agent_id, raw_obs in all_agents_obs.items():
  758. assert agent_id != "__all__"
  759. last_observation: EnvObsType = episode.last_observation_for(
  760. agent_id)
  761. agent_done = bool(all_agents_done or dones[env_id].get(agent_id))
  762. # A new agent (initial obs) is already done -> Skip entirely.
  763. if last_observation is None and agent_done:
  764. continue
  765. policy_id: PolicyID = episode.policy_for(agent_id)
  766. preprocessor = _get_or_raise(worker.preprocessors, policy_id)
  767. prep_obs: EnvObsType = raw_obs
  768. if preprocessor is not None:
  769. prep_obs = preprocessor.transform(raw_obs)
  770. if log_once("prep_obs"):
  771. logger.info("Preprocessed obs: {}".format(
  772. summarize(prep_obs)))
  773. filtered_obs: EnvObsType = _get_or_raise(worker.filters,
  774. policy_id)(prep_obs)
  775. if log_once("filtered_obs"):
  776. logger.info("Filtered obs: {}".format(summarize(filtered_obs)))
  777. episode._set_last_observation(agent_id, filtered_obs)
  778. episode._set_last_raw_obs(agent_id, raw_obs)
  779. episode._set_last_done(agent_id, agent_done)
  780. # Infos from the environment.
  781. agent_infos = infos[env_id].get(agent_id, {})
  782. episode._set_last_info(agent_id, agent_infos)
  783. # Record transition info if applicable.
  784. if last_observation is None:
  785. sample_collector.add_init_obs(episode, agent_id, env_id,
  786. policy_id, episode.length - 1,
  787. filtered_obs)
  788. elif agent_infos is None or agent_infos.get(
  789. "training_enabled", True):
  790. # Add actions, rewards, next-obs to collectors.
  791. values_dict = {
  792. SampleBatch.T: episode.length - 1,
  793. SampleBatch.ENV_ID: env_id,
  794. SampleBatch.AGENT_INDEX: episode._agent_index(agent_id),
  795. # Action (slot 0) taken at timestep t.
  796. SampleBatch.ACTIONS: episode.last_action_for(agent_id),
  797. # Reward received after taking a at timestep t.
  798. SampleBatch.REWARDS: rewards[env_id].get(agent_id, 0.0),
  799. # After taking action=a, did we reach terminal?
  800. SampleBatch.DONES: (False
  801. if (no_done_at_end
  802. or (hit_horizon and soft_horizon))
  803. else agent_done),
  804. # Next observation.
  805. SampleBatch.NEXT_OBS: filtered_obs,
  806. }
  807. # Add extra-action-fetches (policy-inference infos) to
  808. # collectors.
  809. pol = worker.policy_map[policy_id]
  810. for key, value in episode.last_extra_action_outs_for(
  811. agent_id).items():
  812. if key in pol.view_requirements:
  813. values_dict[key] = value
  814. # Env infos for this agent.
  815. if "infos" in pol.view_requirements:
  816. values_dict["infos"] = agent_infos
  817. sample_collector.add_action_reward_next_obs(
  818. episode.episode_id, agent_id, env_id, policy_id,
  819. agent_done, values_dict)
  820. if not agent_done:
  821. item = PolicyEvalData(
  822. env_id, agent_id, filtered_obs, agent_infos, None
  823. if last_observation is None else
  824. episode.rnn_state_for(agent_id), None
  825. if last_observation is None else
  826. episode.last_action_for(agent_id), rewards[env_id].get(
  827. agent_id, 0.0))
  828. to_eval[policy_id].append(item)
  829. # Invoke the `on_episode_step` callback after the step is logged
  830. # to the episode.
  831. # Exception: The very first env.poll() call causes the env to get reset
  832. # (no step taken yet, just a single starting observation logged).
  833. # We need to skip this callback in this case.
  834. if episode.length > 0:
  835. callbacks.on_episode_step(
  836. worker=worker,
  837. base_env=base_env,
  838. policies=worker.policy_map,
  839. episode=episode,
  840. env_index=env_id)
  841. # Episode is done for all agents (dones[__all__] == True)
  842. # or we hit the horizon.
  843. if all_agents_done:
  844. is_done = dones[env_id]["__all__"]
  845. check_dones = is_done and not no_done_at_end
  846. # If, we are not allowed to pack the next episode into the same
  847. # SampleBatch (batch_mode=complete_episodes) -> Build the
  848. # MultiAgentBatch from a single episode and add it to "outputs".
  849. # Otherwise, just postprocess and continue collecting across
  850. # episodes.
  851. ma_sample_batch = sample_collector.postprocess_episode(
  852. episode,
  853. is_done=is_done or (hit_horizon and not soft_horizon),
  854. check_dones=check_dones,
  855. build=not multiple_episodes_in_batch)
  856. if ma_sample_batch:
  857. outputs.append(ma_sample_batch)
  858. # Call each (in-memory) policy's Exploration.on_episode_end
  859. # method.
  860. # Note: This may break the exploration (e.g. ParameterNoise) of
  861. # policies in the `policy_map` that have not been recently used
  862. # (and are therefore stashed to disk). However, we certainly do not
  863. # want to loop through all (even stashed) policies here as that
  864. # would counter the purpose of the LRU policy caching.
  865. for p in worker.policy_map.cache.values():
  866. if getattr(p, "exploration", None) is not None:
  867. p.exploration.on_episode_end(
  868. policy=p,
  869. environment=base_env,
  870. episode=episode,
  871. tf_sess=p.get_session())
  872. # Call custom on_episode_end callback.
  873. callbacks.on_episode_end(
  874. worker=worker,
  875. base_env=base_env,
  876. policies=worker.policy_map,
  877. episode=episode,
  878. env_index=env_id,
  879. )
  880. # Horizon hit and we have a soft horizon (no hard env reset).
  881. if hit_horizon and soft_horizon:
  882. episode.soft_reset()
  883. resetted_obs: Dict[AgentID, EnvObsType] = all_agents_obs
  884. else:
  885. del active_episodes[env_id]
  886. resetted_obs: Dict[AgentID, EnvObsType] = base_env.try_reset(
  887. env_id)
  888. # Reset not supported, drop this env from the ready list.
  889. if resetted_obs is None:
  890. if horizon != float("inf"):
  891. raise ValueError(
  892. "Setting episode horizon requires reset() support "
  893. "from the environment.")
  894. # Creates a new episode if this is not async return.
  895. # If reset is async, we will get its result in some future poll.
  896. elif resetted_obs != ASYNC_RESET_RETURN:
  897. new_episode: Episode = active_episodes[env_id]
  898. if observation_fn:
  899. resetted_obs: Dict[AgentID, EnvObsType] = observation_fn(
  900. agent_obs=resetted_obs,
  901. worker=worker,
  902. base_env=base_env,
  903. policies=worker.policy_map,
  904. episode=new_episode)
  905. # types: AgentID, EnvObsType
  906. for agent_id, raw_obs in resetted_obs.items():
  907. policy_id: PolicyID = new_episode.policy_for(agent_id)
  908. preproccessor = _get_or_raise(worker.preprocessors,
  909. policy_id)
  910. prep_obs: EnvObsType = raw_obs
  911. if preproccessor is not None:
  912. prep_obs = preproccessor.transform(raw_obs)
  913. filtered_obs: EnvObsType = _get_or_raise(
  914. worker.filters, policy_id)(prep_obs)
  915. new_episode._set_last_raw_obs(agent_id, raw_obs)
  916. new_episode._set_last_observation(agent_id, filtered_obs)
  917. # Add initial obs to buffer.
  918. sample_collector.add_init_obs(
  919. new_episode, agent_id, env_id, policy_id,
  920. new_episode.length - 1, filtered_obs)
  921. item = PolicyEvalData(
  922. env_id, agent_id, filtered_obs,
  923. episode.last_info_for(agent_id) or {},
  924. episode.rnn_state_for(agent_id), None, 0.0)
  925. to_eval[policy_id].append(item)
  926. # Try to build something.
  927. if multiple_episodes_in_batch:
  928. sample_batches = \
  929. sample_collector.try_build_truncated_episode_multi_agent_batch()
  930. if sample_batches:
  931. outputs.extend(sample_batches)
  932. return active_envs, to_eval, outputs
  933. def _do_policy_eval(
  934. *,
  935. to_eval: Dict[PolicyID, List[PolicyEvalData]],
  936. policies: PolicyMap,
  937. sample_collector,
  938. active_episodes: Dict[EnvID, Episode],
  939. ) -> Dict[PolicyID, Tuple[TensorStructType, StateBatch, dict]]:
  940. """Call compute_actions on collected episode/model data to get next action.
  941. Args:
  942. to_eval: Mapping of policy IDs to lists of PolicyEvalData objects
  943. (items in these lists will be the batch's items for the model
  944. forward pass).
  945. policies: Mapping from policy ID to Policy obj.
  946. sample_collector: The SampleCollector object to use.
  947. active_episodes: Mapping of EnvID to its currently active episode.
  948. Returns:
  949. Dict mapping PolicyIDs to compute_actions_from_input_dict() outputs.
  950. """
  951. eval_results: Dict[PolicyID, TensorStructType] = {}
  952. if log_once("compute_actions_input"):
  953. logger.info("Inputs to compute_actions():\n\n{}\n".format(
  954. summarize(to_eval)))
  955. for policy_id, eval_data in to_eval.items():
  956. # In case the policyID has been removed from this worker, we need to
  957. # re-assign policy_id and re-lookup the Policy object to use.
  958. try:
  959. policy: Policy = _get_or_raise(policies, policy_id)
  960. except ValueError:
  961. # Important: Get the policy_mapping_fn from the active
  962. # Episode as the policy_mapping_fn from the worker may
  963. # have already been changed (mapping fn stay constant
  964. # within one episode).
  965. episode = active_episodes[eval_data[0].env_id]
  966. policy_id = episode.policy_mapping_fn(
  967. eval_data[0].agent_id, episode, worker=episode.worker)
  968. policy: Policy = _get_or_raise(policies, policy_id)
  969. input_dict = sample_collector.get_inference_input_dict(policy_id)
  970. eval_results[policy_id] = \
  971. policy.compute_actions_from_input_dict(
  972. input_dict,
  973. timestep=policy.global_timestep,
  974. episodes=[active_episodes[t.env_id] for t in eval_data])
  975. if log_once("compute_actions_result"):
  976. logger.info("Outputs of compute_actions():\n\n{}\n".format(
  977. summarize(eval_results)))
  978. return eval_results
  979. def _process_policy_eval_results(
  980. *,
  981. to_eval: Dict[PolicyID, List[PolicyEvalData]],
  982. eval_results: Dict[PolicyID, Tuple[TensorStructType, StateBatch,
  983. dict]],
  984. active_episodes: Dict[EnvID, Episode],
  985. active_envs: Set[int],
  986. off_policy_actions: MultiEnvDict,
  987. policies: Dict[PolicyID, Policy],
  988. normalize_actions: bool,
  989. clip_actions: bool,
  990. ) -> Dict[EnvID, Dict[AgentID, EnvActionType]]:
  991. """Process the output of policy neural network evaluation.
  992. Records policy evaluation results into the given episode objects and
  993. returns replies to send back to agents in the env.
  994. Args:
  995. to_eval: Mapping of policy IDs to lists of PolicyEvalData objects.
  996. eval_results: Mapping of policy IDs to list of
  997. actions, rnn-out states, extra-action-fetches dicts.
  998. active_episodes: Mapping from episode ID to currently ongoing
  999. Episode object.
  1000. active_envs: Set of non-terminated env ids.
  1001. off_policy_actions: Doubly keyed dict of env-ids -> agent ids ->
  1002. off-policy-action, returned by a `BaseEnv.poll()` call.
  1003. policies: Mapping from policy ID to Policy.
  1004. normalize_actions: Whether to normalize actions to the action
  1005. space's bounds.
  1006. clip_actions: Whether to clip actions to the action space's bounds.
  1007. Returns:
  1008. Nested dict of env id -> agent id -> actions to be sent to
  1009. Env (np.ndarrays).
  1010. """
  1011. actions_to_send: Dict[EnvID, Dict[AgentID, EnvActionType]] = \
  1012. defaultdict(dict)
  1013. # types: int
  1014. for env_id in active_envs:
  1015. actions_to_send[env_id] = {} # at minimum send empty dict
  1016. # types: PolicyID, List[PolicyEvalData]
  1017. for policy_id, eval_data in to_eval.items():
  1018. actions: TensorStructType = eval_results[policy_id][0]
  1019. actions = convert_to_numpy(actions)
  1020. rnn_out_cols: StateBatch = eval_results[policy_id][1]
  1021. extra_action_out_cols: dict = eval_results[policy_id][2]
  1022. # In case actions is a list (representing the 0th dim of a batch of
  1023. # primitive actions), try converting it first.
  1024. if isinstance(actions, list):
  1025. actions = np.array(actions)
  1026. # Store RNN state ins/outs and extra-action fetches to episode.
  1027. for f_i, column in enumerate(rnn_out_cols):
  1028. extra_action_out_cols["state_out_{}".format(f_i)] = column
  1029. policy: Policy = _get_or_raise(policies, policy_id)
  1030. # Split action-component batches into single action rows.
  1031. actions: List[EnvActionType] = unbatch(actions)
  1032. # types: int, EnvActionType
  1033. for i, action in enumerate(actions):
  1034. # Normalize, if necessary.
  1035. if normalize_actions:
  1036. action_to_send = unsquash_action(action,
  1037. policy.action_space_struct)
  1038. # Clip, if necessary.
  1039. elif clip_actions:
  1040. action_to_send = clip_action(action,
  1041. policy.action_space_struct)
  1042. else:
  1043. action_to_send = action
  1044. env_id: int = eval_data[i].env_id
  1045. agent_id: AgentID = eval_data[i].agent_id
  1046. episode: Episode = active_episodes[env_id]
  1047. episode._set_rnn_state(agent_id, [c[i] for c in rnn_out_cols])
  1048. episode._set_last_extra_action_outs(
  1049. agent_id, {k: v[i]
  1050. for k, v in extra_action_out_cols.items()})
  1051. if env_id in off_policy_actions and \
  1052. agent_id in off_policy_actions[env_id]:
  1053. episode._set_last_action(agent_id,
  1054. off_policy_actions[env_id][agent_id])
  1055. else:
  1056. episode._set_last_action(agent_id, action)
  1057. assert agent_id not in actions_to_send[env_id]
  1058. actions_to_send[env_id][agent_id] = action_to_send
  1059. return actions_to_send
  1060. def _fetch_atari_metrics(base_env: BaseEnv) -> List[RolloutMetrics]:
  1061. """Atari games have multiple logical episodes, one per life.
  1062. However, for metrics reporting we count full episodes, all lives included.
  1063. """
  1064. sub_environments = base_env.get_sub_environments()
  1065. if not sub_environments:
  1066. return None
  1067. atari_out = []
  1068. for sub_env in sub_environments:
  1069. monitor = get_wrapper_by_cls(sub_env, MonitorEnv)
  1070. if not monitor:
  1071. return None
  1072. for eps_rew, eps_len in monitor.next_episode_results():
  1073. atari_out.append(RolloutMetrics(eps_len, eps_rew))
  1074. return atari_out
  1075. def _to_column_format(rnn_state_rows: List[List[Any]]) -> StateBatch:
  1076. num_cols = len(rnn_state_rows[0])
  1077. return [[row[i] for row in rnn_state_rows] for i in range(num_cols)]
  1078. def _get_or_raise(mapping: Dict[PolicyID, Union[Policy, Preprocessor, Filter]],
  1079. policy_id: PolicyID) -> Union[Policy, Preprocessor, Filter]:
  1080. """Returns an object under key `policy_id` in `mapping`.
  1081. Args:
  1082. mapping (Dict[PolicyID, Union[Policy, Preprocessor, Filter]]): The
  1083. mapping dict from policy id (str) to actual object (Policy,
  1084. Preprocessor, etc.).
  1085. policy_id (str): The policy ID to lookup.
  1086. Returns:
  1087. Union[Policy, Preprocessor, Filter]: The found object.
  1088. Raises:
  1089. ValueError: If `policy_id` cannot be found in `mapping`.
  1090. """
  1091. if policy_id not in mapping:
  1092. raise ValueError(
  1093. "Could not find policy for agent: PolicyID `{}` not found "
  1094. "in policy map, whose keys are `{}`.".format(
  1095. policy_id, mapping.keys()))
  1096. return mapping[policy_id]