sample_batch_builder.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. import collections
  2. import logging
  3. from typing import TYPE_CHECKING, Any, Dict, List
  4. import numpy as np
  5. from ray._common.deprecation import deprecation_warning
  6. from ray.rllib.env.base_env import _DUMMY_AGENT_ID
  7. from ray.rllib.policy.policy import Policy
  8. from ray.rllib.policy.sample_batch import MultiAgentBatch, SampleBatch
  9. from ray.rllib.utils.annotations import OldAPIStack
  10. from ray.rllib.utils.debug import summarize
  11. from ray.rllib.utils.typing import AgentID, PolicyID
  12. from ray.util.debug import log_once
  13. if TYPE_CHECKING:
  14. from ray.rllib.callbacks.callbacks import RLlibCallback
  15. logger = logging.getLogger(__name__)
  16. def _to_float_array(v: List[Any]) -> np.ndarray:
  17. arr = np.array(v)
  18. if arr.dtype == np.float64:
  19. return arr.astype(np.float32) # save some memory
  20. return arr
  21. @OldAPIStack
  22. class SampleBatchBuilder:
  23. """Util to build a SampleBatch incrementally.
  24. For efficiency, SampleBatches hold values in column form (as arrays).
  25. However, it is useful to add data one row (dict) at a time.
  26. """
  27. _next_unroll_id = 0 # disambiguates unrolls within a single episode
  28. def __init__(self):
  29. self.buffers: Dict[str, List] = collections.defaultdict(list)
  30. self.count = 0
  31. def add_values(self, **values: Any) -> None:
  32. """Add the given dictionary (row) of values to this batch."""
  33. for k, v in values.items():
  34. self.buffers[k].append(v)
  35. self.count += 1
  36. def add_batch(self, batch: SampleBatch) -> None:
  37. """Add the given batch of values to this batch."""
  38. for k, column in batch.items():
  39. self.buffers[k].extend(column)
  40. self.count += batch.count
  41. def build_and_reset(self) -> SampleBatch:
  42. """Returns a sample batch including all previously added values."""
  43. batch = SampleBatch({k: _to_float_array(v) for k, v in self.buffers.items()})
  44. if SampleBatch.UNROLL_ID not in batch:
  45. batch[SampleBatch.UNROLL_ID] = np.repeat(
  46. SampleBatchBuilder._next_unroll_id, batch.count
  47. )
  48. SampleBatchBuilder._next_unroll_id += 1
  49. self.buffers.clear()
  50. self.count = 0
  51. return batch
  52. @OldAPIStack
  53. class MultiAgentSampleBatchBuilder:
  54. """Util to build SampleBatches for each policy in a multi-agent env.
  55. Input data is per-agent, while output data is per-policy. There is an M:N
  56. mapping between agents and policies. We retain one local batch builder
  57. per agent. When an agent is done, then its local batch is appended into the
  58. corresponding policy batch for the agent's policy.
  59. """
  60. def __init__(
  61. self,
  62. policy_map: Dict[PolicyID, Policy],
  63. clip_rewards: bool,
  64. callbacks: "RLlibCallback",
  65. ):
  66. """Initialize a MultiAgentSampleBatchBuilder.
  67. Args:
  68. policy_map (Dict[str,Policy]): Maps policy ids to policy instances.
  69. clip_rewards (Union[bool,float]): Whether to clip rewards before
  70. postprocessing (at +/-1.0) or the actual value to +/- clip.
  71. callbacks: RLlib callbacks.
  72. """
  73. if log_once("MultiAgentSampleBatchBuilder"):
  74. deprecation_warning(old="MultiAgentSampleBatchBuilder", error=False)
  75. self.policy_map = policy_map
  76. self.clip_rewards = clip_rewards
  77. # Build the Policies' SampleBatchBuilders.
  78. self.policy_builders = {k: SampleBatchBuilder() for k in policy_map.keys()}
  79. # Whenever we observe a new agent, add a new SampleBatchBuilder for
  80. # this agent.
  81. self.agent_builders = {}
  82. # Internal agent-to-policy map.
  83. self.agent_to_policy = {}
  84. self.callbacks = callbacks
  85. # Number of "inference" steps taken in the environment.
  86. # Regardless of the number of agents involved in each of these steps.
  87. self.count = 0
  88. def total(self) -> int:
  89. """Returns the total number of steps taken in the env (all agents).
  90. Returns:
  91. int: The number of steps taken in total in the environment over all
  92. agents.
  93. """
  94. return sum(a.count for a in self.agent_builders.values())
  95. def has_pending_agent_data(self) -> bool:
  96. """Returns whether there is pending unprocessed data.
  97. Returns:
  98. bool: True if there is at least one per-agent builder (with data
  99. in it).
  100. """
  101. return len(self.agent_builders) > 0
  102. def add_values(self, agent_id: AgentID, policy_id: AgentID, **values: Any) -> None:
  103. """Add the given dictionary (row) of values to this batch.
  104. Args:
  105. agent_id: Unique id for the agent we are adding values for.
  106. policy_id: Unique id for policy controlling the agent.
  107. values: Row of values to add for this agent.
  108. """
  109. if agent_id not in self.agent_builders:
  110. self.agent_builders[agent_id] = SampleBatchBuilder()
  111. self.agent_to_policy[agent_id] = policy_id
  112. # Include the current agent id for multi-agent algorithms.
  113. if agent_id != _DUMMY_AGENT_ID:
  114. values["agent_id"] = agent_id
  115. self.agent_builders[agent_id].add_values(**values)
  116. def postprocess_batch_so_far(self, episode=None) -> None:
  117. """Apply policy postprocessors to any unprocessed rows.
  118. This pushes the postprocessed per-agent batches onto the per-policy
  119. builders, clearing per-agent state.
  120. Args:
  121. episode (Optional[Episode]): The Episode object that
  122. holds this MultiAgentBatchBuilder object.
  123. """
  124. # Materialize the batches so far.
  125. pre_batches = {}
  126. for agent_id, builder in self.agent_builders.items():
  127. pre_batches[agent_id] = (
  128. self.policy_map[self.agent_to_policy[agent_id]],
  129. builder.build_and_reset(),
  130. )
  131. # Apply postprocessor.
  132. post_batches = {}
  133. if self.clip_rewards is True:
  134. for _, (_, pre_batch) in pre_batches.items():
  135. pre_batch["rewards"] = np.sign(pre_batch["rewards"])
  136. elif self.clip_rewards:
  137. for _, (_, pre_batch) in pre_batches.items():
  138. pre_batch["rewards"] = np.clip(
  139. pre_batch["rewards"],
  140. a_min=-self.clip_rewards,
  141. a_max=self.clip_rewards,
  142. )
  143. for agent_id, (_, pre_batch) in pre_batches.items():
  144. other_batches = pre_batches.copy()
  145. del other_batches[agent_id]
  146. policy = self.policy_map[self.agent_to_policy[agent_id]]
  147. if (
  148. not pre_batch.is_single_trajectory()
  149. or len(set(pre_batch[SampleBatch.EPS_ID])) > 1
  150. ):
  151. raise ValueError(
  152. "Batches sent to postprocessing must only contain steps "
  153. "from a single trajectory.",
  154. pre_batch,
  155. )
  156. # Call the Policy's Exploration's postprocess method.
  157. post_batches[agent_id] = pre_batch
  158. if getattr(policy, "exploration", None) is not None:
  159. policy.exploration.postprocess_trajectory(
  160. policy, post_batches[agent_id], policy.get_session()
  161. )
  162. post_batches[agent_id] = policy.postprocess_trajectory(
  163. post_batches[agent_id], other_batches, episode
  164. )
  165. if log_once("after_post"):
  166. logger.info(
  167. "Trajectory fragment after postprocess_trajectory():\n\n{}\n".format(
  168. summarize(post_batches)
  169. )
  170. )
  171. # Append into policy batches and reset
  172. from ray.rllib.evaluation.rollout_worker import get_global_worker
  173. for agent_id, post_batch in sorted(post_batches.items()):
  174. self.callbacks.on_postprocess_trajectory(
  175. worker=get_global_worker(),
  176. episode=episode,
  177. agent_id=agent_id,
  178. policy_id=self.agent_to_policy[agent_id],
  179. policies=self.policy_map,
  180. postprocessed_batch=post_batch,
  181. original_batches=pre_batches,
  182. )
  183. self.policy_builders[self.agent_to_policy[agent_id]].add_batch(post_batch)
  184. self.agent_builders.clear()
  185. self.agent_to_policy.clear()
  186. def check_missing_dones(self) -> None:
  187. for agent_id, builder in self.agent_builders.items():
  188. if not builder.buffers.is_terminated_or_truncated():
  189. raise ValueError(
  190. "The environment terminated for all agents, but we still "
  191. "don't have a last observation for "
  192. "agent {} (policy {}). ".format(
  193. agent_id, self.agent_to_policy[agent_id]
  194. )
  195. + "Please ensure that you include the last observations "
  196. "of all live agents when setting '__all__' terminated|truncated "
  197. "to True. "
  198. )
  199. def build_and_reset(self, episode=None) -> MultiAgentBatch:
  200. """Returns the accumulated sample batches for each policy.
  201. Any unprocessed rows will be first postprocessed with a policy
  202. postprocessor. The internal state of this builder will be reset.
  203. Args:
  204. episode (Optional[Episode]): The Episode object that
  205. holds this MultiAgentBatchBuilder object or None.
  206. Returns:
  207. MultiAgentBatch: Returns the accumulated sample batches for each
  208. policy.
  209. """
  210. self.postprocess_batch_so_far(episode)
  211. policy_batches = {}
  212. for policy_id, builder in self.policy_builders.items():
  213. if builder.count > 0:
  214. policy_batches[policy_id] = builder.build_and_reset()
  215. old_count = self.count
  216. self.count = 0
  217. return MultiAgentBatch.wrap_as_needed(policy_batches, old_count)